Java Tutorial in One Go: Complete Handbook Covering All Java Concepts


Java Tutorial in One Go: Complete Handbook Covering All Java Concepts


Java Introduction

What is Java?

Java, created in 1995, is a widely used programming language owned by Oracle. More than 3 billion devices run Java.

It is used for:

  • Mobile applications (especially Android apps)
  • Desktop applications
  • Web applications
  • Web servers and application servers
  • Games
  • Database connection
  • And much, much more!

Why Use Java?

  • Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
  • It is one of the most popular programming languages in the world
  • It has a large demand in the current job market
  • It is easy to learn and simple to use
  • It is open-source and free
  • It is secure, fast, and powerful
  • It has a huge community support (tens of millions of developers)
  • Java is an object-oriented language that gives a clear structure to programs and allows code to be reused, lowering development costs
  • As Java is close to C++ and C#, it makes it easy for programmers to switch to Java or vice versa.

How to Install Java

Some PCs might have Java already installed.

To check if you have Java installed on a Windows PC, search in the start bar for Java or type the following in Command Prompt (cmd.exe):

  C:\Users\Your Name>java -version 

If Java is installed, you will see something like this (depending on version):


java version "11.0.1" 2018-10-16 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.1+13-LTS)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.1+13-LTS, mixed mode)

If you do not have Java installed on your computer, you can download it for free at oracle.com.

Note: In this tutorial, we will write Java code in a text editor. However, it is possible to write Java in an Integrated Development Environment, such as IntelliJ IDEA, Netbeans, or Eclipse, which are particularly useful when managing larger collections of Java files.

Setup for Windows

To install Java on Windows:

  1. Go to "System Properties" (Can be found on Control Panel > System and Security > System > Advanced System Settings)
  2. Click on the "Environment variables" button under the "Advanced" tab
  3. Then, select the "Path" variable in System variables and click on the "Edit" button
  4. Click on the "New" button and add the path where Java is installed, followed by \bin. By default, Java is installed in C:\Program Files\Java\jdk-11.0.1 (If nothing else was specified when you installed it). In that case, You will have to add a new path with C:\Program Files\Java\jdk-11.0.1\bin
  5. Then, click "OK", and save the settings
  6. At last, open Command Prompt (cmd.exe) and type java -version to see if Java is running on your machine


Java Quickstart

In Java, every application begins with a class name, and that class must match the filename.

Let's create our first Java file, called Main.java, which can be done in any text editor (like Notepad or Visual Studio Code).

The file should contain a "Hello World" message, which is written with the following code:

Here's an example of how to display Java code in HTML:


        public class Main {
          public static void main(String[] args) {
            System.out.println("Hello World");
          }
        }
        


let's Run the code:

  • Open the integrated terminal in VSCode by selecting Terminal > New Terminal from the menu.
  • Compile your Java code by running the command javac Main.java in the terminal. This will create a Main.class file.
  • Run your Java program by executing the command java Main in the terminal. This will run your Java code, and you should see the output "Hello World" in the terminal.


Java Syntax

Java is a versatile and widely used programming language known for its simplicity and readability. Here's a basic overview of Java syntax:

1. Comments: Java supports single-line comments using // and multi-line comments using /* ... */.

// This is a single-line comment

/* This is
   a multi-line
   comment */


2. Package Declaration: The package statement, if used, must be the first statement in a Java source file.

 package com.example.myapp;


3. Import Statements: Import statements are used to bring classes and packages into scope.

import java.util.ArrayList;


4. Class Declaration: The class keyword is used to declare a class.

public class MyClass {
    // class body
}


5. Method Declaration: Methods are defined within a class using the method keyword.

public void myMethod() {
    // method body
}


6. Variables: Variables in Java must be declared with a specific type.

int myVariable = 10;


7. Control Flow Statements: Java supports various control flow statements like if, else, for, while, and switch.

  
if (condition) {
    // code to execute if condition is true
} else {
    // code to execute if condition is false
}

for (int i = 0; i < 5; i++) {
    // code to execute in each iteration
}

while (condition) {
    // code to execute as long as condition is true
}


8. Inheritance: Java supports single inheritance using the extends keyword.

public class ChildClass extends ParentClass {
    // class body
}


