KEMBAR78
UNIT-2 OOP Lecture Notes | PDF | Constructor (Object Oriented Programming) | Programming
0% found this document useful (0 votes)
13 views55 pages

UNIT-2 OOP Lecture Notes

The document covers Object Oriented Programming concepts, focusing on method and constructor overloading in Java. It explains method overloading through various examples, including changing the number of arguments and data types, as well as the use of the 'this' keyword. Additionally, it discusses passing and returning objects in Java, emphasizing how objects are passed by reference.

Uploaded by

bhargavialluri30
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)
13 views55 pages

UNIT-2 OOP Lecture Notes

The document covers Object Oriented Programming concepts, focusing on method and constructor overloading in Java. It explains method overloading through various examples, including changing the number of arguments and data types, as well as the use of the 'this' keyword. Additionally, it discusses passing and returning objects in Java, emphasizing how objects are passed by reference.

Uploaded by

bhargavialluri30
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
You are on page 1/ 55

UNIT-2 – Object Oriented Programming

❖ Method Overloading:
✓ Overloading allows different methods to have the same name, but different
signatures where the signature can differ by the number of input parameters
or type of input parameters or both.
✓ Overloading is related to compile-time (or static) polymorphism.
✓ Method overloading increases the readability of the program.

Different ways to overload the method

1) Method Overloading: changing no. of arguments


✓ In this example, we have created two methods, first add() method performs
addition of two numbers and second add() method performs addition of three
numbers.
✓ In this example, we are creating static methods, so that we don't need to
create instance for calling methods.
Example:

1. class Adder{
2. static int add(int a,int b){
3. return a+b;}
4. static int add(int a,int b,int c){
5. return a+b+c;}

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 1


UNIT-2 – Object Oriented Programming

6. }
7. class TestOverloading1{ Output:
8. public static void main(String[] args){ 22
9. System.out.println(Adder.add(11,11)); 33
10. System.out.println(Adder.add(11,11,11));
11.}}

2) Method Overloading: changing data type of arguments


✓ In this example, we have created two methods that differs in data type.
✓ The first add method receives two integer arguments and second add method
receives two double arguments.
Example:

1. class Adder{
2. static int add(int a, int b){
3. return a+b;}
4. static double add(double a, double b){
5. return a+b;}
6. }
7. class TestOverloading2{
8. public static void main(String[] args){
9. System.out.println(Adder.add(11,11));
Output:
10. System.out.println(Adder.add(12.3,12.6));
11.}} 22

Note-1: 24.9

✓ In Java, Method Overloading is not possible by changing the return type of


method only because of ambiguity.
✓ Let us see how ambiguity may occur:
Output:
Example:
Compile Time Error: method
1. class Adder{ add(int,int) is already defined
2. static int add(int a,int b){return a+b;} in class Adder
3. static double add(int a,int b){return a+b;}

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 2


UNIT-2 – Object Oriented Programming

4. }
5. class TestOverloading3{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11)); //ambiguity }}

✓ System.out.println(Adder.add(11,11)); //Here, how can java determine


which sum() method should be called?
Note-2:
✓ In Java, main () Method can be Overloaded.
✓ But JVM calls main() method which receives string array as arguments only.
Example:

1. class TestOverloading4{
2. public static void main(String[] args){
3. System.out.println("main with String[]");}
4. public static void main(String args){ Output:t
5. System.out.println("main with String");} main with String[]
6. public static void main(){
7. System.out.println("main without args");} }

Method Overloading and Type Promotion


✓ One type is promoted to another implicitly if no matching datatype is found.
✓ In this, byte can be promoted to short, int, long, float or double.
✓ The short datatype can be promoted to int, long, float or double.
✓ The char datatype can be promoted to int, long, float or double and so on.

Example of Method Overloading with Type Promotion


1. class OverloadingCalculation1{
2. void sum(int a,long b){System.out.println(a+b);}
3. void sum(int a,int b,int c){System.out.println(a+b+c);}
4. public static void main(String args[]){
5. OverloadingCalculation1 obj=new OverloadingCalculation1();
6. obj.sum(20,20); //now second int literal will be promoted to long
7. obj.sum(20,20,20); } }

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 3


UNIT-2 – Object Oriented Programming

Example of Method Overloading with Type Promotion if matching found

✓ If there are matching type arguments in the method, type promotion is not
performed.

1. class OverloadingCalculation2{
2. void sum(int a,int b){System.out.println("int arg method invoked");}
3. void sum(long a,long b){System.out.println("long arg method invoked");}
4. public static void main(String args[]){
5. OverloadingCalculation2 obj=new OverloadingCalculation2();
6. obj.sum(20,20); //now int arg sum() method gets invoked
7. } }

Example of Method Overloading with Type Promotion in case of ambiguity


✓ If there are no matching type arguments in the method, and each method
promotes similar number of arguments, there will be ambiguity.

1. class OverloadingCalculation3{
2. void sum(int a,long b){System.out.println("a method invoked");}
3. void sum(long a,int b){System.out.println("b method invoked");}
4. public static void main(String args[]){
5. OverloadingCalculation3 obj=new OverloadingCalculation3();
6. obj.sum(20,20); //now ambiguity Output:t
7. }
8. } Compile Time Error

❖ Constructor Overloading:
✓ In Java, we can overload constructors like methods.
✓ The constructor overloading can be defined as the concept of having more
than one constructor with different parameters so that every constructor can
perform a different task.
✓ Consider the following Java program, in which we have used different
constructors in the class.

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 4


UNIT-2 – Object Oriented Programming

Example

1. public class Student {


2. int id; //instance variables of the class
3. String name;
4.
5. Student(){
6. System.out.println("this a default constructor"); }
7.
8. Student(int i, String n){
9. id = i;
10. name = n; }
11.
12. public static void main(String[] args) {
13. Student s = new Student();
14. System.out.println("\nDefault Constructor values: \n");
15. System.out.println("Student Id : "+s.id + "\nStudent Name : "+s.name);
16.
17. System.out.println("\nParameterized Constructor values: \n");
18. Student student = new Student(10, "David");
19. System.out.println("Student Id : "+student.id + "\nStudent Name : "+student.n
ame); }
20. }
Output:t
this a default constructor
Default Constructor values:
Student Id : 0
Student Name : null
Parameterized Constructor values:
Student Id : 10
Student Name : David

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 5


UNIT-2 – Object Oriented Programming

✓ Java compiler invokes a default constructor when we do not use any


