Start your journey in object oriented programming
Start learning step by step
Check your understanding
Prepare for real interviews
Test your skills
Java is a high-level, object-oriented programming language used for building applications, web apps, Android apps, games, and more. It's platform-independent thanks to the JVM (Java Virtual Machine).
// Print your first message in Java
public class Main {
public static void main(String[] args) {
System.out.println("Hello, Java!");
}
}
Variables store data. Java has different data types like int, double, boolean, and String.
// Variables in Java
int age = 25;
double price = 19.99;
boolean isJavaFun = true;
String name = "Zohil";
System.out.println("Age: " + age);
System.out.println("Price: " + price);
System.out.println("Learning Java is fun: " + isJavaFun);
System.out.println("Name: " + name);
Operators are used to perform operations on variables and values. Common types: arithmetic, relational, and logical operators.
// Arithmetic Operators
int a = 10;
int b = 5;
System.out.println("a + b = " + (a + b));
System.out.println("a - b = " + (a - b));
System.out.println("a * b = " + (a * b));
System.out.println("a / b = " + (a / b));
// Relational Operators
System.out.println(a > b); // true
System.out.println(a == b); // false
// Logical Operators
System.out.println(a > 5 && b < 10); // true
System.out.println(a < 5 || b < 10); // true
Use if, else if, and else to make decisions in your program.
int number = 20;
if(number > 0) {
System.out.println("Positive number");
} else if(number < 0) {
System.out.println("Negative number");
} else {
System.out.println("Zero");
}
Loops let you repeat actions. Java supports for, while, and do-while loops.
// For loop
for(int i = 1; i <= 5; i++) {
System.out.println("For loop iteration: " + i);
}
// While loop
int j = 1;
while(j <= 5) {
System.out.println("While loop iteration: " + j);
j++;
}
// Do-while loop
int k = 1;
do {
System.out.println("Do-while loop iteration: " + k);
k++;
} while(k <= 5);
Arrays store multiple values of the same type in a single variable.
// Declare and initialize an array
int[] numbers = {10, 20, 30, 40, 50};
// Access elements
System.out.println("First element: " + numbers[0]);
System.out.println("Third element: " + numbers[2]);
// Loop through array
for(int i = 0; i < numbers.length; i++) {
System.out.println("Array element: " + numbers[i]);
}
Methods are blocks of code that perform a task and can be reused.
// Method example
public class Main {
public static void main(String[] args) {
greet("Zohil");
int sum = addNumbers(5, 10);
System.out.println("Sum: " + sum);
}
// Method to greet
public static void greet(String name) {
System.out.println("Hello, " + name + "!");
}
// Method to add numbers
public static int addNumbers(int a, int b) {
return a + b;
}
}
Strings store sequences of characters. Java has many built-in methods to manipulate strings.
String text = "Hello, Java!";
// String length
System.out.println("Length: " + text.length());
// Convert to uppercase
System.out.println(text.toUpperCase());
// Substring
System.out.println(text.substring(7, 11)); // Java
// Replace
System.out.println(text.replace("Java", "World"));
You can take input from the user using the Scanner class.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = input.nextLine();
System.out.print("Enter your age: ");
int age = input.nextInt();
System.out.println("Name: " + name + ", Age: " + age);
}
}
Use switch for multiple conditional branches instead of multiple if-else statements.
int day = 3;
String dayName;
switch(day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
default:
dayName = "Weekend";
}
System.out.println("Day: " + dayName);
Classes are blueprints for objects. Objects are instances of classes.
// Define a class
public class Car {
String color;
String model;
}
// Create objects
public class Main {
public static void main(String[] args) {
Car car1 = new Car();
car1.color = "Red";
car1.model = "Toyota";
Car car2 = new Car();
car2.color = "Blue";
car2.model = "Honda";
System.out.println("Car1: " + car1.model + ", " + car1.color);
System.out.println("Car2: " + car2.model + ", " + car2.color);
}
}
Constructors initialize objects when they are created. They have the same name as the class.
public class Car {
String model;
String color;
// Constructor
public Car(String model, String color) {
this.model = model;
this.color = color;
}
}
public class Main {
public static void main(String[] args) {
Car car1 = new Car("Toyota", "Red");
Car car2 = new Car("Honda", "Blue");
System.out.println("Car1: " + car1.model + ", " + car1.color);
System.out.println("Car2: " + car2.model + ", " + car2.color);
}
}
Classes can have methods that define actions the object can perform.
public class Car {
String model;
String color;
public Car(String model, String color) {
this.model = model;
this.color = color;
}
// Method
public void drive() {
System.out.println(model + " is driving");
}
}
public class Main {
public static void main(String[] args) {
Car car = new Car("Toyota", "Red");
car.drive(); // Call method
}
}
Encapsulation hides the internal state of an object and allows access only through methods (getters and setters).
public class Person {
private String name;
private int age;
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class Main {
public static void main(String[] args) {
Person p = new Person();
p.setName("Zohil");
p.setAge(25);
System.out.println("Name: " + p.getName() + ", Age: " + p.getAge());
}
}
Static variables and methods belong to the class instead of instances. They can be accessed without creating an object.
public class Counter {
public static int count = 0;
public static void increment() {
count++;
}
}
public class Main {
public static void main(String[] args) {
Counter.increment();
Counter.increment();
System.out.println("Count: " + Counter.count);
}
}
Inheritance allows a class to inherit fields and methods from another class using extends.
class Vehicle {
void start() {
System.out.println("Vehicle starting...");
}
}
class Car extends Vehicle {
void drive() {
System.out.println("Car is driving...");
}
}
public class Main {
public static void main(String[] args) {
Car car = new Car();
car.start(); // Inherited method
car.drive();
}
}
Child classes can override parent class methods to provide their own implementation.
class Animal {
void sound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Bark");
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
a.sound(); // Outputs "Bark" due to overriding
}
}
Polymorphism allows objects to be treated as instances of their parent class, enabling flexibility in code.
class Shape {
void draw() {
System.out.println("Drawing shape");
}
}
class Circle extends Shape {
@Override
void draw() {
System.out.println("Drawing circle");
}
}
class Square extends Shape {
@Override
void draw() {
System.out.println("Drawing square");
}
}
public class Main {
public static void main(String[] args) {
Shape s1 = new Circle();
Shape s2 = new Square();
s1.draw(); // Drawing circle
s2.draw(); // Drawing square
}
}
Abstract classes cannot be instantiated. They can have abstract methods (without body) that must be implemented by child classes.
abstract class Animal {
abstract void sound(); // Abstract method
void eat() { // Regular method
System.out.println("Eating...");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Bark");
}
}
public class Main {
public static void main(String[] args) {
Animal dog = new Dog();
dog.sound();
dog.eat();
}
}
Interfaces define methods without implementation. Classes implement interfaces to provide the actual behavior.
interface Vehicle {
void start();
void stop();
}
class Car implements Vehicle {
@Override
public void start() {
System.out.println("Car starting...");
}
@Override
public void stop() {
System.out.println("Car stopping...");
}
}
public class Main {
public static void main(String[] args) {
Vehicle myCar = new Car();
myCar.start();
myCar.stop();
}
}
Exceptions are runtime errors. You can handle them using try, catch, and finally blocks.
public class Main {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero!");
} finally {
System.out.println("This block always executes.");
}
}
}
You can throw exceptions manually using throw and declare exceptions using throws.
class Main {
static void checkAge(int age) throws Exception {
if(age < 18) {
throw new Exception("Age must be at least 18.");
} else {
System.out.println("Access granted!");
}
}
public static void main(String[] args) {
try {
checkAge(15);
} catch(Exception e) {
System.out.println(e.getMessage());
}
}
}
Java can read from and write to files using classes like File, Scanner, and FileWriter.
import java.io.File;
import java.io.FileWriter;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
try {
// Write to a file
FileWriter writer = new FileWriter("example.txt");
writer.write("Hello, Java File I/O!");
writer.close();
// Read from a file
File file = new File("example.txt");
Scanner reader = new Scanner(file);
while(reader.hasNextLine()) {
String line = reader.nextLine();
System.out.println(line);
}
reader.close();
} catch(Exception e) {
System.out.println(e.getMessage());
}
}
}
Packages organize classes into namespaces. Use package and import to structure code.
// File: vehicles/Car.java
package vehicles;
public class Car {
public void info() {
System.out.println("This is a car.");
}
}
// File: Main.java
import vehicles.Car;
public class Main {
public static void main(String[] args) {
Car car = new Car();
car.info();
}
}
Classes can be defined inside other classes. Inner classes have access to the outer class members.
public class Outer {
private String message = "Hello from Outer";
class Inner {
void showMessage() {
System.out.println(message);
}
}
public static void main(String[] args) {
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.showMessage();
}
}
ArrayList is a resizable array from the java.util package.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList fruits = new ArrayList<>();
// Add elements
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Mango");
// Access elements
System.out.println("First fruit: " + fruits.get(0));
// Loop through ArrayList
for(String fruit : fruits) {
System.out.println(fruit);
}
// Remove element
fruits.remove("Banana");
System.out.println("After removal: " + fruits);
}
}
HashMap stores key-value pairs and allows fast access.
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap scores = new HashMap<>();
// Add key-value pairs
scores.put("Alice", 90);
scores.put("Bob", 85);
scores.put("Charlie", 95);
// Access value
System.out.println("Alice's score: " + scores.get("Alice"));
// Loop through keys
for(String name : scores.keySet()) {
System.out.println(name + ": " + scores.get(name));
}
// Remove a key
scores.remove("Bob");
System.out.println("After removal: " + scores);
}
}
Generics allow you to create classes, interfaces, and methods with type parameters for type safety.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
for(int num : numbers) {
System.out.println(num);
}
}
}
Wrapper classes allow primitive types to be used as objects.
public class Main {
public static void main(String[] args) {
int a = 10;
Integer b = Integer.valueOf(a); // Wrap int to Integer
int c = b.intValue(); // Unwrap back to int
System.out.println("Wrapped: " + b);
System.out.println("Unwrapped: " + c);
// Auto-boxing and Auto-unboxing
Integer x = a; // auto-box
int y = x; // auto-unbox
System.out.println("Auto-box: " + x + ", Auto-unbox: " + y);
}
}
Lambda expressions provide a concise way to represent anonymous methods (introduced in Java 8).
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
// Using lambda to print each element
names.forEach(name -> System.out.println(name));
// Lambda with condition
names.stream().filter(name -> name.startsWith("A")).forEach(System.out::println);
}
}
Java can handle files with BufferedReader, BufferedWriter, and FileReader/FileWriter for efficient reading/writing.
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
// Write using BufferedWriter
BufferedWriter writer = new BufferedWriter(new FileWriter("data.txt"));
writer.write("Hello, Java File Handling!\n");
writer.write("BufferedWriter makes writing efficient.");
writer.close();
// Read using BufferedReader
BufferedReader reader = new BufferedReader(new FileReader("data.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Threads allow concurrent execution. You can create threads by extending Thread or implementing Runnable.
class MyThread extends Thread {
public void run() {
for(int i=1; i<=5; i++) {
System.out.println("Thread running: " + i);
}
}
}
public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start(); // Start thread
}
}
Implement Runnable for multithreading without extending Thread class.
class MyRunnable implements Runnable {
public void run() {
for(int i=1; i<=5; i++) {
System.out.println("Runnable thread: " + i);
}
}
}
public class Main {
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable());
t.start();
}
}
Synchronization prevents race conditions by allowing only one thread to access a block/method at a time.
class Counter {
private int count = 0;
// synchronized method
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Thread t1 = new Thread(() -> {
for(int i=0; i<1000; i++) counter.increment();
});
Thread t2 = new Thread(() -> {
for(int i=0; i<1000; i++) counter.increment();
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Final count: " + counter.getCount());
}
}
Threads can communicate using wait(), notify(), and notifyAll().
class Shared {
int data;
boolean ready = false;
public synchronized void produce(int value) {
data = value;
ready = true;
notify(); // Notify waiting thread
}
public synchronized int consume() throws InterruptedException {
while(!ready) wait(); // Wait until data is ready
ready = false;
return data;
}
}
public class Main {
public static void main(String[] args) {
Shared shared = new Shared();
Thread producer = new Thread(() -> {
for(int i=1; i<=5; i++) {
shared.produce(i);
System.out.println("Produced: " + i);
}
});
Thread consumer = new Thread(() -> {
for(int i=1; i<=5; i++) {
try {
int val = shared.consume();
System.out.println("Consumed: " + val);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
producer.start();
consumer.start();
}
}
Java provides java.net package to work with networking, like sockets and URLs.
import java.net.*;
public class Main {
public static void main(String[] args) {
try {
// URL example
URL url = new URL("https://www.example.com");
System.out.println("Protocol: " + url.getProtocol());
System.out.println("Host: " + url.getHost());
System.out.println("File: " + url.getFile());
} catch (MalformedURLException e) {
System.out.println("Invalid URL");
}
}
}
Sockets allow communication between client and server over the network.
import java.io.*;
import java.net.*;
public class Main {
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(5000);
System.out.println("Server started, waiting for client...");
Socket socket = server.accept(); // accept client connection
System.out.println("Client connected");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String message = in.readLine();
System.out.println("Client says: " + message);
server.close();
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
JDBC allows Java to connect to databases like MySQL or SQLite.
import java.sql.*;
public class Main {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/testdb";
String user = "root";
String password = "password";
try {
Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
// Create table
stmt.executeUpdate("CREATE TABLE IF NOT EXISTS users(id INT PRIMARY KEY, name VARCHAR(50))");
// Insert data
stmt.executeUpdate("INSERT INTO users VALUES(1, 'Zohil')");
// Query data
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
while(rs.next()) {
System.out.println("ID: " + rs.getInt("id") + ", Name: " + rs.getString("name"));
}
conn.close();
} catch (SQLException e) {
System.out.println("Database error: " + e.getMessage());
}
}
}
JavaFX is used to create graphical user interfaces (GUI) in Java.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
Button btn = new Button("Click Me!");
btn.setOnAction(e -> System.out.println("Button clicked!"));
StackPane root = new StackPane();
root.getChildren().add(btn);
Scene scene = new Scene(root, 300, 200);
primaryStage.setTitle("JavaFX Example");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Build a complete project to practice everything you learned in Java:
Project: Student Management System
Features:
- Add, update, delete, and view students (OOP + ArrayList/HashMap)
- Save data to a file or database (File I/O or JDBC)
- GUI with JavaFX
- Exception handling and validation
- Multithreading for background tasks
- Optional: Network feature to sync students across systems
This project will combine all major concepts: OOP, Collections, File/DB, GUI, Threads, and Networking.
1. What is Java primarily used for?
2. Which keyword is used to define a class in Java?
3. Which method is the entry point for a Java program?
4. Which keyword is used for inheritance in Java?
5. Which of these is a valid Java data type?
6. Which operator is used for comparison in Java?
7. Which keyword is used to prevent a class from being inherited?
8. Which method is used to get the length of a string in Java?
9. Which exception is thrown when dividing by zero?
10. Which keyword is used to declare an interface?
11. What is the default value of a boolean in Java?
12. Which loop is guaranteed to execute at least once?
13. Which package is automatically imported in every Java program?
14. Which operator is used for logical AND in Java?