unit:1 Introduction to java

What is java

Java is a high-level, object-oriented programming language known for its portability, security, and robustness. It was developed by James Gosling at Sun Microsystems (now owned by Oracle) and released in 1995.

Key Features of Java:

1. Platform Independence – Java follows the "Write Once, Run Anywhere" (WORA) principle, meaning Java code can run on any operating system with a Java Virtual Machine (JVM).

2. Object-Oriented – Everything in Java is based on objects and classes.

3. Secure – Java runs inside a sandboxed environment and has strong memory management.

4. Multi-threaded – Supports concurrent programming with built-in threading.

5. Automatic Garbage Collection – No need to manually manage memory; Java's Garbage Collector (GC) handles it.

6. Rich API & Libraries – Java provides extensive libraries for networking, database handling, GUI development, etc.

7. Used in Various Domains – Java is widely used in web development, mobile apps (Android), enterprise software, cloud computing, AI, and IoT.


Basics of Java Programming

Java is a high-level, object-oriented, and platform-independent programming language. Here’s a quick guide to its basics.

1. Setting Up Java

To start coding in Java, you need:

Java Development Kit (JDK) – Includes tools to compile and run Java programs.

Integrated Development Environment (IDE) – Examples: Eclipse, IntelliJ IDEA, or VS Code.

2. Writing Your First Java Program

A simple Java program that prints "Hello, World!":

// HelloWorld.java
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

Explanation:

public class HelloWorld → Defines a class named HelloWorld.

public static void main(String[] args) → The main method, where execution starts.

System.out.println("Hello, World!"); → Prints output to the console.

3. Basic Java Syntax

(a) Variables and Data Types

Java is a statically typed language, meaning every variable must have a data type.

int age = 25; // Integer
double price = 99.99; // Decimal number
char grade = 'A'; // Single character
boolean isJavaFun = true; // Boolean value
String name = "Samarth"; // String (sequence of characters)

(b) Operators

Java supports arithmetic, relational, and logical operators.

int a = 10, b = 5;
System.out.println(a + b); // Addition (15)
System.out.println(a - b); // Subtraction (5)
System.out.println(a * b); // Multiplication (50)
System.out.println(a / b); // Division (2)
System.out.println(a % b); // Modulus (0)

(c) Conditional Statements

if-else

int num = 10;
if (num > 0) {
    System.out.println("Positive Number");
} else {
    System.out.println("Negative Number");
}

Switch Case

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

(d) Loops

For Loop

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

While Loop

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

4. Functions (Methods)

Functions (methods) help in code reusability.

Program 
public class Example {
    // Method definition
    public static void greet() {
        System.out.println("Hello from Java!");
    }

    public static void main(String[] args) {
        greet(); // Calling the method
    }
}
5. Object-Oriented Programming (OOP)
Java is object-oriented, meaning everything revolves around classes and objects.

Program 
Class and Object Example

class Car {
    String brand = "Toyota";

    void honk() {
        System.out.println("Beep Beep!");
    }
}

public class Main {
    public static void main(String[] args) {
        Car myCar = new Car(); // Creating an object
        System.out.println(myCar.brand); // Accessing attribute
        myCar.honk(); // Calling method
    }
}

6. Exception Handling
Java provides a way to handle errors gracefully using try-catch.

Program 
try {
    int result = 10 / 0; // This will cause an error
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero!");
}

7. Taking User Input

Using Scanner to get input from the user.
Program:
import java.util.Scanner;

public class InputExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter your name: ");
        String name = scanner.nextLine();

        System.out.println("Hello, " + name + "!");
    }
}

Where to Go Next?

•Learn about Arrays & Collections (Lists, HashMaps, Sets).

•Explore Multithreading and File Handling.

•Build real-world projects like a Calculator, To-Do List, or Web Apps (Spring Boot).

Data types

 In Java, data types specify the kind of data that variables can hold. They are broadly categorized into primitive and non-primitive data types.

1. Primitive Data Types

Java defines eight primitive data types:

1. byte: 8-bit signed integer ranging from -128 to 127.

2. short: 16-bit signed integer ranging from -32,768 to 32,767.

3. int: 32-bit signed integer ranging from -2,147,483,648 to 2,147,483,647.

4. long: 64-bit signed integer ranging from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.

5. float: 32-bit floating-point number.

6. double: 64-bit floating-point number.

7. boolean: Represents two values: true or false.

8. char: 16-bit Unicode character.
Primitive types are predefined by the language and named by reserved keywords. 

2. Non-Primitive Data Types

Non-primitive data types, also known as reference types, include classes, interfaces, arrays, and strings. Unlike primitive types, they reference objects and can be null. For example, String is a class in Java that represents a sequence of characters.