constructor in the class.
✓ However, the default constructor is not invoked if we have used any
constructor in the class, whether it is no-args or parameterized.
✓ In this case, the java compiler throws an exception saying the constructor is
undefined.
✓ Consider the following example, which contains the error since the Colleges
object cannot be created using the default constructor now since it does not
contain one.

1. public class Colleges {


2. String collegeId; // Instances Variables
3. Colleges(String collegeId){ // Parameterized constructor
4. this.collegeId = "IIT "; }
5. public static void main(String[] args) {
6. Colleges clg = new Colleges(); //this cannot create colleges constructor now.
7. } }

Use of this () in constructor overloading:


✓ this keyword is used inside the constructor, which can be used to invoke the
other constructor of the same class.
✓ Consider the following example to understand the use of this keyword in
constructor overloading.

1. public class Student {


2. //instance variables of the class
3. int id,passoutYear;
4. String name,contactNo,collegeName;
5. // Constructor 1
6. Student(String contactNo, String collegeName, int passoutYear){
7. this.contactNo = contactNo;
8. this.collegeName = collegeName;
9. this.passoutYear = passoutYear;

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 6


UNIT-2 – Object Oriented Programming

10. }
11. // Constructor 2 Output:t
12. Student(int id, String name){ Printing Student Information:
13. this("9899234455", "IIT Kanpur", 2018);
14. this.id = id; Name: John
15. this.name = name; Id: 101
16. } Contact No.: 9899234455

17. public static void main(String[] args) { College Name: 9899234455


18. //object creation Passing Year: 2018
19. Student s = new Student(101, "John");
20. System.out.println("Printing Student Information: \n");
21. System.out.println("Name: "+s.name+"\nId: "+s.id+"\nContact No.: "+s.conta
ctNo+"\nCollege Name: "+s.contactNo+"\nPassing Year: "+s.passoutYear);
22. }
23. }

❖ this keyword in Java


✓ In Java, this keyword is a reference variable that refers to the current object.
Usage of Java this keyword
1) this: to refer current class instance variable
✓ The “this” keyword can be used to refer current class instance variable.
✓ If there is ambiguity between the instance variables and parameters, this
keyword resolves the problem of ambiguity.
Understanding the problem without this keyword: Example:
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee)
{
rollno=rollno;

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 7


UNIT-2 – Object Oriented Programming

name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Output: 0 null 0.0
0 null 0.0
✓ In the above example, parameters (formal arguments) and instance variables are
same. So, we are using this keyword to distinguish local variable and instance
variable.
Solution of the above problem by this keyword
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 8


UNIT-2 – Object Oriented Programming

s2.display();
}}
Output: 111 ankit 5000.0
112 sumit 6000.0
Note: If local variables (formal arguments) and instance variables are different,
there is no need to use this keyword.
2) this: to invoke current class method
✓ You may invoke the method of the current class by using the “this” keyword.
✓ If you do not use this keyword, compiler automatically adds this keyword while
invoking the method. Let us see the example
class A{
void m(){System.out.println("hello m");}
void n(){
System.out.println("hello n");
this.m(); //same as m() }
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n(); }}
Output: hello n
hello m
3) this() : to invoke current class constructor
✓ The this() constructor call can be used to invoke the current class constructor.
✓ It is used to reuse the constructor. In other words, it is used for constructor
chaining. Calling default constructor from parameterized constructor is follows.
class A{
A(){System.out.println("hello a");}
A(int x){
this();
System.out.println(x); } }
class TestThis5{
public static void main(String args[]){
A a=new A(10); }}

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 9


UNIT-2 – Object Oriented Programming

Output: hello a
10

❖ Passing and Returning Objects in Java


✓ While creating a variable of a class type, we only create a reference to an
object. Thus, when we pass this reference to a method, the parameter that
receives it will refer to the same object as that referred to by the argument.
✓ This effectively means that objects act as if they are passed to methods by use
call-by-reference.
✓ Changes to the object inside the method do reflect in the object used as an
argument.
✓ In Java we can pass objects to methods.
✓ For example, consider the following program:
Example:
// Java Program to Demonstrate Objects Passing to Methods.
class ObjectPassDemo {
int a, b;
// Constructor
ObjectPassDemo(int i, int j)
{
a = i;
b = j;
}
// Method
boolean equalTo(ObjectPassDemo o)
{
// Returns true if o is equal to the invoking object notice an object
is passed as an argument to method
return (o.a == a && o.b == b); Output:
}
} ob1 == ob2: true
ob1 == ob3: false
public class CSE {

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 10


UNIT-2 – Object Oriented Programming

public static void main(String args[])


{
// Creating object of above class inside mian()
ObjectPassDemo ob1 = new ObjectPassDemo(100, 22);
ObjectPassDemo ob2 = new ObjectPassDemo(100, 22);
ObjectPassDemo ob3 = new ObjectPassDemo(-1, -1);

// Checking whether object arw equal as custom values above passed


and printing corresponding boolean value
System.out.println("ob1 == ob2: " + ob1.equalTo(ob2));
System.out.println("ob1 == ob3: " + ob1.equalTo(ob3));
}}
Illustration: Let us suppose three objects ‘ob1’, ‘ob2’ and ‘ob3’ are created:

ObjectPassDemo ob1 = new ObjectPassDemo(100, 22);


ObjectPassDemo ob2 = new ObjectPassDemo(100, 22);
ObjectPassDemo ob3 = new ObjectPassDemo(-1, -1);

From the method side, a reference of type Foo with a name a is declared and it is
initially assigned to null.
boolean equalTo(ObjectPassDemo o);

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 11


UNIT-2 – Object Oriented Programming

As we call the method equalTo, the reference ‘o’ will be assigned to the object,
which is passed as an argument, i.e. ‘o’ will refer to ‘ob2’ as the following
statement execute.
System.out.println("ob1 == ob2: " + ob1.equalTo(ob2));

Now as we can see, equalTo method is called on ‘ob1’ , and ‘o’ is referring to
‘ob2’. Since values of ‘a’ and ‘b’ are same for both the references, so
if(condition) is true, so boolean true will be return.
if(o.a == a && o.b == b)
Again ‘o’ will reassign to ‘ob3’ as the following statement execute.
System.out.println("ob1 == ob3: " + ob1.equalTo(ob3));

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 12


UNIT-2 – Object Oriented Programming

Now as we can see, the equalTo method is called on ‘ob1’ , and ‘o’ is referring to
‘ob3’. Since values of ‘a’ and ‘b’ are not the same for both the references, so
if(condition) is false, so else block will execute, and false will be returned.