9. Interfaces: Interfaces define a contract for classes to implement.

public interface MyInterface {
    void myMethod();
}


10. Exception Handling: Java uses try, catch, and finally blocks for exception handling.

try {
    // code that may throw an exception
} catch (Exception e) {
    // handle the exception
} finally {
    // optional block of code that always executes
}

These are just some basic aspects of Java syntax. Java offers a wide range of features and capabilities that make it suitable for a variety of applications, from desktop to web and mobile development.


Java Output

Print Text

You learned that you can use the println() method to output values or print text in Java:

System.out.println("Hello World!"); 

You can add println() methods multiple times


System.out.println("Hello World!");
System.out.println("I am learning Java.");
System.out.println("Pratap Solution is the best resources");

When you are working with text, it must be wrapped inside double quotation marks "".


System.out.println("This sentence will work!");
System.out.println(This sentence will produce an error);


Print() Method

print() and println()are very similar. The only difference is that the print() function does not insert a new line at the end of the output. It always prints the text on the same line.

System.out.print("Hello world! ");
System.out.print("I will print on the same line");

Note: Make sure to add extra space for better readability like "Hello world! ".

For Printing Numbers

You can also use the println() method to print numbers. However, unlike text, we don't put numbers inside double quotes:

Example

System.out.println(3);
System.out.println(358);
System.out.println(50000);

You can perform mathematical calculations like println(3+3)

Example

System.out.println(3 + 3);
System.out.println(3 - 3);
System.out.println(3 * 5);

Data Types and Variables

What is a Variable?

  • Variable: Think of a variable as a box that can hold different kinds of things. For example, it can hold a number, a letter, or a true/false value.
  • Naming a Variable: Just like you give a name to your pet, you give a name to your variable so you can easily find out what's inside the box.

Primitive Data Types

Primitive data types are the basic building blocks in Java. Here are the most common ones:

1. int (Integer):

  • Holds whole numbers without any decimal point.
  • Example: int age = 14; This means the variable named "age" holds the number 14.

2. float (Floating Point):

  • Holds numbers with decimal points. It's like measuring weight or height.
  • Example: float height = 5.8f; This means the variable named "height" holds the number 5.8. The f at the end tells Java it's a float.

3. double:

  • Also holds numbers with decimal points but with more precision (more digits after the decimal point).
  • Example: double price = 19.99; This means the variable named "price" holds the number 19.99.

4. char (Character):

  • Holds a single letter or symbol.
  • Example:  char grade = 'A'; This means the variable named "grade" holds the letter A.

5. boolean:

  • Holds either true or false. It's like answering a yes/no question.
  • Example: boolean isRaining = true; This means the variable named "isRaining" holds the value true, indicating that it's raining.

Reference Data Types

Reference data types are a bit more complex and can hold more complex data structures.

1. Objects:

  • Objects are like containers that can hold multiple pieces of information. For example, a car object can have properties like colour, make, and model.
  • Example: Car myCar = new Car(); This creates a new object of type Car and assigns it to the variable "myCar".

2. Arrays:

  • Arrays are like lists that can hold multiple values of the same type. For example, an array of integers can hold multiple numbers.
  • Example: int[] numbers = {1, 2, 3, 4, 5}; This creates an array named "numbers" that holds five integers.

In simple terms, primitive data types are like basic building blocks, while reference data types are like containers that can hold more complex information. Understanding these concepts is essential for writing and understanding Java programs.

Declaring and Initializing Variables

Declaring Variables:

When you declare a variable, you're telling the computer to set aside some space in its memory to store a piece of information. It's like giving a name to a box where you can keep things.

For example, if you want to store a number, you can declare a variable like this:

int numbers;

Here, int tells the computer that the variable number will hold whole numbers (like 1, 2, 3, etc.).

Initializing Variables: 

Initializing a variable means giving it an initial value. It's like putting something inside the box you've named.

For example, to give the number variable a value of 5, you would do:

numbers = 5;

Now, the variable number has been declared and initialized with the value 5.

Declare Many Variables:

You can declare many variables by using commas;


int x = 5;
int y = 6;
int z = 50;
System.out.println(x + y + z);


We can also write like this:
int x = 5, y = 6, z = 50;
System.out.println(x + y + z);