Understanding these data types is fundamental to effective Java programming, as they determine the operations that can be performed on variables and the memory allocation.

Variables

Variables are used in programming to store data that can be changed and used throughout a program. A variable has a name, a value, and a data type.

Key Features of Variables:
1. Name (Identifier): A unique name to identify the variable.
2. Value: The actual data stored in the variable.
3. Data Type: The type of data the variable holds (e.g., integer, string, boolean).
4. Memory Allocation: The system assigns memory to store the variable.

Examples in Different Languages:

Python:

x = 10 # Integer
name = "Sam" # String
pi = 3.14 # Float
is_valid = True # Boolean

Java:

int x = 10;
String name = "Sam";
double pi = 3.14;
boolean isValid = true;

C++:

int x = 10;
string name = "Sam";
float pi = 3.14;
bool isValid = true;

Variable Naming Rules:

1. Can contain letters (a-z, A-Z), digits (0-9), and underscores (_).
2. Cannot start with a digit.
3. Cannot use reserved keywords (e.g., int, class, return in Java).
4. Case-sensitive (Name and name are different).


Operators

Operators in Java are special symbols or keywords used to perform operations on variables and values. Java provides different types of operators, categorized as follows:

1. Arithmetic Operators

These operators perform basic arithmetic operations:

👉+ (Addition)

👉- (Subtraction)

👉* (Multiplication)

👉/ (Division)

👉% (Modulus - Remainder)


Example:

int a = 10, b = 5;
System.out.println(a + b); // Output: 15
System.out.println(a % b); // Output: 0

2. Relational (Comparison) Operators

These operators compare values and return true or false:

👉== (Equal to)

👉!= (Not equal to)

👉> (Greater than)

👉< (Less than)

👉>= (Greater than or equal to)

👉<= (Less than or equal to)


Example:

int a = 10, b = 5;
System.out.println(a > b); // Output: true
System.out.println(a == b); // Output: false

3. Logical Operators

These operators perform logical operations:

👉&& (Logical AND)

👉|| (Logical OR)

👉! (Logical NOT)


Example:

boolean x = true, y = false;
System.out.println(x && y); // Output: false
System.out.println(x || y); // Output: true

4. Bitwise Operators

These operators work at the bit level:

👉& (Bitwise AND)

👉| (Bitwise OR)

👉^ (Bitwise XOR)

👉~ (Bitwise Complement)

👉<< (Left shift)

👉>> (Right shift)

👉>>> (Unsigned right shift)


Example:

int a = 5, b = 3;
System.out.println(a & b); // Output: 1
System.out.println(a | b); // Output: 7

5. Assignment Operators

Used to assign values to variables:

👉= (Assign)

👉+= (Add and assign)

👉-= (Subtract and assign)

👉*= (Multiply and assign)

👉/= (Divide and assign)

👉%= (Modulus and assign)


Example:

int a = 10;
a += 5; // Equivalent to a = a + 5;
System.out.println(a); // Output: 15

6. Unary Operators

Operators that work with a single operand:

👉 + (Positive)

👉@- (Negative)

👉++ (Increment)

👉-- (Decrement)

👉! (Logical NOT)


Example:

int a = 5;
System.out.println(++a); // Output: 6 (Pre-increment)
System.out.println(a--); // Output: 6 (Post-decrement)

7. Ternary Operator

A shorthand for if-else condition:

condition ? value_if_true : value_if_false


Example:

int a = 10, b = 20;
int min = (a < b) ? a : b;
System.out.println(min); // Output: 10

8. Instanceof Operator

Used to check whether an object is an instance of a particular class: Example:

String str = "Hello";
System.out.println(str instanceof String); // Output: true

9. Type Cast Operator

Used to convert one data type into another: Example:

double d = 10.5;
int a = (int) d; // Explicit casting
System.out.println(a); // Output: 10

Control Structures in Java

Control structures determine the flow of execution in a Java program. These are classified into three types:

1. Selection (Decision-Making) Statements
2. Iteration (Looping) Statements
3. Jump Statements
1. Selection (Decision-Making) Statements

Selection statements allow a program to choose different execution paths based on conditions.

a) if Statement

Executes a block of code if the condition is true.

Syntax:

if (condition) {
    // Code to execute if condition is true
}

Example:

int num = 10;
if (num > 0) {
    System.out.println("Positive number");
}


b) if-else Statement

Executes one block if the condition is true, otherwise executes another block.

Syntax:

if (condition) {
    // Code if condition is true
} else {
    // Code if condition is false
}

Example:

int num = -5;
if (num > 0) {
    System.out.println("Positive number");
} else {
    System.out.println("Negative number");
}

c) if-else if-else Statement

Used when multiple conditions need to be checked.

Syntax:

if (condition1) {
    // Code if condition1 is true
} else if (condition2) {
    // Code if condition2 is true
} else {
    // Code if none of the conditions are true
}

Example:

int marks = 85;
if (marks >= 90) {
    System.out.println("Grade: A+");
} else if (marks >= 75) {
    System.out.println("Grade: A");
} else if (marks >= 50) {
    System.out.println("Grade: B");
} else {
    System.out.println("Fail");
}

d) switch Statement

Used when a variable is compared against multiple values.

Syntax:

switch (expression) {
    case value1:
        // Code for value1
        break;
    case value2:
        // Code for value2
        break;
    default:
        // Code if no case matches
}

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


Looping

Loops in Java allow executing a block of code multiple times. Java provides three types of loops:

1. for Loop (Used when the number of iterations is known)

2. while Loop (Used when the number of iterations is unknown)

3. do-while Loop (Executes at least once before checking the condition)

1. for Loop

The for loop is used when we know how many times we need to execute a statement.

Syntax:

for (initialization; condition; update) {
    // Code to execute
}

Example:

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

Output:

Iteration: 1  
Iteration: 2  
Iteration: 3  
Iteration: 4  
Iteration: 5

Variations of for Loop

a) Enhanced for Loop (for-each loop)

Used to iterate through arrays or collections.

Example:

int[] numbers = {10, 20, 30, 40, 50};
for (int num : numbers) {
    System.out.println(num);
}

Output:

10  
20  
30  
40  
50

b) Infinite for Loop

A for loop can run indefinitely if no condition is given.

for (;;) {
    System.out.println("Infinite Loop");
}

2. while Loop

The while loop is used when the number of iterations is not known beforehand. It checks the condition before executing the loop body.

Syntax:

while (condition) {
    // Code to execute
}

Example:

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

Output:

Iteration: 1  
Iteration: 2  
Iteration: 3  
Iteration: 4  
Iteration: 5

Infinite while Loop

If the condition is always true, the loop will run indefinitely.

while (true) {
    System.out.println("Infinite Loop")

}

3. do-while Loop

The do-while loop executes at least once before checking the condition.

Syntax:

do {
    // Code to execute
} while (condition);

Example:

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

Output:

Iteration: 1  
Iteration: 2  
Iteration: 3  
Iteration: 4  
Iteration: 5

Difference Between while and do-while Loops

4. Nested Loops

A loop inside another loop is called a nested loop.

Example:

for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) {
        System.out.print(i + "," + j + " ");
    }
    System.out.println();
}

Output:

1,1 1,2 1,3  
2,1 2,2 2,3  
3,1 3,2 3,3


5. Jump Statements in Loops

a) break Statement

Stops the loop execution immediately.

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

Output:
1  
2

b) continue Statement

Skips the current iteration and moves to the next one.

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

Output:

1  
2  
4  
5

Java Methods

A method in Java is a block of code that performs a specific task. Methods help in code reusability, organization, and readability.


1. Types of Methods in Java

Java methods can be classified into:

1. Predefined Methods (Built-in methods like Math.sqrt(), System.out.println(), etc.)

2. User-Defined Methods (Methods created by the programmer)

2. Defining a Method in Java

A method consists of:

Method Name (Identifies the method)

Return Type (Specifies the type of value the method returns)

Parameters (Optional) (Input values passed to the method)

Method Body (Code that executes when the method is called)


Syntax:

returnType methodName(parameters) {
    // Method body
    return value; // (if returnType is not void)
}

3. Example of a Simple Method

public class Example {
    // Method without parameters
    static void sayHello() {
        System.out.println("Hello, Java!");
    }

    public static void main(String[] args) {
        sayHello(); // Calling the method
    }
}

Output:

Hello, Java!


4. Methods with Parameters and Return Values

a) Method with Parameters

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

    public static void main(String[] args) {
        greet("Samarth"); // Calling method with argument
    }
}

Output:

Hello, Samarth!

b) Method with Return Value

public class Example {
    static int square(int num) {
        return num * num;
    }

    public static void main(String[] args) {
        int result = square(5);
        System.out.println("Square: " + result);
    }
}

Output:

Square: 25

5. Method Overloading

Java allows multiple methods with the same name but different parameters (type/number).

Example:

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

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

    public static void main(String[] args) {
        System.out.println(add(5, 10)); // Calls int method
        System.out.println(add(5.5, 2.5)); // Calls double method
    }
}

Output:

15  
8.0


6. Static vs. Non-Static Methods

Static Methods can be called without creating an object. (static keyword is used)

Non-Static Methods require an object to be called.


Example of a Non-Static Method:

public class Example {
    void display() {
        System.out.println("Non-Static Method Called");
    }

    public static void main(String[] args) {
        Example obj = new Example(); // Creating an object
        obj.display(); // Calling non-static method
    }
}

