unit:2 Objects and class

Basic Objects and Classes in Java

In Java, classes and objects are fundamental building blocks of Object-Oriented Programming (OOP).


1. What is a Class?

A class is a blueprint for creating objects. It defines properties (fields) and behaviors (methods) of an object.

Syntax of a Class:

class Car {
    // Fields (Properties)
    String brand;
    int speed;
    
    // Method (Behavior)
    void showDetails() {
        System.out.println("Brand: " + brand);
        System.out.println("Speed: " + speed + " km/h");
    }
}

2. What is an Object?

An object is an instance of a class. It is created using the new keyword.

Creating an Object:

public class Main {
    public static void main(String[] args) {
        // Creating an object of the Car class
        Car myCar = new Car();
        
        // Assigning values to object properties
        myCar.brand = "Toyota";
        myCar.speed = 120;
        
        // Calling method
        myCar.showDetails();
    }
}

Output:

Brand: Toyota
Speed: 120 km/h

3. Key Concepts Related to Classes and Objects

✨Encapsulation: Wrapping data (fields) and methods together in a class.

✨Abstraction: Hiding implementation details and exposing only necessary features.

✨Inheritance: Acquiring properties and behaviors from another class.

✨Polymorphism: Ability to take multiple forms (e.g., method overloading and overriding).

Constructors 

A constructor in Java is a special method used to initialize objects. It is automatically called when an object is created.

1. Features of a Constructor

💫Has the same name as the class.

💫Does not have a return type (not even void).

💫Can have parameters or be parameterless (default constructor).

💫Used to initialize object properties.

2. Types of Constructors in Java

(a) Default Constructor

A constructor with no parameters. It initializes default values.

Example:

class Car {
    String brand;
    int speed;

    // Default Constructor
    Car() {
        brand = "Unknown";
        speed = 0;
    }

    void display() {
        System.out.println("Brand: " + brand);
        System.out.println("Speed: " + speed + " km/h");
    }
}

public class Main {
    public static void main(String[] args) {
        Car myCar = new Car(); // Default constructor is called
        myCar.display();
    }
}

Output:

Brand: Unknown
Speed: 0 km/h

(b) Parameterized Constructor

A constructor that takes arguments to initialize object properties.

Example:

class Car {
    String brand;
    int speed;

    // Parameterized Constructor
    Car(String b, int s) {
        brand = b;
        speed = s;
    }

    void display() {
        System.out.println("Brand: " + brand);
        System.out.println("Speed: " + speed + " km/h");
    }
}

public class Main {
    public static void main(String[] args) {
        Car myCar = new Car("Toyota", 120); // Passing values
        myCar.display();
    }
}

Output:

Brand: Toyota
Speed: 120 km/h

(c) Copy Constructor

A constructor that copies values from another object.

Example:

class Car {
    String brand;
    int speed;

    // Parameterized Constructor
    Car(String b, int s) {
        brand = b;
        speed = s;
    }

    // Copy Constructor
    Car(Car obj) {
        brand = obj.brand;
        speed = obj.speed;
    }

    void display() {
        System.out.println("Brand: " + brand);
        System.out.println("Speed: " + speed + " km/h");
    }
}

public class Main {
    public static void main(String[] args) {
        Car car1 = new Car("Honda", 150); // Original object
        Car car2 = new Car(car1); // Copy constructor is called

        car1.display();
        car2.display();
    }
}

Output:

Brand: Honda
Speed: 150 km/h
Brand: Honda
Speed: 150 km/h


3. Constructor Overloading

Multiple constructors with different parameters in the same class.

Example:

class Car {
    String brand;
    int speed;

    // Default Constructor
    Car() {
        brand = "Unknown";
        speed = 0;
    }

    // Parameterized Constructor
    Car(String b, int s) {
        brand = b;
        speed = s;
    }

    void display() {
        System.out.println("Brand: " + brand);
        System.out.println("Speed: " + speed + " km/h");
    }
}

public class Main {
    public static void main(String[] args) {
        Car car1 = new Car(); // Calls default constructor
        Car car2 = new Car("Ford", 180); // Calls parameterized constructor

        car1.display();
        car2.display();
    }
}

Output:

Brand: Unknown
Speed: 0 km/h
Brand: Ford
Speed: 180 km/h

4. Why Use Constructors?

💫Ensures object initialization during creation.

💫Eliminates the need to call a separate method for assigning values.

💫Provides flexibility using constructor overloading.

Visibility modifiers

In Java, visibility modifiers (also known as access modifiers) define the scope and accessibility of classes, variables, methods, and constructors. Java provides four main visibility modifiers:

1. private

✨Accessible only within the same class.

✨Not accessible outside the class, even in subclasses.

✨Commonly used for encapsulation (data hiding).


class Example {
    private int data = 10; // private variable

    private void display() { // private method
        System.out.println("Data: " + data);
    }
}

2. default (no modifier)

✨Accessible only within the same package.