❖ Returning Objects
✓ In java, a method can return any type of data, including objects.
✓ For example, in the following program, the incrByTen( ) method returns an
object in which the value of an (an integer variable) is ten greater than it is in
the invoking object.
Example:
// Java Program to Demonstrate Returning of Objects
class ObjectReturnDemo {
int a;
// Constructor
ObjectReturnDemo(int i) { a = i; }

// Method returns an object


ObjectReturnDemo incrByTen()
{
ObjectReturnDemo temp = new ObjectReturnDemo(a + 10);
return temp;
}
}

public class CSE {


public static void main(String args[])
{
// Creating object of class1 inside main() method
ObjectReturnDemo ob1 = new ObjectReturnDemo(2);
ObjectReturnDemo ob2;

ob2 = ob1.incrByTen();

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 13


UNIT-2 – Object Oriented Programming

System.out.println("ob1.a: " + ob1.a);


System.out.println("ob2.a: " + ob2.a);
}}

❖ Recursion in Java
✓ Recursion in java is a process in which a method calls itself continuously.
✓ A method in java that calls itself is called recursive method.
Java Recursion Example 1: Factorial Number
1. public class RecursionExample3 {
2. static int factorial(int n){ if (n == 1) return 1;
3. else return(n * factorial(n-1));
4. }
5. public static void main(String[] args)
6. { System.out.println("Factorial of 5 is: "+factorial(5));
7. } }
Output: Factorial of 5 is: 120

❖ Access Control
Access Modifiers in java:
✓ There are two types of modifiers in java: access modifiers and non-access
modifiers.
✓ The access modifiers in java specifies accessibility (scope) of a data member,
method, constructor, or class.
✓ There are 4 types of java access modifiers:
1. private access modifier:
✓ The private access modifier is accessible only within class.
Simple example of private access modifier
✓ In this example, we have created two classes A and Simple.
✓ A class contains private data member and private method. We are accessing
these private members from outside the class, so there is compile time error.
1. class A{
2. private int data=40;
3. private void msg(){System.out.println("Hello java");}

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 14


UNIT-2 – Object Oriented Programming

4. }
5. public class Simple{
6. public static void main(String args[]){
7. A obj=new A();
8. System.out.println(obj.data);//Compile Time Error
9. obj.msg();//Compile Time Error
10. } }
2) default access modifier
✓ If you do not use any modifier, it is treated as default by default. The default
modifier is accessible only within package.
✓ Example of default access modifier
✓ In this example, we have created two packages pack and mypack. We are
accessing the A class from outside its package, since A class is not public, so it
cannot be accessed from outside the package.
//save by A.java
1. package pack;
2. class A{
3. void msg(){System.out.println("Hello");}
4. }
//save by B.java
5. package mypack;
6. import pack.*;
7. class B{
8. public static void main(String args[]){
9. A obj = new A();//Compile Time Error
10. obj.msg();//Compile Time Error
11. } }
✓ In the above example, the scope of class A and its method msg() is default so it
cannot be accessed from outside the package.
3) protected access modifier
✓ The protected access modifier is accessible within package and outside the
package but through inheritance only.
✓ The protected access modifier can be applied on the data member, method, and
constructor. It cannot be applied on the class.

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 15


UNIT-2 – Object Oriented Programming

✓ Example of protected access modifier


➢ In this example, we have created the two packages pack and mypack.
➢ The A class of pack package is public, so can be accessed from outside the
package.
➢ But msg method of this package is declared as protected, so it can be
accessed from outside the class only through inheritance.
//save by A.java
1. package pack;
2. public class A{
3. protected void msg(){System.out.println("Hello");}
4. }
//save by B.java
5. package mypack;
6. import pack.*;
7. class B extends A{
8. public static void main(String args[]){
9. B obj = new B();
10. obj.msg();
11. } }
Output: Hello
4) public access modifier
✓ The public access modifier is accessible everywhere. It has the widest scope
among all other modifiers.
//save by A.java
1. package pack;
2. public class A{
3. public void msg(){System.out.println("Hello");} }
//save by B.java
4. package mypack;
5. import pack.*;
6. class B{
7. public static void main(String args[]){
8. A obj = new A();
9. obj.msg(); } } Output: Hello

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 16


UNIT-2 – Object Oriented Programming

Understanding all java access modifiers

❖ Nested Classes in Java


In Java, it is possible to define a class within another class, such classes are known
as nested classes.
They enable you to logically group classes that are only used in one place, thus this
increases the use of encapsulation, and creates more readable and maintainable
code.
✓ The scope of a nested class is bounded by the scope of its enclosing class.
class NestedClass does not exist independently of class OuterClass.
✓ A nested class has access to the members, including private members, of the
class in which it is nested. However, the reverse is not true i.e., the enclosing
class does not have access to the members of the nested class.
✓ A nested class is also a member of its enclosing class.
✓ As a member of its enclosing class, a nested class can be
declared private, public, protected, or package private(default).
✓ Nested classes are divided into two categories:
1. static nested class : Nested classes that are declared static are called static
nested classes.
2. inner class : An inner class is a non-static nested class.

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 17


UNIT-2 – Object Oriented Programming

Syntax:
class OuterClass
{
...
class NestedClass
{
...
}
}

✓ As with class methods and variables, a static nested class is associated with its
outer class.
✓ And like static class methods, a static nested class cannot refer directly to
instance variables or methods defined in its enclosing class: it can use them
only through an object reference.
✓ They are accessed using the enclosing class name.
OuterClass.StaticNestedClass
✓ For example, to create an object for the static nested class, use this syntax:
OuterClass.StaticNestedClass nestedObject =new OuterClass.StaticNestedClass();
Example:
// Java program to demonstrate accessing a static nested class
// outer class
class OuterClass
{
// static member
static int outer_x = 10;
// instance(non-static) member
int outer_y = 20;

// private member

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 18


UNIT-2 – Object Oriented Programming

private static int outer_private = 30;

// static nested class


static class StaticNestedClass
{
void display()
{
// can access static member of outer class
System.out.println("outer_x = " + outer_x);

// can access display private static member of outer class


System.out.println("outer_private = " + outer_private);

// The following statement will give compilation error as static


nested class cannot directly access non-static members
// System.out.println("outer_y = " + outer_y);

}
}
}

// Driver class
public class StaticNestedClassDemo
{
public static void main(String[] args)
{
// accessing a static nested class
OuterClass.StaticNestedClas nestedObject = new OuterClass.StaticNestedClass();
nestedObject.display();

}
}

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 19


UNIT-2 – Object Oriented Programming

