0% found this document useful (0 votes)
33 views72 pages

Understanding Java Classes and Objects

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)
33 views72 pages

Understanding Java Classes and Objects

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

MODULE 2

Java Classes
A class in Java is a template with the help of which we create real-world entities known as
objects that share common characteristics and properties or in other words, we can say that a
class is a blueprint for objects.
It defines a Student class with two instance variables (id and n), creates an object s1 and prints
values of s1.

class Student {
int id;
String n;

// Added constructor to initialize both fields


public Student(int id, String n) {
[Link] = id;
this.n = n;
}
}
public class Main {
public static void main(String[] args) {

// Creating Student object using the new constructor


Student s1 = new Student(10, "Alice");

[Link]([Link]);
[Link](s1.n);
}
}
Output
10
Alice

Components of Java Classes


• Modifiers: A class can be public or has default access.
• Class keyword: Class keyword is used to create a class.
• Class name: The name should begin with an initial letter (capitalized by convention).
• Superclass (if any): The name of the class's parent (superclass), if any, preceded by
the keyword extends. A class can only extend (subclass) one parent.
• Body: The class body is surrounded by braces, { }.
• Fields: Fields are variables defined within a class that hold the data or state of an
object.
• Constructors: It is a special method in a class that is automatically called when an
object is created. And it's name is same as class name.
Java Objects
Objects are the instances of a class that are created to use the attributes and methods of a
class. A typical Java program creates many objects, which as you know, interact by invoking
methods. An object consists of:
• State: It is represented by attributes of an object. It also reflects the properties of an
object.
• Behavior: It is represented by the methods of an object. It also reflects the response of
an object with other objects.
• Identity: It gives a unique name to an object and enables one object to interact with
other objects.

As mentioned previously, a class provides the blueprints for objects. So basically, an object is
created from a class. In Java, the new keyword is used to create new objects.

There are three steps when creating an object from a class −


• Declaration − A variable declaration with a variable name with an object type.
• Instantiation − The 'new' keyword is used to create the object.
• Initialization − The 'new' keyword is followed by a call to a constructor. This call
initializes the new object.

Ways to create Java Object


1. Using “new” keyword
Class_name object_name = new Class_name([parameters]);
Note: parameters are optional and can be used while you're using constructors in the class.

2. Using [Link](String className) method:


There is a pre-defined class in [Link] package with name Class. The forName(String
className) method returns the Class object associated with the class with the given string
name.
On calling new Instance() method on this Class object returns new instance of the
class with the given string name.
// creating object of public class Test
// consider class Test present in com.p1 package
Test obj = (Test)[Link]("[Link]").newInstance();

3. Using clone() method


The clone() method is present in the Object class. It creates and returns a copy of the object.
// creating object of class Test
Test t1 = new Test();
// creating clone of above object
Test t2 = (Test)[Link]();

4. Deserialization
De-serialization is technique of reading an object from the saved state in a file.
FileInputStream file = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file);
Object obj = [Link]();

Creating Multiple Objects by one type only


In real-time, we need different objects of a class in different methods. Creating a number of
references for storing them is not a good practice and therefore we declare a static reference
variable and use it whenever required. In this case, the wastage of memory is less. The
objects that are not referenced anymore will be destroyed by the Garbage Collector of Java.

Example:
Test test = new Test();
test = new Test();

In the inheritance system, we use a parent class reference variable to store a sub-class object.
In this case, we can switch into different subclass objects using the same referenced variable.
Example:
class Animal {
}
class Dog extends Animal {
}
class Cat extends Animal {
}
public class Test {
// using Dog object
Animal obj = new Dog();
// using Cat object
obj = new Cat();
}

Blocks in Java
1. Static Block
• Declared using static { ... }.
• Executes only once when the class is loaded into memory by the JVM.
• Runs before the main() method and before any object is created.
• Used for static initialization (like initializing static variables, loading drivers, etc.).

class Demo {
static int count;

// Static Block
static {
count = 100;
[Link]("Static Block executed, count = " + count);
}
public static void main(String[] args) {
[Link]("Main method executed");
}
}
Output:
Static Block executed, count = 100
Main method executed

2. Non-Static Block (Instance Initialization Block, IIB)


• Declared simply as { ... } (without static).
• Executes every time an object is created.
• Runs before the constructor.
• Used for object-level initialization.

class Demo {
int x;

// Non-Static Block
{
x = 10;
[Link]("Non-Static Block executed, x = " + x);
}

Demo() {
[Link]("Constructor executed");
}

public static void main(String[] args) {


new Demo(); // First object
new Demo(); // Second object
}
}
Output:
Non-Static Block executed, x = 10
Constructor executed
Non-Static Block executed, x = 10
Constructor executed

Methods in Java
• A method is a collection of statements that perform some specific task and return the
result to the caller.
• A method can perform some specific task without returning anything.
• Methods allow us to reuse the code without retyping the code.
• In Java, every method must be part of some class which is different from languages
like C, C++, and Python.

Why Do We Break Code into Methods?


Breaking code into separate methods helps improve readability, reusability, and
maintainability
• Reusability: Write once, use multiple times without repeating code so that code
reusability increase.
• Readability: Smaller, named methods make the code easier to read and understand.
• Maintainability: It’s easier to fix bugs or update code when it's organized into
methods.

Syntax to Create a Java Method


Considering the following example to explain the syntax of a method −
modifier returnType nameOfMethod (Parameter List) {
// method body
}

The syntax shown above includes −


• modifier − It defines the access type of the method and it is optional to use.
• returnType − Method may return a value.
• nameOfMethod − This is the method name. The method signature consists of the
method name and the parameter list.
• Parameter List − The list of parameters, it is the type, order, and number of
parameters of a method. These are optional, method may contain zero parameters.
• method body − The method body defines what the method does with the statements.

Calling a Java Method


For using a method, it should be called. There are two ways in which a method is called i.e.,
method returns a value or returning nothing (no return value).
The process of method calling is simple. When a program invokes a method, the program
control gets transferred to the called method. This called method then returns control to the
caller in two conditions, when −
• the return statement is executed.
• it reaches the method ending closing brace.

The methods returning void is considered as call to a statement. Lets consider an example –
void hello()
{
[Link]("This is [Link]!");
}

The method returning value can be understood by the following example −


int result = sum(6, 9);
Example: Defining and Calling a Java Method
public class ExampleMinNumber {

public static void main(String[] args) {


int a = 11;
int b = 6;
int c = minFunction(a, b);
[Link]("Minimum Value = " + c);
}

/** returns the minimum of two numbers */


public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;

return min;
}
}
Output
Minimum value = 6

Types of Methods in Java


1. Predefined Method
Predefined methods are the method that is already defined in the Java class libraries. It is also
known as the standard library method or built-in method. For example, random() method
which is present in the Math class and we can call it using the [Link]() as
shown in the below example.
Example:
[Link]() // returns random value
[Link]() // return pi value

2. User-defined Method
The method written by the user or programmer is known as a user-defined method. These
methods are modified according to the requirement.
Example:
sayHello() // user define method
Greet()
setName()

3. Instance Methods
Instance Methods are the group of codes that performs a particular task. Sometimes the
program grows in size, and we want to separate the logic of the main method from other
methods.
A method is a function written inside the class. Since java is an object-oriented programming
language, we need to write a method inside some classes.

Key Points about Instance Methods:


1. Defined without the static keyword.
2. Can access instance variables (non-static fields) and other instance methods directly.
3. To call them, you must create an object of the class.
4. Each object can have its own data, and the instance method operates on that data.
5. They can also access static variables and methods, but usually deal with object-
specific data.

Instance Method without parameter


Syntax:
modifier return_type method_name( )
{
method body ;
}

Example:
public void disp( )
{
int a= 10;
[Link](a);
}

Instance Method With Parameter


Syntax:
modifier return_type method_name( parameter list)
{
method body ;
}
• Parameter List: The list of parameters separated by a comma. These are optional; the
method may contain zero parameters.

Example:
public void disp(int a, int b)
{
int x=a ;
int y=b;
int z = x+y;
[Link](z);
}

Calling Instance Method:


You can not call an instance method in the static method directly, so the Instance method can
be invoked using an object of the class. We know that the java program's execution starts
from the main method and the main method is static, so we can not directly call the instance
method. We have to create the class object; then, we can call the instance method in the main
method.
Example:
// Java program to see how can we call an instance method without parameter
import [Link].*;

class GFG {
// static method
public static void main (String[] args) {

// Creating object of the class


GFG obj = new GFG();

// Calling instance method


[Link]();

[Link]("GFG!");
}

// Instance method
void disp()
{
// Local variable
int a = 20;
[Link](a);
}
}

Output
20
GFG!

[Link] Method
In Java, the static keyword is used to create methods that belongs to the class rather than any
specific instance of the class.

Features of Static Method:


• A static method in Java is associated with the class, not with any object or instance.
• Static methods can access static variables directly without the need for an object.
• They cannot access non-static variables (instance) or methods directly.
• Static methods can be accessed directly in both static and non-static contexts.