Output:

Non-Static Method Called

7. Method with Variable Arguments (varargs)

Java allows methods to accept variable numbers of arguments using ... (three dots).

Example:

public class VarargsExample {
    static void printNumbers(int... nums) {
        for (int num : nums) {
            System.out.print(num + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        printNumbers(1, 2, 3);
        printNumbers(10, 20, 30, 40, 50);
    }
}

Output:

1 2 3  
10 20 30 40 50

8. Recursive Methods

A method that calls itself is called recursion.

Example: Factorial Using Recursion

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

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

Output:

Factorial of 5: 120

Arrays in Java

An array in Java is a data structure that stores multiple values of the same data type in a single variable.


1. Declaring and Initializing Arrays

a) Declaration

dataType[] arrayName;

OR

dataType arrayName[];

b) Initialization

dataType[] arrayName = new dataType[size];  // Creating an array

c) Combining Declaration and Initialization

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

Example:

public class ArrayExample {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};  
        System.out.println(numbers[0]); // Accessing first element
    }
}

Output:

1

2. Accessing Array Elements

Array elements are accessed using index numbers, starting from 0.

Example:

public class AccessArray {
    public static void main(String[] args) {
        int[] arr = {10, 20, 30, 40, 50};
        System.out.println("First element: " + arr[0]); 
        System.out.println("Last element: " + arr[arr.length - 1]); 
    }
}

Output:

First element: 10  
Last element: 50  

3. Iterating Through an Array

a) Using for Loop

public class ArrayLoop {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}

Output:

1 2 3 4 5

b) Using for-each Loop

public class ForEachExample {
    public static void main(String[] args) {
        int[] arr = {10, 20, 30, 40, 50};
        for (int num : arr) {
            System.out.print(num + " ");
        }
    }
}

Output:

10 20 30 40 50

4. Multi-Dimensional Arrays

a) Declaration and Initialization

int[][] matrix = {
    {1, 2, 3}, 
    {4, 5, 6}, 
    {7, 8, 9}
};

b) Accessing Multi-Dimensional Arrays

public class MultiDimArray {
    public static void main(String[] args) {
        int[][] matrix = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };
        System.out.println("Element at [1][2]: " + matrix[1][2]); // 6
    }
}

Output:

Element at [1][2]: 6

c) Iterating Through a Multi-Dimensional Array

public class MultiDimIteration {
    public static void main(String[] args) {
        int[][] matrix = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
    }
}

Output:

1 2 3  
4 5 6  
7 8 9  

5. Common Array Operations

a) Finding Maximum and Minimum

public class MaxMinArray {
    public static void main(String[] args) {
        int[] arr = {5, 10, 3, 8, 2};
        int max = arr[0], min = arr[0];

        for (int num : arr) {
            if (num > max) max = num;
            if (num < min) min = num;
        }

        System.out.println("Max: " + max);
        System.out.println("Min: " + min);
    }
}

Output:

Max: 10  
Min: 2  

b) Sorting an Array

import java.util.Arrays;

public class SortArray {
    public static void main(String[] args) {
        int[] arr = {5, 10, 3, 8, 2};
        Arrays.sort(arr); // Sorts the array in ascending order
        System.out.println("Sorted Array: " + Arrays.toString(arr));
    }
}

Output:

Sorted Array: [2, 3, 5, 8, 10]

6. Copying an Array

a) Using Loop

public class CopyArray {
    public static void main(String[] args) {
        int[] original = {1, 2, 3, 4, 5};
        int[] copy = new int[original.length];

        for (int i = 0; i < original.length; i++) {
            copy[i] = original[i];
        }

        System.out.println("Copied Array: " + Arrays.toString(copy));
    }
}

b) Using Arrays.copyOf()

int[] copy = Arrays.copyOf(original, original.length);

7. Searching in an Array

a) Linear Search

public class LinearSearch {
    public static void main(String[] args) {
        int[] arr = {10, 20, 30, 40, 50};
        int key = 30;
        boolean found = false;

        for (int num : arr) {
            if (num == key) {
                found = true;
                break;
            }
        }

        if (found)
            System.out.println(key + " found in array.");
        else
            System.out.println(key + " not found.");
    }
}

b) Binary Search (Only for Sorted Arrays)

import java.util.Arrays;

public class BinarySearchExample {
    public static void main(String[] args) {
        int[] arr = {10, 20, 30, 40, 50};
        int key = 30;
        int index = Arrays.binarySearch(arr, key);

        if (index >= 0)
            System.out.println(key + " found at index " + index);
        else
            System.out.println(key + " not found.");
    }












I/O programming

Unit 5 -syllabus  Text and binary I/O,Binary I./O classes, Object I/O, Random Access files, multithreading in java: thread life cycle and m...