Inner classes
✓ To instantiate an inner class, you must first instantiate the outer class. Then,
create the inner object within the outer object with this syntax:
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
There are two special kinds of inner classes :
1. Local inner classes
2. Anonymous inner classes
Example:
// Java program to demonstrate accessing a inner class
// outer class
class OuterClass
{
static int outer_x = 10; // static member
int outer_y = 20; // instance(non-static) member
private int outer_private = 30; // private member
class InnerClass // inner class
{
void display()
{
// can access static member of outer class
System.out.println("outer_x = " + outer_x);
// can also access non-static member of outer class
System.out.println("outer_y = " + outer_y);
// can also access a private member of the outer class
System.out.println("outer_private = " + outer_private);

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 20


UNIT-2 – Object Oriented Programming

}
}
}
public class InnerClassDemo
{
public static void main(String[] args) {
// accessing an inner class
OuterClass outerObject = new OuterClass();
OuterClass.InnerClass innerObject = outerObject.new InnerClass();

innerObject.display(); }
}
Anonymous Inner Class in Java
✓ It is an inner class without a name and for which only a single object is created.
Syntax:
// Test can be interface, abstract/concrete class
Test t = new Test()
{
// data members and methods
public void test_method()
{
........
........
}
};

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 21


UNIT-2 – Object Oriented Programming

Difference between regular class(normal classes) and Anonymous Inner class


✓ A normal class can implement any number of interfaces, but the anonymous
inner class can implement only one interface at a time.
✓ A regular class can extend a class and implement any number of interfaces
simultaneously. But anonymous Inner class can extend a class or can implement
an interface but not both at a time.
✓ For regular/normal class, we can write any number of constructors but we can’t
write any constructor for anonymous Inner class because the anonymous class
does not have any name and while defining constructor class name and
constructor name must be same.
❖ final Keyword
✓ The final keyword in java is used to Stop changing the Value for variables,
Stops Method Overriding, and Stops Inheritance.

✓ The Java final keyword can be used in many contexts. Final can be:
variable, method, and class.

1) Java final variable:


✓ If you make any variable as final, you cannot change the value of final
variable (It will be constant).

Example of final variable

✓ There is a final variable speedlimit, we are going to change the value of this
variable, but It cannot be changed because final variable once assigned a
value can never be changed.

1. class Bike9{
2. final int speedlimit=90; //final variable
3. void run(){
4. speedlimit=400;

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 22


UNIT-2 – Object Oriented Programming

5. }
6. public static void main(String args[]){
Output:t
7. Bike9 obj=new Bike9();
8. obj.run(); Compile Time Error
9. } } //end of class

Can we initialize blank final variable?

✓ The final keyword can be applied with the variables, a final variable that
have no value it is called blank final variable or uninitialized final
variable.

✓ Yes, we can initialize blank final variable but, in the constructor, only.

Example:

1. class Bike10{
2. final int speedlimit; //blank final variable
3. Bike10(){
4. speedlimit=70;
5. System.out.println(speedlimit); }
6.
7. public static void main(String args[]){ Output:t
8. Bike10 obj1 = new Bike10();
70
9. } }

static blank final variable

✓ A static final variable that is not initialized at the time of declaration is


known as static blank final variable. It can be initialized only in static block.

Example:
Output:t
1. class A{
2. static final int data; //static blank final variable 50
3. static{ data=50;}
4. public static void main(String args[]){

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 23


UNIT-2 – Object Oriented Programming

5. System.out.println(A.data);
6. } }

2) Java final method: If you make any method as final, you cannot override it.

Example:

1. class Bike{
2. final void run(){
3. System.out.println("running");}
4. }
5. class Honda extends Bike{
6. void run(){
7. System.out.println("running safely with 100kmph");}
8. public static void main(String args[]){
9. Honda honda= new Honda(); Output:t
10. honda.run();
Compile Time Error
11. } }

3) Java final class: If you make any class as final, you cannot extend it.
Example:

1. final class Bike{}


2. class Honda1 extends Bike{
3. void run(){System.out.println("running safely with 100kmph");}
4. public static void main(String args[]){
Output:t
5. Honda1 honda= new Honda1();
6. honda.run(); Compile Time Error
7. } }

Is final method inherited? Yes, final method is inherited but you cannot
override it.

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 24


UNIT-2 – Object Oriented Programming

Example:

1. class Bike{
2. final void run(){
3. System.out.println("running...");}
4. } Output:t
5. class Honda2 extends Bike{
6. public static void main(String args[]){ running….
7. new Honda2().run();
8. } }

❖ static Keyword
✓ The static keyword in Java is used for memory management mainly.

✓ We can apply static keyword with variables, methods, blocks and nested
classes. The static keyword belongs to the class than an instance of the class.
The static can be:
1. Variable (also known as a class variable)
2. Method (also known as a class method)
3. Block

1) Java static variable


✓ If you declare any variable as static, it is known as a static variable.
✓ The static variable can be used to refer to the common property of all objects
✓ The static variable gets memory only once in the class area at the time of
class loading.

Example of static variable

1. class Student{
2. int rollno;//instance variable
3. String name;
4. static String college ="ITS";//static variable

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 25


UNIT-2 – Object Oriented Programming

5. //constructor
6. Student(int r, String n){
7. rollno = r;
8. name = n;
9. }
10. void display (){System.out.println(rollno+" "+name+" "+college);}
11. }
12. //Test class to show the values of objects
13. public class TestStaticVariable1{
14. public static void main(String args[]){
15. Student s1 = new Student(111,"Karan");
16. Student s2 = new Student(222,"Aryan");
17. //we can change the college of all objects by the single line of code
18. //Student.college="BBDIT";
19. s1.display(); Output:t
20. s2.display(); 111 Karan ITS
21. } 222 Aryan ITS
22. }

2) Java static method


✓ If you apply static keyword with any method, it is known as static method.
✓ A static method belongs to the class rather than the object of a class.
✓ A static method can be invoked without the need for creating an instance of
a class.
✓ A static method can access static data member and can change the value of
it.
Example of static method

1. class Student{
2. int rollno;
3. String name;
4. static String college = "ITS";
5. //static method to change the value of static variable
6. static void change(){

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 26


UNIT-2 – Object Oriented Programming

7. college = "BBDIT";
8. }
9. //constructor to initialize the variable
10. Student(int r, String n){
11. rollno = r;
12. name = n;
13. }
14. void display(){System.out.println(rollno+" "+name+" "+college);}
15. }
16. //Test class to create and display the values of object
17. public class TestStaticMethod{
18. public static void main(String args[]){
19. Student.change();//calling change method
20. //creating objects
21. Student s1 = new Student(111,"Karan");
22. Student s2 = new Student(222,"Aryan");
23. Student s3 = new Student(333,"Sonoo");
24. //calling display method Output:t
25. s1.display();
26. s2.display(); 111 Karan BBDIT
222 Aryan BBDIT
27. s3.display();
333 Sonoo BBDIT
28. } }
3) Java static block