Syntax to Declare a Static Method


access_modifier static return_type methodName() {
// method body
}

Syntax to Call a Static Method


[Link]();

The JVM executes the static method first, even before creating class objects. So, static
methods cannot access instance variables, as no object exists at that point.

// Java program to demonstrate that the static method does not have access to the instance
//variable
import [Link].*;

public class Geeks {

// static variable
static int a = 40;

// instance variable
int b = 50;

void simpleDisplay()
{
[Link](a);
[Link](b);
}

// Declaration of a static method


static void staticDisplay()
{
[Link](a);
}
// main method
public static void main(String[] args)
{
Geeks obj = new Geeks();
[Link]();

// Calling static method directly within the same class


staticDisplay();
}
}
Output
40
50
40

[Link] Method
• When a method is declared with final keyword, it is called a final method in Java.
• We must declare methods with the final keyword for which we are required to follow
the same implementation throughout all the derived classes.
• Once a method is declared final, it cannot be overridden by any subclass.

class A
{
final void m1()
{
[Link]("This is a final method.");
}
}
class B extends A
{
void m1()
{
// Compile-error! We can not override
[Link]("Illegal!");
}
}

Call by Value
• Changes made to formal parameter do not get transmitted back to the caller.
• Any modifications to the formal parameter variable inside the called function or
method affect only the separate storage location and will not be reflected in the actual
parameter in the calling environment.

class CallByValue1 {
void change(int a) {
a = a + 10;
[Link]("Inside method: " + a);
}

public static void main(String[] args) {


int x = 5;
CallByValue1 obj = new CallByValue1();

[Link]("Before call: " + x);


[Link](x);
[Link]("After call: " + x);
}
}
Output:
Before call: 5
Inside method: 15
After call: 5

Call by reference
• Changes made to formal parameter do get transmitted back to the caller through
parameter passing.
• Any changes to the formal parameter are reflected in the actual parameter in the
calling environment as formal parameter receives a reference (or pointer) to the actual
data.
• This method is also called as call by reference. This method is efficient in both time
and space.
• When we pass a reference, a new reference variable to the same object is created.
• So we can only change members of the object whose reference is passed.
• We cannot change the reference to refer to some other object as the received reference
is a copy of the original reference.

class Student {
String name;
}

class CallByReferenceExample {
void modify(Student s) {
[Link] = "Alice"; // modifies object content
}

public static void main(String[] args) {


Student st = new Student();
[Link] = "Bob";

CallByReferenceExample obj = new CallByReferenceExample();


[Link]("Before method call: " + [Link]);
[Link](st);
[Link]("After method call: " + [Link]);
}
}

Output:
Before method call: Bob
After method call: Alice

Encapsulation in Java
In Java, encapsulation is one of the core concepts of Object Oriented Programming (OOP) in
which we bind the data members and methods into a single unit. Encapsulation is used to
hide the implementation part and show the functionality for better readability and usability.
The following are important points about encapsulation.
• Better Code Management: We can change data representation and implementation
any time without changing the other codes using it if we keep method parameters and
return values the same. With encapsulation, we ensure that no other code would have
access to implementation details and data members.
• Simpler Parameter Passing: When we pass an object to a method, everything
associated data members and methods are passed along. We do not have to pass
individual members.
• getter and setter: getter (display the data) and setter method ( modify the data) are
used to provide the functionality to access and modify the data, and the
implementation of this method is hidden from the user. The user can use this method,
but cannot access the data directly.

This image below demonstrates the concept of encapsulation, where a class (represented by
the capsule) hides its internal data (variables) and only exposes a controlled interface
(encapsulation).

Example: Below is a simple example of Encapsulation in Java.


// Java program demonstrating Encapsulation
class Programmer {

private String name; // data hiding


// Getter method used to get the data
public String getName()
{
return name;
}

// Setter method is used to set or modify the data


public void setName(String name)
{
[Link] = name;
}
}
public class Geeks {

public static void main(String[] args) {


Programmer p = new Programmer();
[Link]("Geek");
[Link]("Name=> " + [Link]());
}
}
Output
Name=> Geek

Uses of Encapsulation in Java


• Data Hiding: The internal data of an object is hidden from the outside world,
preventing direct access.
• Data Integrity: Only validated or safe values can be assigned to an object’s attributes
via setter methods.
• Reusability: Encapsulated code is more flexible and reusable for future modifications
or requirements.
• Security: Sensitive data is protected as it cannot be accessed directly.

Data Hiding
Data hiding is a key concept in object-oriented programming (OOP) that focuses on
restricting access to an object’s internal state. In Java, data hiding is primarily achieved
using encapsulation, which involves controlling how data is accessed or modified via getter
and setter methods. By hiding the implementation details and exposing only the necessary
functionalities, data hiding helps to protect the integrity of the data and ensures that the
object’s state is not directly manipulated by outside code.
In simpler terms, data hiding is like keeping your personal information in a secure locker. You
provide authorized access to others only when necessary, through a controlled process (like a
key or password). This ensures that no one can access or alter your information without your
consent.
How Data Hiding Works in Java
In Java, data hiding is implemented using encapsulation, which combines two essential
features:
• Private Fields: Variables that store an object’s state are declared as private so that
they cannot be accessed directly from outside the class. This ensures that the object’s
internal state is protected from external modifications.
• Public Getter and Setter Methods: These methods provide controlled access to the
private fields. A getter method retrieves the value of a private variable, while a setter
method allows you to modify it. This provides a level of abstraction, so you can
control what happens when the data is accessed or changed.

Why is Data Hiding Important?


• Increased Security: Data hiding protects an object’s internal state from unauthorized
access or modification. Without data hiding, malicious code could change an object’s
state directly, potentially causing bugs or security vulnerabilities.
• Data Integrity: With data hiding, you can validate and control how data is modified.
For example, you can ensure that only valid data is set for an object’s variables,
maintaining its consistency and integrity.
• Easier Maintenance and Debugging: Since data is hidden, the internal
implementation of a class can be changed without affecting other parts of the
program. This makes the code more modular, easier to maintain, and reduces the risk
of introducing errors when modifying the class.
• Reduced Complexity: By providing a simplified interface (getter and setter
methods), data hiding helps abstract away complex details, making the code easier to
use and understand.

Example of Data Hiding in Java


Java Program: Data Hiding Example
class Student {
// Private variable - data hiding
private String name;

// Setter method - allows controlled modification


public void setName(String newName) {
name = newName;
}
// Getter method - allows controlled access
public String getName() {
return name;
}
}

public class DataHidingExample {


public static void main(String[] args) {
Student s1 = new Student();

// Trying to access name directly (not allowed)


//[Link] = "Disha"; // Error: name has private access in Student

// Using setter method to set value


[Link]("Disha");

// Using getter method to access value


[Link]("Student Name: " + [Link]());
}
}
Output:
Student Name: Disha

Difference between Data Hiding and Encapsulation

Data Hiding Encapsulation

It can be defined as the wrapping up of data into a single


It is associated with data security.
module.

It focuses on hiding/restricting the


It focuses on hiding the complexity of the system.
data usage.

It is considered as a process and a It is considered as a sub process in the bigger process of


technique. data hiding.

The data is always private and The encapsulated data can be private or public,
inaccessible. depending on the requirement.

Java Constructors
In Java, constructors play an important role in object creation. A constructor is a special block
of code that is called when an object is created. Its main job is to initialize the object, to set
up its internal state, or to assign default values to its attributes. This process happens
automatically when we use the "new" keyword to create an object. It is a special type of
method.

Characteristics of Constructors:
• Same Name as the Class: A constructor has the same name as the class in which it is
defined.
• No Return Type: Constructors do not have any return type, not even void. The main
purpose of a constructor is to initialize the object, not to return a value.
• Automatically Called on Object Creation: When an object of a class is created, the
constructor is called automatically to initialize the object’s attributes.
• Used to Set Initial Values for Object Attributes: Constructors are primarily used to
set the initial state or values of an object’s attributes when it is created.

Example: This program demonstrates how a constructor is automatically called when


an object is created in Java.
// Java Program to demonstrate Constructor usage
import [Link].*;

// Driver Class
class A {
int a;
string name;

// Constructor
A()
{
a=0;
name=null;
}
void show();
{
[Link](a+ “ “ +name);
}
}

Class B
{
// main function
public static void main(String[] args)
{
A ref = new A();
[Link]();
}
}
Output
0 null

Note: It is not necessary to write a constructor for a class. It is because the Java compiler
creates a default constructor (constructor with no arguments) if your class doesn't have any.
Constructor vs Method in Java

Features Constructor Method

Constructors must have


Methods can have any
the same name as the
valid name
Name class name

Methods have the return


Constructors do not
type or void if does not
return any type
Return Type return any value.

Constructors are called


Methods are called
automatically with new
explicitly
Invocation keyword

Constructors are used to Methods are used to


Purpose initialize objects perform operations