We can also assign same value to multiple variable in one line:
int x, y, z;
x = y = z = 50;
System.out.println(x + y + z);


The general rules for naming variables are:

  • Names may contain letters, numerical, underscores, and dollar signs
  • Names have to start with a letter.
  • Names should start with a lowercase letter and they cannot contain whitespace
  • Names can also begin with $ and _ (but we will not use it in this tutorial)
  • Names are case sensitive ("myVar" and "myvar" are different variables)
  • Reserved words (like Java keywords, such as int or boolean) cannot be used as names

Type Casting

Type Casting: 

Type casting is when you convert a variable from one type to another. It's like changing the label on a box to say it's now for something else.

For example, let's say you have a variable num1 that's a whole number (int type), and you want to store it in a variable num2 that can hold decimal numbers (double type). You would do:


  int numbers = 10;
  double num2 = (double) num1;
  

Here, (double) is the typecast, which tells the computer to treat num1 as a double when assigning it to num2.

Operators in Java

1. Arithmetic Operators

  • Definition: Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, and division.
  • Examples:
    • Addition (+): 5 + 3 = 8
    • Subtraction (-): 10 - 4 = 6
    • Multiplication (*): 2 * 6 = 12
    • Division (/): 15 / 3 = 5
    • Modulus (%): 10 % 3 = 1 (remainder of 10 divided by 3)


2. Relational Operators

  • Definition: Relational operators are used to compare two values and determine the relationship between them.
  • Examples:
    • Greater than (>): 7 > 3 (true)
    • Less than (<): 5 < 2 (false)
    • Equal to (==): 4 == 4 (true)
    • Not equal to (!=): 6 != 6 (false)
    • Greater than or equal to (>=): 8 >= 8 (true)
    • Less than or equal to (<=): 9 <= 3 (false)


3. Logical Operators

  • Definition: Logical operators are used to combine multiple conditions and determine the overall result.
  • Examples:
    • AND (&&): true && true (true), true && false (false)
    • OR (||): true || false (true), false || false (false)
    • NOT (!): !true (false), !false (true)

4. Assignment Operators

  • Definition: Assignment operators are used to assign a value to a variable.
  • Examples:
    • : Assigns the value on the right to the variable on the left. int x = 5;
    • += : Adds the value on the right to the variable and assigns the result to the variable. x += 3; is the same as x = x + 3;
    • -= : Subtracts the value on the right from the variable and assigns the result to the variable. x -= 2; is the same as x = x - 2;
    • *= : Multiplies the variable by the value on the right and assigns the result to the variable. x *= 4; is the same as x = x * 4;
    • /= : Divides the variable by the value on the right and assigns the result to the variable. x /= 2; is the same as x = x / 2;
    • %= : Computes the modulus of the variable with the value on the right and assigns the result to the variable. x %= 3; is the same as x = x % 3;


5. Unary Operators

  • Definition: Unary operators act on a single operand.
  • Examples:
    • ++: Increments the value of the variable by 1. x++; is the same as x = x + 1;
    • --: Decrements the value of the variable by 1. x--; is the same as x = x - 1;
    • -: Negates the value of the variable. -x; negates the value of x.
    • +: Indicates the positive value of a variable. +x; is the same as x.


6. Ternary Operator

  • Definition: The ternary operator (conditional operator) evaluates a boolean expression and returns one of two values based on the result of the expression.
  • Syntax: condition ? value1 : value2
  • Example: int result = (x > 5) ? 10 : 5;
    • If x is greater than 5, result will be assigned the value 10. Otherwise, it will be assigned the value 5.


Example of Operators in Java