✓ Is used to initialize the static data member.

✓ It is executed before the main method at the time of class loading.


Example of static block

1. class A2{
2. static{System.out.println("static block is invoked");} Output:t
3. public static void main(String args[]){ static block is invoked
4. System.out.println("Hello main"); Hello main

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 27


UNIT-2 – Object Oriented Programming

5. } }

❖ Command Line Arguments


✓ The command-line arguments in Java allow the programmers to pass the
arguments during the execution of a program.
✓ The users can pass the arguments during the execution by passing the
command-line arguments inside the main() method.
✓ A command-line argument is nothing but the information that we pass after
typing the name of the Java program during the program execution.
✓ These arguments get stored as Strings in a String array that is passed to the
main() function.
✓ We need to pass the arguments as space-separated values. We can pass both
strings and primitive data types(int, double, float, char, etc) as command-line
arguments.
✓ These arguments convert into a string array and provided to the main()
function as a string array argument.
✓ Internally, JVM wraps up these command-line arguments into the args[ ]
array that we pass into the main() function. We can check these arguments
using args.length method.
✓ JVM stores the first command-line argument at args[0], the second at
args[1], third at args[2], and so on.
Example:
class Main {
public static void main(String[] args) {
System.out.println("Command-Line arguments are");
// loop through all arguments
for(String str: args) {
System.out.println(str);
} } }
Compilation : javac Main.java
Running : java Main apple ball cat

Output: Command-Line arguments are

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 28


UNIT-2 – Object Oriented Programming

Apple Ball Cat


Passing Numeric Command-Line Arguments
✓ The main() method of every Java program only accepts string arguments.
Hence it is not possible to pass numeric arguments through the command
line.
✓ However, we can later convert string arguments into numeric values.
✓ The parseInt() method of the Integer class converts the string argument into
an integer.
✓ Similarly, we can use the parseDouble() and parseFloat() method to convert
the string into double and float, respectively.
Example:
class Main {
public static void main(String[] args) {
for(String str: args) {
// convert into integer type
int argument = Integer.parseInt(str);
System.out.print("Argument in integer form: " + argument);
} }}

Compile the code: javac Main.java

Run the code: java Main 11 23


Output: Arguments in integer form
11 23
❖ Inheritance:
✓ Inheritance is the process of forming a new class from an existing class or
base class.
✓ The base class is also known as parent class or super class.
✓ The new class that is formed is called derived class. Derived class is also
known as a child class or sub class.

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 29


UNIT-2 – Object Oriented Programming

✓ Inheritance helps in reducing the overall code size of the program, which is
an important concept in object-oriented programming.
Implementing inheritance in Java: For creating a sub-class which is inherited
from the base class follow the below syntax.
Syntax:
class Subclass-name extends Superclass-name
{
//methods and fields
}
✓ subclass_name is the name of the sub class,
✓ extends keyword indicates that you are making a new class that derives
from an existing class.
✓ superclass_name is the name of the base class from which you want to
inherit the sub class.

❖ Java Multilevel Hierarchy


✓ It allows you to inherit properties of a grandparent in a child class.
✓ In simple inheritance, a sub class or derived class derives its properties from
its parent or super class.
✓ But in multilevel inheritance a sub class is derived from a derived class.
✓ Each class inherits only a single class. Therefore, in multilevel inheritance a
ladder is formed which at each step increases by one and the lowermost class
will have the properties of all the super classes.
✓ Java multilevel hierarchy is highly effective in implementing code reuse.

✓ It reduces programming efforts by using the predefined classes.

Multilevel Inheritance Example

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 30


UNIT-2 – Object Oriented Programming

4. class Dog extends Animal{


5. void bark(){System.out.println("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){System.out.println("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. d.weep(); Output:
14. d.bark();
weeping...
15. d.eat();
16.}} barking...
eating...
Hierarchical Inheritance Example
✓ When two or more classes inherits a single class, it is known as hierarchical
inheritance.
✓ In the example given below, Dog and Cat classes inherits the Animal class,
so there is hierarchical inheritance.

1. class Animal{
2. void eat(){System.out.println("eating...");} }
3. class Dog extends Animal{
4. void bark(){System.out.println("barking...");} }
5. class Cat extends Animal{
6. void meow(){System.out.println("meowing...");} }

7. class TestInheritance3{
8. public static void main(String args[]){
9. Cat c=new Cat();
10. c.meow(); Output:
11. c.eat(); meowing
eating...
Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 31
UNIT-2 – Object Oriented Programming

12. //c.bark();//C.T.Error
13.}}

Note: Multiple inheritance is not supported in java.


✓ Consider a scenario where A, B, and C are three classes.
✓ The C class inherits A and B classes.
✓ If A and B classes have the same method and you call it from child class
object, there will be ambiguity to call the method of A or B class.

❖ Super Keyword in Java:


✓ The super keyword in Java is a reference variable which is used to refer
immediate parent class object.
✓ Whenever you create the instance of subclass, an instance of parent class is
created implicitly which is referred by super reference variable.
Usage of Java super Keyword:
1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.
1) super is used to refer immediate parent class instance variable.
✓ It is used if parent class and child class have same data members. In that
case there is a possibility of ambiguity for the JVM.
✓ Use super keyword to access the data member or field of parent class.
Example:

1. class Animal{
2. String color="white";
3. }
4. class Dog extends Animal{

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 32


UNIT-2 – Object Oriented Programming

5. String color="black";
6. void printColor(){
7. System.out.println(color); //prints color of Dog class
8. System.out.println(super.color); //prints color of Animal class }
9. }
10. class TestSuper1{
11. public static void main(String args[]){ Output:t
12. Dog d=new Dog();
13. d.printColor(); black
14.}} white
✓ In the above example, Animal and Dog both classes have a common
property color.
✓ If we print color property, it will print the color of current class by default.
To access the parent property, we need to use super keyword.
2) super can be used to invoke parent class method.
✓ The super keyword can also be used to invoke parent class method.
✓ It should be used if subclass contains the same method as parent class.
✓ In other words, it is used if method is overridden.
Example:
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void eat(){System.out.println("eating bread...");}
6. void bark(){System.out.println("barking...");}
7. void work() {
8. super.eat();
9. bark(); }
10.}
11. class TestSuper2{
12. public static void main(String args[]){ Output:t

eating…
Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE barking 33
UNIT-2 – Object Oriented Programming

13. Dog d=new Dog();


14. d.work();
15.}}
✓ In the above example Animal and Dog both classes have eat() method if we
call eat() method from Dog class, it will call the eat() method of Dog class
by default because priority is given to local.
✓ To call the parent class method, we need to use super keyword.