When Java Constructor is Called?


Each time an object is created using a new() keyword, at least one constructor (it could be the
default constructor) is invoked to assign initial values to the data members of the same class.

Types of Constructors in Java


• Default Constructor
• Parameterized Constructor
• Copy Constructor
• Private Constructor

1. Default Constructor in Java


A constructor that has no parameters is known as default constructor. A default constructor is
invisible. And if we write a constructor with no arguments, the compiler does not create a
default constructor. Once you define a constructor (with or without parameters), the compiler
no longer provides the default constructor. The default constructor can be implicit or explicit.
// Java Program to demonstrate Default Constructor
import [Link].*;

class A {
int a;
string b;
boolean c;

// Constructor
A()
{
a=100;
b=”ankit”;
c=true;
}
void disp();
{
[Link](a+ “ “ +b+ “ “ +c);
}
}

Class B
{
// main function
public static void main(String[] args)
{
A r = new A();
[Link]();
}
}

Output
100 ankit true

Note: Default constructor provides the default values to the object like 0, null, false etc.
depending on the type.
2. Parameterized Constructor in Java
A constructor that has parameters is known as parameterized constructor. If we want to
initialize fields of the class with our own values, then use a parameterized constructor.
// Java Program for Parameterized Constructor
import [Link].*;
class A {
int x;
int y;

A(int a, int b) // parameterized


{
x=a;
y=b;
}
void show();
{
[Link](x+ “ “+y);
}
}
Class B
{
// main function
public static void main(String[] args)
{
A r = new A(100,200);
[Link]();
}
}

Output
100 200
There are no "return value" statements in the constructor, but the constructor returns the
current class instance. We can write 'return' inside a constructor.
3. Copy Constructor in Java
Unlike other constructors copy constructor is passed with another object which copies the
data available from the passed object to the newly created object.
Note: Java does not provide a built-in copy constructor like C++. We can create our own by
writing a constructor that takes an object of the same class as a parameter and copies its
fields.
Example: This example, demonstrates how a copy constructor can be used to create a new
object by copying the values of another object's attributes.
// Java Program for Copy Constructor
import [Link].*;

class A {
int a;
String b;
A()
{
a=10;
b=”java”;
[Link](a+ “ “+b);

}
A(A ref)
{
a=ref.a;
b=ref.b;
[Link](a+ “ “+b);
}
}
Class B
{
// main function
public static void main(String[] args)
{
A r = new A();
A r2 = new A(r);

}
}
Output
10 java
10 java

4. Private Constructor in Java


In java it is possible to write a constructor as private but according to the rule we cannot
access private members outside of a class.
// Java Program for Private Constructor
import [Link].*;
class A {
int a;
double b;
String c;

private A()
{
a=10;
b=30.56;
c=”ankit”;
[Link](a+ “ “+b+” “+c);
}
public static void main(String[] args)
{
A r = new A();
}
}
Output
10 30.56 ankit

Static Keyword in Java


The static keyword in Java is mainly used for memory management, allowing variables and
methods to belong to the class itself rather than individual instances. The static keyword is
used to share the same variable or method of a given class. The users can apply static
keywords with variables, methods, blocks, and nested classes. The static keyword belongs to
the class rather than an instance of the class. The static keyword is used for a constant
variable or a method that is the same for every instance of a class.
What is a static Keyword in Java?
The static keyword is a non-access modifier used for:
• Variables (class-level, shared across instances)
• Methods (called without object creation)
• Blocks (executed once when the class loads)
• Nested Classes (static inner classes)

Note: To create a static member(block, variable, method, nested class), precede its
declaration with the keyword static.
Characteristics of the "static" Keyword
Here are some characteristics of the static keyword in Java:
• Static variables and methods use memory only once when the program runs, and this
memory is shared by all the objects of the class.
• We do not need to create objects of the class to use static methods
• We can call static members using the class name directly.
• Static members belong to the class, not to any specified object.
• Static members can not access non-static members.
• Static methods cannot be overridden in subclasses because they belong to the class,
not to an object.

Example: This example demonstrates that a static method can be called without
creating an instance of the class.
class Geeks
{
// static method
static void m1()
{
[Link]("from m1");
}

public static void main(String[] args)


{
// calling m1 without creating
// any object of class Test
m1();
}
}

Output
from m1

Static Blocks
If you need to do the computation in order to initialize your static variables, you can declare a
static block that gets executed exactly once, when the class is first loaded.
// Java program to demonstrate use of static blocks
class Geeks
{
// static variable
static int a = 10;
static int b;

// static block
static {
[Link]("Static block initialized.");
b = a * 4;
}

public static void main(String[] args)


{
[Link]("from main");
[Link]("Value of a : "+a);
[Link]("Value of b : "+b);
}
}

Output
Static block initialized.
from main
Value of a : 10
Value of b : 40

Static Variables
When a variable is declared as static, then a single copy of the variable is created and shared
among all objects at the class level. Static variables are, essentially, global variables. All
instances of the class share the same static variable.
Important points for static variables:
• We can create static variables at the class level only.
• static block and static variables are executed in the order they are present in a
program.

// Java program to demonstrate execution of static blocks and variables


class Geeks
{
// static variable
static int a = m1();

// static block
static {
[Link]("Inside static block");
}

// static method
static int m1() {
[Link]("from m1");
return 20;
}

// static method(main !!)


public static void main(String[] args)
{
[Link]("Value of a : "+a);
[Link]("from main");
}
}

Output
from m1
Inside static block
Value of a :20
from main

Static Methods
When a method is declared with the static keyword, it is known as the static method. The
most common example of a static method is the main() method. As discussed above, Any
static member can be accessed before any objects of its class are created, and without
reference to any object. Methods declared as static have several restrictions:
• They can only directly call other static methods.
• They can only directly access static data.
• They cannot refer to this or super in any way.

Static Classes
A class can be made static only if it is a nested class. We cannot declare a top-level class with
a static modifier but can declare nested classes as static. Such types of classes are called
Nested static classes. Nested static class doesn’t need a reference of Outer class. In this case,
a static class cannot access non-static members of the Outer class.
Example: This example demonstrates the use of a static nested class that can be
instantiated without needing an instance of the outer class.
import [Link].*;

public class Geeks {

private static String str = "GeeksforGeeks";

// Static class
static class MyNestedClass {

// non-static method
public void disp(){
[Link](str);
}
}

public static void main(String args[])


{
[Link] obj= new [Link]();
[Link]();
}
}

Output
GeeksforGeeks

The table below demonstrates the difference between Static and Non-Static
Static Non-Static

Static members are accessed via the Non-static members are accessed via an object
class name. reference.

Non-static members can be overridden in


Static members cannot be overridden.
subclasses.

Static members cannot use this or super Non-static members can use this and super
keyword. keyword.

Static members exist for the duration of Non-static members exist as long as the object
the class's lifecycle. they belong to is alive.

Advantages of Static Keyword


• Static members use the memory only once and this helps save memory when we have
to deal with big programs.
• Static members provide fast access because static members belong to the class not to
an object and that's why they can be access faster than regular member.
• We can access static members from anywhere, whether an object of the class has been
created or not.

Disadvantages of Static Keyword


• Static members can't be overridden or dynamically bound like instance members.
• Static variables stay in memory as long as the program runs, which might cause
memory to be used longer than needed.
• Using too many static members can reduce the benefits of object-oriented
programming, like hiding data and using inheritance.

Java this Keyword


Following are the ways to use the "this" keyword in Java mentioned below:
1. Using "this" keyword to distinguish between local variable and instance variable.
2. Using "this" keyword to refer to current class instance variables.
3. Using this() to invoke the current class constructor
4. Using 'this' keyword as the method parameter

1. Using "this" keyword to distinguish between local variable and instance variable.
Class Test
{
int i;
void setValue(int i)
{
this.i=i;
}
void show()
{
[Link](i);
}
}
Class Xyz
{
public static void main(String[]args)
{
Test t=new Test();
[Link](10);
[Link]();
}
}
OUTPUT
10

2. Using "this" to Refer to Current Class Instance Variables


// Java program for using "this" keyword to refer current class instance variables
class Geeks {
int a;
int b;

// Parameterized constructor
Geeks(int a, int b)
{
this.a = a;
this.b = b;
}

void display()
{
// Displaying value of variables a and b
[Link]("a = " + a + " b = " + b);
}

public static void main(String[] args)


{
Geeks object = new Geeks(10, 20);
[Link]();
}
}
Output
a = 10 b = 20
2. Using this() to Invoke Current Class Constructor
// Java program for using this() to invoke current class constructor
class Geeks {
int a;
int b;

// Default constructor
Geeks()
{
this(10, 20);
[Link]( "Inside default constructor \n");
}
// Parameterized constructor
Geeks(int a, int b)
{
this.a = a;
this.b = b;
[Link]( "Inside parameterized constructor");
}

public static void main(String[] args)


{
Geeks object = new Geeks();
}
}

Output
Inside parameterized constructor
Inside default constructor

