0% found this document useful (0 votes)
7 views71 pages

Java Objects and Classes Explained

Chapter Two discusses the concept of objects and classes in Java, highlighting that an object is an instance of a class representing a real-world entity with state, behavior, and identity. It explains how to define classes, create objects, and the importance of modularity in code organization. Additionally, it covers anonymous objects, instance variables, and methods, providing examples to illustrate these concepts.

Uploaded by

mekashfetene89
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views71 pages

Java Objects and Classes Explained

Chapter Two discusses the concept of objects and classes in Java, highlighting that an object is an instance of a class representing a real-world entity with state, behavior, and identity. It explains how to define classes, create objects, and the importance of modularity in code organization. Additionally, it covers anonymous objects, instance variables, and methods, providing examples to illustrate these concepts.

Uploaded by

mekashfetene89
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter Two

Object and Class

Object in Object-Oriented Programming (OOP) - Java

What is an Object in Java?

An object in Java is an instance of a class that represents a real-world entity. Objects are key to
understanding object-oriented technology. An entity that has state and behavior is known as an
object for instance chair, bike, marker, pen, table, car etc. It can be physical or logical (tangible
and intangible). The example of intangible object is banking system.

It consists of:

1. State (Attributes/Fields/Properties)
o Represented by instance variables (data members).
o Stores object-specific information.
o represents data (value) of an object.
2. Behavior (Methods/Functions)
o Represented by functions (methods).
o Defines actions that the object can perform.
o Represents the behavior (functionality) of an object such as deposit, withdraw etc.
3. Identity (Unique Existence in Memory)
o Every object has a unique memory location.
o Multiple objects of the same class can exist independently.
o Object identity is typically implemented via a unique ID. The value of the ID is
not visible to the external user. But, it is used internally by the JVM to identify
each object uniquely.

Example of Object in Java

Let's define a class Car and create objects from it.

// Defining the class (Blueprint)

1|Page
class Car {
// Instance Variables (Attributes)
String brand;
String model;
String color;

// Constructor (To Initialize Objects)


Car(String brand, String model, String color) {
[Link] = brand;
[Link] = model;
[Link] = color;
}

// Method (Behavior)
void displayInfo() {
[Link]("Car Brand: " + brand + ", Model: " + model + ", Color: " + color);
}
}

// Main Class to Create and Use Objects


public class Main {
public static void main(String[] args) {
// Creating Objects (Instances of Car Class)
Car car1 = new Car("Toyota", "Camry", "Red");
Car car2 = new Car("Honda", "Civic", "Blue");

// Accessing Object Methods


[Link](); // Output: Car Brand: Toyota, Model: Camry, Color: Red
[Link](); // Output: Car Brand: Honda, Model: Civic, Color: Blue
}
}

2|Page
Explanation of Java Object Example

1. Class Definition (Car)


o The class Car acts as a blueprint.
o It contains instance variables (brand, model, color).
o It has a constructor to initialize object properties.
2. Creating Objects (car1, car2)
o new Car("Toyota", "Camry", "Red") creates an instance of Car.
o Each object has independent attribute values.
3. Method Execution (displayInfo())
o Each object can call displayInfo(), which prints its details

Real-World Analogy

Think of a class as a blueprint and objects as houses built from the blueprint:

 Class (Car): Defines how a car should be structured.


 Object (car1, car2): Different cars (Toyota, Honda) with specific details.

How Java Stores Objects in Memory

 Objects are stored in the Heap Memory. Heap memory is largest memory area in JVM.
It used to store objects and class instances. Garbage Collector (GC) automatically
removes unused objects to free up space
 References (car1, car2) point to objects in the heap.

Example:

Car car1 = new Car("Toyota");

 car1 holds a reference to the Car object in heap memory.

3|Page
Different Ways to Create Objects in Java

1. Using new Keyword (Most Common)

Car car1 = new Car("Toyota", "Camry", "Red");

 Allocates memory dynamically.

2. Using newInstance() (Reflection API)

Car car2 = [Link]().newInstance();

 Less common, used for dynamic object creation.

3. Using clone() Method

Car car3 = (Car) [Link]();

 Creates a copy of an existing object.

4. Using Serialization and Deserialization

 Objects can be converted to a byte stream and then recreated.

Important Concepts Related to Objects

1. this Keyword

 Refers to the current object instance.


 Example:

[Link] = brand;

2. Garbage Collection

 Java automatically deallocates unused objects.


 Example:

4|Page
car1 = null; // Eligible for garbage collection

3. Object Passing in Methods

 Objects can be passed as arguments.

void modifyCar(Car c) {
[Link] = "Black"; // Modifies the object
}

Software objects
Software objects are conceptually similar to real-world. Objects: they too consist of state and
related behavior. An object stores its state in fields (variables in some programming languages)
and exposes its behavior through methods (functions in some programming languages). Methods
operate on an object's internal state and serve as the primary mechanism for object-to-object
communication

Bundling code into individual software objects provides a number of benefits, including:

5|Page
Modularity in Java refers to the structuring of code into separate, reusable, and independent
components (modules). It improves code organization, maintainability, and reusability.

Key Benefits of Modularity:

Code Reusability – Components can be reused across multiple projects.


Maintainability – Easier to debug and update code.
Scalability – Large applications can be built by integrating small modules.
Readability – Clear separation of concerns.
Encapsulation – Hides implementation details from other modules.

Example: Basic Modular Design Using Classes

// Separate class (module) for user data