3) super is used to invoke parent class constructor.


✓ The super keyword can also be used to invoke the parent class constructor.
Example:

1. class Animal{
2. Animal(){System.out.println("animal is created");}
3. }
4. class Dog extends Animal{
5. Dog(){
6. super();
7. System.out.println("dog is created"); }
8. } Output:t
9. class TestSuper3{
10. public static void main(String args[]){ animal is created
11. Dog d=new Dog(); }} dog is created

Note: super() is added in each class constructor automatically by compiler if there


is no super().

❖ Polymorphism in Java
✓ Polymorphism in Java is a concept by which we can perform a single action
in different ways.

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 34


UNIT-2 – Object Oriented Programming

✓ Polymorphism is derived from 2 Greek words: poly and morphs. The word
"poly" means many and "morphs" means forms. So, polymorphism means
many forms.
✓ There are two types of polymorphism in Java: compile-time polymorphism
and runtime polymorphism. We can perform polymorphism in java by
method overloading and method overriding.
✓ If you overload a static method in Java, it is the example of compile time
polymorphism.

❖ Method Overriding:
✓ Overriding is a feature that allows a subclass or child class to provide a
specific implementation of a method that is already provided by one of its
super-classes or parent classes.
✓ When a method in a subclass has the same name, same parameters or
signature, and same return type(or sub-type) as a method in its super-class,
then the method in the subclass is said to override the method in the super-
class.
✓ If subclass (child class) has the same method as declared in the parent class,
it is known as method overriding in Java.
✓ Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).

Importance of Method Overriding:


✓ The purpose of method overriding is that if the derived class wants to give
its own implementation it can give by overriding the method of the parent
class.

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 35


UNIT-2 – Object Oriented Programming

✓ When we call this overridden method, it will execute the method of the child
class, not the parent class.

Example of method overriding


Consider a scenario where Bank is a class that provides functionality to get the rate
of interest. However, the rate of interest varies according to banks.
For example, SBI, ICICI and AXIS banks could provide 8%, 7%, and 9% rate of
interest.

1. class Bank{ //Creating a parent class.


2. int getRateOfInterest(){
3. return 0;} }
4. class SBI extends Bank{ //Creating child classes.
5. int getRateOfInterest(){
6. return 8;} }
7. class ICICI extends Bank{
8. int getRateOfInterest(){
9. return 7;} }
10. class AXIS extends Bank{
11. int getRateOfInterest(){
12. return 9;}
13. }

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 36


UNIT-2 – Object Oriented Programming

14. //Test class to create objects and call the methods


15. class Test2{ Output:t
16. public static void main(String args[]){
17. SBI s=new SBI(); SBI Rate of Interest: 8
18. ICICI i=new ICICI(); ICICI Rate of Interest: 7
19. AXIS a=new AXIS(); AXIS Rate of Interest: 9
20. System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
21. System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
22. System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest()); }
23. }

Note-1: Can we override Static Method?

✓ No, a static method cannot be overridden.


✓ It is because the static method is bound with class whereas instance method
is bound with an object.
✓ Static belongs to the class area, and an instance belongs to the heap area.

Note-2: In Java, Main method cannot be overridden, because it is a static method.

Difference between method overloading and method overriding:

Method Overloading Method Overriding


Method overriding is used to provide the
Method overloading is used to increase the specific implementation of the method that is
readability of the program.
already provided by its super class.
Method overloading is performed within Method overriding occurs in two classes that
class. have IS-A (inheritance) relationship.
In case of method overloading, parameter In case of method overriding, parameter must
must be different. be same.
Method overloading is the example Method overriding is the example of run time
of compile time polymorphism. polymorphism.
In java, method overloading cannot be Return type must be same in method
performed by changing return type of the overriding.

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 37


UNIT-2 – Object Oriented Programming

method only.
Return type can be same or different in
method overloading. But you must have to
change the parameter.
❖ Runtime Polymorphism in Java
✓ Runtime polymorphism or Dynamic Method Dispatch is a process in which
a call to an overridden method is resolved at runtime rather than compile-
time.
✓ In this process, an overridden method is called through the reference
variable of a superclass.
✓ The determination of the method to be called is based on the object being
referred to by the reference variable.
Upcasting:
✓ If the reference variable of Parent class refers to the object of Child class, it
is known as upcasting.

✓ For example: class A{}


class B extends A{}
A a=new B(); //upcasting
✓ In above example, reference variable is “a” it is defined under parent class
“A” and it is referring to object of child class “B”.
Example of Java Runtime Polymorphism
✓ In the following example, we are creating two classes Bike and Splendor.
✓ Splendor class extends Bike class and overrides its run() method.
✓ We are calling the run() method by the reference variable of Parent class.
✓ Since it refers to the subclass object and subclass method overrides the
Parent class method, the subclass method is invoked at runtime.
✓ Since method invocation is determined by the JVM not compiler, it is known
as runtime polymorphism.
1. class Bike{
2. void run(){

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 38


UNIT-2 – Object Oriented Programming

3. System.out.println("running");}
4. }
5. class Splendor extends Bike{
6. void run(){
7. System.out.println("running safely with 60km");}
8. Output:t
9. public static void main(String args[]){
running safely with 60km.
10. Bike b = new Splendor(); //upcasting
11. b.run(); } }

Java Runtime Polymorphism with Data Member


✓ A method is overridden, not the data members, so runtime polymorphism
cannot be achieved by data members.
✓ In the example given below, both the classes have a data member speedlimit.
We are accessing the data member by the reference variable of Parent class
which refers to the subclass object.
✓ Since we are accessing the data member which is not overridden, hence it
will access the data member of the Parent class always.