4. Using "this" Keyword as a Method Parameter


// Java program for using "this" keyword as method parameter
class Geeks {
int a;
int b;

// Default constructor
Geeks()
{
a = 10;
b = 20;
}

// Method that receives "this" keyword as parameter


void display(Geeks obj)
{
[Link]("a = " + obj.a+ " b = " + obj.b);
}

// Method that returns current class instance


void get() {
display(this);
}

// main function
public static void main(String[] args)
{
Geeks object = new Geeks();
[Link]();
}
}

Output
a = 10 b = 20

Advantages of Using "this" Reference


• It helps to distinguish between instance variables and local variables with the same
name.
• It can be used to pass the current object as an argument to another method.
• It can be used to return the current object from a method.
• It can be used to invoke a constructor from another overloaded constructor in the
same class.

Disadvantages of Using "this" Reference


• Overuse of this can make the code harder to read and understand.
• Using this unnecessarily can add unnecessary overhead to the program.
• Using this in a static context results in a compile-time error.
• Overall, this keyword is a useful tool for working with objects in Java, but it should
be used judiciously and only when necessary.

Super Keyword in Java


The super keyword in Java is a reference variable that is used to refer to the parent class when
we are working with objects.
The Keyword "super" came into the picture with the concept of Inheritance.

Characteristics of Super Keyword in Java


• Calling the Parent Class Constructor: When we create an object of the subclass, its
constructor needs to call the constructor of the parent class. This can be done with the
help of the super keyword and it calls the constructor of the parent class.
• Accessing Parent Class Methods: If the subclass wants to access the methods of the
parent class, it can also be done with the help of the super keyword.
• First Statement in a Constructor: When calling a superclass constructor, the super()
statement must be the first statement in the constructor of the subclass. This ensures
that the parent class is properly initialized before the subclass does anything else.
• Cannot be used in Static Context: We cannot use super in a static variable, static
method and static block.
Note: It allows subclasses to inherit the behavior and functionality of the parent class.

Use of super Keyword in Java


1. Use of super with Variables
When the super class and sub class are same then it can be used only.

Program:
Class A
{
int a=10;
}
Class B extends A
{
int a=20;
void show()
{
[Link](a);
[Link](super.a);
}
}
Class Test
{
public static void main(String[]args) {
B r = new B();
[Link]();
}
}

Output
20
10

2. Use of super with Methods


This is used when we want to call the parent class method. So, whenever a parent and child
class have the same-named methods then to resolve ambiguity we use the super keyword.

Program:
Class A
{
void show()
{
[Link](“Hello”);
}
}
Class B extends A
{
void show()
{
[Link]();
[Link](“Bye”);
}
}
Class Test
{
public static void main(String[]args) {
B r = new B();
[Link]();
}
}

Output
Hello
Bye

3. Use of super with Constructors


The super keyword can also be used to access the parent class constructor. One more
important thing is that ‘super’ can call both parametric as well as non-parametric constructors
depending on the situation.

Program:
Class A
{
A()
{
[Link](“Hello”);
}
}
Class B extends A
{
B()
{
super(); // if you will write super keyword it will give the same output if you will not
write the super keyword in case of default constructor
[Link](“Bye”);
}
}
Class Test
{
public static void main(String[]args) {
B r = new B();
}
}
Output
Hello
Bye

Program:
Class A
{
A(int a)
{
[Link](“Hello”+a);
}
}
Class B extends A
{
B()
{
super(100); // it is compulsory to write super keyword in case of parameterized
constructor
[Link](“Bye”);
}
}
Class Test
{
public static void main(String[]args) {
B r = new B();
}
}
Output
Hello 100
Bye

Advantages of Using Java Super Keyword


• With the help of super keyword, subclasses can inherit the functionality from their
parent classes.
• Subclasses can override methods and can access fields and methods from their parent
class with the help of super keyword, because of this the code becomes more flexible.

Access Modifiers in Java


In Java, access modifiers are essential tools that define how the members of a class,
like variables, methods, and even the class itself, can be accessed from other parts of our
program. They are an important part of building secure and modular code when designing large
applications.

Algorithm to Use Access Modifier in Java


1. Define a class: Create a class to represent the object you want to manage.
2. Define instance variables: Inside the class, define variables for the data you want to
manage.
3. Set an access modifier:

• Use private for variables only accessible within the class.


• Use protected for variables accessible within the class and its subclasses.
• Use public for variables accessible from anywhere.
[Link] getter and setter methods: To access or modify variables, use getter (accessor) and
setter (mutator) methods, even for public variables, to maintain encapsulation.

1. Default Access Modifier


When no access modifier is specified for a class, method, or data member, it is said to have
the default access modifier by default. This means only classes within the same package can
access it.

2. Private Access Modifier


The private access modifier is specified using the keyword private. The methods or data
members declared as private are accessible only within the class in which they are declared.
• Any other class of the same package will not be able to access these members.
• Top-level classes or interfaces can not be declared as private because, private means
"only visible within the enclosing class". Protected means "only visible within the
enclosing class and any subclasses".
These modifiers in terms of application to classes, apply only to nested classes and not on
top-level classes.

3. Protected Access Modifier


The protected access modifier is specified using the keyword protected. The methods or data
members declared as protected are accessible within the same package or subclasses in
different packages.

4. Public Access Modifier


The public access modifier is specified using the keyword public.
• The public access modifier has the widest scope among all other access modifiers.
• Classes, methods, or data members that are declared as public are accessible from
everywhere in the program. There is no restriction on the scope of public data
members.

1. Base Class (in mypackage)


[Link]
package mypackage;

public class Student {


public String name = "Alice"; // Public member
protected int age = 21; // Protected member
String course = "Java"; // Default (no modifier)
private double marks = 90.5; // Private member

public void displayInfo() {


// Accessible inside the same class
[Link]("Name: " + name); //
[Link]("Age: " + age); //
[Link]("Course: " + course); //
[Link]("Marks: " + marks); //
}
}
Output (when called from within same class):
Name: Alice
Age: 21
Course: Java
Marks: 90.5

2. Same Package Subclass


[Link]
package mypackage;

public class SubclassStudent extends Student {


void showData() {
[Link](name); // public
[Link](age); // protected (same package)
[Link](course); // default (same package)
// [Link](marks); // private (not accessible)
}

public static void main(String[] args) {


SubclassStudent s = new SubclassStudent();
[Link]();
}
}
Output:
Alice
21
Java
marks not accessible because it is private.

3. Same Package Non-Subclass


[Link]
package mypackage;

public class NonSubclass {


public static void main(String[] args) {
Student s = new Student();
[Link]([Link]); // public
[Link]([Link]); // protected (same package)
[Link]([Link]); // default (same package)
// [Link]([Link]); // private
}
}
Output:
Alice
21
Java
Same as before — private member inaccessible.

4. Different Package Subclass


[Link]
package other;

import [Link];

public class SubclassInOther extends Student {


void show() {
[Link](name); // public
[Link](age); // protected (accessible via inheritance)
// [Link](course); // default (different package)
// [Link](marks); // private
}

public static void main(String[] args) {


SubclassInOther obj = new SubclassInOther();
[Link]();
}
}
Output:
Alice
21
default and private not accessible across packages.

5. Different Package Non-Subclass


[Link]
package other;

import [Link];

public class NonSubclassInOther {


public static void main(String[] args) {
Student s = new Student();
[Link]([Link]); // public
// [Link]([Link]); protected
// [Link]([Link]); default
// [Link]([Link]); private
}
}
Output:
Alice

Comparison Table of Access Modifiers in Java

Context Default Private Protected Public

Same Class Yes Yes Yes Yes

Same Package Subclass Yes No Yes Yes


Context Default Private Protected Public

Same Package Non-Subclass Yes No Yes Yes

Different Package Subclass No No Yes Yes

Different Package Non-Subclass No No No Yes

Inheritance in Java
Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the
mechanism in Java by which one class is allowed to inherit the features(fields and methods)
of another class. In Java, Inheritance means creating new classes based on existing ones. A
class that inherits from another class can reuse the methods and fields of that class.
Syntax
class ChildClass extends ParentClass {
// Additional fields and methods
}
Example: In the following example, Animal is the base class and Dog, Cat and Cow are
derived classes that extend the Animal class.

Implementation:
// Parent class
class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}

// Child class
class Dog extends Animal {
void sound() {
[Link]("Dog barks");
}
}

// Child class
class Cat extends Animal {
void sound() {
[Link]("Cat meows");
}
}

// Child class
class Cow extends Animal {
void sound() {
[Link]("Cow moos");
}
}

// Main class
public class Geeks {
public static void main(String[] args) {
Animal a;
a = new Dog();
[Link]();

a = new Cat();
[Link]();

a = new Cow();
[Link]();
}
}

Output
Dog barks
Cat meows
Cow moos

Why Use Inheritance in Java?