public class OperatorsExample {
    public static void main(String[] args) {
        // Arithmetic Operators
        int num1 = 10;
        int num2 = 5;
        int sum = num1 + num2;  // Addition
        int difference = num1 - num2;  // Subtraction
        int product = num1 * num2;  // Multiplication
        int quotient = num1 / num2;  // Division
        int remainder = num1 % num2;  // Modulus

        System.out.println("Arithmetic Operators:");
        System.out.println("Sum: " + sum);
        System.out.println("Difference: " + difference);
        System.out.println("Product: " + product);
        System.out.println("Quotient: " + quotient);
        System.out.println("Remainder: " + remainder);

        // Relational Operators
        boolean greaterThan = num1 > num2;  // Greater than
        boolean equalTo = num1 == num2;  // Equal to
        boolean notEqualTo = num1 != num2;  // Not equal to

        System.out.println("\nRelational Operators:");
        System.out.println("Greater than: " + greaterThan);
        System.out.println("Equal to: " + equalTo);
        System.out.println("Not equal to: " + notEqualTo);

        // Logical Operators
        boolean logicalAnd = (num1 > 0) && (num2 > 0);  // Logical AND
        boolean logicalOr = (num1 > 0) || (num2 > 0);  // Logical OR
        boolean logicalNot = !(num1 > 0);  // Logical NOT

        System.out.println("\nLogical Operators:");
        System.out.println("Logical AND: " + logicalAnd);
        System.out.println("Logical OR: " + logicalOr);
        System.out.println("Logical NOT: " + logicalNot);
        
        // Assignment Operators
        int num = 10;
        num += 5;  // num = num + 5
        System.out.println("Assignment Operators: " + num);

        // Unary Operators
        int x = 5;
        int result;
        result = +x;  // Unary plus, result is 5
        System.out.println("Unary Plus: " + result);
        result = -x;  // Unary minus, result is -5
        System.out.println("Unary Minus: " + result);
        boolean isTrue = true;
        boolean notTrue = !isTrue;  // Logical complement, result is false
        System.out.println("Logical Complement: " + notTrue);

        // Ternary Operator
        int a = 10;
        int b = 5;
        int max = (a > b) ? a : b;  // Ternary operator, max is 10
        System.out.println("Ternary Operator: " + max);
    }
}
  

Control Flow Statements

Control flow statements in Java are used to control the flow of the program, determining which lines of code should be executed next based on certain conditions. They help in making decisions and repeating tasks.

These are the  control flow statements:

  • If-Else Statements: It decides what to do based on the condition.
  • Switch Statements: It Choose from multiple options based on Value
  • For Loop: It repeats the code for a specific number of times.
  • While Loop: It Repeats the code as long as a condition is true.
  • Do-While Loop: Like a while loop, but always runs the code at least once.
  • Break Statement: Exit a loop or switch statement immediately
  • Continue Statements: Skip the current loop iteration and move to the next one.

Let's understand each of them one by one in a simple and easy-to-understand way:

If-Else Statements

If-Else statements let the program decide what to do based on certain conditions.

  • If the condition is true, do something.
  • Else (if the condition is false), do something else.

Example:


int number = 10;

if (number > 0) {
    System.out.println("The number is positive.");
} else {
    System.out.println("The number is not positive.");
}

 

This checks if number is greater than 0. If true, it prints "The number is positive." Otherwise, it prints "The number is not positive."

Switch Statement

A switch statement is used to perform different actions based on different conditions. It is a cleaner way of handling multiple if-else conditions.

Example:


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");
}

This checks the value of day and prints the corresponding day name. If day is 1, it prints "Monday", and so on. If none of the cases match, it prints "Invalid day".

For Loop

A for loop is used when you know how many times you want to repeat a block of code.

Example:


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

This prints the numbers from 1 to 5. It starts at 1 and repeats the code inside the loop, increasing i by 1 each time, until i is greater than 5.

While Loop

A while loop repeats a block of code as long as the condition is true.

Example:


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

This prints the numbers from 1 to 5. It keeps printing and increasing i by 1 until i is greater than 5.

Do-While Loop

A do-while loop is similar to a while loop, but it guarantees that the code block is executed at least once, even if the condition is false from the start.

Example:


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

This prints the numbers from 1 to 5. It runs the code block once before checking if i is less than or equal to 5, then repeats as long as the condition is true.

Break Statement

A break statement exits a loop or switch statement immediately.

Example:


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

This prints the numbers 1 and 2. When i becomes 3, the break statement stops the loop.

Continue Statement

A continue statement skips the current iteration of a loop and proceeds to the next iteration.

Example:


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

This prints the numbers 1, 2, 4, and 5. When i is 3, the continue statement skips the rest of the code in the loop for that iteration.

Java Arrays

An array in Java is a collection of variables of the same type. Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.

Creating an Array

To create an array, you must declare a variable of the desired array type and then instantiate it.

Syntax of an Array:


type[] arrayName = new type[size];

  • type: The data type of the array elements (e.g., int, String).
  • arrayName: The name of the array.
  • size: The number of elements the array can hold.

Example:


int[] numbers = new int[5];

This creates an array named numbers that can hold 5 integers.

Initializing an Array

You can initialize an array when you create it by providing values inside curly braces.

Example:


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

This creates an array named numbers and initializes it with the values 1, 2, 3, 4, and 5.

Accessing Array Elements

Array elements are accessed using their index. The index of the first element is 0.

Example:


int[] numbers = {1, 2, 3, 4, 5};
System.out.println(numbers[0]); // Outputs: 1
System.out.println(numbers[2]); // Outputs: 3

Changing Array Elements

You can change an element in an array by specifying the index and assigning a new value.

Example:


int[] numbers = {1, 2, 3, 4, 5};
numbers[2] = 10; // Changes the third element to 10
System.out.println(numbers[2]); // Outputs: 10


Array Length

You can find the length of an array (the number of elements it can hold) using the length property.

Example:

int[] numbers = {1, 2, 3, 4, 5};
System.out.println(numbers.length); // Outputs: 5



Iterating Through an Array

You can use a loop to iterate through all the elements of an array.

Example using for loop:


int[] numbers = {1, 2, 3, 4, 5};
for (int i = 0; i < numbers.length; i++) {
    System.out.println(numbers[i]);
}



Example using Enhanced for loop:

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



Example Program

Here is a complete program that demonstrates the creation, initialization, and iteration of an array:


public class Main {
    public static void main(String[] args) {
        // Declare and initialize an array
        int[] numbers = {1, 2, 3, 4, 5};

        // Access and print array elements
        System.out.println("First element: " + numbers[0]);
        System.out.println("Third element: " + numbers[2]);

        // Change an element
        numbers[2] = 10;

        // Print the updated element
        System.out.println("Updated third element: " + numbers[2]);

        // Print the length of the array
        System.out.println("Array length: " + numbers.length);

        // Iterate through the array using a for loop
        System.out.println("Array elements using for loop:");
        for (int i = 0; i < numbers.length; i++) {
            System.out.println(numbers[i]);
        }

        // Iterate through the array using an enhanced for loop
        System.out.println("Array elements using enhanced for loop:");
        for (int number : numbers) {
            System.out.println(number);
        }
    }
}



Key Ponts in Array:

  • Declaration: Arrays must be declared with a specific type.
  • Initialization: Arrays can be initialized with values at the time of declaration.
  • Accessing Elements: Use the index to access specific elements in the array.
  • Length: Use the length property to find out how many elements an array can hold.
  • Iteration: Use loops to iterate through array elements.

Java Methods

A method in Java is a block of code that performs a specific task. Methods help you to organize your code into manageable sections, make it reusable, and improve readability.

Why Method is Important: Understand by real-life example:

Scenario:  Suppose you want to make a sandwich.

Without using Methods:

  • Get bread
  • Spread butter on bread
  • Add cheese
  • Add ham
  • Put another slice of bread on top

Every time you want to make a sandwich, you have to remember and do all these steps.😩

With Methods:

  • You have a method called makeSandwich() that knows how to make a sandwich. Whenever you want a sandwich, you just call makeSandwich(), and it does everything for you. it makes your life easier.😊

Example in Programming

Without Method:😩


public class Main {
    public static void main(String[] args) {
        System.out.println("Sum of 5 and 3: " + (5 + 3));
        System.out.println("Sum of 7 and 2: " + (7 + 2));
        System.out.println("Sum of 10 and 5: " + (10 + 5));
    }
}


You write the addition code multiple times.

With Method:😃


public class Main {
    // Define a method to add two numbers
    public static int add(int a, int b) {
        return a + b;
    }

    public static void main(String[] args) {
        // Call the method whenever you need to add numbers
        System.out.println("Sum of 5 and 3: " + add(5, 3));
        System.out.println("Sum of 7 and 2: " + add(7, 2));
        System.out.println("Sum of 10 and 5: " + add(10, 5));
    }
}


You write the addition code once in the add method and reuse it.

Benefits of using Methods in Java:

  • Methods: Help organize, reuse, and manage your code effectively.
  • Simplicity: Make your code simpler and easier to understand.
  • Efficiency: This allows you to write less code and maintain it more easily.

