Java 2
Java 2
Object oriented concepts in Java and apply for solving the problems.
Course Outcomes:
UNIT II:
➢ A class is a user defined blueprint or prototype from which objects are created.
➢ It represents the set of properties or methods that are common to all objects of one type.
✓ Fields
✓ Methods
✓ Constructors
✓ Blocks
{
//declare methods
// body of method
type method1(parameters)
}
{
// body of method } }
object
➢ An entity that has state and behaviour is known as an object.
❖Behaviour: It is represented by methods of an object. It also reflects the response of an object with
other objects.
❖Identity: It gives a unique name to an object and enables one object to interact with other objects.
➢ When an object of a class is created, the class is said to be instantiated. All the instances share the
attributes and the behaviour of the class.
➢ But the values of those attributes are unique for each object. A single class may have any number
of instances.
Bharath Yannam
Syntax for Creating Objects:
Example
Bharath Yannam
Reference Variables and Assignment
➢ A variable that holds reference of an object is called a reference variable.
➢ Variable is a name that is used to hold a value of any type during program execution.
➢ If the type is an object, then the variable is called reference variable, and if the variable holds
primitive types(int, float, etc.), then it is called non-reference variables.
Bharath Yannam
➢ In Java, if we have two different objects of the same class, and if we assign the reference of
one object to the other reference of the other object, then they refer to the same object.
Test t2 = t1;
➢ Here an object t1 is created for Test class and assigned to another object t2.
➢ The assignment of t1 to t2 did not allocate any memory or copy and part of the original
object.
➢ Thus, any changes made to the object through t2 will affect the object to which t1 is referring
Bharath Yannam
Java Methods
➢ A method is a block of code that performs a specific task.
➢ It provides the reusability of code. We write a method once and use it many times
➢ We can also provides the easy modification and readability of code using methods.
❖User-defined Methods: We can create our own method based on our requirements.
❖Standard Library Methods: These are built-in methods in Java that are available to use.
Bharath Yannam
Method Declaration
➢ The method declaration provides information about method attributes.
// method body }
Bharath Yannam
Method Signature: Every method has a method signature. It is a part of the method
declaration. It includes the method name and parameter list.
➢ Access Specifier: Access specifier or modifier is the access type of the method. It specifies the
visibility of the method. Java provides four types of access specifier:
❖Public: The method is accessible by all classes when we use public specifier in our
application.
❖Private: When we use a private access specifier, the method is accessible only in the classes in
which it is defined.
❖Protected: When we use protected access specifier, the method is accessible within the same
package or subclasses in a different package.
❖Default: When we do not use any access specifier in the method declaration, Java uses default
access specifier by default. It is visible only from the same package only.
Bharath Yannam
➢ Return Type: Return type is a data type that the method returns. If the method does not
return anything, we use void keyword.
➢ Method Name: It is a unique name that is used to define the name of a method. It must be
corresponding to the functionality of the method. Suppose, if we are creating a method for
subtraction of two numbers, the method name must be subtraction(). A method is invoked by
its name.
➢ Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of
parentheses. It contains the data type and variable name. If the method has no parameter, left
the parentheses blank.
➢ Method Body: It is a part of the method declaration. It contains all the actions to be
performed. It is enclosed within the pair of curly braces.
Bharath Yannam
Example:
int min;
min = n2;
else
min = n1;
return min;
Bharath Yannam
Method Calling
➢ There are two ways in which a method is called i.e., method returns a value or returning
nothing (no return value).
➢ The process of method calling is simple. When a program invokes a method, the program
control gets transferred to the called method.
➢ This called method then returns control to the caller in two conditions, when −
Bharath Yannam
public class MyClass {
myMethod();
In the above example if you remove the static keyword, java complains that you can’t
call a method from a static function:
Bharath Yannam
If you don’t want to use static, you can only call instance method:
void myMethod() {
x.myMethod();
Bharath Yannam
A method can also be called multiple times:
myMethod();
myMethod();
myMethod();
} }
Bharath Yannam
Returning a Value from a Method
➢ You declare a method's return type in its method declaration. Within the body of the method,
you use the return statement to return the value.
➢ Any method declared void doesn't return a value. It does not need to contain a return
statement.
➢ If you try to return a value from a method that is declared void, you will get a compiler error.
➢ Any method that is not declared void must contain a return statement with a corresponding
return value, like this:
return returnValue;
➢ The data type of the return value must match the method's declared return type; you can't
return an integer value from a method declared to return a boolean.
Bharath Yannam
public class MyClass { public class MyClass {
public static void main(String[] args) { public static void main(String[] args) {
MyClass x= new MyClass(); MyClass x= new MyClass();
} }
} }
Method Parameters
➢ Information can be passed to methods as public class Math {
parameter. static int multiplyBytwo(int number)
➢ Parameters act as variables inside the method. {
} } Bharath Yannam
Multiple Parameters
Bharath Yannam
Method Overloading
➢ If a class has multiple methods having same name but different in parameters, it is known as
Method Overloading.
➢ If we have to perform only one operation, having same name of the methods increases the
readability of the program
➢ In Java, Method Overloading is not possible by changing the return type of the method only.
Bharath Yannam
Method Overloading: changing no. of arguments
class Adder{
return a+b;
return a+b+c;
} }
class Test{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
Bharath Yannam
Method Overloading: changing data type of arguments:
class Adder{
return a+b;
return a+b;
} }
class TestOverloading2{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
Bharath Yannam
passing objects to methods
➢ In Java there is always pass by value and not by pass by reference.
➢ when a primitive type is passed to a method as argument then the value assigned to this primitive is
get passed to the method and that value becomes local to that method.
➢ which means that any change to that value by the method would not change the value of primitive
that you have passed to the method.
➢ 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 of call-by-reference.
➢ Changes to the object inside the method do reflect in the object used as an argument.
Bharath Yannam
class Ob System.out.println(c);
{ else
Ob(int i) }
a=i; {
if(b.a==a) } }
Bharath Yannam
Returning Objects from Methods
➢ When a method returns an object, the return type of the method is the name of the class to
➢ The normal return statement in the method is used to return the object
➢ In order to return an object from a Java method, you must first declare a variable to hold a
Bharath Yannam
class Sample { } }
Sample(int i) { {
} {
{ Sample s2;
return x; } s2.show(); } }
➢ Java has a feature that simplifies the creation of methods that need to take a variable number
of arguments.
➢ Before varargs either we use overloaded method or take an array as the method parameter.
➢ If we don't know how many argument we will have to pass in the method, varargs is the better
approach.
Bharath Yannam
Syntax : for (int i: a)
The varargs uses ellipsis i.e. three dots System.out.print(i + " ");
after the data type. Syntax is as follows: System.out.println();
return_type method_name(data_type... variableNa }
me){}
class Test1 {
➢ At the time of calling constructor, memory for the object is allocated in the memory.
➢ There are two types of constructors in Java: no-arg constructor, and parameterized
constructor.
➢ The name of the constructor must be the same as the name of the class.
Bharath Yannam
Example:
class Test {
Test() {
// constructor body
Here, Test() is a constructor. It has the same name as that of the class and doesn't have a return
type.
Bharath Yannam
Default Constructor Example
} }
Bharath Yannam
Parameterized Constructor
➢ A constructor which has a specific number of class Pc
parameters is called a parameterized {
constructor. Pc(int a, int b)
➢ The parameterized constructor is used to {
provide different values to distinct objects.
System.out.println(a+b);
}
public static void main(String[] args)
{
Pc p1=new Pc(5,6);
}
}
Bharath Yannam
Constructor Overloading
➢ Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists.
➢ They are arranged in a way that each constructor performs a different task.
➢ They are differentiated by the compiler by the number of parameters in the list and their
types.
Bharath Yannam
class Pc public static void main(String[] args)
{ {
{ Pc p2=new Pc('5');
System.out.println(a+b); }
} }
Pc(char a)
System.out.println(a);
Bharath Yannam
new Keyword
➢ The Java new keyword is used to instantiates a class by allocating memory for a new object
and returning a reference to that memory.
➢ We can also use the new keyword to create the array object.
Syntax
Bharath Yannam
Example 1 public static void main(String[] args) {
Create an object using new keyword and invoking NewExample1 obj=new NewExample1();
void display()
System.out.println("Invoking Method");
Bharath Yannam
Example 2
}
Bharath Yannam
static keyword
➢ The static keyword in Java is used for memory management mainly.
➢ The static keyword belongs to the class than an instance of the class.
❑ Block
❑ Nested class
Bharath Yannam
Java 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.
Bharath Yannam
class H18 public static void main(String[] args)
{ {
static int a=20,b=30; H18 h= new H18();
H18()
{ H18 h1= new H18();
a++; H18 h2= new H18();
b++; dis();
} dis();
static void dis() }
{
System.out.println(a+" "+b); }
}
Bharath Yannam
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.
➢ The static method can not use non static data member or call non-static method directly.
Bharath Yannam
class Calculate{
return x*x*x;
System.out.println(result);
Bharath Yannam
this Keyword
➢ this keyword in Java is a reference variable that refers to the current object of a method or a
constructor.
➢ The main purpose of using this keyword in Java is to remove the confusion between class
attributes and parameters that have same names.
Bharath Yannam
this: to refer current class instance variable: this.fee=fee;
➢ The this keyword can be used to refer current
class instance variable. }
this.rollno=rollno; s2.display();
}}
this.name=name;
Bharath Yannam
this: to invoke current class method: void n(){
a.n();
void m()
}}
{
System.out.println("hello m");
}
Bharath Yannam
this() : to invoke current class constructor: A(int x){
class TestThis5{
class A{
public static void main(String args[]){
A()
A a=new A(10);
{
}}
System.out.println("hello a");
Bharath Yannam
this: to pass as an argument in the method: void p(){
➢ It is mainly used in the event handling. Let's public static void main(String args[]){
s1.p();
class Cs{ }
}
void m(Cs obj){
System.out.println("method is invoked");
Bharath Yannam
this: to pass as argument in the constructor class Yx
call {
We can pass the this keyword in the constructor int a=2;
also. It is useful if we have to use one object in Yx()
multiple classes. {
Xy x=new Xy(this);
class Xy }
{ void display()
Yx y; {
System.out.println(a);
Xy(Yx y)
}
{ public static void main(String[] args)
this.y=y; {
y.display(); Yx y= new Yx();
} }
}
}
Bharath Yannam
Wrapper Classes
➢ A Wrapper class is a class whose object wraps or contains primitive data types.
➢ When we create an object to a wrapper class, it contains a field and in this field, we can store
primitive data types.
➢ It provides the mechanism to convert primitive into object and object into primitive.
➢ They convert primitive data types into objects. Objects are needed if we wish to modify the
arguments passed into a method (because primitive types are passed by value).
➢ The classes in java.util package handles only objects and hence wrapper classes help in this case
also.
➢ Data structures in the Collection framework, such as ArrayList and Vector, store only objects
(reference types) and not primitive types.
Bharath Yannam
Primitive Data types and their Corresponding Wrapper class:
Bharath Yannam
Autoboxing
➢ The automatic conversion of primitive data type into its corresponding wrapper class is
known as autoboxing.
➢ for example, byte to Byte, char to Character, int to Integer, long to Long, float to Float,
boolean to Boolean, double to Double, and short to Short.
Bharath Yannam
Unboxing
➢ The automatic conversion of wrapper type into its corresponding primitive type is known as
unboxing.
Bharath Yannam
Garbage Collection
➢ In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming the
runtime unused memory automatically.
➢ To do so, we were using free() function in C language and delete() in C++. But, in java it is
performed automatically.
Advantages:
➢ It makes java memory efficient because garbage collector removes the unreferenced objects
from heap memory.
➢ It is automatically done by the garbage collector(a part of JVM) so we don't need to make
extra efforts.
Bharath Yannam
How an object be unreferenced?
e=null;
➢ By anonymous object
new Employee();
Bharath Yannam
finalize()
➢ The finalize() method of Object class is a method that the Garbage Collector always calls just
before destroying the object which is eligible for Garbage Collection, to perform clean-up
activity.
➢ Clean-up activity means closing the resources associated with that object like Database
Connection, Network Connection or we can say resource de-allocation.
➢ Once the finalize method completes immediately Garbage Collector destroy that object.
Syntax:
Bharath Yannam
➢ Object class contains the finalize method hence finalize method is available for every java
class. Bcz, Object is the superclass of all java classes.
➢ it is available for every java class hence Garbage Collector can call the finalize method on any
java object
➢ finalize() method releases system resources before the garbage collector runs for a specific
object.
gc() method
➢ The gc() method is used to invoke the garbage collector to perform cleanup processing. The
gc() is found in System and Runtime classes.
Bharath Yannam
Example of garbage collection: H25 h1=new H25();
{ h1=null;
{ System.gc();
System.out.println("garbage");
Bharath Yannam
Command Line Arguments
➢ command-line argument is an argument i.e. passed at the time of running the java program.
➢ The arguments passed from the console can be received in the java program and it can be used
as an input.
➢ They are stored as strings in the String array passed to the args parameter of main() method
in Java.
Bharath Yannam
public class CommandLine {
Bharath Yannam
BufferedReader Class
➢ Java provides several mechanisms to read from File.
➢ The most useful package that is provided for this is the java.io
➢ BufferedReader class is used to read the text from a character-based input stream.
➢ This class provides a method named read() and readLine() which reads and returns the
character and next line from the source.
➢ Now, read data from the current reader as String using the readLine() or read() method.
Bharath Yannam
import java.io.*;
String name=br.readLine();
System.out.println("Welcome "+name);
Bharath Yannam
Scanner Class
➢ Scanner is a class in java.util package used for obtaining the input of the primitive types like int,
double, etc. and strings.
➢ Scanner class breaks the input into tokens using a delimiter which is whitespace by default. It
provides many methods to read and parse various primitive values.
➢ To create an object of Scanner class, we usually pass the predefined object System.in, which
represents the standard input stream.
➢ We may pass an object of class File if we want to read input from a file.
➢ To read numerical values of a certain data type XYZ, the function to use is nextXYZ(). For
example, to read a value of type short, we can use nextShort()
Bharath Yannam
Input Types
Method Description
Bharath Yannam
import java.util.*;
in.close();
Bharath Yannam
Controlling Access to Class Members
Access level modifiers determine whether other classes can use a particular field or invoke a
particular method.
➢ Private: The access level of a private modifier is only within the class. It cannot be accessed from
outside the class.
➢ Default: The access level of a default modifier is only within the package. It cannot be accessed
from outside the package. If you do not specify any access level, it will be the default.
➢ Protected: The access level of a protected modifier is within the package and outside the package
through child class. If you do not make the child class, it cannot be accessed from outside the
package.
➢ Public: The access level of a public modifier is everywhere. It can be accessed from within the
class, outside the class, within the package and outside the package.
Bharath Yannam
outside
Access outside
within class within package package by
Modifier package
subclass only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Bharath Yannam
class Test6 }
{ class Test7
System.out.println("hello"); {
{ a.dis();
} }
Bharath Yannam
Arrays
➢ An array is a collection of similar types of data.
➢ Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value.
➢ Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on.
➢ array itself has a type that specifies what kind of elements it can contain.
➢ An int array can contain int values, for example, and a String array can contain strings.
Bharath Yannam
some important points about Java arrays:
➢ Since arrays are objects in Java, we can find their length using the object property length.
➢ A Java array variable can also be declared like other variables with [] after the data type.
➢ The variables in the array are ordered and each have an index beginning from 0.
➢ Java array can be also be used as a static field, a local variable or a method parameter.
➢ The size of an array must be specified by an int or short value and not long.
Bharath Yannam
Declaring Array Variables:
➢ To use an array in a program, you must declare a variable to reference the array, and you must
specify the type of array the variable can reference.
Syntax:
❖dataType arr[];
Example:
String[] cars;
Bharath Yannam
Creating (Instantiation) Arrays:
Syntax:
datatype[] arrayRefVar;
arrayRefVar=new datatype[size];
➢ It assigns the reference of the newly created array to the variable arrayRefVar.
Declaring an array variable, creating an array, and assigning the reference of the array to the
variable can be combined in one statement, as shown below −
(OR)
// initialize array
age[0] = 12;
age[1] = 4;
age[2] = 5;
..
Bharath Yannam
Access Elements of an Array:
array[index]
Bharath Yannam
Example: Access Array Elements
class Main {
// create an array
} }
Bharath Yannam
Example to print array:
class Testarray1{
//printing array
System.out.println(a[i]);
for(int i:a)
System.out.println(i);
}}
Bharath Yannam
Types of Array in java:
➢ Multidimensional Array
Single dimensional array − A single dimensional array of Java is a normal array where, the array
contains sequential elements (of same type) −
Example:
class Testarray3{
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
System.out.println();
} }}
Bharath Yannam
import java.util.*; }
class Test22 for(int i=0;i<3;i++)
{ {
public static void main(String[] args) for(int j=0;j<3;j++)
{ {
Scanner s=new Scanner(System.in); for(int k=0;k<4;k++)
int[][][] a=new int[3][3][4]; {
for(int i=0;i<3;i++) System.out.print(a[i][j][k]+" ");
{ }
for(int j=0;j<3;j++) System.out.println();
{ }
for(int k=0;k<4;k++) System.out.println();
{ }
a[i][j][k]=s.nextInt(); }
} } }
Bharath Yannam
Irregular(Jagged) Arrays
➢ When you allocate memory for a multidimensional array, you need to specify only the
memory for the first (leftmost) dimension.
➢ You can allocate the remaining dimensions separately.
➢ For example, the following code allocates memory for the first dimension of table when it is
declared. It allocates the second dimension manually.
➢ When declaring an irregular array, at least one dimension does not contain a specific value
(empty brackets [ ]).
Bharath Yannam
Example:
Bharath Yannam
Difference between irregular arrays and regular arrays:
➢ In a regular array, the number of elements in each dimension is known in advance. This
number is set at the time of allocating memory for the array with the new operator.
➢ In an irregular array, the number of elements in at least one dimension is unknown. This
number may vary within this dimension.
For example. Let a regular array A be declared for which memory is allocated
• int[][] B = new int[3][]; // irregular array, the total number of elements is unknown
• it is known that this array B contains 3 one-dimensional arrays. The number of elements in
any of these arrays is unknown.
Bharath Yannam
class Test25 a[i][j]=i+j;
{ } }
{ {
a[0]=new int[5]; {
for(int i=0;i<2;i++) }
{ System.out.println();
for(int j=0;j<5;j++) }
{ } }
Bharath Yannam
import java.util.*; for(int i=0;i<a.length;i++)
class Jarray {
{ for(int j=0;j<a[i].length;j++)
public static void main(String[] args) {
{ a[i][j]=s.nextInt();
int b,c,d; }
Scanner s=new Scanner(System.in); }
b=s.nextInt(); for(int i=0;i<a.length;i++)
c=s.nextInt(); {
d=s.nextInt(); for(int j=0;j<a[i].length;j++)
int a[][] = new int[3][]; {
System.out.println(a[i][j]);
a[0] = new int[b]; }
}
a[1] = new int[c];
}
a[2] = new int[d]; }
Bharath Yannam
Array Copy in Java
Given an array, we need to copy its elements in a different array
Methods:
➢ Iterating each element of the given original array and copy one element at a time
Iterating each element of the given original array and copy one element at a time. With
the usage of this method, it guarantees that any modifications to b, will not alter the original
array a.
➢ Using clone() method :
Object cloning means to create an exact copy of the original object.
➢ Using arraycopy() method:
We can also use System.arraycopy() Method. The system is present in java.lang
package. Its signature is as :
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
Bharath Yannam
import java.util.*; for(int i=0;i<a.length;i++) for(int i:d)
import java.lang.*; { {
class Clone a[i]=s.nextInt(); System.out.println(i);
} }
{
int[] e=new int[a.length]; }
static void dis(int a[]) for(int i=0;i<a.length;i++) }
{ {
for(int i:a) e[i]=a[i];
System.out.println(i); }
for(int i:e)
}
{
public static void main(String[] System.out.println(i);
args)
}
{
Scanner int[] c=a.clone();
s=new Scanner(System.in); dis(c);
int b=4; int d[]= new int[a.length];
System.arraycopy(a, 0, d,
int[] a=new int[b]; 0, 3);
Bharath Yannam
Anonymous Array
An array in Java without any name is known as an anonymous array. It is an array just
for creating and using instantly. Using an anonymous array, we can pass an array with user
values without the referenced variable.
➢ We can create an array without a name. Such types of nameless arrays are called anonymous
arrays.
➢ The main purpose of an anonymous array is just for instant use (just for one-time usage).
Syntax:
Bharath Yannam
String
➢ In Java, string is basically an object that represents sequence of char values.
example:
char[] ch={‘h’,’e’,’l’,’l’,’o’};
is same as:
String s=“Hello";
Bharath Yannam
create a string object
There are two ways to create String object:
➢ By string literal
➢ By new keyword
String Literal:
String s="welcome";
➢ Each time you create a string literal, the JVM checks the "string constant pool" first.
➢ If the string already exists in the pool, a reference to the pooled instance is returned.
➢ If the string doesn't exist in the pool, a new string instance is created and placed in the pool.
➢ JVM will create a new string object in normal memory, and the literal "Welcome" will be
placed in the string constant pool.
Bharath Yannam
StringExample.java:
char ch[]={'s','t','r','i','n','g','s'};
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
Bharath Yannam
String Constructor
➢ String class supports several types of constructors in Java APIs.
The most commonly used constructors of the String class are as follows:
➢ String()
➢ String(String str)
➢ String(char chars[ ])
char chars[ ] = { 'w', 'i', 'n', 'd', 'o', 'w', 's' }; String str = new String(chars, 2, 3);
Bharath Yannam
➢ String(byte byteArr[ ])
byte b[] = { 97, 98, 99, 100 }; // Range of bytes: -128 to 127. These byte values will be
converted into corresponding characters.
byte b[] = { 65, 66, 67, 68, 69, 70 }; // Range of bytes: -128 to 127.
Bharath Yannam
String length()
➢ The Java String class length() method finds the length of a string
String s1="java";
String s2="program";
}}
Bharath Yannam
concatenation
➢ In Java, String concatenation forms a new String that is the combination of multiple strings.
➢ By concat() method
String s2=“Program";
String s3=s1.concat(s2);
Bharath Yannam
to String()
➢ A toString() is an in-built method in Java that returns the value given to it in string format.
➢ Any object that this method is applied on, will then be returned as a string object.
Integer number=10;
System.out.println( number.toString() );
➢ The second implementation is when you call the member method of the relevant class by
passing the value as an argument.
System.out.println(Double.toString(11.0));
Bharath Yannam
Character extraction
➢ The Java String class charAt() method returns a char value at the given index number.
➢ The index number starts from 0 and goes to n-1, where n is the length of the string.
String s1="javaprogram";
System.out.println(s1.charAt(4));
Bharath Yannam
string comparison
2. By Using == Operator
3. By compareTo() Method
Bharath Yannam
equals() Method:
The String class equals() method compares the original content of the string. It compares values
of string for equality.
String s1="Java";
String s2="Java";
String s4=“Programming";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
Bharath Yannam
Using == operator:
String s1="Java";
String s2="Java";
Bharath Yannam
compareTo():
➢ The String class compareTo() method compares values lexicographically and returns an
integer value that describes if first string is less than, equal to or greater than second string.
Bharath Yannam
String s1="Java";
String s2="Java";
String s3=“Program";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
Bharath Yannam
searching strings
➢ The Java String class indexOf() method returns the position of the occurrence of the specified
character or string in a specified string.
Bharath Yannam
modifying
Java String class replace() method returns a string replacing all the old char to new char.
Example:
System.out.println(s1.replace('j','k'));
System.out.println(s1.replace("java","MD"));
Bharath Yannam
Data conversion
➢ If you want to convert a String to specific data type, We use Wrapper class of the concern
datatype and parseDatype().
Example:
String s="200";
int i=Integer.parseInt(s);
Long i1=Long.parseLong(i1)
Bharath Yannam
changing the case
Example:
String s=“hello”;
System.out.println(“s,toUpperCase());
String s1=“HELLO”;
System.out.println(“s,toLowerCase());
Bharath Yannam
joining
➢ Java String class join() method returns a string joined with a given delimiter.
➢ In the String join() method, the delimiter is copied for each element.
Example:
String s2=String.join("/","12","11");
System.out.println(s2);
Bharath Yannam
split()
➢ The string split() method breaks a given string around matches of the given regular
expression.
➢ After splitting against the given regular expression, this method returns a char array.
Example:
for(String k:s4)
System.out.println(k);
Bharath Yannam
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.
Constructors:
Constructor Description
StringBuffer() It creates an empty String buffer
with the initial capacity of 16.
StringBuffer(String str) It creates a String buffer with the
specified string..
StringBuffer(int capacity) It creates an empty String buffer
with the specified capacity as
Example: length.
Bharath Yannam
Methods
length():
➢ This method is used to find the length of string similar to String class
➢ System.out.println(s.length());
Bharath Yannam
capacity():
➢ The capacity() method of the StringBuffer class returns the current capacity of the buffer.
➢ If the number of character increases from its current capacity, it increases the capacity by
(oldcapacity*2)+2.
➢ System.out.println(s.length());
➢ System.out.println(s.capacity());
Bharath Yannam
ensureCapacity():
➢ The ensureCapacity(int minimumCapacity) method of Java StringBuffer class ensures that the
capacity should at least equal to the specified minimum capcity.
➢ If the current capacity of string buffer is less than the specified capacity, then a new internal array
is allocated with the minimumCapacity or the capacity will increase as (old-capacity * 2) + 2.
Syntax:
Example:
str.ensureCapacity(18);
➢ The setLength(int newLength) method of StringBuffer class is the inbuilt method used to set the
length of the character sequence equal to newLength.
➢ If the newLength passed as argument is less than the old length, the old length is changed to the
newLength.
➢ If the newLength passed as argument is greater than or equal to the old length, null characters
are appended at the end of old sequence so that length becomes the newLength argument.
Syntax:
Bharath Yannam
charAt():
➢ The Java String class charAt() method returns a char value at the given index number.
➢ The setCharAt(int index, char ch) method of Java StringBuffer class is used to set the
specified character at the given index.
➢ The specified character altered this sequence by replacing the old character at the given index.
➢ The Java String class getChars() method copies the content of this string into a specified char
array.
➢ There are four arguments passed in the getChars() method. The signature of the getChars()
method is given below:
Signature:
public void getChars(int srcBeginIndex, int srcEndIndex, char[] destination, int dstBeginIndex)
Bharath Yannam
append():
The java.lang.StringBuffer.append() method is used public StringBuffer append(char[] str, int offset,
There are various overloaded append() methods public StringBuffer append(CharSequence cs,
{ System.out.println(s1.capacity());
s1.setLength(50);
public static void main(String[] args)
System.out.println(s1.length());
{
s1=s1.append(“CSE AIML GRIET");
StringBuffer s1=new StringBuffer("hello java");
System.out.println(s1.capacity());
System.out.println(s1);
s1.ensureCapacity(220);
System.out.println(s1.append(" class"));
System.out.println(s1.capacity());
System.out.println(s1.replace(2,4,“java")); }
System.out.println(s1.insert(2,“java")); }
System.out.println(s1.delete(2,4));
Bharath Yannam
String Tokenizer
➢ The java.util.StringTokenizer class allows you to break a String into tokens.
Bharath Yannam
Constructors:
Constructor Description
Bharath Yannam
Methods:
Methods Description
It checks if there is more
boolean hasMoreTokens()
tokens available.
It returns the next token
String nextToken() from the StringTokenizer
object.
String nextToken(String It returns the next token
delim) based on the delimiter.
It is the same as
boolean hasMoreElements()
hasMoreTokens() method.
It is the same as nextToken()
Object nextElement()
but its return type is Object.
It returns the total number
int countTokens()
of tokens.
Bharath Yannam
import java.util.*; {
class Sto System.out.println(s1.nextToken());
{ }
public static void main(String[] args)
while(s2.hasMoreTokens())
{
{
StringTokenizer s1=new StringTokenizer("hello System.out.println(s2.nextToken("-"));
java class");
}
StringTokenizer s2=new }
StringTokenizer("hello-java-class");
System.out.println(s1.countTokens()); }
while(s1.hasMoreTokens())
{
System.out.println(s1.nextToken());
}
while(s1.hasMoreElements())
Bharath Yannam
Inheritance
➢ Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of
a parent object.
➢ The concept of inheritance in Java is that new classes can be constructed on top of older ones.
➢ A class that inherits from another class can reuse the methods and fields of that class. Moreover,
you can add new methods and fields in your current class also.
➢ Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
➢ Code Reusability: The code written in the Superclass is common to all subclasses. Child classes
can directly use the parent class code.
➢ Method Overriding: Method Overriding is achievable only through Inheritance. It is one of the
ways by which Java achieves Run Time Polymorphism.
➢ Abstraction: The concept of abstract where we do not have to provide all details is achieved
through inheritance. Abstraction only shows the functionality to the user.
Bharath Yannam
Terms used in Inheritance:
➢ Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a
derived class, extended class, or child class.
➢ Super Class/Parent Class: Superclass is the class from where a subclass inherits the features.
It is also called a base class or a parent class.
➢ Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse
the fields and methods of the existing class when you create a new class. You can use the
same fields and methods already defined in the previous class.
Bharath Yannam
Inheritance Syntax :
class superclass
{
// superclass data variables
// superclass member functions
}
class subclass extends superclass
{
// subclass data variables
// subclass member functions
}
Bharath Yannam
Types of inheritance:
Bharath Yannam
Method Overriding
➢ If subclass (child class) has the same method as declared in the parent class, it is known as
method overriding in Java.
➢ When a method in a subclass has the same name, the same parameters or signature, and the
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.
Bharath Yannam
Usage
➢ The method must have the same name as in the parent class
➢ The method must have the same parameter as in the parent class.
Bharath Yannam
class Vehicle{
obj.run();//calling method
Bharath Yannam
super Keyword
➢ 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.
Bharath Yannam
1. super is used to refer immediate parent System.out.println(color);//prints color of
class instance variable. Dog class
class Animal{ }
class Animal{ }
Dog(){
Bharath Yannam
final keyword
➢ In Java, the final keyword is used to denote constants. It can be used with variables, methods,
and classes.
➢ Once any entity (variable, method or class) is declared final, it can be assigned only once. That
is,
Bharath Yannam
1. Java final Variable
class Main {
AGE = 45;
Bharath Yannam
2. Java final Method:
In Java, the final method cannot be overridden by the child class. For example,
Bharath Yannam
3. Java final Class
In Java, the final class cannot be inherited by another class. For example,
Bharath Yannam
Abstract class
➢ A class which is declared as abstract is known as an abstract class.
❑ It cannot be instantiated.
❑ It can have final methods which will force the subclass not to change the body of the
method.
Bharath Yannam
abstract class Swaran {
{ Harsha h=new Harsha();
abstract void show(); h.dis();
void dis() h.show();
{ }
System.out.println("hello"); }
}
}
class Harsha extends Swaran
{
void show()
{
System.out.println("hello show");
}
public static void main(String[] args)
Bharath Yannam
Nested Classes
➢ Java inner class or nested class is a class that is declared inside the class or interface.
➢ We use inner classes to logically group classes and interfaces in one place to be more readable and
maintainable.
➢ Additionally, it can access all the members of the outer class, including private data members and
methods.
➢ Also known as a static inner class, it is a static class that is defined within another class.
➢ It does not have access to the instance-specific data of the outer class but can access its static
members.
➢ You can create an instance of a static nested class without an instance of the outer class.
Bharath Yannam
class Outer { Outer. Nested n = new Outer. Nested ();
} } }
{
Bharath Yannam
Inner Class (Non-static Nested Class):
➢ It can access both static and instance-specific data of the outer class.
➢ To create an instance of an inner class, you typically need an instance of the outer class.
Bharath Yannam
Bharath Yannam
Local Inner Class:
➢ Local inner classes can access both static and instance-specific data of the enclosing method
or block.
Bharath Yannam
class OuterClass LocalInnerClass localInner = new
{ LocalInnerClass();
localInner.display();
void methodWithLocalInnerClass()
}
{
}
class LocalInnerClass
public class Main
{
{
public void display() public static void main(String[] args)
{ {
} } }}
Bharath Yannam
Anonymous Inner Class:
➢ An anonymous inner class is an inner class without a name that is defined and instantiated at
the same time.
➢ They are often used for creating one-time-use classes and overriding methods or interfaces.
Bharath Yannam