Java (Unit 2)
Java (Unit 2)
Unit 2
Classes and Objects
Class:
• A class is a user-defined data type or blueprint that is used to create objects.
• It defines the properties (fields or variables) and behaviors (methods or functions) that the
objects created from the class will have.
• A class groups data members (fields) and member functions (methods) together into a single
unit.
• The variables inside a class store information about an object, while the methods define the
operations that can be performed on that data.
• Syntax: access_specifier class Classname
{
// Field declaration
//Method declaration
}
➢ Field Declaration:
▪ A field declaration is the process of defining a variable inside a class that is used
to store the data or attributes of an object
▪ Fields represent the characteristics or properties of a class.
▪ They are declared within the class body but outside any method.
▪ Each object created from the class gets its own copy of these fields, which store
the values related to that object.
▪ Syntax: dataType fieldName;
▪ Example: int a;
➢ Method Declaration:
▪ A method declaration is the process of defining a function inside a class that
specifies the behavior or actions that an object can perform.
▪ A method describes what operation will be performed when it is called.
▪ It consists of a method name, return type, parameters (optional), and a method
body containing the statements that perform a specific task.
▪ Methods operate on the fields (data members) of a class and help implement the
functionality of the program.
▪ They are declared inside the class body and are executed when they are invoked
or called by an object.
▪ Syntax:
returnType methodName(parameterList)
{
// method body
}
JSSCW, Chamarajanagara 1
Java (Unit 2) Mohankumari B S
Parts of a Method Declaration
1. returnType
• Specifies the type of value the method will return after execution.
• If the method does not return any value, the void keyword is used.
• The returned value must match the declared return type.
2. methodName
• The identifier used to call the method.
• It should be meaningful and describe the action performed by the method.
• Method names usually follow camelCase naming convention (e.g., calculateTotal,
displayDetails).
3. parameterList
• Contains the input values passed to the method.
• Each parameter has a data type and variable name.
• Multiple parameters are separated by commas.
• Parameters are optional; a method can also have no parameters.
4. methodBody
• The block of code inside curly braces { }.
• It contains statements that define what the method does.
• It may include calculations, printing output, or manipulating data.
Objects:
• An object is an instance of a class.
• An object represents a real-world entity and contains data and behavior.
• The data is stored in fields (variables), and the behavior is defined by methods (functions) in
the class.
• Objects are created from a class, which acts as a blueprint.
• Each object created from the same class has the same structure and methods, but it can store
different values in its fields.
• For example: if there is a Student class, multiple objects such as student1, student2, and
student3 can be created, each representing a different student with different data like id, name,
and marks.
• Syntax: ClassName objectName = new ClassName();
JSSCW, Chamarajanagara 2
Java (Unit 2) Mohankumari B S
Constructor
• A constructor is a special type of method used to initialize objects of a class.
• A constructor is automatically called when an object of the class is created.
• Its main purpose is to initialize the data members (fields) of the class.
• The constructor has the same name as the class and it does not have a return type, not even
void.
• Constructors help assign initial values to the variables when an object is created.
• Syntax:
class ClassName
{
Constructor/ClassName()
{
// constructor body
}
}
• There are three types
➢ Default Constructor
➢ Parameterized Constructor
➢ Copy Constructor
1) Default Constructor
• A default constructor is a constructor that does not take any parameters. It assigns
default values to the object variables.
• Default constructor has no parameters.
• It is used to assign default values to fields.
• If no constructor is written in a class, the compiler may provide a default constructor
automatically.
• Syntax:
ClassName()
{
// initialization code
}
• The default constructor is automatically called when an object is created without
arguments.
• Example: Student s1 = new Student();
2) Parameterized Constructor
• A parameterized constructor is a constructor that accepts parameters to initialize objects
with different values.
• This constructor takes arguments (parameters).
• It is used to initialize objects with different values.
• It helps to reduce repeated assignments.
• Syntax:
ClassName(3atatype parameter1, 3atatype parameter2)
{
// initialization code
}
JSSCW, Chamarajanagara 3
Java (Unit 2) Mohankumari B S
• Syntax:
ClassName(4atatype parameter1, 4atatype parameter2)
{
// initialization code
}
• Example:
Student s1 = new Student(101, “Rahul”);
Student s2 = new Student(102, “Anita”);
3) Copy Constructor
• A copy constructor creates a new object by copying values from another object of the
same class.
• Takes another object of the same class as parameter.
• It is used to copy data from one object to another.
• It helps create duplicate objects with the same values.
• Syntax:
ClassName(ClassName objectName)
{
// copy values
}
• The copy constructor is called by passing an existing object as an argument.
• Example:
Student s1 = new Student();
Student s2 = new Student(s1);
JSSCW, Chamarajanagara 4
Java (Unit 2) Mohankumari B S
void display()
{
[Link](id + “ “ + name);
}
}
class Test
{
public static void main(String[] args)
{
Student s1 = new Student(); // Calling default constructor
[Link]();
OUTPUT
0 Unknown
101 Rahul
101 Rahul
Method Overloading
• Method overloading is a feature in object-oriented programming where two or more methods
in the same class have the same name but different parameters (number, type, or sequence of
parameters).
• It allows multiple methods to perform similar tasks but with different input values.
• Key Points:
1. Methods must have the same name.
2. Methods must have different parameter lists (different number, type, or order of
parameters).
3. Return type can be the same or different, but cannot be the only difference.
4. Overloading helps improve code readability and reusability.
• Syntax:
class ClassName
{
void methodName(int a) { }
void methodName(int a, int b) { }
void methodName(String s) { }
}
JSSCW, Chamarajanagara 5
Java (Unit 2) Mohankumari B S
• Example:
class Calculator
{
// Method with 2 integer parameters
int add(int a, int b)
{
return a + b;
}
// Method with 3 integer parameters
int add(int a, int b, int c)
{
return a + b + c;
}
// Method with 2 double parameters
double add(double a, double b)
{
return a + b;
}
}
class Test
{
public static void main(String[] args)
{
Calculator calc = new Calculator();
[Link]([Link](10, 20)); // calls method with 2 ints
[Link]([Link](10, 20, 30)); // calls method with 3 ints
[Link]([Link](10.5, 20.5)); // calls method with 2 doubles
}
}
OUTPUT
30
60
31.0
JSSCW, Chamarajanagara 6
Java (Unit 2) Mohankumari B S
Constructor Overloading
• Constructor overloading is a feature in object-oriented programming languages like Java where
a class can have more than one constructor with the same name (the class name) but different
parameters (number, type, or order of parameters).
• It allows creating objects in different ways with different initial values.
• Key Points
1. All constructors have the same name as the class.
2. Constructors must have different parameter lists (number, type, or order of parameters).
3. Return type is not used in constructors.
4. Helps in flexible object initialization.
• Syntax:
class ClassName
{
ClassName() { } // Default constructor
ClassName(int a) { } // Parameterized constructor
ClassName(int a, String s) { } // Another parameterized constructor
}
• Example:
class Student
{
int id;
String name;
Student() // Default constructor
{
id = 0;
name = "Unknown";
}
Student(int i) // Constructor with 1 parameter
{
id = i;
name = "Unknown";
}
Student(int i, String n)
{
id = i;
name = n;
}
void display()
{
[Link](id + " " + name);
}
}
class Test
{
public static void main(String[] args)
{
JSSCW, Chamarajanagara 7
Java (Unit 2) Mohankumari B S
Student s1 = new Student(); // calls default constructor
Student s2 = new Student(101); // calls constructor with 1 parameter
Student s3 = new Student(102, "Rahul"); // calls constructor with 2
parameters
[Link]();
[Link]();
[Link]();
}
}
OUTPUT
0 Unknown
101 Unknown
102 Rahul
Static Members
• Static members are class-level variables and methods that are shared by all objects of the
class rather than belonging to individual objects.
• Declared using the static keyword.
• Only one copy exists, regardless of how many objects are created.
• Useful for common data or behavior across all objects.
• Example:
A schoolName for all students in a Student class can be a static variable because it is
the same for everyone.
JSSCW, Chamarajanagara 8
Java (Unit 2) Mohankumari B S
[Link] Methods
• A static method is a method declared with the keyword static inside a class.
• Static methods belong to the class itself, not to any particular object.
• They can be called directly using the class name without creating an object.
• Important Characteristics:
▪ Static methods can directly access only static variables and other static methods.
▪ Static methods cannot access instance variables or instance methods directly
because instance data belongs to objects, and static methods belong to the class.
▪ They are commonly used for utility or helper methods that perform tasks
independent of object data.
• Uses:
▪ Writing utility functions like [Link]() or [Link]().
▪ Accessing static variables shared across objects.
▪ Providing common operations that do not require object-specific data.
• Example:
class Student
{
static String schoolName = "ABC School";
static void showSchool()
{
[Link]("School: " + schoolName);
}
}
class Student
{
// Static variable (shared by all objects)
static String school = "ABC School";
// Instance variables (unique for each object)
int id;
String name;
// Constructor to initialize instance variables
Student(int i, String n)
{
id = i;
name = n;
}
// Instance method
void display()
{
[Link](id + " " + name + " " + school);
}
// Static method
static void showSchool()
{
[Link]("School: " + school);
}
}
JSSCW, Chamarajanagara 9
Java (Unit 2) Mohankumari B S
class Test
{
public static void main(String[] args)
{
// Creating objects
Student s1 = new Student(101, "Rahul");
Student s2 = new Student(102, "Anita");
// Accessing instance methods
[Link](); // 101 Rahul ABC School
[Link](); // 102 Anita ABC School
// Accessing static method without creating an object
[Link](); // School: ABC School
}
}
Recursion
• Recursion is a programming technique in which a method or function calls itself directly
or indirectly to solve a problem.
• Recursion is useful for solving problems that can be broken down into smaller, similar sub-
problems, such as factorial calculation, Fibonacci series, tree traversal, and many
algorithmic problems.
• Key Points:
1. Self-calling function – A recursive function calls itself.
2. Base condition – Every recursive function must have a base case to stop recursion;
otherwise, it will result in infinite recursion and a stack overflow error.
3. Recursive case – Defines how the function reduces the problem and calls itself.
4. Recursion uses stack memory to store function calls.
• Syntax:
returnType methodName(parameters)
{
if (baseCondition)
{
// stop recursion
return;
}
else
{
// recursive call
methodName(modifiedParameters);
}
}
JSSCW, Chamarajanagara 10
Java (Unit 2) Mohankumari B S
this keyword
• this keyword is a reference variable that refers to the current object of a class.
• It is mainly used inside a class to differentiate between instance variables and local
variables, call other constructors, or pass the current object.
• Key Points
1. Refers to current object – this points to the object that is currently executing the method
or constructor.
2. Distinguish variables – Used when local variables or parameters have the same name
as instance variables.
3. Call another constructor – Can be used to invoke another constructor of the same class
using this(parameters).
4. Pass current object – Can pass the current object to methods or constructors.
5. Cannot be used in static context – Static methods do not belong to any object, so this
cannot be used there.
OUTPUT
ID: 101, Name: Rahul
JSSCW, Chamarajanagara 11
Java (Unit 2) Mohankumari B S
Access Control
• In Java, access control is a mechanism that controls the visibility and accessibility of classes,
variables, methods, and constructors.
• It determines which parts of a program can access certain members of a class.
• Access control helps in protecting data, achieving encapsulation, and improving program
security.
• Java provides four access control keywords (access modifiers): public, private, protected, and
default.
• Each keyword defines a different level of accessibility.
• public:
o The public access modifier allows a class member to be accessed from anywhere in
the program.
o When a variable or method is declared as public, it can be used by any class inside the
same package or in a different package.
o Therefore, public provides the widest level of accessibility.
• private:
o The private access modifier restricts the accessibility of a member to the same class
only.
o A private variable or method cannot be accessed from outside the class in which it is
declared.
• default:
o This modifier is mainly used to achieve data hiding and protect sensitive data.
o The default access modifier is applied when no access modifier is specified.
o Members with default access can be accessed only within the same package but
cannot be accessed from classes that belong to different packages.
o It provides package-level visibility.
• protected:
o The protected access modifier allows a member to be accessed within the same
package and also by subclasses even if they are located in different packages.
o This modifier is mainly used when inheritance is involved.
private Yes No No No
default (no
Yes Yes No No
keyword)
JSSCW, Chamarajanagara 12
Java (Unit 2) Mohankumari B S
Garbage Collection
• Garbage in Java refers to unreferenced objects, which are objects that are no longer used by
the program.
• These objects still occupy memory but cannot be accessed anymore.
• Garbage Collection is the process of automatically reclaiming runtime unused memory by
destroying unused objects.
• It helps in freeing memory and improving memory management.
• Garbage collection in Java is handled automatically by the Java Virtual Machine (JVM).
3) By Anonymous Object
• An anonymous object is created without assigning it to a reference variable.
• Since no reference points to it, it becomes eligible for garbage collection immediately.
Example:
new Employee();
JSSCW, Chamarajanagara 13
Java (Unit 2) Mohankumari B S
gc() Method
• The gc() method is used to request the JVM to run the garbage collector.
• It helps in performing cleanup processing by removing unused objects from memory.
• The gc() method is available in the System class in Java and the Runtime class in Java.
• It does not guarantee immediate garbage collection, but it requests the JVM to perform it.
Example:
[Link]();
• Here, the program requests the JVM to start garbage collection.
Example program
class GarbageExample
{
protected void finalize()
{
[Link]("Finalize method called before garbage collection");
}
public static void main(String[] args)
{
GarbageExample obj1 = new GarbageExample();
GarbageExample obj2 = new GarbageExample();
obj1 = null; // object becomes eligible for garbage collection
obj2 = null; // object becomes eligible for garbage collection
[Link](); // request JVM to run garbage collector
}
}
Inheritance in Java
• Inheritance is one of the most important concepts of Object-Oriented Programming (OOP) in
the Java programming language.
• It allows a class to acquire the properties and behaviors (fields and methods) of another class.
• In simple words, inheritance enables code reusability by allowing a new class to reuse the
features of an existing class.
• The class that inherits the properties is called the Child Class (Subclass) and the class whose
properties are inherited is called the Parent Class (Superclass).
• Syntax
class ChildClass extends ParentClass {
// Additional fields and methods
}
Here, the keyword extends is used to inherit a class.
• Advantages of Inheritance
▪ Code Reusability – Reuse existing code without rewriting it.
▪ Method Overriding – Allows runtime polymorphism.
▪ Better Code Organization – Makes programs structured and hierarchical.
▪ Reduces Redundancy – Avoids duplication of code.
▪ Improves Maintainability – Changes in parent class automatically affect child classes.
JSSCW, Chamarajanagara 14
Java (Unit 2) Mohankumari B S
Types of Inheritance
Java supports the following types of inheritance:
➢ Single Inheritance
➢ Multilevel Inheritance
➢ Hierarchical Inheritance
➢ Multiple Inheritance (through Interfaces)
➢ Hybrid Inheritance (combination using interfaces)
1. Single Inheritance
• In Single Inheritance, one subclass inherits from only one superclass.
• It is also known as simple inheritance.
• Example
class One
{
public void printNumber()
{
[Link]("Java");
}
}
class Two extends One
{
public void printFor()
{
[Link]("for");
}
}
public class Main
{
public static void main(String[] args)
{
Two obj = new Two();
[Link]();
[Link]();
[Link]();
}
}
Output
Java
for
Java
2. Multilevel Inheritance
• In Multilevel Inheritance, a class inherits from another class, and that class further acts as a
parent for another class.
• Example
class One
{
public void printMulti()
{
JSSCW, Chamarajanagara 15
Java (Unit 2) Mohankumari B S
[Link]("multi");
}
}
class Two extends One
{
public void printFor()
{
[Link]("for");
}
}
class Three extends Two
{
public void printLastWord()
{
[Link]("inheritance");
}
}
public class Main
{
public static void main(String[] args)
{
Three obj = new Three();
[Link]();
[Link]();
[Link]();
}
}
Output
multi
for
inheritance
3. Hierarchical Inheritance
• In Hierarchical Inheritance, multiple subclasses inherit from a single superclass.
• Example
class A {
public void printA() {
[Link]("Class A");
}
}
class B extends A{
public void printB() {
[Link]("Class B");
}
}
class C extends A
{
public void printC()
{
JSSCW, Chamarajanagara 16
Java (Unit 2) Mohankumari B S
[Link]("Class C");
}
}
class D extends A
{
public void printD()
{
[Link]("Class D");
}
}
public class Test
{
public static void main(String[] args)
{
B objB = new B();
[Link]();
[Link]();
C objC = new C();
[Link]();
[Link]();
D objD = new D();
[Link]();
[Link]();
}
}
Output
Class A
Class B
Class A
Class C
Class A
Class D
JSSCW, Chamarajanagara 17
Java (Unit 2) Mohankumari B S
public void printWork()
{
[Link]("inter");
}
public void printFor()
{
[Link]("for");
}
}
public class Main
{
public static void main(String[] args)
{
Child obj = new Child();
[Link]();
[Link]();
}
}
Output
inter
for
5. Hybrid Inheritance
• Hybrid Inheritance is a combination of two or more types of inheritance.
• Java does not support hybrid inheritance using classes, but it can be implemented using
interfaces.
• Example
class Parents
{
public void displayParents()
{
[Link]("Two Parents");
}
}
interface Mother
{
void show();
}
interface Father
{
void show();
}
public class Child extends Parents implements Mother, Father
{
public void show()
{
[Link]("Mother and Father are parents");
}
JSSCW, Chamarajanagara 18
Java (Unit 2) Mohankumari B S
public void displayChild()
{
[Link]("Mother and Father have one child");
}
public static void main(String[] args)
{
Child obj = new Child();
[Link]("Implementation of Hybrid Inheritance in Java");
[Link]();
[Link]();
}
}
Output
Implementation of Hybrid Inheritance in Java
Mother and Father are parents
Mother and Father have one child
JSSCW, Chamarajanagara 19
Java (Unit 2) Mohankumari B S
Method Overriding
• Method Overriding in Java occurs when a subclass provides a specific implementation of a
method that is already defined in its superclass.
Or
Method overriding is the process in which a child class redefines a method of its parent class
with the same method signature to provide a different implementation.
• The method in the child class must have the same name, parameters, and return type as the
method in the parent class.
• It is mainly used to achieve runtime polymorphism.
Output
This is child class method.
JSSCW, Chamarajanagara 20
Java (Unit 2) Mohankumari B S
Dynamic Method Dispatch
• Dynamic Method Dispatch in Java is a mechanism by which a call to an overridden method
is resolved at runtime rather than compile time.
Or
Dynamic Method Dispatch is the process where the method call is determined at runtime
based on the object being referred to, not the reference type
• It is an important concept used to achieve runtime polymorphism in object-oriented
programming.
• In this process, a superclass reference variable can refer to a subclass object, and the method
that gets executed depends on the actual object type at runtime..
• Syntax
Superclass object = new Subclass();
[Link]();
• Example
Animal a = new Dog();
[Link]();
Here, Method execution depends on Dog class implementation.
Example Program
class Animal
{
void makeSound()
{
[Link]("Generic Animal Sound");
}
}
class Dog extends Animal
{
@Override
void makeSound()
{
[Link]("Bark");
}
}
class Cat extends Animal {
@Override
void makeSound() {
[Link]("Meow");
}
}
public class Demo {
public static void main(String[] args) {
Animal[] animals = { new Dog(), new Cat() };
for (Animal animal : animals) {
[Link]();
}
}
}
Output
Bark
Meow
JSSCW, Chamarajanagara 21
Java (Unit 2) Mohankumari B S
Abstract Classes and Abstract Methods
• In Java, abstract classes and abstract methods are used to provide a blueprint for other
classes.
• They are a key feature of Object-Oriented Programming (OOP) and help in achieving
abstraction.
1. Abstract Class
An abstract class is a class that:
• Cannot be instantiated (we cannot create objects of an abstract class directly).
• Can have abstract methods (without body) and concrete methods (with body).
• Is declared using the abstract keyword.
• Syntax
abstract class ClassName {
// Abstract method
abstract void methodName();
// Concrete method
void normalMethod() {
// method body
}
}
2. Abstract Method
An abstract method:
• Is a method without a body.
• Must be overridden by the subclass.
• Declared using the abstract keyword.
• Only allowed inside an abstract class or interface.
• Syntax
abstract void methodName();
Rules
1. A class containing at least one abstract method must be declared abstract.
2. Abstract methods cannot have a body.
3. Abstract methods are implicitly public if declared in an interface, but in a class, they can
have default access modifiers.
4. Subclasses must override abstract methods, or they must also be declared abstract.
JSSCW, Chamarajanagara 22
Java (Unit 2) Mohankumari B S
Example Program (Abstract Class + Abstract Method)
Output
This is Java Programming Language
Languages are used to communicate with computers.
Final Classes
JSSCW, Chamarajanagara 23
Java (Unit 2) Mohankumari B S
• Syntax
final class ClassName
{
// fields and methods
}
Example Program
final class Vehicle {
void display() {
[Link]("This is a final class");
}
}
class Car extends Vehicle { } // The following will cause an error
public class Main {
public static void main(String[] args)
{
Vehicle obj = new Vehicle();
[Link]();
}
}
Output
This is a final class
In Java, visibility control determines which classes or objects can access variables and
methods. This is controlled using access modifiers. Proper use of visibility control helps in
encapsulation, data hiding, and security.
Visibility of Variables
Visibility of Methods
JSSCW, Chamarajanagara 24
Java (Unit 2) Mohankumari B S
Arrays
• An array stores multiple values of the same data type using a single variable.
• Array elements are accessed using an index, starting from 0.
• The size of an array is fixed once it is created, and it can store primitive types or objects.
One-Dimensional Arrays
• A one-dimensional array is a linear sequence of elements stored in a single row.
• Indexing starts from 0, i.e., the first element is at index 0.
• The length of the array can be obtained using [Link].
• Memory allocation is static – once created, the size cannot change.
• Creating an Array
1. Declaration:
dataType[] arrayName; // Preferred style
or
dataType arrayName[];
2. Intialization / Memory allocation
arrayName = new dataType[size];
3. Combined Way
int[] numbers = new int[5]; // Declare and create array of size 5
numbers[0] = 10; // Assign value to first element
int first = numbers[0]; // Access first element
• Example program
public class Main
{
public static void main(String[] args)
{
int[] numbers = new int[5]; // Create an array of size 5
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
for (int i = 0; i < [Link]; i++) {
[Link]("Element at index " + i + ": " + numbers[i]);
}
}
}
2. Two-Dimensional Arrays
• A two-dimensional array is like a matrix with rows and columns.
• Length properties:
o [Link] → Number of rows
o array[i].length → Number of columns in row i
• Used to represent tables, matrices, and grids.
• Can be initialized at declaration:
int[][] matrix = { {1, 2}, {3, 4}, {5, 6} };
• Access elements using two indices: array[row][column].
• Iteration can be done with nested loops.
• Syntax: datatype[][] arrayName = new dataType[rows][columns];
JSSCW, Chamarajanagara 25
Java (Unit 2) Mohankumari B S
• Example Program
public class Main {
public static void main(String[] args) {
int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
jagged[0][0] = 1; jagged[0][1] = 2;
jagged[1][0] = 3; jagged[1][1] = 4; jagged[1][2] = 5;
jagged[2][0] = 6;
JSSCW, Chamarajanagara 26
Java (Unit 2) Mohankumari B S
String
A String in Java is a sequence of characters used to store and manipulate text such as names,
sentences, or messages.
➔ We can create a string in two ways
A. Using String Literal
Example: String name = "John";
• Stored in the String Constant Pool
• More memory efficient
➔ Properties of String
• Once a string is created, it cannot be changed.
• String is not a primitive data type.
• It is a class in Java.
String Methods
Method Description Example Code Output
Returns the number of String s="Java";
length() 4
characters in the string [Link]([Link]());
Returns character at given String s="Java";
charAt(index) v
index [Link]([Link](2));
Returns part of string from
substring(start, String s="Programming";
start index to end index (end gra
end) [Link]([Link](3,6));
not included)
Checks if a string contains a String s="Java Programming";
contains() true
specific sequence [Link]([Link]("Program"));
String s="JAVA";
toLowerCase() Converts string to lowercase java
[Link]([Link]());
String s="java";
toUpperCase() Converts string to uppercase JAVA
[Link]([Link]());
Compares two strings (case- String a="Java"; String b="Java";
equals() true
sensitive) [Link]([Link](b));
equalsIgnoreCase( Compares two strings ignoring String a="java"; String b="JAVA";
true
) case [Link]([Link](b));
String s="Java";
replace(old,new) Replaces characters or words Jovo
[Link]([Link]('a','o'));
Returns index of first String s="Java";
indexOf() 1
occurrence of character/string [Link]([Link]('a'));
Checks if string starts with String s="Java Programming";
startsWith() true
given prefix [Link]([Link]("Java"));
Checks if string ends with String s="Java Programming";
endsWith() true
given suffix [Link]([Link]("ing"));
["apple","b
Splits string into array based String s="apple,banana,mango"; String[]
split() anana","ma
on delimiter arr=[Link](",");
ngo"]
JSSCW, Chamarajanagara 27
Java (Unit 2) Mohankumari B S
Example program
public class StringFunctions
{
public static void main(String[] args)
{
String str = "Java Programming";
[Link]("Length: " + [Link]());
[Link]("Character at 2: " + [Link](2));
[Link]("Substring: " + [Link](5, 11));
[Link]("Contains 'Java': " + [Link]("Java"));
[Link]("Lowercase: " + [Link]());
[Link]("Uppercase: " + [Link]());
[Link]("Index of 'g': " + [Link]('g'));
[Link]("Starts with Java: " + [Link]("Java"));
[Link]("Ends with ing: " + [Link]("ing"));
[Link]("Replace: " + [Link]("Java","Python"));
}
}
StringBuffer
• StringBuffer is a class in Java used to create mutable (changeable) strings.
• Unlike String, the content of a StringBuffer can be modified without creating a new object.
• It belongs to the [Link] package.
• Example:
StringBuffer sb = new StringBuffer("Hello");
StringBuffer Methods
Method Description Example Output
append() Adds text to the end [Link](" World"); Hello World
insert() Inserts text at specified index [Link](5," Java"); Hello Java
replace() Replaces characters [Link](0,5,"Hi"); Hi
delete() Deletes characters from index range [Link](0,2); Java
reverse() Reverses the string [Link](); avaJ
length() Returns length of string [Link](); 4
Example program
public class StringBufferExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Java");
[Link](" Programming");
[Link]("After append: " + sb);
[Link](5, "Language ");
[Link]("After insert: " + sb);
[Link](0,4,"Python");
[Link]("After replace: " + sb);
[Link]();
[Link]("After reverse: " + sb);
}
}
JSSCW, Chamarajanagara 28
Java (Unit 2) Mohankumari B S
Wrapper Classes
• Wrapper Classes are used to convert primitive data types into objects.
• Java provides wrapper classes in the [Link] package so that primitive types can be used as
objects when required (for example in collections).
Autoboxing:
It is an automatic conversion of a primitive datatype into its corresponding wrapper class
object.
Example:
int a = 5;
Integer obj = a; // Autoboxing
Unboxing:
It is an automatic conversion of a wrapper class object into its corresponding primitive
datatype.
Example:
Integer obj = 20;
int num = obj; // Unboxing
NOTE:
• We can manually convert primitive data types to wrapper objects and wrapper objects to
primitive data types using methods.
• Example 1: Autoboxing
int num = 10;
Integer obj = [Link](num);
[Link](obj);
• Example 2: Unboxing
Integer obj = [Link](20);
int num = [Link]();
[Link](num);
JSSCW, Chamarajanagara 29
Java (Unit 2) Mohankumari B S
Interface
An interface in Java is:
• A blueprint of a class.
• Contains abstract methods (methods without body) and constants (variables that are
public static final).
• Used to achieve abstraction (hiding implementation details).
• Used to achieve multiple inheritance in Java (a class can implement multiple interfaces).
• Introduced for flexible and modular design.
Key Point:
• All methods in an interface are implicitly public and abstract.
• All variables are implicitly public, static, and final.
Syntax:
interface InterfaceName
{
// constant fields (optional)
int MY_CONSTANT = 100; // public static final by default
// abstract methods
void method1(); // public abstract by default
int method2();
}
Implementing an interface
A class implements an interface using implements keyword.
• Must provide implementation for all interface methods.
• Syntax:
class ClassName implements InterfaceName
{
// Must provide implementation for all abstract methods of the interface
}
• Use implements keyword.
• Must override all abstract methods from the interface.
• If a method is not implemented, the class must be declared abstract.
Extending an Interface
An interface can extend one or more interfaces using extends.
• Inherits all methods and constants from the parent interface(s).
• Can declare new methods or constants.
• It is also called interface Inheritance
• Syntax:
interface ChildInterface extends ParentInterface
{
// declare new abstract methods or constants
}
• Use the extends keyword.
• An interface can extend one or more interfaces (multiple inheritance).
• The child interface inherits all abstract methods and constants from parent interface(s).
• Child interface can declare new methods or constants.
JSSCW, Chamarajanagara 30
Java (Unit 2) Mohankumari B S
Nested Interface
• An interface inside another interface or class is called a nested interface.
• Used to group related interfaces.
• It can be accessed via [Link].
• Syntax:
interface OuterInterface
{
void outerMethod();
interface InnerInterface
{
void innerMethod();
}
}
• Example:
interface Showable
{
void show();
interface Message
{
void msg();
}
}
class TestNested implements [Link]
{
public void msg()
{
[Link]("Hello nested interface");
}
public static void main(String[] args)
{
[Link] message = new TestNested(); // upcasting
[Link]();
}
}
JSSCW, Chamarajanagara 31
Java (Unit 2) Mohankumari B S
Various forms of interface implementation
JSSCW, Chamarajanagara 32
Java (Unit 2) Mohankumari B S
• Example:
interface Engine
{
void startEngine();
}
interface Horn
{
void honk();
}
class Bike implements Engine, Horn
{
public void startEngine()
{
[Link]("Bike engine started");
}
public void honk()
{
[Link]("Bike honking");
}
}
public class Main
{
public static void main(String[] args)
{
Bike bike = new Bike();
[Link](); // Output: Bike engine started
[Link](); // Output: Bike honking
}
}
3. Extending an Interface
• An interface can inherit another interface using the extends keyword.
• A class implementing the derived interface must implement all methods from both interfaces.
• Syntax:
interface Interface1
{
void method1();
}
interface Interface2 extends Interface1
{
void method2();
}
class ClassName implements Interface2
{
public void method1()
{ ... }
public void method2()
{ ... }
}
JSSCW, Chamarajanagara 33
Java (Unit 2) Mohankumari B S
• Example:
interface Animal
{
void eat();
}
interface Pet extends Animal
{
void play();
}
class Dog implements Pet
{
public void eat()
{
[Link]("Dog is eating");
}
public void play()
{
[Link]("Dog is playing");
}
}
public class Main
{
public static void main(String[] args)
{
Dog dog = new Dog();
[Link](); // Output: Dog is eating
[Link](); // Output: Dog is playing
}
}
JSSCW, Chamarajanagara 34
Java (Unit 2) Mohankumari B S
• Example:
interface Shape
{
void draw();
}
class Circle implements Shape
{
public void draw()
{
[Link]("Drawing Circle");
}
}
class Rectangle implements Shape
{
public void draw()
{
[Link]("Drawing Rectangle");
}
}
public class Main
{
public static void main(String[] args)
{
Shape s1 = new Circle();
Shape s2 = new Rectangle();
[Link](); // Output: Drawing Circle
[Link](); // Output: Drawing Rectangle
}
}
JSSCW, Chamarajanagara 35