✨If no access modifier is specified, it is treated as default.

✨Not accessible outside the package, even in subclasses.


class Example { // default class
    int data = 20; // default variable

    void display() { // default method
        System.out.println("Data: " + data);
    }
}

3. protected
✨Accessible within the same package.
✨Also accessible in subclasses (even in different packages).
✨Commonly used in inheritance.

class Example {
    protected int data = 30; // protected variable

    protected void display() { // protected method
        System.out.println("Data: " + data);
    }
}

4. public

✨Accessible from anywhere, inside or outside the package.

✨No restrictions on access.


public class Example {
    public int data = 40; // public variable

    public void display() { // public method
        System.out.println("Data: " + data);
    }
}



Methods and Objects in Java

In Java, methods define behavior, while objects are instances of classes that store data and invoke methods.


1. Objects in Java

An object is an instance of a class that contains state (fields/variables) and behavior (methods).

Creating an Object

Objects are created using the new keyword.

class Car {
    String brand = "Toyota"; // Instance variable

    void showBrand() { // Method
        System.out.println("Car brand: " + brand);
    }
}

public class Main {
    public static void main(String[] args) {
        Car myCar = new Car(); // Object creation
        myCar.showBrand(); // Calling a method
    }
}

Output:

Car brand: Toyota

2. Methods in Java

A method is a block of code that performs a specific task. It can be called (invoked) on an object.

Types of Methods

  1. Instance Methods – Operate on object data.
  2. Static Methods – Belong to the class, not an object.
  3. Parameterized Methods – Accept parameters to process values.
  4. Return Type Methods – Return a value.

Example of Different Method Types

class Calculator {
    // Instance method
    int add(int a, int b) {
        return a + b;
    }

    // Static method
    static void greet() {
        System.out.println("Welcome to the Calculator!");
    }
}

public class Main {
    public static void main(String[] args) {
        Calculator calc = new Calculator(); // Object creation
        int result = calc.add(5, 3); // Calling instance method
        System.out.println("Sum: " + result);

        Calculator.greet(); // Calling static method without object
    }
}

Output:

Sum: 8  
Welcome to the Calculator
Inbuilt Classes in Java (Like String)
Java provides several built-in classes in its standard library (java.lang package) to handle common functionalities. One of the most commonly used built-in classes is String.

1. The String Class in Java
A String in Java is an immutable sequence of characters. It is part of the java.lang package, so no import is needed.
Creating Strings
There are two ways to create a String:
1. Using String Literal (Stored in String Pool)
String str1 = "Hello";
2. Using new Keyword (Stored in Heap)
String str2 = new String("Hello");
2. Important Methods of String Class

Example Usage

public class Main {
    public static void main(String[] args) {
        String s = "  Java Programming  ";
        
        System.out.println("Length: " + s.length()); // 20
        System.out.println("Uppercase: " + s.toUpperCase()); // JAVA PROGRAMMING
        System.out.println("Trimmed: " + s.trim()); // "Java Programming"
        System.out.println("Substring: " + s.substring(2, 6)); // "Java"
        System.out.println("Contains 'Java': " + s.contains("Java")); // true
    }
}

Output:

Length: 20
Uppercase: JAVA PROGRAMMING
Trimmed: Java Programming
Substring: Java
Contains 'Java': true

3. Other Important Built-in Classes
Apart from String, Java provides several built-in classes:
Would you like more details on any of these classes?

Character 

In Java, the char data type 
represents a single character and
is 2 bytes (16 bits) in size 
because it uses Unicode (which 
supports international characters).

1. Declaring a char Variable
char letter = 'A'; // Single 
character (in single quotes)
char digit = '5';
char symbol = '#';

2. ASCII and Unicode Representation
Since char uses Unicode, you can 
assign values using Unicode escape 
sequences (\uXXXX):
char unicodeChar = '\u0041'; // Unicode for 'A'
System.out.println(unicodeChar); // Output: A
ASCII characters (e.g., 'A', '1') are a subset of Unicode.
Unicode allows international characters like 'अ' (Hindi) or '你' (Chinese).

3. Useful Character Class Methods (java.lang.Character)
Java provides a wrapper class Character with helpful methods.

4. Example: Using Character Class Methods
public class Main {
    public static void main(String[] args) {
        char ch = 'a';

        System.out.println("Is letter? " + Character.isLetter(ch)); // true
        System.out.println("Is digit? " + Character.isDigit(ch)); // false
        System.out.println("Uppercase: " + Character.toUpperCase(ch)); // 'A'
    }
}

Output:

Is letter? true
Is digit? false
Uppercase: A

5. Converting char to int (ASCII/Unicode)
You can convert a character to its ASCII/Unicode value:
char ch = 'A';
int asciiValue = ch; // Implicit conversion
System.out.println(asciiValue); // Output: 65

To convert a digit character to an integer:
char digit = '7';
int num = Character.getNumericValue(digit);
System.out.println(num); // Output: 7


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...