Components of a Method

  1. Method Signature: This includes the method name and parameter list.
  2. Method Body: The block of code that performs the task.
  3. Return Type: The data type of the value the method returns. If it doesn't return a value, use void.
  4. Access Modifiers: These define the visibility of the method (e.g., public, private).

Defining Method

Syntax:

accessModifier returnType methodName(parameters) {
    // method body
}


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


Access Modifiers

  • public: The method can be accessed from any other class.
  • private: The method can only be accessed within the same class.
  • protected: The method can be accessed in the same package or subclasses.
  • default (no modifier): The method can be accessed within the same package.

Return Type

  • If the method returns a value, specify the data type (e.g., int, String).
  • If the method does not return a value, use void.

Method Name

  • Should be a meaningful name that describes what the method does.
  • Follow the camelCase naming convention (e.g., calculateSum).

Paramerters

  • Input values passed to the method.
  • Defined inside the parentheses in the method signature.
  • Can have zero or more parameters.

Example with Parameters:

public void greet(String name) {
    System.out.println("Hello, " + name);
}


Calling a Method

To execute the code inside a method, you need to call it from another method (like main) or another method within the same class.

Example :

public class Main {
    public static void main(String[] args) {
        Main obj = new Main();
        obj.greet("Alice");
    }

    public void greet(String name) {
        System.out.println("Hello, " + name);
    }
}


Method Overloading

You can have multiple methods with the same name but different parameters (type, number, or both).

Example :

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

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

    public static void main(String[] args) {
        Main obj = new Main();
        System.out.println(obj.add(5, 3));      // Calls the int version
        System.out.println(obj.add(5.5, 3.3));  // Calls the double version
    }
}


Static Methods

  • Belong to the class rather than any object instance.
  • Called using the class name.


Recursion

A method can call itself, which is known as recursion. It's useful for tasks that can be broken down into similar subtasks.

Example:

public class Main {
    public int factorial(int n) {
        if (n == 0) {
            return 1;
        } else {
            return n * factorial(n - 1);
        }
    }

    public static void main(String[] args) {
        Main obj = new Main();
        System.out.println("Factorial of 5: " + obj.factorial(5));
    }
}

