Category: Blog

Your blog category

  • Exception Handling

    1. Introduction to Exception Handling

    1.1 What is an Exception

    An exception is an event that disrupts the normal flow of a program during execution.

    1.2 Errors vs Exceptions

    • Errors → Serious issues (system-level)
    • Exceptions → Can be handled in code

    1.3 Why Exception Handling

    • Prevents program crash
    • Maintains normal flow
    • Improves reliability

    1.4 Example

    int a = 10;
    int b = 0;
    System.out.println(a / b); // ArithmeticException

    2. Types of Exceptions

    2.1 Checked Exceptions

    • Checked at compile time
    • Example: IOException

    2.2 Unchecked Exceptions

    • Occur at runtime
    • Example: NullPointerException

    2.3 Errors

    • Not handled by program
    • Example: OutOfMemoryError

    2.4 Common Exceptions

    • ArithmeticException
    • NullPointerException
    • ArrayIndexOutOfBoundsException

    3. try, catch, finally

    3.1 try Block

    Contains code that may cause exception.

    3.2 catch Block

    Handles exception.

    3.3 finally Block

    Always executes (optional).

    3.4 Example

    try {
        int result = 10 / 0;
    } catch (ArithmeticException e) {
        System.out.println("Error occurred");
    } finally {
        System.out.println("Done");
    }

    3.5 Multiple catch

    try {
        // code
    } catch (ArithmeticException e) {
    } catch (NullPointerException e) {
    }

    4. throw and throws

    4.1 throw Keyword

    Used to explicitly throw an exception.

    throw new ArithmeticException("Error");

    4.2 throws Keyword

    Declares exceptions in method.

    void readFile() throws IOException {
    }

    4.3 Difference

    throwthrows
    Used inside methodUsed in method declaration
    Throws one exceptionCan declare multiple

    5. Creating Custom Exceptions

    5.1 Definition

    User-defined exceptions.

    5.2 Steps

    1. Extend Exception class
    2. Create constructor
    3. Use throw

    5.3 Example

    class MyException extends Exception {
        MyException(String msg) {
            super(msg);
        }
    }

    5.4 Using Custom Exception

    void checkAge(int age) throws MyException {
        if (age < 18) {
            throw new MyException("Not eligible");
        }
    }

    Conclusion

    Exception handling is essential for building robust Java applications. By properly handling errors using try-catch blocks and creating custom exceptions, developers can ensure their programs run smoothly even in unexpected situations. Mastering this concept is crucial for real-world application development.

  • Abstraction

    1. Introduction to Abstraction

    1.1 What is Abstraction

    Abstraction means hiding internal details and showing only essential functionality to the user.

    1.2 Why Use Abstraction

    • Reduces complexity
    • Improves code readability
    • Enhances security

    1.3 Real-World Example

    ATM machine:

    • User → withdraw money
    • Hidden → internal processing

    1.4 Abstraction vs Encapsulation

    • Abstraction → hides implementation
    • Encapsulation → hides data

    1.5 Ways to Achieve Abstraction

    • Abstract classes
    • Interfaces

    2. Abstract Classes

    2.1 Definition

    An abstract class is a class that cannot be instantiated and may contain abstract methods.

    2.2 Syntax

    abstract class Vehicle {
    abstract void start();
    }

    2.3 Features

    • Can have abstract and non-abstract methods
    • Can have constructors
    • Cannot create objects directly

    2.4 Example

    abstract class Animal {
        abstract void sound();    void sleep() {
            System.out.println("Sleeping");
        }
    }

    2.5 When to Use

    • When classes share common behavior
    • When partial abstraction is needed

    3. Abstract Methods

    3.1 Definition

    A method declared without implementation.

    3.2 Syntax

    abstract void display();

    3.3 Rules

    • Must be inside abstract class
    • Must be implemented in subclass

    3.4 Example

    class Dog extends Animal {
        void sound() {
            System.out.println("Dog barks");
        }
    }

    4. Interfaces

    4.1 Definition

    An interface is a blueprint of a class that contains abstract methods.

    4.2 Syntax

    interface Animal {
    void sound();
    }

    4.3 Features

    • All methods are abstract by default (basic concept)
    • Cannot create objects
    • Supports multiple inheritance

    4.4 Example

    class Dog implements Animal {
        public void sound() {
            System.out.println("Dog barks");
        }
    }

    4.5 Interface vs Abstract Class

    FeatureAbstract ClassInterface
    MethodsCan have bothMostly abstract
    InheritanceSingleMultiple

    5. Implementing Interfaces

    5.1 implements Keyword

    Used to implement an interface.

    5.2 Example

    interface Vehicle {
        void start();
    }class Car implements Vehicle {
        public void start() {
            System.out.println("Car starts");
        }
    }

    5.3 Key Points

    • Must override all methods
    • Use public access

    6. Multiple Interface Implementation

    6.1 Definition

    A class can implement more than one interface.

    6.2 Example

    interface A {
        void show();
    }interface B {
        void display();
    }class Test implements A, B {
        public void show() {
            System.out.println("Show method");
        }    public void display() {
            System.out.println("Display method");
        }
    }

    6.3 Advantages

    • Achieves multiple inheritance
    • Improves flexibility

    Conclusion

    Abstraction is a powerful concept that helps simplify complex systems by hiding unnecessary details. By using abstract classes and interfaces, developers can build flexible and scalable Java applications. Understanding abstraction is essential for mastering Object-Oriented Programming and real-world software design.

  • Polymorphism

    1. Introduction to Polymorphism

    1.1 What is Polymorphism

    Polymorphism means “many forms.” In Java, it allows methods or objects to behave differently based on context.

    1.2 Types of Polymorphism

    • Compile-time polymorphism
    • Runtime polymorphism

    1.3 Importance

    • Improves code flexibility
    • Promotes reusability
    • Simplifies code design

    1.4 Real-World Example

    A person can have multiple roles:

    • Teacher
    • Parent
    • Employee

    2. Method Overloading (Compile-Time Polymorphism)

    2.1 Definition

    Method overloading occurs when multiple methods have the same name but different parameters.

    2.2 Example

    class Calculator {    int add(int a, int b) {
            return a + b;
        }    double add(double a, double b) {
            return a + b;
        }    int add(int a, int b, int c) {
            return a + b + c;
        }
    }

    2.3 Rules

    • Method name must be same
    • Parameters must differ (number or type)
    • Return type alone is not enough

    2.4 Advantages

    • Improves readability
    • Reuses method name

    3. Method Overriding (Runtime Polymorphism)

    3.1 Definition

    Method overriding occurs when a subclass provides its own implementation of a method defined in the parent class.

    3.2 Example

    class Animal {
        void sound() {
            System.out.println("Animal sound");
        }
    }class Dog extends Animal {
        void sound() {
            System.out.println("Dog barks");
        }
    }

    3.3 Rules

    • Same method name
    • Same parameters
    • Same return type
    • Must use inheritance

    3.4 Dynamic Method Dispatch

    The method to be executed is decided at runtime.

    Animal a = new Dog();
    a.sound(); // Calls Dog's method

    3.5 @Override Annotation

    @Override
    void sound() {
    System.out.println("Dog barks");
    }

    3.6 Advantages

    • Supports runtime flexibility
    • Enables dynamic behavior

    4. Compile-Time vs Runtime Polymorphism

    4.1 Compile-Time Polymorphism

    • Achieved using method overloading
    • Decision made at compile time

    4.2 Runtime Polymorphism

    • Achieved using method overriding
    • Decision made at runtime

    4.3 Differences

    FeatureCompile-TimeRuntime
    MethodOverloadingOverriding
    BindingEarly bindingLate binding
    Decision TimeCompile timeRuntime
    PerformanceFasterSlightly slower

    4.4 Use Cases

    • Overloading → Same operation with different inputs
    • Overriding → Different behavior in subclasses

    Conclusion

    Polymorphism is a powerful feature in Java that allows flexibility and dynamic behavior in programs. By understanding method overloading and overriding, beginners can write cleaner, more reusable, and scalable code. This concept is widely used in real-world applications and is essential for mastering Object-Oriented Programming.

  • Inheritance

    1. Introduction to Inheritance

    1.1 What is Inheritance

    Inheritance is a mechanism where one class acquires properties and methods of another class.

    1.2 Why Use Inheritance

    • Code reuse
    • Reduces redundancy
    • Improves maintainability

    1.3 Real-World Example

    • Parent → Animal
    • Child → Dog

    1.4 Syntax

    class Parent {
    // properties and methods
    }class Child extends Parent {
    // additional features
    }

    2. Types of Inheritance

    2.1 Single Inheritance

    One class inherits from one parent.

    class A {}
    class B extends A {}

    2.2 Multilevel Inheritance

    A chain of inheritance.

    class A {}
    class B extends A {}
    class C extends B {}

    2.3 Hierarchical Inheritance

    Multiple classes inherit from one parent.

    class A {}
    class B extends A {}
    class C extends A {}

    2.4 Multiple Inheritance (Concept)

    Java does not support multiple inheritance with classes.

    2.5 Hybrid Inheritance

    Combination of different types (not directly supported with classes).


    3. Method Overriding

    3.1 Definition

    Method overriding allows a subclass to provide a specific implementation of a method already defined in the parent class.

    3.2 Example

    class Animal {
        void sound() {
            System.out.println("Animal sound");
        }
    }class Dog extends Animal {
        void sound() {
            System.out.println("Dog barks");
        }
    }

    3.3 Rules

    • Same method name
    • Same parameters
    • Same return type

    3.4 @Override Annotation

    @Override
    void sound() {
    System.out.println("Dog barks");
    }

    3.5 Runtime Polymorphism

    Method is decided at runtime based on object.


    4. super Keyword

    4.1 Definition

    The super keyword refers to the parent class object.

    4.2 Access Parent Variable

    super.variableName;

    4.3 Call Parent Method

    super.methodName();

    4.4 Call Parent Constructor

    super();

    4.5 Example

    class Animal {
        void show() {
            System.out.println("Animal class");
        }
    }class Dog extends Animal {
        void show() {
            super.show();
            System.out.println("Dog class");
        }
    }

    5. final Keyword

    5.1 Definition

    The final keyword is used to restrict changes.

    5.2 final Variable

    final int MAX = 100;

    5.3 final Method

    final void display() {}

    Cannot be overridden.

    5.4 final Class

    final class A {}

    Cannot be extended.

    5.5 Example

    final class Animal {}class Dog extends Animal {} // Error

    Conclusion

    Inheritance is a powerful feature in Java that allows code reuse and better organization of programs. By understanding inheritance types, method overriding, and keywords like super and final, beginners can build efficient and scalable applications.

  • Classes and Objects

    1. Introduction to Classes and Objects

    1.1 Overview

    Classes and objects are used to structure programs in Java.

    1.2 Relationship

    • Class → Blueprint
    • Object → Instance of a class

    1.3 Real-World Example

    • Class → Car
    • Object → BMW, Audi

    1.4 Importance

    • Helps organize code
    • Makes programs modular and reusable

    2. What is a Class

    2.1 Definition

    A class is a blueprint used to create objects.

    2.2 Structure

    A class contains:

    • Variables (fields)
    • Methods (functions)

    2.3 Example

    class Student {
        String name;
        int age;    void display() {
            System.out.println(name + " " + age);
        }
    }

    2.4 Naming Convention

    • Use PascalCase
    • Example: StudentRecord

    3. What is an Object

    3.1 Definition

    An object is an instance of a class.

    3.2 Characteristics

    • State → variables
    • Behavior → methods
    • Identity → unique instance

    3.3 Memory Allocation

    Objects are created in heap memory.

    3.4 Example

    Student s1 = new Student();

    4. Creating Classes and Objects

    4.1 Creating Object

    Student s1 = new Student();

    4.2 Accessing Members

    s1.name = "Pooja";
    s1.age = 20;

    4.3 Calling Method

    s1.display();

    4.4 Multiple Objects

    Student s2 = new Student();

    4.5 Complete Example

    class Student {
        String name;
        int age;    void display() {
            System.out.println(name + " " + age);
        }    public static void main(String[] args) {
            Student s1 = new Student();
            s1.name = "Pooja";
            s1.age = 20;
            s1.display();
        }
    }

    5. Constructors

    5.1 Definition

    A constructor is a special method used to initialize objects.

    5.2 Characteristics

    • Same name as class
    • No return type
    • Automatically called

    5.3 Default Constructor

    class Student {
        Student() {
            System.out.println("Constructor called");
        }
    }

    5.4 Parameterized Constructor

    class Student {
        String name;    Student(String n) {
            name = n;
        }
    }

    5.5 Constructor Overloading

    Student() {}
    Student(String name) {}

    5.6 this Keyword

    this.name = name;

    5.7 Constructor vs Method

    ConstructorMethod
    Initializes objectPerforms action
    No return typeHas return type

    6. Instance vs Static Members

    6.1 Instance Members

    • Belong to object
    • Each object has its own copy
    class Student {
    String name;
    }

    6.2 Static Members

    • Shared among all objects
    • Belong to class
    class Student {
    static String college = "ABC";
    }

    6.3 Accessing Static Members

    Student.college;

    6.4 Differences

    InstanceStatic
    Object-basedClass-based
    Separate copyShared copy

    6.5 When to Use Static

    • Common values
    • Utility methods

    Conclusion

    Classes and objects are the core of Java programming. By understanding how to create and use them, along with constructors and static members, beginners can build structured and reusable applications. These concepts are the foundation for advanced topics in Java and real-world software development.

  • Introduction to Object-Oriented Programming

    1. What is OOP

    1.1 Definition

    Object-Oriented Programming (OOP) is a programming paradigm based on objects and classes.

    1.2 Procedural vs OOP

    • Procedural → focuses on functions
    • OOP → focuses on objects

    1.3 Real-World Analogy

    Think of a car:

    • Object → Car
    • Properties → color, speed
    • Methods → drive(), brake()

    1.4 Objects and Classes

    • Class → blueprint
    • Object → instance of a class

    1.5 Example

    class Car {
        String color;    void drive() {
            System.out.println("Car is moving");
        }
    }

    2. Benefits of OOP

    2.1 Code Reusability

    Reuse code using inheritance.

    2.2 Modularity

    Break program into smaller parts (classes).

    2.3 Maintainability

    Easy to update and fix bugs.

    2.4 Scalability

    Programs can grow easily.

    2.5 Security

    Encapsulation hides data.

    2.6 Real-World Modeling

    Represents real-life objects effectively.


    3. OOP Principles


    3.1 Encapsulation

    3.1.1 Definition

    Wrapping data and methods into a single unit (class).

    3.1.2 Data Hiding

    Use private variables.

    3.1.3 Example

    class Student {
        private int marks;    public void setMarks(int m) {
            marks = m;
        }    public int getMarks() {
            return marks;
        }
    }

    3.1.4 Advantages

    • Protects data
    • Controls access

    3.2 Inheritance

    3.2.1 Definition

    One class inherits properties of another.

    3.2.2 Example

    class Animal {
        void eat() {
            System.out.println("Eating");
        }
    }class Dog extends Animal {
        void bark() {
            System.out.println("Barking");
        }
    }

    3.2.3 Advantages

    • Code reuse
    • Reduces duplication

    3.3 Polymorphism

    3.3.1 Definition

    One method behaves differently in different situations.

    3.3.2 Method Overloading

    int add(int a, int b) {
        return a + b;
    }double add(double a, double b) {
        return a + b;
    }

    3.3.3 Method Overriding

    class Animal {
        void sound() {
            System.out.println("Animal sound");
        }
    }class Dog extends Animal {
        void sound() {
            System.out.println("Dog barks");
        }
    }

    3.3.4 Advantages

    • Flexibility
    • Improves code design

    3.4 Abstraction

    3.4.1 Definition

    Hiding implementation details and showing only functionality.

    3.4.2 Abstract Class Example

    abstract class Vehicle {
        abstract void start();
    }

    3.4.3 Interface Example

    interface Animal {
        void sound();
    }

    3.4.4 Difference

    • Abstract class → can have methods with body
    • Interface → only method declarations (before Java 8 basics)

    3.4.5 Advantages

    • Reduces complexity
    • Improves maintainability

    Conclusion

    Object-Oriented Programming is the core of Java development. By understanding concepts like encapsulation, inheritance, polymorphism, and abstraction, you can design clean, reusable, and scalable applications. These principles are widely used in real-world software development and form the foundation for advanced Java concepts.

  • Arrays in Java

    1. Introduction to Arrays

    1.1 What is an Array

    An array is a collection of elements of the same data type stored in contiguous memory locations.

    1.2 Need for Arrays

    Instead of creating multiple variables:

    int a = 10, b = 20, c = 30;

    We use:

    int[] numbers = {10, 20, 30};

    1.3 Characteristics

    • Fixed size
    • Same data type
    • Indexed (starts from 0)

    1.4 Advantages

    • Easy data management
    • Faster access using index

    1.5 Limitations

    • Fixed size
    • Cannot store different data types

    2. Declaring and Initializing Arrays

    2.1 Declaration

    int[] arr;

    2.2 Initialization

    arr = new int[5];

    2.3 Declaration + Initialization

    int[] arr = {1, 2, 3, 4, 5};

    2.4 Default Values

    • int → 0
    • float → 0.0
    • boolean → false
    • object → null

    2.5 Example

    int[] marks = new int[3];

    3. Accessing Array Elements

    3.1 Indexing

    Array index starts from 0.

    3.2 Accessing

    int[] arr = {10, 20, 30};
    System.out.println(arr[0]); // 10

    3.3 Updating

    arr[1] = 50;

    3.4 Looping

    for (int i = 0; i < arr.length; i++) {
    System.out.println(arr[i]);
    }

    3.5 Common Error

    Accessing invalid index:

    arr[5]; // Error

    4. Multidimensional Arrays

    4.1 Definition

    Array of arrays.

    4.2 Declaration

    int[][] matrix;

    4.3 Initialization

    int[][] matrix = {
    {1, 2},
    {3, 4}
    };

    4.4 Accessing Elements

    System.out.println(matrix[0][1]); // 2

    4.5 Using Nested Loops

    for (int i = 0; i < matrix.length; i++) {
    for (int j = 0; j < matrix[i].length; j++) {
    System.out.print(matrix[i][j] + " ");
    }
    }

    4.6 Jagged Arrays

    Arrays with different column sizes:

    int[][] jagged = new int[2][];
    jagged[0] = new int[2];
    jagged[1] = new int[3];

    5. Array Operations

    5.1 Traversing

    for (int num : arr) {
    System.out.println(num);
    }

    5.2 Searching

    int key = 20;
    for (int num : arr) {
    if (num == key) {
    System.out.println("Found");
    }
    }

    5.3 Sorting

    java.util.Arrays.sort(arr);

    5.4 Copying

    int[] copy = java.util.Arrays.copyOf(arr, arr.length);

    5.5 Reversing

    for (int i = arr.length - 1; i >= 0; i--) {
    System.out.println(arr[i]);
    }

    5.6 Max and Min

    int max = arr[0];
    for (int num : arr) {
    if (num > max) max = num;
    }

    5.7 Adding/Removing (Concept)

    Arrays are fixed, so we create a new array.


    6. Array Utility Methods

    6.1 Arrays Class

    Java provides Arrays class in java.util package.

    6.2 Sorting

    import java.util.Arrays;
    Arrays.sort(arr);

    6.3 Searching

    Arrays.binarySearch(arr, 20);

    6.4 Comparing

    Arrays.equals(arr1, arr2);

    6.5 Filling

    Arrays.fill(arr, 0);

    6.6 Convert to String

    System.out.println(Arrays.toString(arr));

    Conclusion

    Arrays are a powerful and essential concept in Java that allow efficient data storage and manipulation. By understanding how to create, access, and perform operations on arrays, beginners can handle large amounts of data effectively and build more complex applications.

  • Methods in Java

    1. Introduction to Methods

    1.1 What is a Method

    A method is a block of code that performs a specific task and can be reused whenever needed.

    1.2 Importance of Methods

    • Reduces code repetition
    • Improves readability
    • Makes debugging easier

    1.3 Advantages

    • Code reusability
    • Modularity
    • Better organization

    1.4 Real-World Analogy

    A method is like a machine: you give input, it processes it, and gives output.


    2. Method Declaration and Definition

    2.1 Syntax

    returnType methodName(parameters) {
    // method body
    }

    2.2 Components

    • Access modifier (public, private)
    • Return type (int, void, etc.)
    • Method name
    • Parameters
    • Method body

    2.3 Example

    public static void greet() {
        System.out.println("Hello!");
    }

    2.4 Calling a Method

    greet();

    2.5 Static vs Non-Static

    • Static → called without object
    • Non-static → requires object

    3. Method Parameters

    3.1 What are Parameters

    Parameters are inputs passed to methods.

    3.2 Example

    public static void add(int a, int b) {
        System.out.println(a + b);
    }

    3.3 Calling with Arguments

    add(5, 3);

    3.4 Pass by Value

    Java always passes values, not references.

    3.5 Multiple Parameters

    You can pass multiple values:

    multiply(int x, int y, int z);

    4. Return Types

    4.1 What is Return Type

    Specifies what a method returns.

    4.2 void Method

    public static void show() {
        System.out.println("No return value");
    }

    4.3 Non-void Method

    public static int sum(int a, int b) {
        return a + b;
    }

    4.4 Returning Values

    int result = sum(5, 3);

    4.5 Multiple Values

    Use arrays or objects.


    5. Method Overloading

    5.1 Definition

    Method overloading means having multiple methods with the same name but different parameters.

    5.2 Example

    public static int add(int a, int b) {
        return a + b;
    }public static double add(double a, double b) {
        return a + b;
    }

    5.3 Rules

    • Must differ in parameters
    • Return type alone is not enough

    5.4 Benefits

    • Improves readability
    • Reuse method names

    6. Recursion

    6.1 What is Recursion

    A method calling itself is called recursion.

    6.2 Base Case

    Stops the recursion.

    6.3 Example (Factorial)

    public static int factorial(int n) {
        if (n == 1) {
            return 1;
        }
        return n * factorial(n - 1);
    }

    6.4 How it Works

    • Function calls itself
    • Keeps reducing problem
    • Stops at base case

    6.5 Example (Fibonacci)

    public static int fib(int n) {
        if (n <= 1) return n;
        return fib(n-1) + fib(n-2);
    }

    6.6 Advantages

    • Simple and clean code
    • Good for problems like trees

    6.7 Disadvantages

    • Can be slower
    • Uses more memory

    6.8 Recursion vs Loop

    • Recursion → function calls
    • Loop → iteration

    Conclusion

    Methods are one of the most powerful features in Java. They help break programs into smaller, reusable parts, making code easier to write, understand, and maintain. Concepts like parameters, return types, overloading, and recursion are essential for building efficient Java applications.

  • Control Flow Statements

    1. Introduction to Control Flow

    1.1 What are Control Flow Statements

    Control flow statements determine the order in which code is executed.

    1.2 Importance

    They help in:

    • Decision making
    • Repeating tasks
    • Controlling execution path

    1.3 Types

    • Conditional statements
    • Looping statements
    • Jump statements

    2. Conditional Statements

    2.1 Overview

    Conditional statements are used to execute code based on conditions.


    2.2 if Statement

    Syntax

    if (condition) {
    // code
    }

    Example

    int age = 20;
    if (age > 18) {
        System.out.println("Adult");
    }

    2.3 if-else Statement

    Syntax

    if (condition) {
    // true block
    } else {
    // false block
    }

    Example

    int num = 5;
    if (num % 2 == 0) {
        System.out.println("Even");
    } else {
        System.out.println("Odd");
    }
    
    if-else-if Ladder
    
    int marks = 75;if (marks >= 90) {
        System.out.println("Grade A");
    } else if (marks >= 75) {
        System.out.println("Grade B");
    } else {
        System.out.println("Grade C");
    }

    2.4 Nested if Statements

    Definition

    An if statement inside another if statement.

    Example

    int age = 20;
    boolean hasID = true;if (age > 18) {
        if (hasID) {
            System.out.println("Allowed");
        }
    }

    2.5 switch Statement

    Syntax

    switch (value) {
    case 1:
    // code
    break;
    case 2:
    // code
    break;
    default:
    // code
    }

    Example

    int day = 2;switch (day) {
        case 1:
            System.out.println("Monday");
            break;
        case 2:
            System.out.println("Tuesday");
            break;
        default:
            System.out.println("Other day");
    }

    Key Points

    • Uses break to stop execution
    • default executes if no case matches

    3. Looping Statements

    3.1 Introduction

    Loops are used to repeat a block of code multiple times.


    3.2 for Loop

    Syntax

    for (initialization; condition; update) {
    // code
    }

    Example

    for (int i = 1; i <= 5; i++) {
        System.out.println(i);
    }

    3.3 while Loop

    Syntax

    while (condition) {
    // code
    }

    Example

    int i = 1;while (i <= 5) {
        System.out.println(i);
        i++;
    }

    3.4 do-while Loop

    Syntax

    do {
    // code
    } while (condition);

    Example

    int i = 1;do {
        System.out.println(i);
        i++;
    } while (i <= 5);

    Difference

    • Executes at least once

    3.5 Enhanced for Loop

    Syntax

    for (type variable : array) {
    // code
    }

    Example

    int[] numbers = {1, 2, 3, 4};for (int num : numbers) {
        System.out.println(num);
    }

    4. Jump Statements

    4.1 Introduction

    Jump statements alter the normal flow of loops and methods.


    4.2 break Statement

    Definition

    Terminates the loop immediately.

    Example

    for (int i = 1; i <= 5; i++) {
        if (i == 3) {
            break;
        }
        System.out.println(i);
    }

    4.3 continue Statement

    Definition

    Skips the current iteration.

    Example

    for (int i = 1; i <= 5; i++) {
        if (i == 3) {
            continue;
        }
        System.out.println(i);
    }

    4.4 return Statement

    Definition

    Exits from a method.

    Example

    public static int add(int a, int b) {
        return a + b;
    }

    Conclusion

    Control flow statements are essential for building logical and interactive Java programs. By mastering conditional statements, loops, and jump statements, you can control how your program behaves and responds to different situations. These concepts form the foundation for solving real-world programming problems.

  • Operators in Java


    1. Introduction to Operators

    1.1 What are Operators

    Operators are symbols used to perform operations on variables and values.

    1.2 Types of Operators

    • Arithmetic
    • Assignment
    • Relational
    • Logical
    • Bitwise
    • Unary
    • Ternary

    1.3 Importance

    Operators help in:

    • Performing calculations
    • Making decisions
    • Writing logical conditions

    1.4 Operator Precedence

    Operators follow a priority order (e.g., multiplication before addition).


    2. Arithmetic Operators

    2.1 Overview

    Used for mathematical calculations.

    2.2 Addition (+)

    int sum = 10 + 5;

    2.3 Subtraction (-)

    int diff = 10 - 5;

    2.4 Multiplication (*)

    int product = 10 * 5;

    2.5 Division (/)

    int result = 10 / 5;

    2.6 Modulus (%)

    int remainder = 10 % 3;

    2.7 Example

    int a = 10, b = 3;
    System.out.println(a + b);
    System.out.println(a % b);

    2.8 Common Mistakes

    • Integer division removes decimals
    • Division by zero causes error

    3. Assignment Operators

    3.1 Definition

    Used to assign values to variables.

    3.2 Simple Assignment

    int x = 10;

    3.3 Compound Assignment

    x += 5;   // x = x + 5
    x -= 2;
    x *= 3;
    x /= 2;
    x %= 2;

    3.4 Chained Assignment

    int a, b, c;
    a = b = c = 10;

    4. Relational Operators

    4.1 Definition

    Used to compare two values.

    4.2 Operators

    10 == 10   // true
    10 != 5 // true
    10 > 5 // true
    10 < 5 // false
    10 >= 10 // true
    10 <= 5 // false

    4.3 Result

    • Always returns boolean (true/false)

    5. Logical Operators

    5.1 Definition

    Used to combine conditions.

    5.2 AND (&&)

    true && false   // false

    5.3 OR (||)

    true || false   // true

    5.4 NOT (!)

    !true   // false

    5.5 Example

    int age = 20;
    if (age > 18 && age < 30) {
        System.out.println("Eligible");
    }

    5.6 Short-Circuit

    • Stops evaluation early if result is already known

    6. Bitwise Operators

    6.1 Introduction

    Operate on binary (bit-level) values.

    6.2 Operators

    5 & 3   // AND
    5 | 3 // OR
    5 ^ 3 // XOR
    ~5 // Complement
    5 << 1 // Left shift
    5 >> 1 // Right shift

    6.3 Example

    int a = 5;   // 0101
    int b = 3; // 0011
    System.out.println(a & b); // 0001 → 1

    7. Unary Operators

    7.1 Definition

    Operate on a single operand.

    7.2 Increment (++)

    int x = 5;
    x++;

    7.3 Decrement (–)

    x--;

    7.4 Unary Plus and Minus

    int a = +10;
    int b = -10;

    7.5 Pre vs Post

    int x = 5;
    System.out.println(++x); // 6
    System.out.println(x++); // 6 (then becomes 7)

    8. Ternary Operator

    8.1 Definition

    A shortcut for if-else.

    8.2 Syntax

    condition ? value1 : value2;

    8.3 Example

    int age = 18;
    String result = (age >= 18) ? "Adult" : "Minor";

    8.4 Nested Ternary

    int num = 10;
    String res = (num > 0) ? "Positive" : (num < 0) ? "Negative" : "Zero";

    8.5 Best Practices

    • Keep it simple
    • Avoid complex nesting

    Conclusion

    Operators are essential in Java programming as they allow you to perform calculations, compare values, and control program logic. By understanding different types of operators and their usage, beginners can write more efficient and meaningful Java programs.