• Code Reusability: The code written in the Superclass is common to all subclasses.
Child classes can directly use the parent class code.
• Method Overriding: Method Overriding is achievable only through Inheritance. It is
one of the ways by which Java achieves Run Time Polymorphism.
Key Terminologies Used in Java Inheritance
• Class: Class is a set of objects that share common characteristics/ behavior and
common properties/ attributes. Class is not a real-world entity. It is just a template or
blueprint or prototype from which objects are created.
• Super Class/Parent Class: The class whose features are inherited is known as a
superclass(or a base class or a parent class).
• Sub Class/Child Class: The class that inherits the other class is known as a
subclass(or a derived class, extended class or child class). The subclass can add its
own fields and methods in addition to the superclass fields and methods.
• Extends Keyword: This keyword is used to inherit properties from a superclass.

Note
• We cannot access private members of class through inheritance
• A sub class contains all the features of super class so we should create the object of
sub class.

Types of Inheritance in Java


• Single Inheritance
• Multilevel Inheritance
• Hierarchical Inheritance
• Multiple Inheritance
1. Single Inheritance
In single inheritance, a sub-class is derived from only one super class. It inherits the
properties and behavior of a single-parent class. Sometimes, it is also known as simple
inheritance.

Example:
//Super class
class Vehicle {
Vehicle() {
[Link]("This is a Vehicle");
}
}

// Subclass
class Car extends Vehicle {
Car() {
[Link]("This Vehicle is Car");
}
}

public class Test {


public static void main(String[] args) {
// Creating object of subclass invokes base class constructor
Car obj = new Car();
}
}

Output
This is a Vehicle
This Vehicle is Car

2. Multilevel Inheritance
In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the
derived class also acts as the base class for other classes.

Example:
class Vehicle {
Vehicle() {
[Link]("This is a Vehicle");
}
}
class FourWheeler extends Vehicle {
FourWheeler() {
[Link]("4 Wheeler Vehicles");
}
}
class Car extends FourWheeler {
Car() {
[Link]("This 4 Wheeler Vehicle is a Car");
}
}
public class Geeks {
public static void main(String[] args) {
Car obj = new Car(); // Triggers all constructors in order
}
}
Output
This is a Vehicle
4 Wheeler Vehicles
This 4 Wheeler Vehicle is a Car

3. Hierarchical Inheritance
In hierarchical inheritance, more than one subclass is inherited from a single base class. i.e.
more than one derived class is created from a single base class. For example, cars and buses
both are vehicle.

Example:
class Vehicle {
Vehicle() {
[Link]("This is a Vehicle");
}
}
class Car extends Vehicle {
Car() {
[Link]("This Vehicle is Car");
}
}

class Bus extends Vehicle {


Bus() {
[Link]("This Vehicle is Bus");
}
}

public class Test {


public static void main(String[] args) {
Car obj1 = new Car();
Bus obj2 = new Bus();
}
}
Output
This is a Vehicle
This Vehicle is Car
This is a Vehicle
This Vehicle is Bus

4. Multiple Inheritance (Through Interfaces)


In Multiple inheritances, one class can have more than one superclass and inherit features
from all parent classes.
Note: that Java does not support multiple inheritances with classes. In Java, we can achieve
multiple inheritances only through Interfaces.

Example:
interface LandVehicle {
default void landInfo() {
[Link]("This is a LandVehicle");
}
}
interface WaterVehicle {
default void waterInfo() {
[Link]("This is a WaterVehicle");
}
}
// Subclass implementing both interfaces
class AmphibiousVehicle implements LandVehicle, WaterVehicle {
AmphibiousVehicle() {
[Link]("This is an AmphibiousVehicle");
}
}
public class Test {
public static void main(String[] args) {
AmphibiousVehicle obj = new AmphibiousVehicle();
[Link]();
[Link]();
}
}
Output
This is an AmphibiousVehicle
This is a WaterVehicle
This is a LandVehicle

Polymorphism in Java
Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that
allows objects to behave differently based on their specific class type. The
word polymorphism means having many forms, and it comes from the Greek words poly
(many) and morph (forms), this means one entity can take many forms.

Real-Life Illustration of Polymorphism


Consider a person who plays different roles in life, like a father, a husband, and an employee.
Each of these roles defines different behaviors of the person depending on the object calling
it.

Why Use Polymorphism In Java?


• Code Reusability: Polymorphism allows the same method or class to be used with
different types of objects, which makes the code more useable.
• Flexibility: Polymorphism enables object of different classes to be treated as objects of
a common superclass, which provides flexibility in method execution and object
interaction.
• Dynamic Behavior: With polymorphism, Java can select the appropriate method to
call at runtime, giving the program dynamic behavior based on the actual object type
rather than the reference type, which enhances flexibility.

Types of Polymorphism in Java


1. Compile-Time Polymorphism (Static)
2. Runtime Polymorphism (Dynamic)
Compile-Time Polymorphism (Static)
A polymorphism which exists at the time of compilation is called compile time or early
binding or static polymorphism.
Eg- Method Overloading

Method Overloading in Java


• Java can distinguish the methods with different method signatures.i.e. the methods can
have the same name but with different parameters list (i.e. the number of the
parameters, the order of the parameters, and data types of the parameters) within the
same class.
• Overloaded methods are differentiated based on the number and type of the
parameters passed as an argument to the methods.
• You cannot declare two methods with the same signature and different return type. It
will throw a compile- time error.

Why do we need Method Overloading?


If we need to do some kind of the operation with different ways i.e. for different inputs.
For example , we are doing the addition operation for different inputs.

Different ways of doing overloading methods


Method overloading can be done by changing:
• The number of parameters in methods.
• The data types of the parameters of methods.
• The Order of the parameters of methods.

Method 1: By changing the number of parameters.


// Importing required classes
import [Link].*;

class Product {

// Method 1
public int multiply(int a, int b)
{
int prod = a * b;
return prod;
}

// Method 2
public int multiply(int a, int b, int c)
{
int prod = a * b * c;
return prod;
}
}
class Geeks {

public static void main(String[] args)


{
// Creating object of above class inside main() method
Product ob = new Product();

// Calling method to Multiply 2 numbers


int prod1 = [Link](1, 2);

// Printing Product of 2 numbers


[Link]("Product of the two integer value: " + prod1);

// Calling method to multiply 3 numbers


int prod2 = [Link](1, 2, 3);

// Printing product of 3 numbers


[Link]("Product of the three integer value: " + prod2);
}
}
Output
Product of the two integer value: 2
Product of the three integer value: 6

Method 2: By changing the Data types of the parameters


import [Link].*;

class Product {

// Multiplying three integer values


public int prod(int a, int b, int c)
{
int prod1 = a * b * c;
return prod1;
}

// Multiplying three double values.


public double prod(double a, double b, double c)
{
double prod2 = a * b * c;
return prod2;
}
}
class Geeks {
public static void main(String[] args)
{
Product obj = new Product();

int prod1 = [Link](1, 2, 3);


[Link]("Product of the three integer value: " + prod1);

double prod2 = [Link](1.0, 2.0, 3.0);


[Link]("Product of the three double value: " + prod2);
}
}
Output
Product of the three integer value: 6
Product of the three double value: 6.0

Method 3: By changing the Order of the parameters


import [Link].*;

