1. Java - Home
Java is a high-level, class-based, object-oriented programming language...
Welcome to the Java Programming Tutorial
Learn Java with practical examples and tutorials.
Output: Displays a welcome message for Java programming.
2. Java - Overview
Java is widely used for building enterprise applications, mobile applications, and web-based applications...
Java is a versatile language that runs on multiple platforms...
Output: Provides an overview of Java programming language.
3. Java - History
Java was developed by Sun Microsystems in 1995, and it is now owned by Oracle Corporation...
Java was initially called Oak and was designed for interactive television...
Output: Displays the history of Java programming language.
4. Java - Features
Java offers several features such as platform independence, automatic memory management, and support for multithreading...
- Platform Independence
- Object-Oriented
- Automatic Garbage Collection
- Security
Output: Lists the key features of Java.
5. Java Vs. C++
Java and C++ are both powerful programming languages, but they have key differences in syntax, memory management, and platform independence...
Java is platform-independent while C++ is not.
C++ requires manual memory management while Java has automatic garbage collection.
Output: Compares Java and C++ based on key features.
6. JVM - Java Virtual Machine
The Java Virtual Machine (JVM) is responsible for running Java programs...
JVM is a virtual machine that enables Java programs to run on different hardware architectures without modification.
Output: Describes the role of JVM in Java programming.
7. Java - JDK vs JRE vs JVM
JDK (Java Development Kit), JRE (Java Runtime Environment), and JVM (Java Virtual Machine) are key components for Java development...
JDK includes JRE and development tools, JRE provides libraries and JVM, and JVM runs Java bytecode.
Output: Compares JDK, JRE, and JVM based on their roles.
8. Java - Hello World Program
The simplest Java program is the "Hello, World!" program, which is often used to demonstrate the basic structure of Java code...
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } }
Output: Prints "Hello, World!" to the console.
9. Java - Environment Setup
Setting up the Java development environment involves installing JDK and configuring the system environment variables...
1. Download JDK from the official Java website.
2. Install JDK and set the JAVA_HOME environment variable.
3. Add JDK/bin directory to the system PATH.
Output: Provides setup instructions for Java development environment.
10. Java - Basic Syntax
Java syntax is based on C++, making it familiar to developers who have experience with C-like languages...
public class Example { public static void main(String[] args) { int number = 10; System.out.println("The number is: " + number); } }
Output: Prints "The number is: 10" to the console.
11. Java - Variable Types
Java supports various types of variables including primitive data types (such as int, float) and object references...
public class VariableTypes { public static void main(String[] args) { int age = 30; double salary = 55000.5; boolean isStudent = false; String name = "John"; System.out.println("Name: " + name + ", Age: " + age); } }
Output: Prints "Name: John, Age: 30" to the console.
12. Java - Data Types
In Java, data types define the type of data a variable can store. Java has two categories of data types: primitive and reference data types.
public class DataTypes { public static void main(String[] args) { int age = 25; double price = 19.99; char grade = 'A'; boolean isStudent = true; String name = "John Doe"; System.out.println("Age: " + age + ", Price: " + price + ", Grade: " + grade + ", Student: " + isStudent + ", Name: " + name); } }
Output: Age: 25, Price: 19.99, Grade: A, Student: true, Name: John Doe
13. Java - Type Casting
Type casting is the process of converting one data type into another. It can be done explicitly or implicitly in Java.
public class TypeCasting { public static void main(String[] args) { int num = 10; double result = num; // Implicit casting (widening) System.out.println("Double value: " + result); double decimal = 9.78; int wholeNumber = (int) decimal; // Explicit casting (narrowing) System.out.println("Integer value: " + wholeNumber); } }
Output: Double value: 10.0, Integer value: 9
14. Java - Unicode System
Java supports the Unicode system, which allows representation of text in any language. Java uses 16-bit Unicode characters.
public class Unicode { public static void main(String[] args) { char ch = '\u0041'; // Unicode for 'A' System.out.println("Unicode character: " + ch); } }
Output: Unicode character: A
15. Java - Basic Operators
Java supports several operators, including arithmetic, relational, logical, and assignment operators.
public class BasicOperators { public static void main(String[] args) { int a = 10, b = 5; System.out.println("Addition: " + (a + b)); System.out.println("Subtraction: " + (a - b)); System.out.println("Multiplication: " + (a * b)); System.out.println("Division: " + (a / b)); } }
Output: Addition: 15, Subtraction: 5, Multiplication: 50, Division: 2
16. Java Comments
In Java, comments are used to explain the code and make it more readable. There are three types of comments: single-line, multi-line, and documentation comments.
public class Comments { public static void main(String[] args) { // Single-line comment System.out.println("This is a single-line comment."); /* Multi-line comment that spans multiple lines */ System.out.println("This is a multi-line comment."); /** * Documentation comment * used for generating API documentation */ System.out.println("This is a documentation comment."); } }
Output: This is a single-line comment. This is a multi-line comment. This is a documentation comment.
17. Java - User Input
Java provides several ways to take input from the user, such as using the Scanner class.
import java.util.Scanner; public class UserInput { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter your name: "); String name = sc.nextLine(); System.out.println("Hello, " + name + "!"); } }
Output: Enter your name: (user enters "John"), Hello, John!
18. Java Date & Time
Java provides the `java.time` package for handling dates and times. This package includes classes like `LocalDate`, `LocalTime`, and `LocalDateTime`.
import java.time.LocalDate; import java.time.LocalTime; import java.time.LocalDateTime; public class DateTime { public static void main(String[] args) { LocalDate date = LocalDate.now(); LocalTime time = LocalTime.now(); LocalDateTime dateTime = LocalDateTime.now(); System.out.println("Current Date: " + date); System.out.println("Current Time: " + time); System.out.println("Current Date and Time: " + dateTime); } }
Output: Current Date: 2025-01-19, Current Time: 14:30:15.123, Current Date and Time: 2025-01-19T14:30:15.123
19. Java - Control Statements
Control statements in Java are used to control the flow of execution of the program. These include `if`, `else`, `switch`, `while`, `for`, etc.
public class ControlStatements { public static void main(String[] args) { int num = 10; if (num > 5) { System.out.println("Number is greater than 5"); } else { System.out.println("Number is less than or equal to 5"); } } }
Output: Number is greater than 5
20. Java - Loop Control
Loop control statements are used to alter the flow of a loop. These include `break`, `continue`, and `return`.
public class LoopControl { public static void main(String[] args) { for (int i = 0; i < 5; i++) { if (i == 3) { continue; // Skip when i equals 3 } System.out.println("i = " + i); } } }
Output: i = 0, i = 1, i = 2, i = 4
21. Java - Decision Making
Decision-making statements in Java allow you to execute certain parts of code based on conditions. This includes `if`, `else if`, and `switch`.
public class DecisionMaking { public static void main(String[] args) { int num = 20; if (num > 30) { System.out.println("Number is greater than 30"); } else if (num > 10) { System.out.println("Number is greater than 10 but less than or equal to 30"); } else { System.out.println("Number is less than or equal to 10"); } } }
Output: Number is greater than 10 but less than or equal to 30
22. Java - If-else
The `if-else` statement in Java is used to test a condition. If the condition is true, the code inside the `if` block executes; otherwise, the code inside the `else` block executes.
public class IfElse { public static void main(String[] args) { int num = 10; if (num > 5) { System.out.println("Number is greater than 5"); } else { System.out.println("Number is less than or equal to 5"); } } }
Output: Number is greater than 5
23. Java - Switch
The `switch` statement is used to execute one out of multiple possible code blocks based on the value of a variable or expression.
public class SwitchExample { public static void main(String[] args) { int day = 3; switch(day) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; default: System.out.println("Invalid day"); } } }
Output: Wednesday
24. Java - For Loops
The `for` loop in Java is used to repeat a block of code a fixed number of times.
public class ForLoop { public static void main(String[] args) { for (int i = 0; i < 5; i++) { System.out.println("i = " + i); } } }
Output: i = 0, i = 1, i = 2, i = 3, i = 4
25. Java - For-Each Loops
The `for-each` loop in Java is used to iterate over elements in arrays or collections.
public class ForEachLoop { public static void main(String[] args) { int[] numbers = {1, 2, 3, 4, 5}; for (int num : numbers) { System.out.println(num); } } }
Output: 1, 2, 3, 4, 5
26. Java - While Loops
The `while` loop in Java repeats a block of code as long as the specified condition is true.
public class WhileLoop { public static void main(String[] args) { int i = 0; while (i < 5) { System.out.println("i = " + i); i++; } } }
Output: i = 0, i = 1, i = 2, i = 3, i = 4
27. Java - do-while Loops
The `do-while` loop in Java guarantees that the code will be executed at least once, even if the condition is false initially.
public class DoWhileLoop { public static void main(String[] args) { int i = 0; do { System.out.println("i = " + i); i++; } while (i < 5); } }
Output: i = 0, i = 1, i = 2, i = 3, i = 4
28. Java Break
The `break` statement in Java is used to exit from a loop or switch statement prematurely.
public class BreakExample { public static void main(String[] args) { for (int i = 0; i < 5; i++) { if (i == 3) { break; } System.out.println("i = " + i); } } }
Output: i = 0, i = 1, i = 2
29. Java - Continue
The `continue` statement in Java is used to skip the current iteration of a loop and continue with the next iteration.
public class ContinueExample { public static void main(String[] args) { for (int i = 0; i < 5; i++) { if (i == 2) { continue; } System.out.println("i = " + i); } } }
Output: i = 0, i = 1, i = 3, i = 4
30. Object Oriented Programming
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of objects, which can contain data and methods to operate on that data.
class Person { String name; int age; Person(String name, int age) { this.name = name; this.age = age; } void displayInfo() { System.out.println("Name: " + name + ", Age: " + age); } } public class OOPExample { public static void main(String[] args) { Person person1 = new Person("John", 30); person1.displayInfo(); } }
Output: Name: John, Age: 30
31. Java OOPS Concepts
Java supports Object-Oriented Programming (OOP) principles like inheritance, polymorphism, encapsulation, and abstraction.
class Animal { void sound() { System.out.println("Animal makes sound"); } } class Dog extends Animal { void sound() { System.out.println("Dog barks"); } } public class OOPSConcepts { public static void main(String[] args) { Animal animal = new Animal(); animal.sound(); Dog dog = new Dog(); dog.sound(); } }
Output: Animal makes sound, Dog barks
32. Java - Object & Classes
In Java, a class is a blueprint for objects. An object is an instance of a class. Objects can have attributes (fields) and methods (functions).
class Car { String model; int year; // Method to display information void displayInfo() { System.out.println("Model: " + model + ", Year: " + year); } } public class ObjectClassExample { public static void main(String[] args) { Car car1 = new Car(); car1.model = "Tesla"; car1.year = 2022; car1.displayInfo(); } }
Output: Model: Tesla, Year: 2022
33. Java - Class Attributes
Class attributes (fields) are variables defined within a class. They define the state of an object.
class Car { String model; // Attribute int year; // Attribute } public class ClassAttributes { public static void main(String[] args) { Car car1 = new Car(); car1.model = "BMW"; car1.year = 2021; System.out.println("Model: " + car1.model + ", Year: " + car1.year); } }
Output: Model: BMW, Year: 2021
34. Java - Class Methods
Class methods define the behavior of the objects of a class. They are functions inside the class.
class Car { String model; int year; // Method to display car details void displayInfo() { System.out.println("Model: " + model + ", Year: " + year); } } public class ClassMethods { public static void main(String[] args) { Car car1 = new Car(); car1.model = "Audi"; car1.year = 2020; car1.displayInfo(); } }
Output: Model: Audi, Year: 2020
35. Java - Methods
Methods are blocks of code that perform a specific task. They can accept parameters and return values.
class Calculator { // Method to add two numbers int add(int a, int b) { return a + b; } } public class MethodsExample { public static void main(String[] args) { Calculator calc = new Calculator(); int result = calc.add(5, 3); System.out.println("Sum: " + result); } }
Output: Sum: 8
36. Java - Variables Scope
Scope of a variable refers to the region in which the variable can be accessed. Local variables are accessible only within methods, while instance variables are accessible throughout the class.
class ScopeExample { int instanceVar = 10; // Instance variable void display() { int localVar = 5; // Local variable System.out.println("Instance Variable: " + instanceVar); System.out.println("Local Variable: " + localVar); } } public class VariablesScope { public static void main(String[] args) { ScopeExample obj = new ScopeExample(); obj.display(); } }
Output: Instance Variable: 10, Local Variable: 5
37. Java - Constructors
Constructors in Java are special methods that are used to initialize objects. They have the same name as the class and are called automatically when an object is created.
class Car { String model; int year; // Constructor to initialize object Car(String model, int year) { this.model = model; this.year = year; } void displayInfo() { System.out.println("Model: " + model + ", Year: " + year); } } public class ConstructorsExample { public static void main(String[] args) { Car car1 = new Car("Mercedes", 2022); car1.displayInfo(); } }
Output: Model: Mercedes, Year: 2022
38. Java - Access Modifiers
Access modifiers in Java determine the visibility of classes, methods, and variables. There are four types of access modifiers: `public`, `private`, `protected`, and default (no modifier).
class Person { public String name; // Public access private int age; // Private access void displayInfo() { System.out.println("Name: " + name); System.out.println("Age: " + age); } } public class AccessModifiersExample { public static void main(String[] args) { Person person = new Person(); person.name = "John"; // person.age = 30; // Error: age is private person.displayInfo(); } }
Output: Name: John, Age: 0
39. Java - Inheritance
Inheritance is an OOP concept where a class inherits fields and methods from another class.
class Animal { void sound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { void sound() { System.out.println("Dog barks"); } } public class InheritanceExample { public static void main(String[] args) { Dog dog = new Dog(); dog.sound(); // Calls the overridden method } }
Output: Dog barks
40. Java - Aggregation
Aggregation is a special type of association where one class is a part of another class. The associated object can exist independently.
class Engine { void start() { System.out.println("Engine started"); } } class Car { Engine engine; // Aggregation: Car has an Engine Car(Engine engine) { this.engine = engine; } void startCar() { engine.start(); System.out.println("Car is moving"); } } public class AggregationExample { public static void main(String[] args) { Engine engine = new Engine(); Car car = new Car(engine); car.startCar(); } }
Output: Engine started, Car is moving
41. Java - Polymorphism
Polymorphism allows objects of different classes to be treated as objects of a common superclass. The method to be invoked is determined at runtime.
class Animal { void sound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { void sound() { System.out.println("Dog barks"); } } public class PolymorphismExample { public static void main(String[] args) { Animal animal = new Dog(); // Polymorphism animal.sound(); // Calls the Dog's sound method } }
Output: Dog barks
42. Java - Overriding
Method overriding allows a subclass to provide a specific implementation of a method already provided by its superclass.
class Animal { void sound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { @Override void sound() { System.out.println("Dog barks"); } } public class OverridingExample { public static void main(String[] args) { Animal dog = new Dog(); dog.sound(); // Calls the overridden method in Dog } }
Output: Dog barks
43. Java - Method Overloading
Method Overloading in Java allows a class to have more than one method having the same name, if their parameter lists are different.
class Calculator { // Overloaded add method with two parameters int add(int a, int b) { return a + b; } // Overloaded add method with three parameters int add(int a, int b, int c) { return a + b + c; } } public class MethodOverloadingExample { public static void main(String[] args) { Calculator calc = new Calculator(); System.out.println("Sum of 5 and 3: " + calc.add(5, 3)); System.out.println("Sum of 1, 2, and 3: " + calc.add(1, 2, 3)); } }
Output: Sum of 5 and 3: 8, Sum of 1, 2, and 3: 6
44. Java - Dynamic Binding
Dynamic binding in Java is the process of linking a method call to the method's body at runtime. It occurs when an overridden method is called using a reference variable of a superclass.
class Animal { void sound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { void sound() { System.out.println("Dog barks"); } } public class DynamicBindingExample { public static void main(String[] args) { Animal animal = new Dog(); // Dynamic binding animal.sound(); // Calls Dog's sound method } }
Output: Dog barks
45. Java - Static Binding
Static binding occurs when the method call is resolved at compile-time. It occurs for methods that are private, final, or static.
class Animal { static void sound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { static void sound() { System.out.println("Dog barks"); } } public class StaticBindingExample { public static void main(String[] args) { Animal animal = new Dog(); // Static binding animal.sound(); // Calls Animal's sound method due to static binding } }
Output: Animal makes a sound
46. Java Instance Initializer Block
An instance initializer block is used to initialize an object before calling the constructor. It is executed every time an object is created.
class Person { String name; // Instance Initializer Block { name = "John"; } Person() { System.out.println("Constructor called"); } void displayInfo() { System.out.println("Name: " + name); } } public class InstanceInitializerExample { public static void main(String[] args) { Person person = new Person(); person.displayInfo(); } }
Output: Constructor called, Name: John
47. Java - Abstraction
Abstraction in Java is the concept of hiding implementation details and exposing only the essential features of an object. It can be achieved using abstract classes and interfaces.
abstract class Animal { abstract void sound(); // Abstract method } class Dog extends Animal { void sound() { System.out.println("Dog barks"); } } public class AbstractionExample { public static void main(String[] args) { Animal animal = new Dog(); animal.sound(); } }
Output: Dog barks
48. Java - Encapsulation
Encapsulation is the process of wrapping data (variables) and code (methods) together as a single unit. It is achieved by using access modifiers like private, protected, etc., and providing getter and setter methods.
class Person { private String name; // Getter method public String getName() { return name; } // Setter method public void setName(String name) { this.name = name; } } public class EncapsulationExample { public static void main(String[] args) { Person person = new Person(); person.setName("John"); System.out.println("Name: " + person.getName()); } }
Output: Name: John
49. Java - Interfaces
Interfaces in Java are abstract types used to specify a set of methods that a class must implement. A class can implement multiple interfaces.
interface Animal { void sound(); // Abstract method } class Dog implements Animal { public void sound() { System.out.println("Dog barks"); } } public class InterfacesExample { public static void main(String[] args) { Animal animal = new Dog(); animal.sound(); } }
Output: Dog barks
50. Java - Packages
Packages are used to group related classes and interfaces in Java. They help in organizing the project structure.
package com.example; class Person { void displayInfo() { System.out.println("Person information"); } } public class PackagesExample { public static void main(String[] args) { com.example.Person person = new com.example.Person(); person.displayInfo(); } }
Output: Person information
51. Java Inner Classes
Inner classes are classes defined within another class. They can access the members of the outer class.
class OuterClass { private String message = "Hello from Outer Class"; class InnerClass { void display() { System.out.println(message); } } } public class InnerClassesExample { public static void main(String[] args) { OuterClass outer = new OuterClass(); OuterClass.InnerClass inner = outer.new InnerClass(); inner.display(); } }
Output: Hello from Outer Class
52. Java - Static Class
A static class in Java is a nested class that is declared with the static keyword. It can access only the static members of the outer class.
class OuterClass { static String message = "Hello from Outer Class"; static class StaticInnerClass { void display() { System.out.println(message); // Accessing static member of outer class } } } public class StaticClassExample { public static void main(String[] args) { OuterClass.StaticInnerClass inner = new OuterClass.StaticInnerClass(); inner.display(); } }
Output: Hello from Outer Class
53. Java - Anonymous Class
An anonymous class in Java is a class without a name that is used to instantiate a class or interface at the time of its declaration.
interface Animal { void sound(); } public class AnonymousClassExample { public static void main(String[] args) { // Anonymous class implementing Animal interface Animal animal = new Animal() { public void sound() { System.out.println("Dog barks"); } }; animal.sound(); } }
Output: Dog barks
54. Java - Singleton Class
A Singleton class in Java ensures that only one instance of the class is created and provides a global access point to that instance.
class Singleton { private static Singleton instance; private Singleton() { } public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } } public class SingletonExample { public static void main(String[] args) { Singleton singleton = Singleton.getInstance(); System.out.println("Singleton instance created: " + singleton); } }
Output: Singleton instance created: Singleton@15db9742
55. Java - Wrapper Classes
Wrapper classes in Java provide a way to use primitive data types as objects. Java provides wrapper classes for each primitive type like Integer, Double, etc.
public class WrapperClassesExample { public static void main(String[] args) { int num = 10; Integer wrappedNum = Integer.valueOf(num); // Wrapper class System.out.println("Wrapped Number: " + wrappedNum); } }
Output: Wrapped Number: 10
56. Java Enums
Enums in Java are special classes that represent a group of constants (unchangeable variables).
enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY } public class EnumExample { public static void main(String[] args) { Day today = Day.MONDAY; System.out.println("Today is: " + today); } }
Output: Today is: MONDAY
57. Java - Enum Constructor
Enum constructors allow you to associate additional data with each constant in the enum. The constructor is called when the enum is initialized.
enum Day { MONDAY("Start of the week"), TUESDAY("Second day"), WEDNESDAY("Middle of the week"); private String description; Day(String description) { this.description = description; } public String getDescription() { return description; } } public class EnumConstructorExample { public static void main(String[] args) { System.out.println(Day.MONDAY.getDescription()); } }
Output: Start of the week
58. Java - Enum Strings
Enums can be used to convert strings into enum constants and vice versa using methods like valueOf and toString.
enum Day { MONDAY, TUESDAY, WEDNESDAY } public class EnumStringsExample { public static void main(String[] args) { String dayString = "MONDAY"; Day day = Day.valueOf(dayString); // Convert string to enum System.out.println("Enum value: " + day); } }
Output: Enum value: MONDAY
59. Java Built-in Classes
Java provides several built-in classes that are part of the Java standard library, such as String, Math, and System.
public class BuiltInClassesExample { public static void main(String[] args) { int result = Math.max(10, 20); // Using Math class System.out.println("Max value: " + result); } }
Output: Max value: 20
60. Java Number
The Number class in Java is the superclass of classes like Integer, Double, and others that represent numerical values.
public class NumberExample { public static void main(String[] args) { Integer num = 10; System.out.println("Integer value: " + num); } }
Output: Integer value: 10
61. Java Boolean
The Boolean class in Java wraps the primitive type boolean into an object.
public class BooleanExample { public static void main(String[] args) { Boolean isJavaFun = true; System.out.println("Is Java fun? " + isJavaFun); } }
Output: Is Java fun? true
62. Java Characters
The Character class in Java wraps a char type into an object and provides various methods for working with characters.
public class CharacterExample { public static void main(String[] args) { char letter = 'A'; System.out.println("Character: " + letter); System.out.println("Is letter a digit? " + Character.isDigit(letter)); } }
Output: Character: A, Is letter a digit? false
63. Java - Arrays
Arrays in Java are used to store multiple values in a single variable, instead of declaring separate variables for each value.
public class ArraysExample { public static void main(String[] args) { int[] numbers = {1, 2, 3, 4, 5}; for (int i = 0; i < numbers.length; i++) { System.out.println(numbers[i]); } } }
Output: 1 2 3 4 5
64. Java - Math Class
The Math class in Java provides methods for performing basic numeric operations such as exponential, logarithm, square root, etc.
public class MathClassExample { public static void main(String[] args) { double result = Math.sqrt(25); // Square root of 25 System.out.println("Square root: " + result); } }
Output: Square root: 5.0
65. Java File Handling
File Handling in Java allows us to create, read, write, and delete files. It uses the classes from the java.io package.
import java.io.*; public class FileHandlingExample { public static void main(String[] args) { File file = new File("example.txt"); if (file.exists()) { System.out.println("File exists."); } else { System.out.println("File does not exist."); } } }
Output: File does not exist.
66. Java - Files
The java.io.File class represents a file or directory path in the filesystem.
import java.io.File; public class FileExample { public static void main(String[] args) { File file = new File("testfile.txt"); System.out.println("File exists: " + file.exists()); } }
Output: File exists: false
67. Java Create a File
This code shows how to create a new file in Java using the File class and its createNewFile() method.
import java.io.File; import java.io.IOException; public class CreateFileExample { public static void main(String[] args) { File file = new File("newfile.txt"); try { if (file.createNewFile()) { System.out.println("File created: " + file.getName()); } else { System.out.println("File already exists."); } } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); } } }
Output: File created: newfile.txt
68. Java - Write to File
In Java, you can write to a file using FileWriter or BufferedWriter class.
import java.io.File; import java.io.FileWriter; import java.io.IOException; public class WriteToFileExample { public static void main(String[] args) { try { FileWriter writer = new FileWriter("writefile.txt"); writer.write("Hello, Java File Handling!"); writer.close(); System.out.println("Successfully wrote to the file."); } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); } } }
Output: Successfully wrote to the file.
69. Java - Read Files
You can read a file in Java using FileReader or BufferedReader class.
import java.io.File; import java.io.FileReader; import java.io.BufferedReader; import java.io.IOException; public class ReadFileExample { public static void main(String[] args) { try { FileReader reader = new FileReader("writefile.txt"); BufferedReader bufferedReader = new BufferedReader(reader); String line; while ((line = bufferedReader.readLine()) != null) { System.out.println(line); } bufferedReader.close(); } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); } } }
Output: Hello, Java File Handling!
70. Java - Delete Files
To delete a file in Java, you can use the delete() method of the File class.
import java.io.File; public class DeleteFileExample { public static void main(String[] args) { File file = new File("writefile.txt"); if (file.delete()) { System.out.println("Deleted the file: " + file.getName()); } else { System.out.println("Failed to delete the file."); } } }
Output: Deleted the file: writefile.txt
71. Java - Directories
You can create, list, and check directories using the File class in Java.
import java.io.File; public class DirectoryExample { public static void main(String[] args) { File directory = new File("newDirectory"); if (!directory.exists()) { directory.mkdir(); System.out.println("Directory created: " + directory.getName()); } File[] files = directory.listFiles(); if (files != null) { System.out.println("Files in directory:"); for (File file : files) { System.out.println(file.getName()); } } } }
Output: Directory created: newDirectory
72. Java - I/O Streams
In Java, I/O Streams are used to read from and write to files, memory, or other resources. Java provides byte and character streams.
import java.io.*; public class IOStreamExample { public static void main(String[] args) { try (FileInputStream fis = new FileInputStream("input.txt"); FileOutputStream fos = new FileOutputStream("output.txt")) { int byteRead; while ((byteRead = fis.read()) != -1) { fos.write(byteRead); } System.out.println("File copy successful!"); } catch (IOException e) { e.printStackTrace(); } } }
Output: File copy successful!
73. Java Error & Exceptions
In Java, errors are abnormal conditions that are typically outside of a program’s control (e.g., JVM errors). Exceptions are issues that occur during program execution and can be caught and handled.
74. Java - Exceptions
Exceptions are events that disrupt the normal flow of the program. Java provides mechanisms to handle exceptions and prevent crashes.
public class ExceptionExample { public static void main(String[] args) { try { int result = 10 / 0; // This will cause an ArithmeticException } catch (ArithmeticException e) { System.out.println("Error: Division by zero!"); } } }
Output: Error: Division by zero!
75. Java - try-catch Block
The try-catch block is used to handle exceptions in Java. Code that might throw an exception is placed in the try block, while the catch block handles the exception.
public class TryCatchExample { public static void main(String[] args) { try { String str = null; System.out.println(str.length()); } catch (NullPointerException e) { System.out.println("Caught a null pointer exception!"); } } }
Output: Caught a null pointer exception!
76. Java - try-with-resources
The try-with-resources statement ensures that each resource is closed at the end of the statement. It works with classes that implement the AutoCloseable interface.
import java.io.*; public class TryWithResourcesExample { public static void main(String[] args) { try (FileReader fr = new FileReader("file.txt"); BufferedReader br = new BufferedReader(fr)) { String line; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } } }
Output: Contents of the file will be printed.
77. Java - Multi-catch Block
Java allows multiple exceptions to be caught in a single catch block using the multi-catch syntax introduced in Java 7.
public class MultiCatchExample { public static void main(String[] args) { try { String str = null; System.out.println(str.length()); int result = 10 / 0; } catch (NullPointerException | ArithmeticException e) { System.out.println("Caught exception: " + e); } } }
Output: Caught exception: java.lang.NullPointerException
78. Java - Nested try Block
In Java, we can nest try-catch blocks, meaning that a try block can contain another try-catch block.
public class NestedTryExample { public static void main(String[] args) { try { try { int[] arr = new int[5]; arr[10] = 30; // This will throw ArrayIndexOutOfBoundsException } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Inner catch: Array index out of bounds"); } } catch (Exception e) { System.out.println("Outer catch: Exception caught"); } } }
Output: Inner catch: Array index out of bounds
79. Java - Finally Block
The finally block is always executed after a try-catch block, regardless of whether an exception was thrown or not.
public class FinallyExample { public static void main(String[] args) { try { int result = 10 / 2; System.out.println("Result: " + result); } catch (ArithmeticException e) { System.out.println("Error: Division by zero!"); } finally { System.out.println("Finally block executed"); } } }
Output: Result: 5 Finally block executed
80. Java - throw Exception
The throw statement is used to explicitly throw an exception in Java.
public class ThrowExceptionExample { public static void main(String[] args) { try { throw new Exception("This is a custom exception!"); } catch (Exception e) { System.out.println(e.getMessage()); } } }
Output: This is a custom exception!
81. Java - Exception Propagation
Exception propagation refers to the process of passing an exception from one method to another. If a method doesn't handle an exception, it is passed to the method that called it.
public class ExceptionPropagationExample { public static void main(String[] args) { try { methodA(); } catch (Exception e) { System.out.println("Exception caught in main: " + e.getMessage()); } } public static void methodA() throws Exception { methodB(); } public static void methodB() throws Exception { throw new Exception("Exception thrown from methodB"); } }
Output: Exception caught in main: Exception thrown from methodB
82. Java - Built-in Exceptions
Java provides several built-in exceptions like `NullPointerException`, `ArithmeticException`, `ArrayIndexOutOfBoundsException`, and more for handling common error scenarios.
public class BuiltInExceptionExample { public static void main(String[] args) { try { int[] arr = new int[2]; arr[3] = 10; // This will cause ArrayIndexOutOfBoundsException } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Error: Array index out of bounds"); } } }
Output: Error: Array index out of bounds
83. Java - Custom Exception
Custom exceptions in Java allow you to define your own exception classes by extending the `Exception` class.
class InvalidAgeException extends Exception { public InvalidAgeException(String message) { super(message); } } public class CustomExceptionExample { public static void main(String[] args) { try { int age = -1; if (age < 0) { throw new InvalidAgeException("Age cannot be negative!"); } } catch (InvalidAgeException e) { System.out.println(e.getMessage()); } } }
Output: Age cannot be negative!
84. Java - Multithreading
Multithreading in Java allows a program to execute multiple threads concurrently. This is useful for performing multiple tasks simultaneously.
85. Java - Thread Life Cycle
The life cycle of a thread includes states like New, Runnable, Blocked, Waiting, Timed Waiting, and Terminated.
public class ThreadLifeCycleExample extends Thread { public void run() { System.out.println("Thread is running"); } public static void main(String[] args) { ThreadLifeCycleExample thread = new ThreadLifeCycleExample(); System.out.println("Thread state: " + thread.getState()); thread.start(); System.out.println("Thread state after start: " + thread.getState()); } }
Output: Thread state: NEW, Thread state after start: RUNNABLE
86. Java - Creating a Thread
In Java, you can create a thread by extending the `Thread` class or implementing the `Runnable` interface.
class MyThread extends Thread { public void run() { System.out.println("Thread is running..."); } public static void main(String[] args) { MyThread thread = new MyThread(); thread.start(); // Starting the thread } }
Output: Thread is running...
87. Java - Starting a Thread
The `start()` method is used to begin the execution of a thread. It calls the `run()` method internally.
public class StartingThreadExample { public static void main(String[] args) { Thread thread = new Thread(() -> { System.out.println("Thread is started"); }); thread.start(); // Starting the thread } }
Output: Thread is started
88. Java - Joining Threads
The `join()` method is used to pause the execution of the main thread until the thread it is called on finishes.
public class JoiningThreadsExample { public static void main(String[] args) { Thread thread = new Thread(() -> { System.out.println("Thread is running..."); }); thread.start(); try { thread.join(); // Main thread waits for the thread to finish } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Main thread is done"); } }
Output: Thread is running... Main thread is done
89. Java - Naming Thread
You can set a name for a thread using the `setName()` method, and retrieve it using the `getName()` method.
public class NamingThreadExample { public static void main(String[] args) { Thread thread = new Thread(() -> { System.out.println("Thread is running..."); }); thread.setName("MyCustomThread"); System.out.println("Thread name: " + thread.getName()); thread.start(); } }
Output: Thread name: MyCustomThread Thread is running...
90. Java - Thread Scheduler
Thread scheduling is the process of determining which thread will run at any given time. The Java thread scheduler is responsible for managing the threads' execution.
91. Java Thread Pools
Thread pools manage a pool of worker threads and execute tasks in an efficient way. Java provides the `ExecutorService` interface to manage thread pools.
import java.util.concurrent.*; public class ThreadPoolExample { public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(3); executor.submit(() -> { System.out.println("Task 1 is running"); }); executor.submit(() -> { System.out.println("Task 2 is running"); }); executor.submit(() -> { System.out.println("Task 3 is running"); }); executor.shutdown(); } }
Output: Task 1 is running Task 2 is running Task 3 is running
92. Java Main Thread
The main thread is the entry point of any Java program. It is created by the Java Virtual Machine (JVM) when the program is started.
public class MainThreadExample { public static void main(String[] args) { Thread mainThread = Thread.currentThread(); System.out.println("Main thread name: " + mainThread.getName()); } }
Output: Main thread name: main
93. Java - Thread Priority
Thread priority determines the order in which threads are scheduled for execution. The priority can be set using the `setPriority()` method.
public class ThreadPriorityExample extends Thread { public void run() { System.out.println(Thread.currentThread().getName() + " is running with priority " + Thread.currentThread().getPriority()); } public static void main(String[] args) { Thread thread1 = new ThreadPriorityExample(); Thread thread2 = new ThreadPriorityExample(); thread1.setPriority(Thread.MIN_PRIORITY); thread2.setPriority(Thread.MAX_PRIORITY); thread1.start(); thread2.start(); } }
Output: main is running with priority 5
94. Java - Daemon Threads
Daemon threads are background threads that run in the JVM and are terminated when the main program finishes. They can be created using `setDaemon(true)`.
public class DaemonThreadExample { public static void main(String[] args) { Thread daemonThread = new Thread(() -> { while (true) { System.out.println("Daemon thread is running..."); } }); daemonThread.setDaemon(true); daemonThread.start(); try { Thread.sleep(500); // Main thread sleeps for a while before exiting } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Main thread is done"); } }
Output: Daemon thread is running... Main thread is done
95. Java - Thread Group
Thread groups allow us to group multiple threads and manage them collectively. They are created using `ThreadGroup` class.
public class ThreadGroupExample { public static void main(String[] args) { ThreadGroup group = new ThreadGroup("Group1"); Thread thread1 = new Thread(group, () -> System.out.println("Thread 1 is running")); Thread thread2 = new Thread(group, () -> System.out.println("Thread 2 is running")); thread1.start(); thread2.start(); System.out.println("Active thread count in group: " + group.activeCount()); } }
Output: Active thread count in group: 2
96. Java - Shutdown Hook
A shutdown hook is a special thread that runs when the JVM is shutting down. It can be registered using `Runtime.addShutdownHook()`.
public class ShutdownHookExample { public static void main(String[] args) { Runtime.getRuntime().addShutdownHook(new Thread(() -> { System.out.println("Shutdown hook is running..."); })); System.out.println("Main program is running..."); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } }
Output: Main program is running... Shutdown hook is running...
97. Java Synchronization
Synchronization ensures that only one thread can access a resource at a time. This prevents thread interference and consistency issues.
98. Java - Block Synchronization
Block synchronization locks a specific block of code instead of the entire method, improving performance and reducing contention.
public class BlockSynchronizationExample { private static int counter = 0; public static void main(String[] args) { Runnable task = () -> { synchronized (BlockSynchronizationExample.class) { counter++; System.out.println("Counter: " + counter); } }; Thread thread1 = new Thread(task); Thread thread2 = new Thread(task); thread1.start(); thread2.start(); } }
Output: Counter: 1 Counter: 2
99. Java - Static Synchronization
Static synchronization ensures that only one thread can access static methods at a time.
public class StaticSynchronizationExample { private static int counter = 0; public synchronized static void increment() { counter++; } public static void main(String[] args) { Runnable task = () -> { increment(); System.out.println("Counter: " + counter); }; Thread thread1 = new Thread(task); Thread thread2 = new Thread(task); thread1.start(); thread2.start(); } }
Output: Counter: 1 Counter: 2
100. Java Inter-thread Communication
Inter-thread communication is the mechanism that allows threads to communicate with each other using methods like `wait()`, `notify()`, and `notifyAll()`.
public class InterThreadCommunicationExample { private static final Object lock = new Object(); public static void main(String[] args) throws InterruptedException { Thread thread1 = new Thread(() -> { synchronized (lock) { try { System.out.println("Thread 1 is waiting..."); lock.wait(); System.out.println("Thread 1 resumed"); } catch (InterruptedException e) { e.printStackTrace(); } } }); Thread thread2 = new Thread(() -> { synchronized (lock) { System.out.println("Thread 2 is notifying..."); lock.notify(); } }); thread1.start(); Thread.sleep(500); // Ensure thread1 starts waiting before thread2 notifies thread2.start(); } }
Output: Thread 1 is waiting... Thread 2 is notifying... Thread 1 resumed
101. Java Thread Deadlock
A deadlock occurs when two threads are waiting for each other to release resources, causing both threads to be stuck.
public class ThreadDeadlockExample { private static final Object lock1 = new Object(); private static final Object lock2 = new Object(); public static void main(String[] args) { Thread thread1 = new Thread(() -> { synchronized (lock1) { System.out.println("Thread 1 holding lock1..."); try { Thread.sleep(100); } catch (InterruptedException e) {} synchronized (lock2) { System.out.println("Thread 1 holding lock1 and lock2..."); } } }); Thread thread2 = new Thread(() -> { synchronized (lock2) { System.out.println("Thread 2 holding lock2..."); try { Thread.sleep(100); } catch (InterruptedException e) {} synchronized (lock1) { System.out.println("Thread 2 holding lock2 and lock1..."); } } }); thread1.start(); thread2.start(); } }
Output: Thread 1 holding lock1... Thread 2 holding lock2...
102. Java - Interrupting a Thread
Interrupting a thread can be done using the `interrupt()` method, which will cause the thread to stop executing when it checks for the interrupt flag.
public class InterruptingThreadExample { public static void main(String[] args) { Thread thread = new Thread(() -> { try { for (int i = 0; i < 5; i++) { if (Thread.currentThread().isInterrupted()) { System.out.println("Thread was interrupted."); break; } System.out.println("Thread is running..."); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Thread was interrupted while sleeping."); } }); thread.start(); // Interrupting the thread try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } thread.interrupt(); } }
Output: Thread is running... Thread is running... Thread was interrupted while sleeping.
103. Java - Thread Control
Thread control allows you to pause, resume, or stop threads using methods like `sleep()`, `yield()`, and `interrupt()`.
public class ThreadControlExample { public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(() -> { for (int i = 0; i < 5; i++) { System.out.println("Running thread: " + i); try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println("Thread interrupted."); } } }); thread.start(); // Pause for 3 seconds before interrupting the thread Thread.sleep(3000); thread.interrupt(); // Interrupting the thread } }
Output: Running thread: 0 Running thread: 1 Running thread: 2 Thread interrupted.
104. Java - Reentrant Monitor
A reentrant monitor allows the same thread to acquire the lock multiple times. This can be achieved using synchronized blocks.
public class ReentrantMonitorExample { private synchronized void method1() { System.out.println("Method 1 is running..."); method2(); } private synchronized void method2() { System.out.println("Method 2 is running..."); } public static void main(String[] args) { ReentrantMonitorExample example = new ReentrantMonitorExample(); example.method1(); } }
Output: Method 1 is running... Method 2 is running...
105. Java Networking
Java Networking allows you to connect and communicate between two devices over the internet using `Socket` and `ServerSocket` classes.
106. Java - Socket Programming
Socket programming in Java allows you to create client-server applications using `Socket` and `ServerSocket` classes for communication.
import java.io.*; import java.net.*; public class SocketProgrammingExample { public static void main(String[] args) throws IOException { // Server side ServerSocket server = new ServerSocket(1234); System.out.println("Server is waiting for a connection..."); Socket socket = server.accept(); System.out.println("Client connected."); // Client side PrintWriter out = new PrintWriter(socket.getOutputStream(), true); out.println("Hello, Client!"); // Close connection socket.close(); server.close(); } }
Output: Server is waiting for a connection... Client connected.
107. Java - URL Processing
URL Processing in Java involves parsing and handling URLs with classes like `URL` and `URLConnection` to access and manage network resources.
108. Java URL Class
The `URL` class in Java is used to represent a Uniform Resource Locator, which is a reference to a web resource.
import java.net.*; public class URLClassExample { public static void main(String[] args) throws MalformedURLException { URL url = new URL("https://www.example.com"); System.out.println("Protocol: " + url.getProtocol()); System.out.println("Host: " + url.getHost()); System.out.println("Port: " + url.getPort()); System.out.println("File: " + url.getFile()); } }
Output: Protocol: https Host: www.example.com Port: -1 File:
109. Java URLConnection Class
The `URLConnection` class is used to handle communication with the resource pointed to by a URL.
import java.net.*; import java.io.*; public class URLConnectionClassExample { public static void main(String[] args) throws IOException { URL url = new URL("https://www.example.com"); URLConnection connection = url.openConnection(); InputStream inputStream = connection.getInputStream(); int data; while ((data = inputStream.read()) != -1) { System.out.print((char) data); } inputStream.close(); } }
Output: HTML content of the webpage will be printed here.
110. Java - HttpURLConnection Class
The `HttpURLConnection` class provides a way to send HTTP requests and handle HTTP responses.
import java.net.*; import java.io.*; public class HttpURLConnectionClassExample { public static void main(String[] args) throws IOException { URL url = new URL("https://www.example.com"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); } in.close(); } }
Output: HTTP response content will be printed here.
111. Java Socket Class
The `Socket` class represents a client-side socket, used for establishing a connection to a server for data exchange.
import java.net.*; import java.io.*; public class SocketClassExample { public static void main(String[] args) throws IOException { Socket socket = new Socket("localhost", 1234); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); out.println("Hello, Server!"); socket.close(); } }
Output: Client sends data to the server, which then responds.
112. Java Generics
Generics in Java allow you to create classes, interfaces, and methods with type parameters, making your code more flexible and reusable.
public class GenericsExample { public staticvoid printArray(T[] array) { for (T element : array) { System.out.println(element); } } public static void main(String[] args) { Integer[] intArray = {1, 2, 3, 4}; String[] strArray = {"A", "B", "C"}; printArray(intArray); printArray(strArray); } }
Output: 1 2 3 4 A B C
113. Java Collections
Java Collections framework provides a set of interfaces and classes that implement the collection of objects. It is a part of Java's standard library.
114. Java Collection Interface
The `Collection` interface is the root of the Java collections framework. It defines basic operations like add, remove, and clear.
import java.util.*; public class CollectionInterfaceExample { public static void main(String[] args) { Collectioncollection = new ArrayList<>(); collection.add("Java"); collection.add("Python"); collection.add("C++"); System.out.println("Collection: " + collection); } }
Output: Collection: [Java, Python, C++]
115. Java - List Interface
The `List` interface is a part of the Java Collections framework. It represents an ordered collection of elements, allowing duplicates and null elements.
import java.util.*; public class ListInterfaceExample { public static void main(String[] args) { Listlist = new ArrayList<>(); list.add("Java"); list.add("Python"); list.add("C++"); System.out.println("List: " + list); } }
Output: List: [Java, Python, C++]
116. Java - Queue Interface
The `Queue` interface is designed for holding elements before processing them. It follows the First-In-First-Out (FIFO) principle.
import java.util.*; public class QueueInterfaceExample { public static void main(String[] args) { Queuequeue = new LinkedList<>(); queue.add("Java"); queue.add("Python"); queue.add("C++"); System.out.println("Queue: " + queue); queue.remove(); System.out.println("Queue after remove: " + queue); } }
Output: Queue: [Java, Python, C++] Queue after remove: [Python, C++]
117. Java Map Interface
The `Map` interface represents a collection of key-value pairs, where each key is unique and maps to a single value.
import java.util.*; public class MapInterfaceExample { public static void main(String[] args) { Mapmap = new HashMap<>(); map.put(1, "Java"); map.put(2, "Python"); map.put(3, "C++"); System.out.println("Map: " + map); } }
Output: Map: {1=Java, 2=Python, 3=C++}
118. Java - SortedMap Interface
The `SortedMap` interface extends `Map` and ensures that the keys are sorted in natural order or by a specified comparator.
import java.util.*; public class SortedMapInterfaceExample { public static void main(String[] args) { SortedMapsortedMap = new TreeMap<>(); sortedMap.put(3, "Java"); sortedMap.put(1, "Python"); sortedMap.put(2, "C++"); System.out.println("Sorted Map: " + sortedMap); } }
Output: Sorted Map: {1=Python, 2=C++, 3=Java}
119. Java - Set Interface
The `Set` interface represents a collection of unique elements, with no duplicates allowed.
import java.util.*; public class SetInterfaceExample { public static void main(String[] args) { Setset = new HashSet<>(); set.add("Java"); set.add("Python"); set.add("C++"); set.add("Java"); // Duplicate element System.out.println("Set: " + set); } }
Output: Set: [Java, Python, C++]
120. Java SortedSet Interface
The `SortedSet` interface extends `Set` and ensures that the elements are ordered in a sorted manner.
import java.util.*; public class SortedSetInterfaceExample { public static void main(String[] args) { SortedSetsortedSet = new TreeSet<>(); sortedSet.add("Java"); sortedSet.add("Python"); sortedSet.add("C++"); System.out.println("Sorted Set: " + sortedSet); } }
Output: Sorted Set: [C++, Java, Python]
121. Java Data Structures
Java provides various data structures to organize and store data efficiently, including lists, sets, maps, and queues.
122. Java - Enumeration
The `Enumeration` interface is an older interface used to iterate over collections before the introduction of the `Iterator` interface in Java. It has methods like `hasMoreElements()` and `nextElement()`.
import java.util.*; public class EnumerationExample { public static void main(String[] args) { Vectorvector = new Vector<>(); vector.add("Java"); vector.add("Python"); vector.add("C++"); Enumeration enumeration = vector.elements(); while (enumeration.hasMoreElements()) { System.out.println(enumeration.nextElement()); } } }
Output: Java, Python, C++
123. Java Collections Algorithms
Java Collections framework provides a set of algorithms to operate on collections like sorting and shuffling elements. The `Collections` class provides static methods like `sort()`, `shuffle()`, and `reverse()`.
import java.util.*; public class CollectionsAlgorithmsExample { public static void main(String[] args) { Listlist = new ArrayList<>(); list.add("Java"); list.add("Python"); list.add("C++"); // Sort the list Collections.sort(list); System.out.println("Sorted List: " + list); // Shuffle the list Collections.shuffle(list); System.out.println("Shuffled List: " + list); } }
Output: Sorted List: [C++, Java, Python] Shuffled List: [Python, Java, C++]
124. Java Iterators
The `Iterator` interface allows you to iterate over collections. It is more flexible than `Enumeration` and provides methods like `hasNext()`, `next()`, and `remove()`.
import java.util.*; public class IteratorExample { public static void main(String[] args) { Listlist = new ArrayList<>(); list.add("Java"); list.add("Python"); list.add("C++"); Iterator iterator = list.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } } }
Output: Java, Python, C++
125. Java - Comparators
The `Comparator` interface is used to define custom sorting logic. It provides the `compare()` method to compare two objects.
import java.util.*; public class ComparatorExample { public static void main(String[] args) { Listlist = new ArrayList<>(); list.add("Java"); list.add("Python"); list.add("C++"); // Sorting using Comparator Collections.sort(list, new Comparator () { public int compare(String str1, String str2) { return str1.length() - str2.length(); } }); System.out.println("Sorted by Length: " + list); } }
Output: Sorted by Length: [C++, Java, Python]
126. Java - Comparable Interface in Java
The `Comparable` interface is used to define the natural ordering of objects. It has the `compareTo()` method that compares the current object with another object.
import java.util.*; public class ComparableExample implements Comparable{ String name; ComparableExample(String name) { this.name = name; } public int compareTo(ComparableExample obj) { return this.name.compareTo(obj.name); } public static void main(String[] args) { List list = new ArrayList<>(); list.add(new ComparableExample("Java")); list.add(new ComparableExample("Python")); list.add(new ComparableExample("C++")); Collections.sort(list); for (ComparableExample obj : list) { System.out.println(obj.name); } } }
Output: C++, Java, Python
127. Advanced Java
Advanced Java includes concepts like multithreading, networking, JavaBeans, JSP, servlets, JDBC, and design patterns.
128. Java Command-Line Arguments
Command-line arguments are passed to the main method in the form of an array of strings.
public class CommandLineExample { public static void main(String[] args) { System.out.println("Number of arguments: " + args.length); for (String arg : args) { System.out.println(arg); } } }
Output: Number of arguments: 2 Argument1 Argument2
129. Java - Lambda Expressions
Lambda expressions are a feature of Java 8 that allow you to write concise code for functional interfaces.
interface Greet { void greet(String name); } public class LambdaExample { public static void main(String[] args) { Greet greet = (name) -> System.out.println("Hello, " + name); greet.greet("Java"); } }
Output: Hello, Java
130. Java - Sending Email
Java provides the `JavaMail` API to send emails. It requires configuring the SMTP server settings.
import java.util.*; import javax.mail.*; import javax.mail.internet.*; public class SendEmail { public static void main(String[] args) { String to = "recipient@example.com"; String from = "sender@example.com"; String host = "smtp.example.com"; Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", host); Session session = Session.getDefaultInstance(properties); try { MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject("Test Email"); message.setText("This is a test email."); Transport.send(message); System.out.println("Email Sent Successfully!"); } catch (MessagingException mex) { mex.printStackTrace(); } } }
Output: Email Sent Successfully!
131. Java Applet Basics
An applet is a small Java program that runs in a web browser. Applets are used to create interactive web applications.
import java.applet.Applet; import java.awt.Graphics; public class HelloApplet extends Applet { public void paint(Graphics g) { g.drawString("Hello, Applet!", 20, 20); } }
Output: Hello, Applet!
132. Java - Javadoc Comments
Javadoc comments are used to generate documentation for classes, methods, and fields in Java. It is a special comment format that starts with `/**` and ends with `*/`.
/** * This class represents a basic example of Javadoc comments. * It contains methods to perform basic operations. */ public class JavadocExample { /** * Adds two integers. * @param a First number * @param b Second number * @return Sum of a and b */ public int add(int a, int b) { return a + b; } public static void main(String[] args) { JavadocExample example = new JavadocExample(); System.out.println(example.add(10, 20)); } }
Output: 30
133. Java - Autoboxing and Unboxing
Autoboxing is the automatic conversion of primitive types to their corresponding wrapper classes. Unboxing is the reverse operation, converting wrapper classes to primitive types.
public class AutoboxingUnboxingExample { public static void main(String[] args) { Integer intObj = 10; // Autoboxing int primitiveInt = intObj; // Unboxing System.out.println("Autoboxed Integer: " + intObj); System.out.println("Unboxed int: " + primitiveInt); } }
Output: Autoboxed Integer: 10 Unboxed int: 10
134. Java - File Mismatch Method
The `File` class in Java provides the `mismatch()` method to compare two files and return the position of the first mismatched byte.
import java.io.File; import java.io.IOException; import java.nio.file.Files; public class FileMismatchExample { public static void main(String[] args) throws IOException { File file1 = new File("file1.txt"); File file2 = new File("file2.txt"); long mismatchIndex = Files.mismatch(file1.toPath(), file2.toPath()); if (mismatchIndex == -1) { System.out.println("Files are identical."); } else { System.out.println("Files differ at byte index: " + mismatchIndex); } } }
Output: Files are identical (or Files differ at byte index: 15)
135. Java - REPL (JShell)
JShell is an interactive REPL (Read-Eval-Print Loop) introduced in Java 9 that allows you to quickly test Java expressions, statements, and functions.
$ jshell jshell> int a = 10; jshell> int b = 20; jshell> a + b $> 30
Output: 30
136. Java - Multi-Release Jar Files
Multi-release JAR files were introduced in Java 9, allowing a JAR file to contain different versions of classes for different Java versions.
/* No code example here as it requires creating different versions of the JAR and running it across multiple Java versions */
137. Java Private Interface Methods
Starting from Java 9, interfaces can have private methods. These methods can be used to share code between default methods.
interface MyInterface { private void privateMethod() { System.out.println("Private method in interface"); } default void defaultMethod() { privateMethod(); // Using private method } } public class InterfaceExample implements MyInterface { public static void main(String[] args) { MyInterface obj = new InterfaceExample(); obj.defaultMethod(); } }
Output: Private method in interface
138. Java - Inner Class Diamond Operator
The diamond operator (`<>`) can also be used with inner classes to simplify the code by inferring the type parameter of the class.
class OuterClass { class InnerClass{ T value; InnerClass(T value) { this.value = value; } void display() { System.out.println("Value: " + value); } } public static void main(String[] args) { OuterClass outer = new OuterClass(); OuterClass.InnerClass inner = outer.new InnerClass<>(10); inner.display(); } }
Output: Value: 10
139. Java - Multiresolution Image API
Introduced in Java 9, the Multiresolution Image API helps manage multiple versions of an image, which can be selected based on the device resolution.
import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.IOException; import java.net.URL; public class MultiresolutionImageExample { public static void main(String[] args) throws IOException { URL url = new URL("image.jpg"); // Image URL with multiple resolutions BufferedImage image = ImageIO.read(url); System.out.println("Image loaded with resolution: " + image.getWidth() + "x" + image.getHeight()); } }
140. Java - Collection Factory Methods
Java 9 introduced factory methods in the `Collections` class, allowing you to create immutable lists, sets, and maps easily.
import java.util.*; public class CollectionFactoryMethodsExample { public static void main(String[] args) { Listlist = List.of("Java", "Python", "C++"); Set set = Set.of("Apple", "Banana", "Cherry"); Map map = Map.of("key1", "value1", "key2", "value2"); System.out.println("List: " + list); System.out.println("Set: " + set); System.out.println("Map: " + map); } }
Output: List: [Java, Python, C++] Set: [Apple, Banana, Cherry] Map: {key1=value1, key2=value2}
141. Java - Module System
Java 9 introduced the Module System, which allows you to modularize your code into separate modules to improve readability, maintainability, and performance.
module com.example.module { exports com.example.package; } package com.example.package; public class HelloWorld { public void greet() { System.out.println("Hello from the module system!"); } } public class Main { public static void main(String[] args) { HelloWorld helloWorld = new HelloWorld(); helloWorld.greet(); } }
142. Java - Nashorn JavaScript
Nashorn is a JavaScript engine introduced in Java 8 that allows you to embed JavaScript code in Java applications. It has since been deprecated in favor of GraalVM.
import javax.script.*; public class NashornExample { public static void main(String[] args) throws ScriptException { ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn"); String script = "var a = 5; var b = 10; a + b;"; Object result = engine.eval(script); System.out.println("Result: " + result); } }
143. Java - Optional Class
The `Optional` class, introduced in Java 8, is used to represent values that may or may not be present. It helps avoid null pointer exceptions.
import java.util.Optional; public class OptionalExample { public static void main(String[] args) { Optionalname = Optional.ofNullable("John"); System.out.println(name.orElse("Default Name")); Optional emptyName = Optional.ofNullable(null); System.out.println(emptyName.orElse("Default Name")); } }
144. Java - Method References
Method references are a shorthand notation of a lambda expression that calls a method. They were introduced in Java 8.
import java.util.*; public class MethodReferenceExample { public static void main(String[] args) { Listlist = Arrays.asList("Java", "Python", "C++"); // Using method reference to print each item list.forEach(System.out::println); } }
145. Java - Functional Interfaces
A functional interface in Java is an interface that has just one abstract method, and it can have multiple default or static methods. They are the foundation for lambda expressions.
@FunctionalInterface interface MyFunctionalInterface { void myMethod(); } public class FunctionalInterfaceExample { public static void main(String[] args) { MyFunctionalInterface obj = () -> System.out.println("Method executed!"); obj.myMethod(); } }
146. Java - Default Methods
Introduced in Java 8, default methods allow an interface to have methods with implementation. This provides the ability to add new methods to interfaces without breaking existing implementations.
interface MyInterface { default void defaultMethod() { System.out.println("Default method in interface."); } } public class DefaultMethodExample implements MyInterface { public static void main(String[] args) { MyInterface obj = new DefaultMethodExample(); obj.defaultMethod(); } }
147. Java - Base64 Encode Decode
Base64 encoding is used to encode binary data into an ASCII string format. Java provides the `Base64` class for encoding and decoding Base64 data.
import java.util.Base64; public class Base64Example { public static void main(String[] args) { String originalInput = "Java Programming"; // Encode to Base64 String encodedString = Base64.getEncoder().encodeToString(originalInput.getBytes()); System.out.println("Encoded: " + encodedString); // Decode from Base64 byte[] decodedBytes = Base64.getDecoder().decode(encodedString); System.out.println("Decoded: " + new String(decodedBytes)); } }
148. Java - Switch Expressions
Switch expressions, introduced in Java 12, allow you to return values from switch blocks, making it more powerful and compact.
public class SwitchExpressionExample { public static void main(String[] args) { int day = 3; String result = switch (day) { case 1 -> "Monday"; case 2 -> "Tuesday"; case 3 -> "Wednesday"; default -> "Unknown"; }; System.out.println(result); } }
149. Java - Teeing Collectors
Teeing collectors were introduced in Java 12 and allow you to perform two separate reduction operations on the same data in a stream.
import java.util.*; import java.util.stream.*; public class TeeingCollectorsExample { public static void main(String[] args) { Listnumbers = Arrays.asList(1, 2, 3, 4, 5); var result = numbers.stream() .collect(Collectors.teeing( Collectors.summingInt(Integer::intValue), Collectors.averagingInt(Integer::intValue), (sum, avg) -> "Sum: " + sum + ", Avg: " + avg )); System.out.println(result); } }
150. Java - Microbenchmark
Microbenchmarking helps you measure the performance of small code snippets in isolation. The most commonly used tool for microbenchmarking in Java is JMH (Java Microbenchmarking Harness).
import org.openjdk.jmh.annotations.*; public class BenchmarkExample { @Benchmark public void testMethod() { System.out.println("Benchmarking!"); } public static void main(String[] args) throws Exception { org.openjdk.jmh.Main.main(args); } }
151. Java - Text Blocks
Introduced in Java 13, text blocks allow you to represent multi-line string literals in a more readable way, avoiding escape sequences.
public class TextBlocksExample { public static void main(String[] args) { String text = """ This is a text block. It can span multiple lines. Java 13+. """; System.out.println(text); } }
152. Java - Dynamic CDS Archive
The CDS (Class Data Sharing) feature in Java allows you to share classes between multiple Java processes. Dynamic CDS archives were introduced in Java 12 to create archives dynamically at runtime.
java -Xshare:dump -XX:SharedArchiveFile=app.jsa -cp . MyApp
153. Java - Z Garbage Collector (ZGC)
Introduced in Java 11, the Z Garbage Collector (ZGC) is a low-latency garbage collector designed for large heap sizes. It aims to provide high throughput with minimal pause times.
java -XX:+UseZGC -jar myapp.jar
154. Java - Null Pointer Exception
A Null Pointer Exception (NPE) occurs when the JVM attempts to access an object that is null. It's one of the most common runtime exceptions in Java.
public class NPEExample { public static void main(String[] args) { String str = null; System.out.println(str.length()); // This will throw NullPointerException } }
155. Java - Packaging Tools
Java packaging tools are used to bundle and distribute Java applications, including tools like JAR, WAR, and EAR. The Java Packaging API simplifies the process of creating distributable packages.
jar cf MyApp.jar -C bin/ .
156. Java - Sealed Classes
Sealed classes, introduced in Java 15, restrict which classes or interfaces can extend or implement them. This provides more control over inheritance.
public sealed class Shape permits Circle, Rectangle { } public final class Circle extends Shape { } public final class Rectangle extends Shape { }
157. Java - Record Classes
Record classes, introduced in Java 14, provide a compact syntax for declaring classes that are primarily used to hold data.
public record Person(String name, int age) { } public class RecordExample { public static void main(String[] args) { Person person = new Person("John", 25); System.out.println(person.name()); } }
159. Java - Pattern Matching
Pattern matching, introduced in Java 16 and improved in Java 17, allows you to simplify conditional logic by testing whether an object is an instance of a certain type and simultaneously casting it.
public class PatternMatchingExample { public static void main(String[] args) { Object obj = "Hello, World!"; if (obj instanceof String s) { System.out.println(s.toUpperCase()); } } }
160. Java - Compact Number Formatting
Compact number formatting, introduced in Java 12, formats numbers in a more compact form using abbreviations like "K" for thousand, "M" for million, etc.
import java.text.*; import java.util.*; public class CompactNumberFormatExample { public static void main(String[] args) { NumberFormat compact = NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT); System.out.println(compact.format(1000000)); // Output: 1M } }
161. Java - Garbage Collection
Garbage collection in Java is a process by which Java programs automatically reclaim memory that is no longer in use. The Java garbage collector (GC) works in the background to manage heap memory.
public class GCExample { public static void main(String[] args) { String str = new String("Hello, World!"); str = null; // The object is eligible for garbage collection System.gc(); // Suggest the JVM to run garbage collection } }
162. Java - JIT Compiler
The JIT (Just-In-Time) compiler is part of the Java runtime that compiles bytecode into native machine code at runtime, improving the performance of Java applications.
public class JITCompilerExample { public static void main(String[] args) { System.out.println("JIT Compiler is used by the JVM to optimize performance."); } }
163. Java - Miscellaneous
This section covers various other features and utilities in Java that don't necessarily belong to a specific category but are still important for Java development.
public class MiscellaneousExample { public static void main(String[] args) { // Using the String.format() method System.out.println(String.format("My name is %s, and I am %d years old.", "John", 25)); // Converting String to Integer String number = "123"; int num = Integer.parseInt(number); System.out.println(num); } }
164. Java - Miscellaneous
This section covers various other features and utilities in Java that don't necessarily belong to a specific category but are still important for Java development.
public class MiscellaneousExample { public static void main(String[] args) { // Using the String.format() method System.out.println(String.format("My name is %s, and I am %d years old.", "John", 25)); // Converting String to Integer String number = "123"; int num = Integer.parseInt(number); System.out.println(num); } }
165. Java - Recursion
Recursion is a method of solving problems where the function calls itself. It is commonly used for problems that can be broken down into smaller sub-problems.
public class RecursionExample { public static void main(String[] args) { System.out.println(factorial(5)); // Output: 120 } public static int factorial(int n) { if (n == 0) { return 1; } else { return n * factorial(n - 1); } } }
166. Java - Regular Expressions
Regular expressions are a powerful tool for pattern matching in strings. Java provides the `java.util.regex` package to work with regular expressions.
import java.util.regex.*; public class RegexExample { public static void main(String[] args) { String text = "Hello, my name is John!"; String regex = ".*John.*"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(text); if (matcher.matches()) { System.out.println("Text contains 'John'"); } else { System.out.println("Text does not contain 'John'"); } } }
167. Java - Serialization
Serialization is the process of converting an object's state into a byte stream. It allows for saving objects to files or sending them over a network.
import java.io.*; public class SerializationExample { public static void main(String[] args) throws IOException { Person person = new Person("John", 25); // Serialize object to file FileOutputStream fileOut = new FileOutputStream("person.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(person); out.close(); fileOut.close(); System.out.println("Serialized data is saved in person.ser"); } } class Person implements Serializable { String name; int age; public Person(String name, int age) { this.name = name; this.age = age; } }
168. Java - Strings
Strings in Java are objects that represent a sequence of characters. Java provides many methods to manipulate strings, including concatenation, comparison, and searching.
public class StringExample { public static void main(String[] args) { String str1 = "Hello"; String str2 = "World"; // Concatenation String result = str1 + " " + str2; System.out.println(result); // Output: Hello World // String Length System.out.println(str1.length()); // Output: 5 } }
169. Java Process API
The Process API provides methods for managing operating system processes. It includes capabilities for creating and managing subprocesses.
import java.io.*; public class ProcessAPIExample { public static void main(String[] args) throws IOException { Process process = Runtime.getRuntime().exec("ping www.google.com"); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } }
170. Java - Stream API Improvements
In recent versions of Java, the Stream API has been enhanced with new methods for performing operations on sequences of elements, such as filtering, mapping, and reducing.
import java.util.*; import java.util.stream.*; public class StreamAPIExample { public static void main(String[] args) { Listnumbers = Arrays.asList(1, 2, 3, 4, 5); // Using Stream API to filter even numbers numbers.stream() .filter(n -> n % 2 == 0) .forEach(System.out::println); // Output: 2, 4 } }
171. Java - Enhanced @Deprecated Annotation
Java 9 introduced an enhanced version of the `@Deprecated` annotation that provides additional information about the deprecated method, such as replacement methods and since version.
public class DeprecatedExample { @Deprecated(since = "1.8", forRemoval = true) public static void oldMethod() { System.out.println("This method is deprecated."); } public static void main(String[] args) { oldMethod(); } }
172. Java CompletableFuture API Improvements
Java's `CompletableFuture` API provides a way to handle asynchronous programming. In recent versions, it has been enhanced with additional methods to simplify asynchronous tasks.
import java.util.concurrent.*; public class CompletableFutureExample { public static void main(String[] args) { CompletableFuture.supplyAsync(() -> "Hello") .thenApplyAsync(result -> result + " World") .thenAccept(System.out::println); // Output: Hello World } }
173. Java Streams
Java Streams provide a powerful and flexible way to work with collections and sequences of data. Streams allow you to perform operations like filtering, mapping, and reducing in a declarative manner.
import java.util.*; import java.util.stream.*; public class JavaStreamsExample { public static void main(String[] args) { Listnumbers = Arrays.asList(1, 2, 3, 4, 5); // Using Streams to sum even numbers int sum = numbers.stream() .filter(n -> n % 2 == 0) .mapToInt(Integer::intValue) .sum(); System.out.println(sum); // Output: 6 } }
174. Java - DateTime API
The DateTime API was introduced in Java 8 to simplify working with dates and times. It includes the `java.time` package that provides immutable classes for handling date, time, and durations.
import java.time.*; import java.time.format.DateTimeFormatter; public class DateTimeAPIExample { public static void main(String[] args) { LocalDate today = LocalDate.now(); System.out.println("Today: " + today); LocalDate birthday = LocalDate.of(1995, 5, 20); System.out.println("Birthday: " + birthday); // Formatting date DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); String formattedDate = today.format(formatter); System.out.println("Formatted date: " + formattedDate); } }
175. Java 8 - New Features
Java 8 introduced several major features, including lambda expressions, the Stream API, and new DateTime API enhancements.
import java.util.*; public class Java8Example { public static void main(String[] args) { Listlist = Arrays.asList("Apple", "Banana", "Cherry"); // Lambda Expression for iteration list.forEach(item -> System.out.println(item)); } }
176. Java 9 - New Features
Java 9 brought modular programming to Java, enabling the creation of smaller, more maintainable modules. It also introduced the JShell interactive shell.
public class Java9Example { public static void main(String[] args) { System.out.println("Java 9 features include JShell."); } }
177. Java 10 - New Features
Java 10 introduced the `var` keyword for local variable type inference, reducing the need to explicitly specify the type in some cases.
public class Java10Example { public static void main(String[] args) { var name = "Java 10"; System.out.println(name); } }
178. Java 11 - New Features
Java 11 introduced new features such as HTTP client API (Standardized) and new methods for strings, collections, etc.
import java.net.http.*; import java.net.URI; import java.io.IOException; public class Java11Example { public static void main(String[] args) throws IOException, InterruptedException { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://www.example.com")) .build(); HttpResponseresponse = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.body()); } }
179. Java 12 - New Features
Java 12 brought the JEP 189: Shenandoah, a low-latency garbage collector, and other new enhancements.
public class Java12Example { public static void main(String[] args) { String text = "Hello\nWorld"; System.out.println(text.stripIndent()); } }
180. Java 13 - New Features
Java 13 introduced JEP 350, which provided dynamic CDS archives for improved JVM performance.
public class Java13Example { public static void main(String[] args) { String text = """ This is a text block in Java 13. You can write multiline strings without concatenation. """; System.out.println(text); } }
181. Java 14 - New Features
Java 14 introduced helpful features like `Record` classes, the `Foreign-Function Interface` API, and helpful pattern matching syntax.
public class Java14Example { record Person(String name, int age) {} public static void main(String[] args) { Person person = new Person("John", 30); System.out.println(person); } }
182. Java 15 - New Features
Java 15 focused on enhancing the Java platform with features like the `Text Blocks` feature and improved performance.
public class Java15Example { public static void main(String[] args) { String block = """ This is a multiline string in Java 15 which is much easier to read. """; System.out.println(block); } }
183. Java 16 - New Features
Java 16 brought new features like the `JEP 395` to enable easier native code integration and pattern matching enhancements.
public class Java16Example { public static void main(String[] args) { Object obj = "Java 16"; // Pattern Matching for instanceof if (obj instanceof String str) { System.out.println("The string is: " + str); } } }
184. Java JDBC Tutorial
JDBC (Java Database Connectivity) is an API for connecting and executing queries with databases. Below is an example of how to use JDBC to connect to a MySQL database and perform basic operations.
import java.sql.*; public class JdbcExample { public static void main(String[] args) { try { // Load JDBC driver Class.forName("com.mysql.cj.jdbc.Driver"); // Establish connection Connection connection = DriverManager.getConnection( "jdbc:mysql://localhost:3306/mydatabase", "root", "password"); // Create Statement object Statement statement = connection.createStatement(); // Execute query ResultSet resultSet = statement.executeQuery("SELECT * FROM users"); // Process the result set while (resultSet.next()) { System.out.println("User ID: " + resultSet.getInt("user_id")); System.out.println("User Name: " + resultSet.getString("user_name")); } // Close the connection connection.close(); } catch (Exception e) { e.printStackTrace(); } } }
185. SWING Tutorial
SWING is a part of Java Foundation Classes (JFC) used to create window-based applications in Java. It provides a rich set of GUI components for building interactive user interfaces.
import javax.swing.*; public class SwingExample { public static void main(String[] args) { // Create a JFrame JFrame frame = new JFrame("SWING Example"); JButton button = new JButton("Click Me"); // Add action listener to button button.addActionListener(e -> JOptionPane.showMessageDialog(frame, "Button Clicked")); // Add button to frame frame.add(button); // Set frame size and visibility frame.setSize(300, 200); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }
186. AWT Tutorial
The Abstract Window Toolkit (AWT) is the original platform-dependent windowing, graphics, and user-interface toolkit in Java. It provides a set of interfaces for building window-based applications.
import java.awt.*; import java.awt.event.*; public class AWTExample { public static void main(String[] args) { Frame frame = new Frame("AWT Example"); Button button = new Button("Click Me"); // Add action listener to button button.addActionListener(e -> { System.out.println("Button Clicked"); frame.setVisible(false); // Hide frame on button click }); // Add button to frame frame.add(button); // Set frame size and visibility frame.setSize(300, 200); frame.setLayout(new FlowLayout()); frame.setVisible(true); } }
187. Servlets Tutorial
Servlets are server-side Java programs that handle HTTP requests and generate dynamic responses. They are an essential part of Java-based web applications.
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType("text/html"); // Print response PrintWriter out = response.getWriter(); out.println("Hello, Servlet!
"); } }
188. JSP Tutorial
Java Server Pages (JSP) is a server-side technology used for developing dynamic web pages. It allows embedding Java code directly into HTML pages.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>JSP Example Welcome to JSP!
The current date and time is: <%= new java.util.Date() %>