1. class Bike{
2. int speedlimit=90; }
3. class Honda3 extends Bike{
4. int speedlimit=150;
5. public static void main(String args[]){
6. Bike obj=new Honda3();
7. System.out.println(obj.speedlimit); //90 }
Example:
1. class Animal{
2. void eat(){
3. System.out.println("animal is eating...");} }
4. class Dog extends Animal{
5. void eat(){
6. System.out.println("dog is eating...");} }
Output:t
Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE dog is eating... 39
UNIT-2 – Object Oriented Programming

7. class BabyDog1 extends Dog{


8. public static void main(String args[]){
9. Animal a=new BabyDog1();
10. a.eat(); }}

✓ Since, BabyDog is not overriding the eat() method, so eat() method of Dog
class is invoked.
❖ Abstract class
✓ A class which is declared as abstract is known as an abstract class.
✓ Abstraction is a process of hiding the implementation details and showing
only functionality to the user.
✓ Another way, it shows only essential things to the user and hides the internal
details.
✓ Abstraction lets you focus on what the object does instead of how it does it.

Rules for Java Abstract class:


✓ An abstract class must be declared with an abstract keyword.
✓ It can have abstract and non-abstract methods.
✓ It cannot be instantiated.
✓ It can have constructors and static methods also.
✓ It can have final methods which will force the subclass not to change the
body of the method.

Example of abstract class

abstract class A{}

Abstract Method in Java

✓ A method which is declared as abstract and does not have implementation is


known as an abstract method.

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 40


UNIT-2 – Object Oriented Programming

Example of abstract method

abstract void printStatus(); //no method body and abstract

Example of Abstract class that has an abstract method

✓ In this example, Bike is an abstract class that contains only one abstract
method run. Its implementation is provided by the Honda subclass.

1. abstract class Bike{


2. abstract void run(); }
3. class Honda4 extends Bike{
4. void run(){
5. System.out.println("running safely");}
Output:t
6. public static void main(String args[]){
7. Bike obj = new Honda4(); running safely
8. obj.run();
9. } }

Another example of Abstract class in java

1. abstract class Bank{


2. abstract int getRateOfInterest();
3. }
4. class SBI extends Bank{
5. int getRateOfInterest(){return 7;} }
6. class PNB extends Bank{
7. int getRateOfInterest(){return 8;} }
8. Output:t
9. class TestBank{
10. public static void main(String args[]){ Rate of Interest is: 7 %
11. Bank b; Rate of Interest is: 8 %
12. b=new SBI();
13. System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
14. b=new PNB();

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 41


UNIT-2 – Object Oriented Programming

15. System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");


16.} }

Abstract class having constructor, data member and methods

✓ An abstract class can have a data member, abstract method, method body
(non-abstract method), constructor, and even main() method.

✓ Rule: If there is an abstract method in a class, that class must be abstract.

✓ Rule: If you are extending an abstract class that has an abstract method, you
must either provide the implementation of the method or make this class
abstract.

//Example of an abstract class that has abstract and non-abstract methods


1. abstract class Bike{
2. Bike(){ // Constructor
3. System.out.println("bike is created");}
4. abstract void run();
5. void changeGear(){
6. System.out.println("gear changed");}
7. }
8.
9. //Creating a Child class which inherits Abstract class
10. class Honda extends Bike{
11. void run(){
12. System.out.println("running safely..");}
13. }
14.
15. //Creating a Test class which calls abstract and non-abstract methods
16. class TestAbstraction2{
17. public static void main(String args[]){
18. Bike obj = new Honda(); Output:t
19. obj.run();
bike is created
running safely
Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE gear changed 42
UNIT-2 – Object Oriented Programming

20. obj.changeGear();
21. }
22. }

❖ Strings
✓ Strings, which are widely used in Java programming, are a sequence of
characters.
✓ In the Java programming language, strings are objects.
✓ The Java platform provides the String class to create and manipulate strings.
✓ Java String contains an immutable sequence of Unicode characters.
✓ Java String is differ from string in C or C++, where (in C or C++) string is
simply an array of characters.
✓ String class is encapsulated under java.lang package.
char[] ch={'j','a','v','a','p','r','o','g','r','a'.’m’,’m’,’i’,’n’,’g’};
String s=new String(ch);
Is same as String s="javaprogramming";

Creating a String: There are two ways to create a String in Java

1. String literal

✓ In java, Strings can be created like this: Assigning a String literal to a String
instance:
String str1 = "Welcome";
String str2 = "Welcome";

✓ String is an object in Java. However, we have not created any string object
using new keyword above.

✓ The compiler does that task for us it creates a string object having the string
literal (that we have provided , in this case it is “Welcome”) and assigns it to
the provided string instances.

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 43


UNIT-2 – Object Oriented Programming

✓ But if the object already exist in the memory it does not create a new Object
rather it assigns the same old object to the new instance, that means even
though we have two string instances above(str1 and str2) compiler only
created on string object (having the value “Welcome”) and assigned the
same to both the instances.

✓ For example, there are 10 string instances that have same value, it means
that in memory there is only one object having the value and all the 10 string
instances would be pointing to the same object.

2. Using New Keyword


✓ If we want to have two different objects with the same string, than need to
create strings using new keyword.
✓ Create strings like this:
String str1 = new String("Welcome");
String str2 = new String("Welcome");
✓ In this case compiler would create two different objects in memory having
the same string.
Example:
public class Example{
public static void main(String args[]){
//creating a string by java string literal
String str = "Javaprogramming";
char arrch[]={'h','e','l','l','o'};

//converting char array arrch[] to string str2


String str2 = new String(arrch);

//creating another java string str3 by using new keyword


String str3 = new String("Java String Example");
//Displaying all the three strings
System.out.println(str);

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 44


UNIT-2 – Object Oriented Programming

System.out.println(str2);
System.out.println(str3);
} }

Java String Methods

Java Method Syntax Returns Usage

To get character at the


charAt() charAt(int index) char
specified index

compareTo(String To compare two Strings


compareTo() int
anotherString) Lexicographically.

Returns true if and only if


boolean this String represents the
contentEquals() contentEquals(StringBuffer boolean same sequence of
sb) characters as the
specified StringBuffer.

For finding the index of


indexOf(String str, int the first occurrence of a
indexOf() int
fromIndex) character or a string in
the given string.

To form a new character


toCharArray() toCharArray() char[]
array from this string

concat() concat(String str) String To append the passed

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 45


UNIT-2 – Object Oriented Programming

string to the end of the


given string.

To replace all the


replace(char oldChar, char occurrences of the given
replace() String
newChar) character/String from
given String

substring(int beginIndex, To get a part of a string


substring() String
int endIndex) from the given string.

For splitting the given


split() split(String regex,int limit) String[] string based on the given
regular Expression.

To remove all trailing and


strip() or trim() strip() or trim() String leading whitespaces from
the given string.

To return String
valueOf() valueOf(char[] data) String representation of the
passed argument.

Example:
import java.lang.*;
public class Test_Strings {
public static void main(String args[]) {

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 46


UNIT-2 – Object Oriented Programming

String str1 = "Department of CSE, LBRCE";


String str2 = "Department of IT, PVPSIT";
//int Length() method
int result1 = str1.length();
System.out.println("Length of given string str1 is : "+result1);
System.out.println("Length of given string str2 is : "+str2.length());
System.out.println();
// char charAt() method
char result2 = str1.charAt(8);
System.out.println("Character at given Index: "+result2);
System.out.println();
// int compareTo(String anotherString)
/* if (string1 > string2) it returns a positive value.
if both the strings are equal lexicographically
i.e.(string1 == string2) it returns 0.
if (string1 < string2) it returns a negative value.*/
String s1 = "Ram";
String s2 = "Shyam";
String s3 = "ABC";
int result3 = s1.compareTo( s2 );
System.out.println(result3);

result3 = s2.compareTo( s3 );
System.out.println(result3);

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 47


UNIT-2 – Object Oriented Programming

result3 = s3.compareTo( s1 );
System.out.println(result3);
System.out.println();
// boolean contentEquals(StringBuffer sb)
boolean result = str1.contentEquals( str2 );
System.out.println("Is Str1 and Str2 equals: "+result);
String str3 = new String( "Department of EEE, LBRCE");
boolean res2 = str1.contentEquals( str3 );
System.out.println("Is Str1 and Str3 equals: "+res2);
System.out.println();
// int indexOf(String str, int fromIndex)
String Str4 = new String("Welcome to Java Programming");
String SubStr1 = new String("Java" );
System.out.print("Found Index :" );
System.out.println( Str4.indexOf( SubStr1, 15 ));
// toCharArray()
System.out.print("Return Value :" );
System.out.println(Str4.toCharArray() );
// concat(String str)
String Str5 = "Strings are immutable";
Str5 = Str5.concat(" all the time");
System.out.println(Str5);
// replace(char oldChar, char newChar)

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 48


UNIT-2 – Object Oriented Programming

String Str6 = new String("Welcome to Java Programming");


System.out.print("Return Value :" );
System.out.println(Str6.replace('o', 'T'));

System.out.print("Return Value :" );


System.out.println(Str6.replace('m', 'D'));
// substring(int beginIndex, int endIndex)
System.out.print("Return Value :" );
System.out.println(Str6.substring(10, 15) );
// split(String regex,int limit)
String Str7 = new String("Welcome-to-Java Tutorial");
System.out.println("Return Value :" );

for (String retval: Str7.split("-", 2)) {


System.out.println(retval);
}
System.out.println("");

System.out.println("Return Value :" );


for (String retval: Str7.split("-", 3)) {
System.out.println(retval);
}
System.out.println("");
System.out.println("Return Value :" );

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 49


UNIT-2 – Object Oriented Programming

// strip() or trim()
String Str8 = new String(" Welcome to lbrce.com ");
System.out.print("Return Value :" );
System.out.println(Str8.trim() );
// String copyValueOf()
char[] Str1 = {'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'};
String Str2 = "";
Str2 = Str2.copyValueOf( Str1 );
System.out.println("Returned String: " + Str2);
}
}

❖ StringBuffer Class
✓ Java StringBuffer class is used to create mutable (modifiable) String objects.

✓ The StringBuffer class in Java is the same as String class except it is mutable
i.e. it can be changed.
Important Constructors of StringBuffer Class

1) StringBuffer Class append() Method:


✓ The append() method concatenates the given argument with this String.
1. class StringBufferExample{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 50


UNIT-2 – Object Oriented Programming

4. sb.append("Java"); //now original string is changed


5. System.out.println(sb); //prints Hello Java } }

2) StringBuffer insert() Method:


✓ The insert() method inserts the given String within string at the given position.
1. class StringBufferExample2{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. sb.insert(1,"Java"); //now original string is changed
5. System.out.println(sb); //prints HJavaello } }
3) StringBuffer replace() Method:
✓ The replace() method replaces the given String from the specified beginIndex
and endIndex.
1. class StringBufferExample3{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.replace(1,3,"Java");
5. System.out.println(sb); //prints HJavalo } }
4) StringBuffer delete() Method:
✓ The delete() method of the StringBuffer class deletes the String from the
specified beginIndex to endIndex.
1. class StringBufferExample4{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.delete(1,3);
5. System.out.println(sb); //prints Hlo } }
5) StringBuffer reverse() Method
✓ The reverse() method of the StringBuffer class reverses the current String.
1. class StringBufferExample5{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.reverse();
5. System.out.println(sb); //prints olleH } }
6) StringBuffer capacity() Method

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 51


UNIT-2 – Object Oriented Programming

✓ The 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 character increases from its current capacity, it increases the
capacity by (oldcapacity*2)+2.
✓ For example if your current capacity is 16, it will be (16*2)+2=34.
1. class StringBufferExample6{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer();
4. System.out.println(sb.capacity()); //default 16
5. sb.append("Hello");
6. System.out.println(sb.capacity()); //now 16
7. sb.append("java is my favourite language");
8. System.out.println(sb.capacity());//now (16*2)+2=34 [(oldcapacity*2)+ 2]
9. } }