class Student {

// Method 1
public void StudentId(String name, int roll_no)
{
[Link]("Name: " + name + " "+ "Roll-No: " + roll_no);
}

// Method 2
public void StudentId(int roll_no, String name)
{
// Again printing name and id of person
[Link]("Roll-No: " + roll_no + " “+ "Name: " + name);
}
}
class Geeks {
public static void main(String[] args)
{
// Creating object of above class
Student obj = new Student();

// Passing name and id


// Reversing order
[Link]("Sweta", 1);
[Link](2, "Gudly");
}
}
Output
Name: Sweta Roll-No: 1
Roll-No: 2 Name: Gudly

Runtime Polymorphism (Dynamic)


A polymorphism which exists at the time of execution of program is called runtime
polymorphism.
Ex- Method overriding

Method Overriding
Overriding in Java occurs when a subclass or child class implements a method that is already
defined in the superclass or base class. When a subclass provides its own version of a method
that is already defined in its superclass, we call it method overriding. The subclass method
must match the parent class method's name, parameters, and return type.

Rules for Overriding:


• Name, parameters, and return type must match the parent method.
• Static methods cannot be overridden.

// Example of Overriding in Java


class shape
{
void draw()
{
[Link](“ Cant say shape type”);
}
}
class square extends shape
{
@override
void draw()
{
[Link](“ square shape”);
}
}
class Demo
{
public static void main(String[]args) {
shape r=new square();
[Link]();
Output
Square shape

Rules for Java Method Overriding


1. Access Modifiers in overriding
A subclass can make an overridden method more accessible, e.g., upgrade protected to public,
but not less e.g., downgrade public to private. Trying to hide a method this way causes
compiler errors.

2. Final Methods Cannot Be Overriden


If we don't want a method to be overridden, we declare it as final.
Note: If a method is declared as final, subclasses cannot override it.

3. Static Methods Cannot Be Overridden (Method Hiding)


When we define a static method with the same signature as a static method in the base class,
it is known as method hiding.
• Subclass Instance method can override the superclass's Instance method but when we
try to override the superclass static method gives a compile time error.
• Subclass Static method generate compile time when trying to override superclass
Instance method subclass static method hides when trying to override superclass static
method.

4. Private Methods Cannot Be Overridden


Private methods cannot be overridden as they are bonded during compile time. We cannot
even override private methods in a subclass.

6. Invoking Parent’s Overridden Method Using super


We can call the parent class method in the overriding method using the super keyword.
Note: Use [Link]() to call the parent's version.

Method Overloading vs Method Overriding


The table below demonstrates the difference between Method Overloading and Method
Overriding
Feature Method Overloading Method Overriding

Same method name, different Same method signature,


Definition parameters different class

Polymorphism Compile-time polymorphism Runtime polymorphism


Type (Static) (Dynamic)
Feature Method Overloading Method Overriding

Involves inheritance (parent-


No inheritance involved
Inheritance child)

Dynamic Method Dispatch or Runtime Polymorphism in Java


Dynamic method dispatch is the mechanism by which a call to an overridden method is
resolved at run time, rather than compile time.
• When an overridden method is called through a superclass reference, Java determines
which version(superclass/subclasses) of that method is to be executed based upon the
type of the object being referred to at the time the call occurs. Thus, this
determination is made at run time.
• At run-time, it depends on the type of the object being referred to (not the type of the
reference variable) that determines which version of an overridden method will be
executed
• A superclass reference variable can refer to a subclass object. This is also known as
upcasting. Java uses this fact to resolve calls to overridden methods at run time.

Therefore, if a superclass contains a method that is overridden by a subclass, then when


different types of objects are referred to through a superclass reference variable, different
versions of the method are executed.
Here is an example that illustrates dynamic method dispatch:
Class Phone{
Public void showTime(){
[Link](“ Time is 8am”);
}
Public void on(){
[Link](“Turning on Phone”);
}
Class Smartphone extends Phone{
Public void music(){
[Link](“ Playing music”);
}
Public void on(){
[Link](“ Turning on smartphone”);
}
Public class dynamic_method_dispatch{
Public static void main(String[]args){
//Phone obj=new Phone(); //Allowed
//Smartphone smobj=new Smartphone(); //Allowed
//[Link]();
Phone obj=new Smartphone(); //Allowed
//Smartphone obj2=new Phone(); //Not allowed
[Link]();
[Link](); //subclass method run
[Link](); //not allowed

OUTOUT:
Time is 8am
Turning on Smartphone

Advantages of Dynamic Method Dispatch


1. Dynamic method dispatch allow Java to support overriding of methods which is
central for run-time polymorphism.
2. It allows a class to specify methods that will be common to all of its derivatives, while
allowing subclasses to define the specific implementation of some or all of those
methods.
3. It also allow subclasses to add its specific methods subclasses to define the specific
implementation of some.

Constructor Overloading in Java


Constructor overloading means multiple constructors in a class. When you have multiple
constructors with different parameters listed, then it will be known as constructor
overloading.

class A {
int a;
double b;
string c;

A()
{
a=100; b=45.32; c=”ankit”;

A(int x)
{
a=x;
}
A(double y, String z)
{
b=y; c=z;
}
}

class B {
public static void main(String args[])
{
A r=new A();
A r2=new A(10);
A r3=new A(23.89,”Ankush”);
[Link](r.a+” “+r.b+” “+r.c);
[Link](r2.a);
[Link](r3.b+” “+r3.c);
}
}
Output
100 45.32 ankit
10
23.89 Ankush

String Class in Java


The String class in Java is used to create and manipulate sequences of characters. It is
one of the most commonly used classes in Java.

There are two ways to create String object-


1. String literal
2. new keyword

Key Features of the String Class


1. Immutable
Immutable means that once a String object is created, its value cannot be changed.
Example:

class A {
public static void main(String[] args) {
String a = "ankit"; //literal
[Link](a);

String b=”ankit”; //literal


[Link](b);
// [Link](“kumar”);
// [Link](a); //output will be ankit concat will not work

a=[Link](“kumar”);
// [Link](a);
}
}

OUTPUT:
ankit
ankit
ankitkumar

class A {
public static void main(String[] args) {
String a =new String( "ankit"); //object using new keyword
[Link](a);

String b= new String(”ankit”); //object using new keyword


[Link](b);

// [Link](“kumar”);
// [Link](a); //output will be ankit concat will not work

a=[Link](“kumar”);
// [Link](a);
}
}

OUTPUT:
ankit
ankit
ankitkumar

2. Supports Various Utility Methods


String is a predefined final class in Java present in [Link] package. It provides
various methods to create, manipulate, and compare strings, like length(), charAt(),
concat(), equals(), etc.

Example:
import [Link].*;

class GFG {
public static void main (String[] args) {
String str = "hello geeks";
[Link]("Length of String-> "+[Link]());
[Link]("Changed String ->"+[Link]());
}
}
Output
Length of String-> 11
Changed String ->HELLO GEEKS

String Constructors in Java


In Java, String constructors are used to create new String objects from different sources
like character arrays, byte arrays, or another string. Although strings in Java are usually
created using string literals, the String class also provides constructors for more control.

Example of String Constructor


import [Link].*;

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

// Constructor 1: Creating string using new keyword


String str1 = new String("Hello Java");
[Link]("String using new keyword: " + str1);

// Constructor 2: Creating string from character array


char[] charArray = { 'J', 'A', 'V', 'A' };
String str2 = new String(charArray);
[Link]("String from char array: " + str2);

// Constructor 3: Creating string from byte array


byte[] byteArray = { 72, 101, 108, 108, 111 };
String str3 = new String(byteArray);
[Link]("String from byte array: " + str3);

}
}

Output
String using new keyword: Hello Java
String from char array: JAVA
String from byte array: Hello
StringBuffer Class in Java
The StringBuffer class in Java represents a sequence of characters that can be
modified, which means we can change the content of the StringBuffer without
creating a new object every time. It represents a mutable sequence of characters.

The key features of StringBuffer class are listed below:


• Unlike String, we can modify the content of the StringBuffer without creating a new
object.
• All methods of StringBuffer are synchronized, making it safe to use in multithreaded
environments.
• Ideal for scenarios with frequent modifications like append, insert, delete, or replace
operations.

Example: Here is an example of using StringBuffer to concatenate strings:


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

// Creating StringBuffer
StringBuffer s = new StringBuffer();

// Adding elements in StringBuffer


[Link]("Hello");
[Link](" ");
[Link]("world");

// String with the StringBuffer value


String str = [Link]();
[Link](str);
}
}

Output
Hello world

Constructors of StringBuffer Class


1. StringBuffer(): It reserves room for 16 characters without reallocation
2. StringBuffer(int size): It accepts an integer argument that explicitly sets the size of
the buffer.
3. StringBuffer(String str): It accepts a string argument that sets the initial contents of
the StringBuffer object and reserves room for 16 more characters without reallocation.

Example:
public class Geeks {
public static void main(String[] args) {

// 1. Using default constructor


StringBuffer sb1 = new StringBuffer();
[Link]("Hello");
[Link]("Default Constructor: " + sb1);

// 2. Using constructor with specified capacity


StringBuffer sb2 = new StringBuffer(50);
[Link]("Java Programming");
[Link]("With Capacity 50: " + sb2);

// 3. Using constructor with String


StringBuffer sb3 = new StringBuffer("Welcome");
[Link](" to Java");
[Link]("With String: " + sb3);
}
}

Output
Default Constructor: Hello
With Capacity 50: Java Programming
With String: Welcome to Java

Implementation of Java StringBuffer Method


1. append() Method
append() method concatenates the given argument with this string.
Example:
import [Link].*;

class Geeks {
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello ");
[Link]("Java"); // now original string is changed
[Link](sb);
}
}

Output
Hello Java

2. insert() Method
insert() method inserts the given string with this string at the given position.
Example:
import [Link].*;

class Geeks {
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello ");
[Link](1, "Java");

// Now original string is changed


[Link](sb);
}
}
Output
HJavaello

3. replace() Method
replace() method replaces the given string from the specified beginIndex and
endIndex-1.
Example:
import [Link].*;

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

StringBuffer sb = new StringBuffer("Hello");


[Link](1, 3, "Java");
[Link](sb);
}
}
Output
HJavalo

4. delete() Method
delete() method is used to delete the string from the specified beginIndex to endIndex-
1.
Example:
import [Link].*;

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

StringBuffer sb = new StringBuffer("Hello");


[Link](1, 3);
[Link](sb);
}
}
Output
Hlo
5. reverse() Method
reverse() method of the StringBuffer class reverses the current string.
Example:
import [Link].* ;

class Geeks {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Hello");
[Link]();
[Link](sb);
}
}
Output
olleH