Key Points

  • Method Declaration: Includes access modifiers, return type, method name, and parameters.
  • Method Invocation: Calling the method to execute its code.
  • Return Type: Defines what type of value the method returns (use void if it doesn't return anything).
  • Parameters: Input values passed to the method.
  • Overloading: Methods with the same name but different parameters.
  • Static Methods: Belong to the class, not instances of the class.
  • Recursion: A method calling itself.

Example Program:

Here’s a complete example that demonstrates defining, overloading, and calling methods:


public class Main {
    // Method to add two integers
    public int add(int a, int b) {
        return a + b;
    }

    // Method to add two double numbers
    public double add(double a, double b) {
        return a + b;
    }

    // Method to greet a user
    public void greet(String name) {
        System.out.println("Hello, " + name);
    }

    // Static method
    public static void display() {
        System.out.println("Static method called");
    }

    // Main method to test the other methods
    public static void main(String[] args) {
        Main obj = new Main();
        
        // Calling instance methods
        System.out.println("Sum of 5 and 3: " + obj.add(5, 3));
        System.out.println("Sum of 5.5 and 3.3: " + obj.add(5.5, 3.3));
        obj.greet("Alice");
        
        // Calling static method
        Main.display();
    }
}

Java Classes

What is class?

A class in Java is like a recipe 📜. It describes how to make something (an object) and what that thing can do.

Main Parts of a Class

1. Fields (Attributes):

  • These are like ingredients in the recipe. They describe the properties of the object.
  • Example: In a Car class, fields could be color, model, and speed.

2. Methods:

  • These are like steps in the recipe. They describe actions the object can perform.
  • Example: In a Car class, methods could be start(), stop(), and accelerate().

3. Constructor:

  • This is like the starting point of the recipe. It sets up the object with initial values.
  • Example: When you create a new car, the constructor sets its color and model.

Example of a class:

Imagine we are creating a class for a Car 🚗.

public class Car {
    // Fields (Attributes)
    String color;
    String model;
    int speed;

    // Constructor
    public Car(String color, String model) {
        this.color = color;
        this.model = model;
        this.speed = 0; // Default speed is 0 when a car is created
    }

    // Methods
    public void start() {
        System.out.println(model + " is starting.");
    }

    public void stop() {
        System.out.println(model + " is stopping.");
        speed = 0;
    }

    public void accelerate(int increase) {
        speed += increase;
        System.out.println(model + " is accelerating. Current speed: " + speed + " km/h");
    }
}


Creating and Using Objects

To use a class, you need to create objects from it. Think of objects as instances or actual examples made from the blueprint (class).

public class Main {
    public static void main(String[] args) {
        // Creating an object of the Car class
        Car myCar = new Car("Red", "Toyota");
        
        // Using the object's methods
        myCar.start();
        myCar.accelerate(50);
        myCar.stop();
    }
}



Real-Life Example

  • Blueprint 🏗️: A class is like a blueprint for a house. It defines what the house will look like (rooms, doors, windows) and what it can do (open door, close window).
  • House 🏡: An object is like an actual house built from the blueprint. Each house built from the same blueprint will have the same structure but can have different details (like paint color or furniture).

Key Points

  • Class: The blueprint/template that defines properties and behaviours.
  • Object: An instance of the class, like an actual item created from the blueprint.
  • Fields: Variables that hold the state or properties of the object.
  • Methods: Functions that define the behaviour of the object.
  • Constructor: Special method to initialize new objects.

Simple Example

Class: Dog 🐶

  • Fields: name, breed, age
  • Methods: bark(), fetch()

public class Dog {
    String name;
    String breed;
    int age;

    // Constructor
    public Dog(String name, String breed, int age) {
        this.name = name;
        this.breed = breed;
        this.age = age;
    }

    // Method to simulate barking
    public void bark() {
        System.out.println(name + " is barking!");
    }

    // Method to simulate fetching
    public void fetch() {
        System.out.println(name + " is fetching!");
    }
}



Creating and Using a Dog Object:

public class Main {
    public static void main(String[] args) {
        // Creating an object of the Dog class
        Dog myDog = new Dog("Buddy", "Golden Retriever", 3);
        
        // Using the object's methods
        myDog.bark();
        myDog.fetch();
    }
}


Summary of class

  • Classes are blueprints for objects.
  • Objects are instances created from classes.
  • Fields are attributes of the class.
  • Methods are actions the class can perform.
  • Constructors initialize new objects.

Using classes makes your code organized, reusable, and easier to understand, just like how using blueprints helps in building houses efficiently. 🏡✨


Java Object-Oriented Programming (OOP) Concepts

Why Use Object-Oriented Programming (OOP)?

1. Organizes Code 🗂️

  • Explanation: OOP helps to organize your code by grouping related data and functions into objects. This makes your code easier to manage and understand.
  • Example: Instead of having scattered functions for car-related tasks, you can have a Car class that contains all car-related methods and attributes.

2. Reusability 🔄

  • Explanation: OOP allows you to reuse code through inheritance. You can create a base class with common features and then extend it with more specific classes.
  • Example: Create a Vehicle class with general attributes and methods, and then extend it to create Car, Bike, and Truck classes with specific features.

3. Encapsulation 🔒

  • Explanation: Encapsulation keeps data safe from outside interference and misuse. You expose only what’s necessary through methods.
  • Example: In a Car class, you can make speed a private attribute and control access to it through public methods like accelerate() and getSpeed().

4. Polymorphism 🎭

  • Explanation: Polymorphism allows one interface to be used for different data types. It makes your code more flexible and scalable.
  • Example: You can write a function that takes a Vehicle type and call the drive() method, whether it's a Car, Bike, or Truck.

5. Abstraction 🕵️‍♂️

  • Explanation: Abstraction simplifies complex systems by showing only the necessary details and hiding the rest.
  • Example: You can have an abstract Animal class with an abstract method makeSound(), and let each specific animal class (like Dog, Cat) implement the sound in its own way.

6. Easier Maintenance and Modification 🛠️

  • Explanation: OOP makes it easier to update and maintain your code. Changes in one part of the code can be made with minimal impact on others.
  • Example: If you need to change how a Car accelerates, you only need to update the accelerate() method in the Car class, without affecting other parts of your code.

Real-Life Analogy

Imagine you’re organizing a library 📚:

  • Class: Think of each book category (like Fiction and non-fiction) as a class. It defines what properties (title, author) and methods (borrow, return) the books in that category will have.
  • Object: Each book is an object created from the class. A specific book like "Harry Potter" is an instance of the Fiction class.
  • Encapsulation: You keep the book's details (title, author) safe within the class and provide methods to access or modify those details.
  • Inheritance: You can create a base class Book and then extend it to create specific types like EBook or PrintedBook.
  • Polymorphism: You can have a general method read() that works differently for EBook (displaying on a screen) and PrintedBook (physical reading).
  • Abstraction: You only need to know how to use the book (borrow, read, return) without worrying about the complex systems behind library management.

OOP Concepts

Object-Oriented Programming (OOP) is a way to design and write programs using objects. Let's break down the main concepts:

1. Class 📚

  • Definition: A class is like a blueprint or a recipe. It defines what an object will look like and what it can do.
  • Example: Imagine a Car class. It defines attributes like color, model, and speed, and actions (methods) like start(), stop(), and accelerate().

2. Object 🚗

  • Definition: An object is an instance of a class. It's like a real car made from the Car blueprint.
  • Example: If Car is the class, then myCar is an object of that class.

Car myCar = new Car("Red", "Toyota");


3. Encapsulation 🛡️

  • Definition: Encapsulation means bundling the data (fields) and the methods that operate on the data into a single unit (class). It also means restricting access to some of the object's components.
  • Example: In the Car class, you might have a speed attribute that is private, and methods like accelerate() to change the speed. You can't directly change speed from outside the class; you have to use the method.

public class Car {
    private int speed;

    public void accelerate(int increase) {
        speed += increase;
    }

    public int getSpeed() {
        return speed;
    }
}



4. Inheritance 🧬

  • Definition: Inheritance allows one class to inherit the properties and methods of another class. It's like creating a new blueprint from an existing one and adding or modifying features.
  • Example: If you have a Vehicle class, you can create a Car class that inherits from Vehicle.

public class Vehicle {
    String color;
    String model;
}

public class Car extends Vehicle {
    int speed;

    public void start() {
        System.out.println(model + " is starting.");
    }
}


5. Polymorphism 🎭

  • Definition: Polymorphism means "many forms". It allows one interface to be used for a general class of actions. The specific action is determined by the exact nature of the situation.
  • Example: You can have a method drive() in a Vehicle class, and each subclass (Car, Bike) can have its own implementation of drive().

public class Vehicle {
    public void drive() {
        System.out.println("Vehicle is driving");
    }
}

public class Car extends Vehicle {
    @Override
    public void drive() {
        System.out.println("Car is driving");
    }
}

public class Bike extends Vehicle {
    @Override
    public void drive() {
        System.out.println("Bike is driving");
    }
}



6. Abstraction 🕵️‍♂️

  • Definition: Abstraction is the concept of hiding the complex implementation details and showing only the necessary features. It's like using a TV remote; you don't need to know how it works inside, just how to use it.
  • Example: Abstract classes and interfaces in Java allow you to define methods that must be created in any subclass.

abstract class Animal {
    abstract void makeSound();
}

class Dog extends Animal {
    @Override
    void makeSound() {
        System.out.println("Bark");
    }
}

class Cat extends Animal {
    @Override
    void makeSound() {
        System.out.println("Meow");
    }
}


Putting It All Together

Imagine you are building a simple zoo simulation:

  • Class: Create a blueprint for animals.
  • Object: Make specific animals like a lion, tiger, and bear.
  • Encapsulation: Keep each animal's data (like age and health) safe inside the class, with methods to access and update it.
  • Inheritance: Have a base class Animal and create subclasses like Lion, Tiger, and Bear.
  • Polymorphism: Use a general method makeSound() and let each animal type make its specific sound.
  • Abstraction: Create abstract methods that must be implemented by each specific animal, ensuring every animal has a sound.

By understanding these concepts, you can design and build flexible and maintainable programs. OOP helps you manage complexity by breaking down tasks into smaller, manageable pieces, just like how you organize your life by grouping similar tasks together.