class User {

private String name;

private int age;

public User(String name, int age) {

[Link] = name;

[Link] = age;

public void displayUser() {

[Link]("User: " + name + ", Age: " + age);

6|Page
// Main class (Separate module)

public class Main {

public static void main(String[] args) {

User user1 = new User("Alice", 25);

[Link](); // Output: User: Alice, Age: 25

Example: Creating and Using Packages

Step 1: Create a Package (UserModule)

package UserModule; // Declaring package

public class User {

private String name;

public User(String name) {

[Link] = name;

public void displayUser() {

[Link]("User: " + name);

7|Page
Step 2: Import and Use the Package in another Class

import [Link]; // Importing package

public class Main {

public static void main(String[] args) {

User user1 = new User("John");

[Link](); // Output: User: John

Anonymous Object in Java


What is an Anonymous Object?

An anonymous object is an object that is created without being assigned to a reference


variable. It is generally used when an object is needed only once.

Key Characteristics:

1. No Reference Variable – The object is created but not stored in a variable.


2. Short-Lived – The object is used immediately and then becomes eligible for garbage collection.
3. Commonly Used For:
o Method arguments
o Single-use instances
o Anonymous classes (for implementing interfaces or overriding methods)

Example 1: Using an Anonymous Object in a Method Call


class Calculator {
void square(int num) {
[Link]("Square: " + (num * num));
}
}

8|Page
public class Main {
public static void main(String[] args) {
new Calculator().square(5); // Anonymous object used to call square method
}
}

 new Calculator().square(5);
o Creates an object of Calculator without assigning it to a variable.
o Calls the square() method with the argument 5.
o The object is not reusable and will be destroyed after execution.

Example 2: Passing an Anonymous Object as a Method Argument


class Printer {
void printMessage(Message msg) {
[Link]();
}
}

class Message {
void show() {
[Link]("Hello from an Anonymous Object!");
}
}

public class Main {


public static void main(String[] args) {
Printer printer = new Printer();
[Link](new Message()); // Passing an anonymous object
}
}

 new Message() is created and directly passed as a method argument.


 The method printMessage() calls show() on the temporary Message object.

Example 3: Using an Anonymous Object in an Anonymous Class

An anonymous class is an unnamed class that is declared and instantiated in a single expression.

abstract class Animal {


abstract void makeSound();
}

9|Page
public class Main {
public static void main(String[] args) {
// Anonymous object of an anonymous class
new Animal() {
void makeSound() {
[Link]("Woof! Woof! (Anonymous Object)");
}
}.makeSound(); // Calls method immediately
}
}

 new Animal() { ... } creates an anonymous subclass of Animal.


 makeSound() is overridden inside the anonymous class.
 The method is called immediately, and the object is discarded after use.

Advantages of Anonymous Objects

Saves memory – No need for unnecessary object references.


Makes code concise – Reduces lines of code.
Useful for one-time operations – Ideal for method calls and event handling.

Disadvantages of Anonymous Objects

o Cannot be reused – Since they lack references.


o Difficult to debug – No named reference makes debugging harder.
o Not ideal for complex scenarios – Best for simple use cases.

Class
Class in Fundamental Java

In Java, a class is a blueprint for creating objects. It defines the properties (fields/variables) and
behaviors (methods) that an object of that class can have. A class is a fundamental concept in
Object-Oriented Programming (OOP) and helps in encapsulation, inheritance, and
polymorphism.

Syntax of a Class in Java

10 | P a g e
A class is declared using the class keyword:

class ClassName {

// Instance variables (data members)

DataType variableName;

// Constructor

ClassName() {

// Initialization code

// Methods (functions inside a class)

returnType methodName() {

// Method body

The public keyword indicates that this class is available for use by other classes. Although it is
optional, you usually include it on your class declarations. The ClassName is an identifier that
provides a name for your class. You can use any identifier the name a class use the following three
mechanisms:

Begin the class name with a capital letter. If the class name consists of more than one
word, begin each word with capital. For example, Ball, Car, Dog, Bicycle, RetailCustomer

11 | P a g e
Classes create objects, and nouns are the words you use to identify objects. Thus, most
class names should be nouns.
Avoid using the name of a Java API class. This is not must, but if you create a class that
has the same name as a Java API class, you have to use fully qualified names (like
[Link]) to tell your class and the API class with the same name apart.

Example: Defining and Using a Class in Java

Let's create a simple class named Car, with attributes (brand, model, year) and a method
(displayCarDetails()).

// Define a class named "Car"


class Car {
// Instance variables (properties of a car)
String brand;
int speed;

// Constructor to initialize the car's properties


Car(String brand, int speed) {
[Link] = brand;
[Link] = speed;
}

// Method to display car details


void display() {
[Link]("Brand: " + brand + ", Speed: " + speed + " km/h");
}

// Main method to create objects and call methods


public static void main(String[] args) {
// Creating objects of the Car class
Car car1 = new Car("Toyota", 120);

12 | P a g e
Car car2 = new Car("Honda", 140);

// Calling methods using objects


[Link]();
[Link]();
}
}
Output
Brand: Toyota, Speed: 120 km/h
Brand: Honda, Speed: 140 km/h
Explanation:

1. Class Declaration: class Car defines a class named Car.


2. Instance Variables: brand and speed store car details.
3. Constructor: Car(String brand, int speed) initializes the instance variables.
4. Method: display() prints the car's details.
5. Object Creation: Car car1 = new Car("Toyota", 120); creates an instance of Car.
6. Method Invocation: [Link](); calls the method using the object.

Verification:

 The class acts as a blueprint to create multiple objects (car1, car2).


 Each object has its own values for brand and speed.
 The constructor ensures proper initialization.
 The display() method correctly prints object details.

Instance Variable in Java

An instance variable in Java is a variable that belongs to an instance (object) of a class. These
variables are declared inside a class but outside any method, constructor, or block.

Key Characteristics of Instance Variables:

1. Instance-Specific: Each object of the class has its own copy of the instance variable.

13 | P a g e
2. Scope: They are accessible within the class but can have different access modifiers
(private, protected, public, or default).
3. Memory Allocation: They are stored in the heap memory as part of the object.
4. Default Values: If not initialized explicitly, they take default values (e.g., 0 for int, null
for objects).
5. Accessed via Object: They are accessed using the object reference.

Example of Instance Variables in Java


class Car {
// Instance variables
String brand;
int speed;

// Constructor
Car(String brand, int speed) {
[Link] = brand;
[Link] = speed;
}

// Method to display car details


void display() {
[Link]("Brand: " + brand + ", Speed: " + speed + " km/h");
}

public static void main(String[] args) {


// Creating objects
Car car1 = new Car("Toyota", 120);
Car car2 = new Car("Honda", 140);

// Accessing instance variables via objects


[Link]();
[Link]();
}
}
Output:

Brand: Toyota, Speed: 120 km/h


Brand: Honda, Speed: 140 km/h

14 | P a g e
brand and speed are instance variables because they belong to each instance (object) of
the Car class.
Each object (car1, car2) has its own copy of brand and speed.
The constructor initializes the instance variables when an object is created.
The display() method prints the values of instance variables for each object.

Methods in Java

A method in Java is a block of code that performs a specific task. It is used to define the behavior
of an object and can be reused multiple times.

Types of Methods in Java

1. Instance Methods – Belong to an object and operate on instance variables.


2. Static Methods – Belong to the class and can be called without creating an object.
3. Constructors – Special methods used to initialize objects.
4. Getter and Setter Methods – Used to access and modify private variables.
5. Method Overloading – Defining multiple methods with the same name but different
parameters.
6. Method Overriding – Redefining a method in a subclass to provide a different
implementation.

Basic Example of Methods in Java


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

// Static method (performs subtraction)


static int subtract(int a, int b) {
return a - b;
}

public static void main(String[] args) {

15 | P a g e
// Creating an object to call the instance method
Calculator calc = new Calculator();
int sum = [Link](10, 5);
[Link]("Sum: " + sum);

// Calling the static method without creating an object


int difference = [Link](10, 5);
[Link]("Difference: " + difference);
}
}
Output:
Sum: 15
Difference: 5

Explanation:

1. Instance Method (add) – Needs an object ([Link](10, 5)) to be called.


2. Static Method (subtract) – Can be called directly using the class name
([Link](10, 5)).
3. Method Invocation – sum = [Link](10, 5); and difference = [Link](10, 5);.

Key Benefits of Methods in Java:

 Code Reusability – Write once, use multiple times.


 Modularity – Divides the program into smaller, manageable parts.
 Encapsulation – Helps in data hiding and protection.

Create a Method

A method must be declared within a class. It is defined with the name of the method, followed by
parentheses (). Java provides some pre-defined methods, such as [Link](), but you can
also create your own methods to perform certain actions:

Syntax of a Method in Java


returnType methodName(parameters) {
// Method body (code to execute)
return value; // Optional (only if returnType is not void)
}

16 | P a g e
 ReturnType → The type of value the method returns (e.g., int, void).
 MethodName → The name of the method (follows camelCase naming convention).
 Parameters → Inputs (optional) to the method.
 Return → If the method has a return type, it must return a value.

Example: Creating and Using Methods in Java


class MathOperations {
// Method to add two numbers (returns an int)
int add(int a, int b) {
return a + b;
}

// Method to display a message (void means no return value)


void greet() {
[Link]("Hello! Welcome to Java Methods.");
}

public static void main(String[] args) {


// Creating an object to call instance methods
MathOperations obj = new MathOperations();

// Calling the 'add' method and storing the result


int sum = [Link](10, 5);
[Link]("Sum: " + sum);

// Calling the 'greet' method


[Link]();
}
}
Output:

Sum: 15
Hello! Welcome to Java Methods.

Explanation:

1. Method add(int a, int b):


o Takes two integers as input.
o Returns their sum.
o Called using [Link](10, 5).
2. Method greet():
o Prints a greeting message.
o Has no return type (void).
o Called using [Link]();.

17 | P a g e
Call method

To call a method in Java, write the method's name followed by two parentheses () and a semicolon.
In the following example, myMethod() is used to print a text (the action), when it is called.
Example: Inside Student, call the myMethod() method:

Static vs Public Method

In Java, static and public methods serve different purposes:

Static Method

Belongs to the class rather than an instance. It can be called without creating an object. It can’t
access instance variables or non-static methods directly. Commonly used for utility functions.

Example:

class MathUtil {
static int add(int a, int b) { // Static method
return a + b;

18 | P a g e
}
}

public class Main {


public static void main(String[] args) {
int sum = [Link](5, 3); // No object needed
[Link]("Sum: " + sum);
}
}

Public Method

It is belongs to an instance of a class. Requires an object to be invoked. It can access instance


variables and other methods.

Example:

class Calculator {
public int multiply(int a, int b) { // Public method
return a * b;
}
}

public class Main {


public static void main(String[] args) {
Calculator calc = new Calculator();
int result = [Link](4, 2); // Requires an object
[Link]("Product: " + result);
}
}
Java Method Parameters and Arguments

In Java, parameters and arguments are essential components of methods.

1. Parameters: Variables defined in the method signature.


2. Arguments: Actual values passed when calling the method.

1. Method Parameters

A method parameter is a placeholder for the value that will be provided when the method is
called.

Example:

19 | P a g e
class MathUtil {
// 'a' and 'b' are parameters
public int add(int a, int b) {
return a + b;
}
}

Here, a and b are parameters of the add method.

2. Method Arguments

An argument is the actual value passed to a method when calling it.

Example:

public class Main {


public static void main(String[] args) {
MathUtil math = new MathUtil();
int result = [Link](5, 3); // '5' and '3' are arguments
[Link]("Sum: " + result);
}
}

Here, 5 and 3 are arguments provided to the add method.

3. Types of Method Parameters


a) Primitive Data Type Parameters

When passing primitive types (e.g., int, double), Java passes a copy of the value.

class Example {
void modify(int x) {
x = x + 10;
[Link]("Inside method: " + x);
}
}

public class Main {


public static void main(String[] args) {
int num = 20;
Example obj = new Example();
[Link](num); // Passes a copy of 'num'
[Link]("Outside method: " + num);

20 | P a g e
}
}

Output:

Inside method: 30
Outside method: 20

The original value of num remains unchanged because primitives are passed by value.

b) Reference Data Type Parameters

When passing objects (reference types), Java passes the reference.

class Example {
void modify(StringBuilder sb) {
[Link](" World");
}
}

public class Main {


public static void main(String[] args) {
StringBuilder text = new StringBuilder("Hello");
Example obj = new Example();
[Link](text); // Passes the reference of 'text'
[Link]("Modified String: " + text);
}
}

Output:

Modified String: Hello World

Explanation: Since StringBuilder is a reference type, changes inside the method affect the
original object.

4. Varargs (Variable-Length Arguments)

If the number of arguments is unknown, we use varargs (variable-length arguments) with ...
(ellipsis).

class VarArgsExample {

21 | P a g e
void sum(int... numbers) {
int total = 0;
for (int num : numbers) {
total += num;
}
[Link]("Sum: " + total);
}
}

public class Main {


public static void main(String[] args) {
VarArgsExample obj = new VarArgsExample();
[Link](1, 2, 3, 4); // Can pass multiple values
[Link](10, 20); // Can pass fewer values
}
}

Output:

Sum: 10
Sum: 30
Parameters vs. Arguments
Feature Parameters Arguments
Values passed when calling
Definition Variables in method definition
method
Scope Exists only inside the method Exists outside the method
Example void sum(int a, int b) sum(5, 3);
Cannot change outside the Can affect original object (for
Mutability
method (for primitives) references)

Return Values

The void keyword, used in the examples above, indicates that the method should not return a value.
If you want the method to return a value, you can use a primitive data type (such as int, char, etc.)
instead of void, and use the return keyword inside the method:

class MathUtil {

int square(int num) { // Method returning int

return num * num;

22 | P a g e
}

public static void main(String[] args) {

MathUtil math = new MathUtil();

int result = [Link](5);

[Link]("Square: " + result);

If a method does not return anything, its return type is void.

class Logger {

void logMessage(String message) { // void method (no return value)

[Link]("Log: " + message);

public static void main(String[] args) {

Logger logger = new Logger();

[Link]("Application started.");

Ways to Initialize an Object in Java

In Java, an object must be initialized before it can be used. There are several ways to initialize
an object:

1. Using a Constructor (Most Common)

Constructors are special methods used to initialize objects when they are created.

Example:

23 | P a g e
class Person {
String name;
int age;

// Constructor
Person(String name, int age) {
[Link] = name;
[Link] = age;
}
}

public class Main {


public static void main(String[] args) {
// Initializing object using constructor
Person p = new Person("Abebe", 25);
[Link]("Name: " + [Link] + ", Age: " + [Link]);
}
}

Output:

Name: Abebe, Age: 25

2. Using an Instance Initializer Block

Instance Initializer Blocks ({}) run before the constructor and are used to initialize instance
variables.

Example:
class Person {
String name;
int age;

// Instance initializer block


{
name = "Default Name";
age = 18;
}
}

24 | P a g e
public class Main {
public static void main(String[] args) {
Person p = new Person(); // No constructor needed
[Link]("Name: " + [Link] + ", Age: " + [Link]);
}
}

Output:

Name: Default Name, Age: 18

3. Using a Static Block (For Static Variables)

Static blocks are used to initialize static variables before any object is created.

Example:

class Config {
static String appName;

// Static block
static {
appName = "My Application";
}
}

public class Main {


public static void main(String[] args) {
[Link]("Application Name: " + [Link]);
}
}

Output:

Application Name: My Application

4. Using Object Reference (Setter Methods)

We can initialize an object by setting values using setter methods.

Example:
class Car {

25 | P a g e
String model;
int year;
void setModel(String model) {
[Link] = model;
}
void setYear(int year) {
[Link] = year;
}
}
public class Main {
public static void main(String[] args) {
Car car = new Car();
[Link]("Toyota");
[Link](2022);

[Link]("Car Model: " + [Link] + ", Year: " + [Link]);


}
}
Output:
Car Model: Toyota, Year: 2022

5. Using the newInstance() Method (Reflection)

The newInstance() method of the Class class allows dynamic object creation.

Example:

package instance;

import [Link];

import [Link];

public class Instance {

String name = "John Doe";

public static void main(String[] args) {

try {

26 | P a g e
Instance p = [Link](); // Using reflection

[Link]("Name: " + [Link]);

} catch (InstantiationException e) {

[Link]();

} catch (IllegalAccessException e) {

[Link]();

Output:

Name: John Doe

Note: newInstance() is deprecated in Java 9+. Use getDeclaredConstructor().newInstance()


instead.

6. Using a Factory Method

A factory method returns an initialized object instead of using new.

Example:
class Employee {
String name;

private Employee(String name) { // Private constructor


[Link] = name;
}

// Factory method
public static Employee createEmployee(String name) {
return new Employee(name);
}
}

public class Main {


public static void main(String[] args) {
Employee emp = [Link]("Alice");

27 | P a g e
[Link]("Employee Name: " + [Link]);
}
}

Output:

Employee Name: Alice

7. Using Cloning (clone() Method)

An object can be initialized by copying another object.

Example:
class Student implements Cloneable {
String name;

Student(String name) {
[Link] = name;
}

public Object clone() throws CloneNotSupportedException {


return [Link]();
}
}

public class Main {


public static void main(String[] args) throws CloneNotSupportedException {
Student s1 = new Student("Daniel");
Student s2 = (Student) [Link](); // Clone object

[Link]("Original: " + [Link]);


[Link]("Clone: " + [Link]);
}
}

Output:

Original: Daniel
Clone: Daniel

Note: The class must implement the Cloneable interface.

8. Using Deserialization (Reading Object from File)

An object can be initialized by reading it from a file using serialization.

28 | P a g e
Example:
import [Link].*;

class Person implements Serializable {


String name;

Person(String name) {
[Link] = name;
}
}

public class Main {


public static void main(String[] args) throws Exception {
// Writing object to file
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("[Link]"));
Person p1 = new Person("Eden");
[Link](p1);
[Link]();

// Reading object from file


ObjectInputStream in = new ObjectInputStream(new FileInputStream("[Link]"));
Person p2 = (Person) [Link]();
[Link]();

[Link]("Deserialized Name: " + [Link]);


}
}

Output: Deserialized Name: Eden

Comparison of Initialization Methods


Method Description Example
Constructor Most common method Person p = new Person("Abebe", 25);
Runs before the
Instance Initializer Block { name = "Default"; }
constructor
Static Block Used for static variables static { appName = "MyApp"; }
Setter Methods Uses object reference [Link]("John");
Reflection Creates an object Person p =
(newInstance()) dynamically [Link]("Person").newInstance();
Static method that
Factory Method Person p = [Link]("Alice");
returns an object
Creates a copy of an
Cloning Person p2 = (Person) [Link]();
object

29 | P a g e
Access level modifiers
Access level modifiers determine whether external classes can use a particular field or invoke a
particular method of the class being defined. There are two levels of access control:

o At the top level — public, or package-private (no explicit modifier specified).


o At the member level — public, private, protected or package-private (no explicit
modifier specified).

A class may be declared with the modifier public, in which case that class is visible to all classes
everywhere.

If a class has no modifier (the default, also known as package-private), it is visible only within its
own package (packages are named groups of related classes).

The following table shows the access to members permitted by each modifier.

Data Members

There are several kinds of variables in classes such as Member variables in a class—these are
called fields; Variables in a method or block of code—these are called local variables; Variables
in method declarations—these are called parameters. A data member is a variable that is defined
in the body of a class, outside of any of the class’ methods. Fields are available to all the methods

30 | P a g e
of a class. In addition, if the data member/field specifies the public keyword, then it is visible
outside of the class. • If it don’t want the field to be visible outside of the class, use the private
keyword instead.

Constructors

Constructor in java is a special type of method that is used to initialize the object. Java constructor
is invoked at the time of object creation. It constructs the values i.e. provides data for the object
that is why it is known as constructor. Rules for creating java constructor: there are basically two
rules defined for the constructor. Constructor name must be same as its class name. Constructor
must have no explicit return type.

Constructors have no return type, not even void. This is because the implicit return type of a class’s
constructor is the class type itself. Broadly, constructors can be divided into three: default
constructor, parameterized constructor and copy constructor.

Default Constructors

If don’t define a constructor in the class of java creates one of it. This generated constructor is
called the default constructor. A constructor that have no parameter is known as default
constructor.

Syntax of default constructor:<className> (){}

Example of default constructor

In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the
time of object creation.

class Bike1{

Bike1(){[Link]("Bike is created");}

public static void main(String args[]){

Bike1 b=new Bike1();

}
31 | P a g e
Output:

Bike is created

Parameterized Constructors

Copy constructor can be seen one type of parameterized constructor. A constructor that has
parameters is known as parameterized constructor. Parameterized constructor is used to provide
different values to the distinct objects. It initializes the object to the values of the parameter passed
when new keyword is used to create object.

Syntax of copy parameters constructor: <className> (data type variable comma datatype
variableName){}

Example: parameterized constructor

class Student {

String id;

String name;

//parameterized constructor

public Student (String i, String n) {

id = i;

name = n;

public void display() {

[Link](id + " " + name);

public static void main(String args[]) {

Student s1 = new Student(“RU111/16”, “Abdi Bekele");

Student s2 = new Student(“Ru222/15”, "Abebe Bekele");

32 | P a g e
[Link]();

[Link]();

Copy Constructor

Another common form of a constructor is called a copy constructor. A copy constructor is a special
constructor for creating a new object as a copy of an existing object. The first argument of such a
constructor is a reference to an object of the same type as is being constructed, which might be
followed by parameters of any type. Once it gets its object argument, creates a copy of it and create
new object.

class Student6{

int id;

String name;

Student6(int i,String n){

id = i;

name = n;

Student6(Student6 s){

id = [Link];

name =[Link];

void display(){[Link](id+" "+name);}

public static void main(String args[]){

Student6 s1 = new Student6(111,"Karan");

33 | P a g e
Student6 s2 = new Student6(s1);

[Link]();

[Link]();

Destructors

Does Java Have Destructors?

Unlike C++, Java does not have destructors because Java has automatic garbage collection (GC).
Instead of explicitly defining destructors, Java relies on the Garbage Collector (GC) to reclaim
memory when objects are no longer needed. However, Java provides a method called finalize()
(deprecated in Java 9 and removed in Java 18) that used to act like a destructor. Java 9 finalize()
was deprecated (still usable but with warnings). Java 18 finalize() was completely removed.
@Override is an annotation in Java that ensures a method in a subclass properly overrides a
method in a superclass. It helps prevent errors when overriding methods.

How Does Java Handle Resource Cleanup?

Since Java does not have destructors, It use the following techniques for resource cleanup:

1. Garbage Collection (GC): Automatically reclaims memory used by objects that are no
longer accessible.

2. finalize() Method (Deprecated): Used before an object is garbage collected.

3. try-with-resources (AutoCloseable Interface): For explicitly closing resources like files,


sockets, or database connections.

4. Explicit Cleanup Methods: Manually defined methods (close(), dispose(), etc.) for
cleanup.

Example 1: Using finalize() (Deprecated Method)

class MyClass {

34 | P a g e
// Constructor

MyClass() {

[Link]("Constructor is called!");

// finalize method (deprecated in Java 9+)

@Override

protected void finalize() {

[Link]("Destructor (finalize) is called!");

public static void main(String[] args) {

MyClass obj = new MyClass();

obj = null; // Making object eligible or suitable for garbage collection

// Requesting JVM to run Garbage Collector

[Link]();

[Link]("End of main method!");

} }

Output (May Vary)

Constructor is called!
End of main method!
Destructor (finalize) is called!

Note:

The call to [Link]() requests garbage collection but does not guarantee immediate
execution.
finalize() is deprecated in Java 9 and removed in Java 18.

35 | P a g e
Example 2: Using AutoCloseable with try-with-resources (Preferred for Resource Cleanup)

Since Java does not support destructors, the best way to release resources like files or database
connections is to implement the AutoCloseable interface and use the try-with-resources block.

class MyResource implements AutoCloseable {

// Constructor

MyResource() {

[Link]("Resource acquired!");

// Custom cleanup logic

@Override

public void close() {

[Link]("Resource released!");

public class Main {

public static void main(String[] args) {

try (MyResource res = new MyResource()) {

[Link]("Using the resource...");

} // close() is automatically called at the end of try block

36 | P a g e
Output

Resource acquired!

Using the resource...

Resource released!

 This approach is better than finalize() because it ensures timely cleanup.

Console I/O (Input and Output) in Java

In Java, Console I/O (Input/Output) is used to interact with the user through the command-line
interface (CLI). It involves:

1. Reading input from the user

2. Displaying output on the console

Java provides several ways to handle console input and output.

1. Output to Console ([Link])

Java provides the [Link] object to print output to the console.

Example: Printing Output

public class ConsoleOutput {

public static void main(String[] args) {

[Link]("Hello, Java!"); // Prints with a new line

[Link]("Welcome to Console I/O in Java."); // Prints without a new line

[Link]("\nYour score is: %d\n", 95); // Formatted output

Output

Hello, Java!

37 | P a g e
Welcome to Console I/O in [Link] score is: 95

2. Formatting text with printf

[Link]("format string", parameters);

A format string can contain placeholders to insert parameters:

%d integer
%f real number
%s string

These placeholders are used instead of + concatenation

–Example: int x = 3; int y = -17;

[Link]("x is %d and y is %d!\n", x, y); // x is 3 and y is -17!

printf does not drop to the next line unless you write \n

3. Input from Console (Scanner Class)

The Scanner class is the most commonly used method for user input. Communicates with
[Link]

Example: Taking User Input

import [Link];

public class ConsoleInput {

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]); // Create Scanner object

// Taking different types of input

[Link]("Enter your name: ");

String name = [Link](); // Reads full line

[Link]("Enter your age: ");

38 | P a g e
int age = [Link](); // Reads integer

[Link]("Enter your salary: ");

double salary = [Link](); // Reads floating-point number

// Displaying the inputs

[Link]("\nUser Details:");

[Link]("Name: " + name);

[Link]("Age: " + age);

[Link]("Salary: $" + salary);

[Link](); // Close scanner

Sample Output

Enter your name: John Doe

Enter your age: 30

Enter your salary: 45000.75

User Details:

Name: John Doe

Age: 30

Salary: $45000.75

4. Alternative: BufferedReader (For Faster Input)

If you need faster input processing, use BufferedReader with InputStreamReader.

Example: Using BufferedReader

39 | P a g e
import [Link];

import [Link];

import [Link];

public class ConsoleBufferedInput {

public static void main(String[] args) throws IOException {

BufferedReader reader = new BufferedReader(new InputStreamReader([Link]));

[Link]("Enter your name: ");

String name = [Link](); // Reads a full line

[Link]("Enter your age: ");

int age = [Link]([Link]()); // Reads and converts to integer

[Link]("\nHello, " + name + "! You are " + age + " years old.");

[Link]();

Sample Output

Enter your name: Alice

Enter your age: 25

Hello, Alice! You are 25 years old.

5. Using Console Class (For Secure Password Input)

Java provides [Link]() for reading input securely (e.g., passwords).

Example: Using Console for Secure Input

import [Link];

public class SecureInput {

40 | P a g e
public static void main(String[] args) {

Console console = [Link]();

if (console == null) {

[Link]("No console available!");

return;

String username = [Link]("Enter username: ");

char[] password = [Link]("Enter password: ");

[Link]("\nWelcome, " + username + "!");

Output (Example)

Enter username: user123

Enter password: ******

Welcome, user123!

Java Strings - Fundamental Concepts & Examples

In Java, strings are used to store and manipulate sequences of characters. Unlike other
programming languages where strings are arrays of characters, Java treats strings as objects of
the String class, which is part of [Link] package.

1. What is a String in Java?

A string in Java is an immutable (unchangeable) sequence of characters stored as a String object.

Example: Creating Strings

41 | P a g e
public class StringExample {

public static void main(String[] args) {

// Using string literal (Recommended)

String str1 = "Hello, Java!";

// Using new keyword (Not recommended)

String str2 = new String("Hello, Java!");

[Link](str1);

[Link](str2);

Output

Hello, Java!

Hello, Java!

String literals are stored in the string pool, making them memory-efficient.
Using new String() creates a new object in heap memory, which is less efficient.

2. String Immutability

Why are Strings Immutable in Java?

 Security: Prevents modification of sensitive data (e.g., passwords).

 Thread Safety: Multiple threads can use the same string without risk.

 String Pool Optimization: Saves memory by storing only one copy of each string literal.

Example: Proving String Immutability

public class StringImmutable {

42 | P a g e
public static void main(String[] args) {

String str = "Java";

[Link](" Programming"); // This does NOT modify str

[Link](str); // Still "Java"

Output

Java

Since strings are immutable, [Link](" Programming") creates a new string, but str still holds
"Java". To modify, store the result:

str = [Link](" Programming"); // Now it changes

3. String Methods

Java provides many useful methods for working with strings.

Method Description Example


length() Returns string length "Java".length() → 4
charAt(index) Gets character at index "Java".charAt(1) → 'a'
toUpperCase() Converts to uppercase "java".toUpperCase()→ "JAVA"
toLowerCase() Converts to lowercase "JAVA".toLowerCase()→ "java"
trim() Removes leading/trailing spaces " Java ".trim() → "Java"
substring(start, end) Extracts part of a string "Hello".substring(1, 4) → "ell"
replace(old, new) Replaces characters "Java".replace('a', 'o') → "Jovo"
indexOf(char) Finds character position "Java".indexOf('v') → 2
contains(str) Checks if contains substring "Hello".contains("He") → true
split(regex) Splits into array "a,b,c".split(",") → ["a", "b", "c"]

Example: Using String Methods

43 | P a g e
public class StringMethods {

public static void main(String[] args) {

String str = " Java Programming ";

[Link]("Length: " + [Link]());

[Link]("Trimmed: '" + [Link]() + "'");

[Link]("Uppercase: " + [Link]());

[Link]("Substring: " + [Link](2, 6));

[Link]("Replace: " + [Link]("Java", "Python"));

[Link]("Contains 'Java': " + [Link]("Java"));

Output

Length: 20

Trimmed: 'Java Programming'

Uppercase: JAVA PROGRAMMING

Substring: 'Java'

Replace: Python Programming

Contains 'Java': true

4. String Comparison

1. == vs .equals()

Method Compares Example


== Memory reference "Java" == "Java" → true (if both in string pool)
.equals() Actual content "Java".equals("Java") → true

44 | P a g e
public class StringComparison {

public static void main(String[] args) {

String s1 = "Java";

String s2 = "Java";

String s3 = new String("Java");

[Link](s1 == s2); // true (same string pool reference)

[Link](s1 == s3); // false (different object)

[Link]([Link](s3)); // true (content matches)

Output

true

false

true

Use .equals() for content comparison, not ==.

5. StringBuffer & StringBuilder (Mutable Strings)

If you need modifiable strings, use StringBuffer or StringBuilder.

Feature StringBuffer StringBuilder


Mutability Mutable (changeable) Mutable (changeable)
Thread Safety Thread-safe (synchronized) Not thread-safe (faster)
Performance Slower (due to synchronization) Faster

Example: Using StringBuilder for Efficient Modification

45 | P a g e
public class MutableStrings {

public static void main(String[] args) {

StringBuilder sb = new StringBuilder("Java");

[Link](" Programming"); // Modifies the same object

[Link](sb); // "Java Programming"

[Link](4, " is");

[Link](sb); // "Java is Programming"

[Link](5, 7, "was");

[Link](sb); // "Java was Programming"

Output

Java Programming

Java is Programming

Java was Programming

StringBuilder is much faster than String for frequent modifications.

5. Converting Between Strings and Other Types


Conversion Method Example
String → int [Link](str) [Link]("123") → 123
String → double [Link](str) [Link]("3.14") → 3.14
int → String [Link](num) [Link](123) → "123"
double → String [Link](num) [Link](3.14) → "3.14"

46 | P a g e
Example: Type Conversion

public class TypeConversion {

public static void main(String[] args) {

String numStr = "100";

int num = [Link](numStr);

[Link](num + 50); // 150

int val = 42;

String strVal = [Link](val);

[Link](strVal + " is a number"); // "42 is a number"

Output

150

42 is a number

CharSequence Interface in Java - Fundamentals & Examples


1. What is CharSequence in Java?

The CharSequence interface represents a read-only sequence of characters. It provides a


generalized way to work with character sequences, meaning different string-like classes (String,
StringBuilder, StringBuffer) can be treated uniformly.

Key Features of CharSequence

It is an interface (not a class).


Provides read-only access to characters.
Implemented by String, StringBuilder, and StringBuffer.
Useful for polymorphism, allowing flexible handling of character sequences.

47 | P a g e
Declaration of CharSequence Interface
public interface CharSequence {
char charAt(int index); // Returns the character at the given index
int length(); // Returns the length of the sequence
CharSequence subSequence(int start, int end); // Extracts part of the sequence
String toString(); // Converts to a String
}
2. Classes Implementing CharSequence
Class Mutable Thread-Safe Usage
String ❌ No ✅ Yes (Immutable) Fixed character sequences
StringBuilder ✅ Yes ❌ No Fast string modifications
StringBuffer ✅ Yes ✅ Yes (Synchronized) Thread-safe string modifications

3. Using CharSequence with Different Implementations

Since CharSequence is an interface, it cannot be instantiated directly, but we can assign different
implementations (String, StringBuilder, etc.) to a CharSequence variable.

Example: Assigning Different Implementations


public class CharSequenceExample {
public static void main(String[] args) {
CharSequence cs1 = "Hello, Java!"; // String
CharSequence cs2 = new StringBuilder("Mutable Text"); // StringBuilder
CharSequence cs3 = new StringBuffer("Thread-Safe Text"); // StringBuffer
[Link](cs1);
[Link](cs2);
[Link](cs3);
}
}
Output
Hello, Java!
Mutable Text
Thread-Safe Text

48 | P a g e
4. Methods of CharSequence

Let's explore the key methods available in the CharSequence interface.

(i) length() – Returns the number of characters


public class CharSequenceLength {
public static void main(String[] args) {
CharSequence cs = "Hello";
[Link]("Length: " + [Link]());
}
}
Output
Length: 5
(ii) charAt(int index) – Returns a character at a specific position
public class CharSequenceCharAt {
public static void main(String[] args) {
CharSequence cs = "Java";
[Link]("Character at index 2: " + [Link](2));
}
}
Output
Character at index 2: v
(iii) subSequence (int start, int end) – Extracts part of the sequence
public class CharSequenceSubSequence {
public static void main(String[] args) {
CharSequence cs = "Programming";
[Link]("Subsequence: " + [Link](3, 7));
}
}
Output
Subsequence: gram

49 | P a g e
General Unlike substring(), subSequence() returns another CharSequence.

(iv) toString() – Converts CharSequence to a String


public class CharSequenceToString {
public static void main(String[] args) {
CharSequence cs = new StringBuilder("Convert me");
String str = [Link]();
[Link]([Link]());
}
}
Output
CONVERT ME

5. Using CharSequence for Method Arguments

By using CharSequence as a method parameter, we can allow different string representations


(String, StringBuilder, etc.).

Example: Method Accepting Any CharSequence


public class CharSequenceMethod {
public static void printLength(CharSequence cs) {
[Link]("Length: " + [Link]());
}
public static void main(String[] args) {
printLength("Hello"); // String
printLength(new StringBuilder("Mutable")); // StringBuilder
printLength(new StringBuffer("Thread-Safe")); // StringBuffer
}
}
Output
Length: 5
Length: 7
Length: 11

50 | P a g e
Polymorphism allows flexible handling of character sequences.

6. CharSequence in Regular Expressions

The matches() method in String works only on String, but we can use Pattern with
CharSequence.

Example: Pattern Matching on CharSequence


import [Link];
public class CharSequenceRegex {
public static void main(String[] args) {
CharSequence cs = "hello123";
boolean isMatch = [Link]("[a-z]+\\d+", cs);
[Link]("Pattern match: " + isMatch);
}
}
Output
Pattern match: true

Flexible pattern matching with different implementations of CharSequence.

7. Comparison: String vs. CharSequence

Feature String CharSequence


Type Class Interface
Mutable? ❌ No Depends on implementation
Implements CharSequence? ✅ Yes ✅ Yes (but is abstract)

 CharSequence is an interface for handling character sequences in a generic way.


 It provides methods like length(), charAt(), subSequence(), and toString().
 Implemented by String, StringBuilder, and StringBuffer.
 Useful for polymorphism, allowing methods to accept different string types.

Comparing Strings using equals() in Java

51 | P a g e
In Java, comparing strings is fundamental because strings are objects and not just primitive data
types. The equals() method is the recommended way to compare strings based on content rather
than memory reference.

1. Why Use equals() Instead of ==?

In Java:

== compares object references (memory locations).


equals() compares actual content.

Example: Difference Between == and equals()


public class StringComparison {
public static void main(String[] args) {
String s1 = "Java";
String s2 = "Java";
String s3 = new String("Java");
[Link](s1 == s2); // true (both refer to the same string pool object)
[Link](s1 == s3); // false (s3 is a new object in heap memory)
[Link]([Link](s3)); // true (content is the same)
}
}
Output
true
false
true
✅ s1 == s2 → true because both refer to the same object in the string pool.

❌ s1 == s3 → false because s3 is created using new String(), so it has a different memory


reference.
✅ [Link](s3) → true because equals() compares the actual content.
2. How equals() Works Internally

The equals() method is defined in the String class as:

public boolean equals(Object anObject) {

52 | P a g e
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String) anObject;
int n = [Link]();
if (n == [Link]()) {
char v1[] = [Link]();
char v2[] = [Link]();
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}

First, it checks if the objects are the same (this == anObject).


Then, it checks if the object is a String instance.
If lengths match, it compares characters one by one.
Returns true if all characters match, otherwise false.

3. Case-Sensitive Comparison

By default, equals() is case-sensitive.

Example: Case-Sensitive Comparison


public class CaseSensitiveComparison {
public static void main(String[] args) {

53 | P a g e
String s1 = "Java";
String s2 = "java";
[Link]([Link](s2)); // false (case-sensitive)
}
}
Output
False
"Java" and "java" are different because uppercase 'J' and lowercase 'j' are different characters.
4. Case-Insensitive Comparison (equalsIgnoreCase())

To compare strings without considering case, use equalsIgnoreCase().

Example: Case-Insensitive Comparison


public class CaseInsensitiveComparison {
public static void main(String[] args) {
String s1 = "Java";
String s2 = "java";
[Link]([Link](s2)); // true
}
}
Output
True
Use equalsIgnoreCase() when you don't care about letter case differences.
Comparing Strings using compareTo() in Java

The compareTo() method in Java is used to compare two strings lexicographically. It is part of
the Comparable interface and is commonly used for sorting strings.

1. Understanding compareTo()

The compareTo() method belongs to the String class and is defined as: public int
compareTo(String anotherString)

How it Works?

54 | P a g e
Returns 0 → If both strings are equal.
Returns a positive value (> 0) → If the first string is greater than the second string.
Returns a negative value (< 0) → If the first string is less than the second string.

Sorting Order

 compareTo() follows Unicode lexicographical order (dictionary order).


 Uppercase letters (A-Z) come before lowercase letters (a-z).
 Numbers (0-9) come before letters (A-Z, a-z).

2. Basic Example of compareTo()


public class CompareToExample {
public static void main(String[] args) {
String s1 = "Java";
String s2 = "Python";
String s3 = "Java";
[Link]([Link](s2)); // Negative (-ve) value (Java < Python)
[Link]([Link](s1)); // Positive (+ve) value (Python > Java)
[Link]([Link](s3)); // 0 (Both are equal)
}
}
Output
-6
6
0

"Java".compareTo("Python") returns -6 because "Java" comes before "Python"


"Python".compareTo("Java") returns 6 because "Python" comes after "Java".
"Java".compareTo("Java") returns 0 since both strings are equal.

3. Case-Sensitive Comparison

compareTo() is case-sensitive, meaning uppercase and lowercase letters are treated differently.

Example: Case-Sensitive Comparison


public class CaseSensitiveCompare {
public static void main(String[] args) {
String s1 = "Java";
String s2 = "java";

55 | P a g e
[Link]([Link](s2)); // Negative (-ve) value (uppercase < lowercase)
}
}
Output -32

"Java" is less than "java" because uppercase 'J' (Unicode 74) comes before lowercase 'j'
(Unicode 106).
Unicode difference: 74 - 106 = -32.

4. Case-Insensitive Comparison (compareToIgnoreCase())

If you want to ignore case differences, use compareToIgnoreCase().

Example: Case-Insensitive Comparison


public class CaseInsensitiveCompare {
public static void main(String[] args) {
String s1 = "Java";
String s2 = "java";
[Link]([Link](s2)); // 0 (Equal ignoring case)
}
}
Output -> 0

"Java" and "java" are equal when ignoring case.

5. Sorting Strings with compareTo()

The compareTo() method is useful for sorting strings in ascending or descending order.

Example: Sorting Strings Alphabetically


import [Link];

public class StringSorting {


public static void main(String[] args) {
String[] languages = {"Python", "C", "Java", "Ruby"};

[Link](languages); // Uses compareTo() internally

[Link]([Link](languages));
}
}
Output
[C, Java, Python, Ruby]

56 | P a g e
Lexicographical order: "C" < "Java" < "Python" < "Ruby".

6. Comparing Strings Character by Character

compareTo() works by comparing each character in order:

"Apple".compareTo("Ape") → 'p' (Unicode 112) vs 'e' (Unicode 101)


112 - 101 = 11, so "Apple" > "Ape"

Example: Character-by-Character Comparison


public class CharacterComparison {
public static void main(String[] args) {
String s1 = "Apple";
String s2 = "Ape";
[Link]([Link](s2)); // Positive (+ve) value
}
}
Output
11

"Apple" is greater than "Ape" because 'p' has a higher Unicode value than 'e'.

8. compareTo() vs. equals()


Feature compareTo() equals()
Return Type int (positive, negative, zero) boolean (true or false)
Comparison Type Lexicographical (Unicode order) Exact content match
Case-Sensitive? Yes Yes
Sorting? ✅ Yes ❌ No
Best Use Case Sorting & ordering Checking equality

Example: Difference Between compareTo() and equals()


public class CompareToVsEquals {
public static void main(String[] args) {
String s1 = "Apple";
String s2 = "Apple";
String s3 = "Banana";

57 | P a g e
[Link]([Link](s2)); // true (Exact match)
[Link]([Link](s3)); // Negative (-ve) value (Apple < Banana)
}
}
Output
true
-1

 Use equals() when checking equality.


 Use compareTo() when sorting or ranking strings.

String Concatenation in Java


String concatenation in Java refers to combining two or more strings into a single string. Java
provides multiple ways to concatenate strings.
1. Using + Operator (Simple & Common)

The + operator is the easiest way to concatenate strings.

Example
public class StringConcat {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = " World";
String result = s1 + s2;

[Link](result); // Output: Hello World


}
}
2. Using concat() Method

The concat() method is another way to join strings.

Example
public class ConcatMethod {

58 | P a g e
public static void main(String[] args) {
String s1 = "Hello";
String s2 = " Java";
String result = [Link](s2);
[Link](result); // Output: Hello Java
}
}

Note: concat() only works on non-null strings.

3. Using [Link]() (Joining Multiple Strings)

The join() method allows concatenating multiple strings with a separator.

Example
public class JoinExample {
public static void main(String[] args) {
String result = [Link](", ", "Java", "Python", "C++");
[Link](result); // Output: Java, Python, C++
}
}

 Best for formatting output or CSV-style data.

4. Using [Link]() (Concatenation with Formatting)

The format() method helps concatenate with placeholders.

Example
public class FormatExample {
public static void main(String[] args) {
String name = "John";
int age = 25;
String result = [Link]("My name is %s and I am %d years old.", name, age);
[Link](result);

59 | P a g e
}
}

 Useful when combining different data types.

Substring in Java

The substring() method in Java is used to extract a part of a string. It is a very useful method when
you need to retrieve a portion of a string, based on a starting index or a range of indices.

1. Syntax of substring()
public String substring(int beginIndex)
public String substring(int beginIndex, int endIndex)
Parameters:

beginIndex: The starting index (inclusive).


endIndex: The ending index (exclusive), optional.

2. Example 1: Using substring(int beginIndex)

Extracts a substring from the beginIndex to the end of the string.

Example
public class SubstringExample {
public static void main(String[] args) {
String str = "Hello, World!";
String result = [Link](7); // From index 7 to the end
[Link](result); // Output: World!
}
}
3. Example 2: Using substring(int beginIndex, int endIndex)

Extracts a substring from beginIndex to endIndex - 1 (exclusive).

Example
public class SubstringExample {
public static void main(String[] args) {
String str = "Hello, World!";
String result = [Link](7, 12); // From index 7 to 11

60 | P a g e
[Link](result); // Output: World
}
}
Note:

Zero-based indexing: Index starts from 0.


If the beginIndex is greater than the string length, it throws StringIndexOutOfBoundsException.
Negative indices are not allowed.

Java toUpperCase() and toLowerCase() Methods

Both toUpperCase() and toLowerCase() are methods in the String class used to convert the case
of characters in a string.

1. toUpperCase() Method

The toUpperCase() method converts all characters in a string to uppercase.

Syntax:
public String toUpperCase()
Example:
public class ToUpperCaseExample {
public static void main(String[] args) {
String str = "hello, world!";
String result = [Link]();
[Link](result); // Output: HELLO, WORLD!
}
}
2. toLowerCase() Method

The toLowerCase() method converts all characters in a string to lowercase.

Syntax:
public String toLowerCase()
Example:
public class ToLowerCaseExample {
public static void main(String[] args) {

61 | P a g e
String str = "HELLO, WORLD!";
String result = [Link]();
[Link](result); // Output: hello, world!
}
}
Note:

 Both methods do not modify the original string; they return a new string with the
desired case.
 These methods are locale-insensitive, meaning they apply case conversion based on the
default locale of the JVM.

Java trim() Method

The trim() method in Java is used to remove leading and trailing whitespace (spaces, tabs, etc.)
from a string.

Syntax:
public String trim()
Parameters:

 No parameters are required.

Returns:

 A new string with leading and trailing whitespace removed.

Example:
public class TrimExample {
public static void main(String[] args) {
String str = " Hello, World! ";
String result = [Link]();
[Link](result); // Output: "Hello, World!"
}
}
Note:

 Whitespace characters include spaces, tabs, and other control characters.

62 | P a g e
 Does not remove internal spaces between words.
 Returns a new string, the original string remains unchanged.

Java charAt() Method

The charAt() method in Java is used to retrieve the character at a specified index in a string.

Syntax:
public char charAt(int index)
Parameters:

 index: The position of the character (0-based index).

Returns:

 The character at the specified index.

Example:

public class CharAtExample {


public static void main(String[] args) {
String str = "Hello";
char result = [Link](1); // Gets the character at index 1
[Link](result); // Output: 'e'
}
}
Searching Strings in Java

In Java, several methods are available to search for a substring or a character within a string. These
methods help you locate the position of a substring or check for its existence.

1. indexOf() Method

The indexOf() method is used to find the first occurrence of a character or a substring within a
string.

Syntax:
public int indexOf(int ch) // For character
public int indexOf(String str) // For substring
Returns:
63 | P a g e
 The index of the first occurrence of the character or substring.
 Returns -1 if not found.

Example:
public class IndexOfExample {
public static void main(String[] args) {
String str = "Hello, World!";
int index = [Link]("World");
[Link](index); // Output: 7
}
}

2. lastIndexOf() Method

The lastIndexOf() method returns the last occurrence of a character or substring.

Syntax:
public int lastIndexOf(int ch) // For character
public int lastIndexOf(String str) // For substring
Returns:

 The index of the last occurrence or -1 if not found.

Example:
public class LastIndexOfExample {
public static void main(String[] args) {
String str = "Hello, World, Hello!";
int index = [Link]("Hello");
[Link](index); // Output: 14
}
}
3. contains() Method

The contains() method checks if a substring exists within a string.

Syntax:
public boolean contains(CharSequence sequence)

64 | P a g e
Returns:

 true if the substring is found, otherwise false.

Example:
public class ContainsExample {
public static void main(String[] args) {
String str = "Hello, World!";
boolean result = [Link]("World");
[Link](result); // Output: true
}
}
4. startsWith() and endsWith() Methods

 startsWith() checks if a string starts with a specified prefix.


 endsWith() checks if a string ends with a specified suffix.

Syntax:
public boolean startsWith(String prefix)
public boolean endsWith(String suffix)
Example:
public class StartsEndsWithExample {
public static void main(String[] args) {
String str = "Hello, World!";
boolean starts = [Link]("Hello");
boolean ends = [Link]("World!");
[Link](starts); // Output: true
[Link](ends); // Output: true
}
}
5. matches() Method

The matches() method is used to check if a string matches a regular expression pattern.

Syntax:

65 | P a g e
public boolean matches(String regex)
Example:
public class MatchesExample {
public static void main(String[] args) {
String str = "Hello123";
boolean result = [Link]("[A-Za-z0-9]+");
[Link](result); // Output: true
}
}
Replacing Parts of a String in Java

Java provides methods to replace parts of a string. These methods allow you to replace characters
or substrings within a string.

1. replace() Method

The replace() method replaces all occurrences of a specified character or substring with a new
character or substring.

Syntax:
public String replace(char oldChar, char newChar)
public String replace(CharSequence target, CharSequence replacement)

Example (Character replacement):

String str = "Hello, World!";


String result = [Link]('o', 'a');
[Link](result); // Output: Hella, Warld!
Example (Substring replacement):
String str = "Hello, World!";
String result = [Link]("World", "Java");
[Link](result); // Output: Hello, Java!

2. replaceAll() Method

The replaceAll() method replaces substrings that match a regular expression with a specified
replacement.

Syntax:

66 | P a g e
public String replaceAll(String regex, String replacement)
Example:
String str = "abc123xyz";
String result = [Link]("[0-9]", "#");
[Link](result); // Output: abc###xyz
3. replaceFirst() Method

The replaceFirst() method replaces the first occurrence of a substring that matches a regular
expression.

Syntax:

public String replaceFirst(String regex, String replacement)

Example:
String str = "abc123abc";
String result = [Link]("abc", "xyz");
[Link](result); // Output: xyz123abc
Finding Length of a String in Java

In Java, the length of a string can be determined using the length() method.

1. length() Method

The length() method returns the number of characters in a string, including spaces.

Syntax:
public int length()
Returns:

 An integer representing the total number of characters in the string.

Example:
public class StringLengthExample {
public static void main(String[] args) {
String str = "Hello, World!";
int length = [Link]();
[Link](length); // Output: 13

67 | P a g e
}
}
The length() method is a simple and effective way to get the size of a string in Java. It returns the
total number of characters, including any whitespace.

Java Math Class

The Math class in Java is a utility class that provides a collection of static methods for performing
basic mathematical operations such as exponentiation, logarithms, trigonometry, and more.

Commonly Used Methods:


1. abs() – Absolute Value

Returns the absolute value of a number.

[Link](-10); // Output: 10

2. pow() – Power

Returns the value of the first argument raised to the power of the second argument.

[Link](2, 3); // Output: 8.0

3. sqrt() – Square Root

Returns the square root of a number.

[Link](16); // Output: 4.0


4. max() – Maximum of Two Values

Returns the larger of two values.

[Link](5, 10); // Output: 10


5. min() – Minimum of Two Values

Returns the smaller of two values.

[Link](5, 10); // Output: 5

6. random() – Random Number

68 | P a g e
Returns a random double between 0.0 (inclusive) and 1.0 (exclusive).

[Link](); // Output: Random value between 0 and 1

7. round() – Rounding

Rounds a floating-point number to the nearest long or int.

[Link](2.5); // Output: 3

Generally , The Math class provides essential mathematical functions like finding absolute values,
powers, square roots, and generating random numbers. All methods in the Math class are static, so
they are used directly with the class name.

Encapsulation in Java

Encapsulation is one of the fundamental principles of Object-Oriented Programming (OOP).


It refers to the bundling of data (fields) and methods (functions) that operate on the data into a
single unit, or class. It also restricts direct access to some of an object's components, which helps
protect the integrity of the data.

Key Concepts of Encapsulation

1. Private Variables:
Data (fields) of a class are marked as private, making them inaccessible outside the class.
This ensures that the data is protected from direct modification.
2. Public Methods (Getters and Setters):
Public methods (known as getters and setters) are provided to access and update the
values of private variables.

Example:
public class Person {
// Private field
private String name;
private int age;

// Getter for name


public String getName() {
return name;
}

69 | P a g e
// Setter for name
public void setName(String name) {
[Link] = name;
}

// Getter for age


public int getAge() {
return age;
}

// Setter for age


public void setAge(int age) {
if (age > 0) { // Validation inside the setter
[Link] = age;
}
}
}

public class Main {


public static void main(String[] args) {
Person person = new Person();
[Link]("John");
[Link](30);

[Link]("Name: " + [Link]()); // Output: Name: John


[Link]("Age: " + [Link]()); // Output: Age: 30
}
}
Advantages of Encapsulation

 Data Protection: By making fields private, direct modification is prevented, ensuring data
integrity.
 Controlled Access: Getters and setters allow validation or additional logic when accessing or
modifying data.
 Flexibility: Changes to internal implementation can be made without affecting external code, as
long as the interface remains the same.

Therefore, Encapsulation in Java involves using private fields and public getter/setter methods
to control access to an object's data. It ensures that the internal state is protected and only
modified in controlled ways, promoting better maintainability and security.

70 | P a g e
71 | P a g e

You might also like