6. capacity() Method
capacity() method of the StringBuffer class returns the current capacity of the buffer.
The default capacity of the buffer is 16. If the number of characters increases from its
current capacity, it increases the capacity by (oldcapacity*2)+2.
For example, if the current capacity is 16, it will be (16*2)+2=34.
Example:
import [Link].*;

class Geeks {
public static void main(String args[])
{
StringBuffer sb = new StringBuffer();

// default 16
[Link]([Link]());
[Link]("Hello");

// now 16
[Link]([Link]());
[Link]("java is my favourite language");

// (oldcapacity*2)+2
[Link]([Link]());
}
}
Output
16
16
34
7. length()
This method return the number of character in given string.
import [Link].*;

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

// Creating and storing string by creating object of StringBuffer


StringBuffer s = new StringBuffer("GeeksforGeeks");

// Getting the length of the string


int p = [Link]();

// Getting the capacity of the string


[Link]("Length of string GeeksforGeeks=" + p);
}
}
Output
Length of string GeeksforGeeks=13

Advantages of using StringBuffer


• Mutable: StringBuffer are mutable it means that we can change the content after the
object has been created, on the other hand String are immutable once it created it can
not be modified.
• Efficient: Since StringBuffer objects are mutable, it is suitable in scenarios where we
need to modify the string multiple times. If we do the same thing with string,
everytime a new object is created and the old one is deleted, which is very bad in
terms of performance and memory.

Disadvantage of StringBuffer
• Slower in single-threaded programs: It's synchronized, meaning it ensures thread
safety by allowing only one thread to access it at a time. However, in single-threaded
environments, this synchronization is unnecessary and slows down performance
compared to non-synchronized classes like StringBuilder.
• Less efficient than StringBuilder: For non-threaded use cases, StringBuilder is
faster and has similar functionality. Also, StringBuffer operations like append() or
insert() make the code longer compared to using simple '+' with String.

StringBuilder Class in Java


In Java, the StringBuilder class is a part of the [Link] package that provides a mutable
sequence of characters. Unlike String (which is immutable), StringBuilder allows in-place
modifications, making it memory-efficient and faster for frequent string operations.
The key features of the StringBuilder class are listed below:
• It offers similar functionality to StringBuffer, but without thread safety which means it
can be used in a multi threaded environment without any issues.
• StringBuilder is not synchronized, making it faster and more efficient than StringBuffer
in single-threaded applications.
• Use StringBuffer only when thread safety is needed; otherwise, prefer StringBuilder for
better performance.
Declaration:
StringBuilder sb = new StringBuilder("Initial String");

Example: Demonstration of a StringBuilder class in Java.


public class Geeks
{
public static void main(String[] args) {
// Create a new StringBuilder with the initial content "GeeksforGeeks"
StringBuilder sb = new StringBuilder("GeeksforGeeks");
[Link]("Initial StringBuilder: " + sb);

// Append a string to the StringBuilder


[Link](" is awesome!");
[Link]("After append: " + sb);
}
}
Output
Initial StringBuilder: GeeksforGeeks
After append: GeeksforGeeks is awesome!

Explanation:
• In the above code, we first create a StringBuilder with the object sb and put the initial
string as "GeeksforGeeks"
• Then we use the append() method from StringBuilder class to add the " is awesome!"
string in end of current StringBuilder object.

StringBuilder Constructors
The StringBuilder class provides several constructors, which are listed below: Example:
Creating a string using the StringBuilder Constructor StringBuilder(String str).
1. StringBuilder(): Creates an empty StringBuilder with a default initial capacity of 16
characters.
2. StringBuilder(int capacity): Creates an empty StringBuilder with a specified initial
capacity. This is useful if you know the string will grow large.
3. StringBuilder(String str): Creates a StringBuilder initialized with the content of the
given String.
4. StringBuilder(CharSequence cs): Creates a StringBuilder using the content of a
given CharSequence object (like a String, StringBuffer, or any custom class
implementing CharSequence).

Example:
public class StringBuilderConstructorsDemo {
public static void main(String[] args) {

// 1. Default constructor (capacity = 16)


StringBuilder sb1 = new StringBuilder();
[Link]("Hello");
[Link]("sb1: " + sb1);

// 2. Constructor with capacity


StringBuilder sb2 = new StringBuilder(50);
[Link]("This has initial capacity 50");
[Link]("sb2: " + sb2);

// 3. Constructor with String input


StringBuilder sb3 = new StringBuilder("Geeks");
[Link]("ForGeeks");
[Link]("sb3: " + sb3);

// 4. Constructor with CharSequence input


CharSequence cs = "Java";
StringBuilder sb4 = new StringBuilder(cs);
[Link]("Programming");
[Link]("sb4: " + sb4);
}
}

Output
Hello
This has initial capacity 50
GeeksForGeeks
JavaProgramming

Methods of StringBuilder class


The StringBuilder class provides several methods for creating and manipulating strings.

Example: Performing different String manipulation operations using StringBuilder methods


such as appending, inserting, replacing, deleting, reversing and accessing characters.
public class Geeks
{
public static void main(String[] args) {

// Create a new StringBuilder with the initial content "GeeksforGeeks"


StringBuilder sb = new StringBuilder("GeeksforGeeks");
[Link]("Initial StringBuilder: " + sb);

// 1. Append a string to the StringBuilder


[Link](" is awesome!");
[Link]("After append: " + sb);

// 2. Insert a substring at a specific position


[Link](13, " Java");
[Link]("After insert: " + sb);

// 3. Replace a substring with another string


[Link](0, 5, "Welcome to");
[Link]("After replace: " + sb);

// 4. Delete a substring from the StringBuilder


[Link](8, 14);
[Link]("After delete: " + sb);

// 5. Reverse the content of the StringBuilder


[Link]();
[Link]("After reverse: " + sb);

// 6. Get the current capacity of the StringBuilder


int capacity = [Link]();
[Link]("Current capacity: " + capacity);

// 7. Get the length of the StringBuilder


int length = [Link]();
[Link]("Current length: " + length);

// 8. Access a character at a specific index


char charAt5 = [Link](5);
[Link]("Character at index 5: " + charAt5);

// 9. Set a character at a specific index


[Link](5, 'X');
[Link]("After setCharAt: " + sb);

// 10. Get a substring from the StringBuilder


String substring = [Link](5, 10);
[Link]("Substring (5 to 10): " + substring);

// 11. Find the index of a specific substring


[Link](); // Reversing back to original order for search
int indexOfGeeks = [Link]("Geeks");
[Link]("Index of 'Geeks': " + indexOfGeeks);
// 12. Delete a character at a specific index
[Link](5);
[Link]("After deleteCharAt: " + sb);

// 13. Convert the StringBuilder to a String


String result = [Link]();
[Link]("Final String: " + result);
}
}
Output:

String Builder vs String vs String Buffer

Features StringBuilder StringBuffer


String

String are
StringBuilder are StringBuffer are
immutable(creates new
mutable(modifies in mutable (modifies in
objects on
place) place)
Mutability modification)

Thread-Safe It is not thread-safe It is not thread-safe It is thread-safe

It is slow because it It is faster than


It is faster compared
creates an object each StringBuffer because it
to string
Performance time is not thread safe
Features StringBuilder StringBuffer
String

Fixed, unchanging Single-threaded string Multi-threaded string


Use Case strings manipulation manipulation

Java String Tokenizer Class


• String Tokenizer class in Java is used to break a string into tokens based on
delimiters.
• A delimiter is a character or set of characters that separate tokens in the string.
• A token is returned by taking a substring of the string that was used to create the
StringTokenizer object.
• To perform Java String Tokenization, we need to specify an input string and a set of
delimiters.
Example: Below is a simple example that explains the us of Java String Tokenizer to split a
space-separated string into tokens:
import [Link];
public class Geeks {
public static void main(String[] args) {

// Input string
String s = "Hello Geeks how are you";

// Create a StringTokenizer object with space as the delimiter


StringTokenizer st = new StringTokenizer(s, " ");

// Tokenize the string and print each token


while ([Link]()) {
[Link]([Link]());
}
}
}
Output
Hello
Geeks
how
are
you
Explanation: In the above example, we have created a String Tokenizer object by passing
the string s and a space " " as the delimiter. The hasMoreTokens() method checks there are
more tokens available to process or not. The nextToken() method get the next token
(substring).
Constructors of String Tokenizer Class

Description
Constructors

Creates a tokenizer for the specified string.


Uses default delimiters (whitespace, tabs,
StringTokenizer(String str) etc.).

StringTokenizer(String str, Creates a tokenizer for the specified string


String delim) using the given delimiters.

Creates a tokenizer for the specified string


StringTokenizer(String str, using the given delimiters and specifies
String delim, boolean whether the delimiters should be returned as
returnDelims) tokens.

• Default Delimiters: When no delimiter is specified, whitespace is used.


• returnDelims: If true, the delimiters are treated as tokens themselves.

// Demonstration of String Tokenizer Constructors


import [Link].*;

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

// Example with Constructor 1