❖ StringTokenizer
✓ The java.util.StringTokenizer class allows you to break a String into tokens. It
is simple way to break a String.
✓ In the StringTokenizer class, the delimiters can be provided at the time of
creation or one by one to the tokens.

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 52


UNIT-2 – Object Oriented Programming

Constructors of the StringTokenizer Class

Methods of the StringTokenizer Class

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 53


UNIT-2 – Object Oriented Programming

Example:

import java.util.StringTokenizer;
public class Simple{
public static void main(String args[]){
StringTokenizer st1 = new StringTokenizer("Dept. of CSE LBRCE"," ");

// boolean hasMoreTokens()

while (st1.hasMoreTokens()) {
System.out.println(st1.nextToken()); }
System.out.println("");

// String nextToken(String delim) -- printing next token

StringTokenizer st2 = new StringTokenizer("Dept.,of,CSE,LBRCE");

System.out.println("Next token is : " + st2.nextToken(","));

System.out.println("");

// boolean hasMoreElements()

StringTokenizer st3 = new StringTokenizer("Hello everyone I am a Java


developer"," ");

while (st3.hasMoreElements()) {

System.out.println(st3.nextToken()); }

System.out.println("");

// Object nextElement()

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 54


UNIT-2 – Object Oriented Programming

StringTokenizer st4 = new StringTokenizer("Hello everyone welcome to java


class"," ");

while (st4.hasMoreTokens()) {

/* Prints the elements from the String */

System.out.println(st4.nextElement()); }

System.out.println("");

// int countTokens()

StringTokenizer st5 = new StringTokenizer("Hello Everyone Have a nice day","


");

System.out.println("Total number of Tokens: "+st5.countTokens()); } }

Jagadeeswara Rao P, Sr. Asst. Prof, CSE (AI&ML), LBRCE 55

You might also like