[Link]("Using StringTokenizer Constructor 1: ");

// Using StringTokenizer to split the string into tokens using space (" ") as the delimiter
StringTokenizer st1 = new StringTokenizer( "Geeks for Geeks", " ");

// Iterate through tokens while there are more tokens available


while ([Link]())

// Getting and printing the next token


[Link]([Link]());

// Example with Constructor 2


[Link]("Using StringTokenizer Constructor 2: ");

// Using StringTokenizer to split the string using ":" as the delimiter


StringTokenizer st2 = new StringTokenizer( "java : Code : String : Tokenizer", " :");

// Iterate through tokens and print them


while ([Link]())
[Link]([Link]());

// Example with Constructor 3


[Link]("Using StringTokenizer Constructor 3: ");

// Using StringTokenizer with returnDelims = true to include delimiters as tokens


StringTokenizer st3 = new StringTokenizer("java : Code", " :", true);

// Iterate through tokens (including delimiters) and print them


while ([Link]())
[Link]([Link]());
}
}

Output
Using StringTokenizer Constructor 1:
Geeks
for
Geeks
Using StringTokenizer Constructor 2:
java
Code
String
Tokenizer
Using StringTokenizer Constructor 3:
java
:
Code

Methods Of String Tokenizer Class


Action Performed
Method

Returns the total number of tokens


countTokens()
present.

Tests if tokens are present for the


hasMoreTokens()
StringTokenizer's string.

Returns the next token from the given


nextToken()
StringTokenizer.

// Demonstration of String Tokenizer Methods


import [Link].*;

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

// Creating a StringTokenizer
StringTokenizer st = new StringTokenizer("Welcome to GeeksforGeeks");

StringTokenizer st1 = new StringTokenizer("");

// countTokens Method
int c = [Link]();
[Link](c);

// hasMoreTokens Methods
[Link]("Welcome to GeeksforGeeks: "+ [Link]());
[Link]("(Empty String) : "+ [Link]());

// nextElement() Method
[Link]("\nTraversing the String:");

while([Link]()){
[Link]([Link]());
}

}
}

Output
3
Welcome to GeeksforGeeks: true
(Empty String) : false

Traversing the String:


Welcome
to
GeeksforGeeks

Wrapper Classes in Java


A Wrapper class in Java is one whose object wraps or contains primitive data types. When we
create an object in a wrapper class, it contains a field and in this field, we can store primitive
data types. In other words, we can wrap a primitive value into a wrapper class object.

Primitive Data Types and their Corresponding Wrapper Classes


Primitive Data Type Wrapper Class

char Character

byte Byte

short Short

int Integer

long Long

float Float

double Double

boolean Boolean
Example: Demonstration to convert the primitive to its corresponding wrapper.
class Geeks
{
public static void main(String[] args)
{
// Primitive data type
int b;

// Integer wrapper class


Integer a;

// assigning value to primitive


b = 357;

// auto-boxing or auto wrapping converting primitive int to Integer object


a = b;

[Link]("The primitive int b is: " + b);


[Link]("The Integer object a is: " + a);
}
}

Output
The primitive int b is: 357
The Integer object a is: 357

Explanation: In the above example, we first create an primitive int b and assign a
value 357. Then we assign this primitive value to an Integer object b and it automatically
covert it to primitve to a Integer object(Autoboxing).
Need of Wrapper Classes
• They convert primitive data types into objects. Objects are needed if we wish to
modify the arguments passed into a method (because primitive types are passed by
value).
• The classes in [Link] package handle only objects and hence wrapper classes help in
this case.

Different Ways to Create the Instances of Wrapper Classes in Java

Wrapper Class is a class whose object wraps or contains primitive data types. When we create
an object to a wrapper class, it contains a field and in this field, we can store primitive data
types. In other words, we can wrap a primitive value into a wrapper class object.

Methods:
1. Using the constructor of the wrapper class
2. Using the valueOf() method provided by the Wrapper classes
3. Using concept of AutoBoxing

Method 1: Using the constructor of the wrapper class


Syntax:
ClassName object = new ClassName(argument);
Illustration:
Integer number = new Integer(5);

Method 2: Using the valueOf() method provided by the Wrapper classes


Syntax:
ClassName object = [Link](argument);
Illustration:
Integer number = [Link](5);

import [Link].*;
class GFG {

// Main driver method


public static void main (String[] args) {

// Creating and initializing two integer numbers


// Value is passed as an argument to which it is initialized

Integer num1 = new Integer(5);


// Number 2 where N = 5
Integer num2 = new Integer(5);

// Creating objects of Integer class using valueOf() method

// Again, creating and initializing two integer numbers


// Value is passed as an argument to which it is initialized
Integer num3 = [Link](5);
Integer num4 = [Link](5);

// Boolean will return true if numbers are equal else returning false

// Comparing two numbers


boolean value1 = (num1 == num2);
boolean value2 = (num3 == num4);

// Print and display the bool results


[Link](value1);
[Link](value2);
}
}
Output:
false
true

Output explanation:
Note that, the instances of the classes point to the memory locations assigned in the heap and
themselves do not hold the value. While we are creating objects with the help of the
constructor of the wrapper class, each time a new memory is allocated in the heap and the
objects point to the different memory locations. Hence, in the above example, In this case,
both num1 and num2 are pointing to different memory locations, thus on the comparison,
they return false.
Do note is not so in the case of the valueOf() method as the valueOf() method checks if any
memory is allocated to the same value for that class in the heap. If it finds the value, then it
provides the location of the previously allotted memory to the new instance and both start
pointing to the same memory location in the heap. Hence, on the comparison, it returns true.
Since the wrapper class object's values are immutable just like String and thus can not be
changed once allotted, it does not affect how many instances are pointing to the same
memory location. Hence, in the above example, the memory was allotted to value 5 and the
num3 was pointing to that memory location, but when we created one more instance num4
with the same value, it also started pointing to the same memory location as pointed by num3.
Currently, the method using a constructor to create an instance is deprecated, and therefore it
is always best to use the valueOf() method.

Autoboxing and Unboxing


1. Autoboxing
The automatic conversion of primitive types to the object of their corresponding wrapper
classes is known as autoboxing. For example – conversion of int to Integer, long to Long,
double to Double, etc.
Example: Java program to demonstrate the automatic conversion of primitive to wrapper
class (Autoboxing).
import [Link];

class Geeks
{
public static void main(String[] args)
{
char ch = 'a';

// Autoboxing- primitive to Character object conversion


Character a = ch;

ArrayList<Integer> arrayList= new ArrayList<Integer>();


// Autoboxing because ArrayList stores only objects
[Link](25);

// printing the values from object


[Link]([Link](0));
}
}

Output
25

2. Unboxing
It is just the reverse process of autoboxing. Automatically converting an object of a wrapper
class to its corresponding primitive type is known as unboxing. For example, conversion of
Integer to int, Long to long, Double to double, etc.
Example: Java program demonstrates automatic conversion of wrapper class to primitive
(Unboxing).
import [Link];

class Geeks
{
public static void main(String[] args)
{
Character ch = 'a';

// unboxing - Character object to primitive conversion


char a = ch;

ArrayList<Integer> arrayList = new ArrayList<Integer>();


[Link](24);

// unboxing because get method returns an Integer object


int num = [Link](0);

// printing the values from primitive data types


[Link](num);
}
}

Output
24

Java Wrapper Classes Example


import [Link].*;
class Geeks {
public static void main(String[] args)
{
// byte data type
byte a = 1;

// wrapping around Byte object (use valueOf or autoboxing)


Byte byteobj = [Link](a);

// int data type


int b = 10;

// wrapping around Integer object (use valueOf or autoboxing)


Integer intobj = [Link](b);

// float data type


float c = 18.6f;

// wrapping around Float object (use valueOf or autoboxing)


Float floatobj = [Link](c);

// double data type


double d = 250.5;

// Wrapping around Double object (use valueOf or autoboxing)


Double doubleobj = [Link](d);

// char data type


char e = 'a';

// wrapping around Character object (autoboxing)


Character charobj = e;

// printing the values from objects


[Link]("Values of Wrapper objects (printing as objects)");
[Link]("\nByte object byteobj: "+ byteobj);
[Link]("\nInteger object intobj: "+ intobj);
[Link]("\nFloat object floatobj: "+ floatobj);
[Link]("\nDouble object doubleobj: "+ doubleobj);
[Link]("\nCharacter object charobj: "+ charobj);

// objects to data types unwrapping objects to primitive datatypes


byte bv = byteobj;
int iv = intobj;
float fv = floatobj;
double dv = doubleobj;
char cv = charobj;

// printing the values from data types


[Link]("\nUnwrapped values (printing as data types)");
[Link]("\nbyte value, bv: " + bv);
[Link]("\nint value, iv: " + iv);
[Link]("\nfloat value, fv: " + fv);
[Link]("\ndouble value, dv: " + dv);
[Link]("\nchar value, cv: " + cv);
}
}

Output:

You might also like