JAVA (SEM 4) Unit 2
JAVA (SEM 4) Unit 2
Unit – II
Strings
Introduction to OOPS
Classes and Objects
Methods
Inheritance
__________________________________________________________________________
Chapter-1 Strings
Q) Explain about Strings or String class in Java . (or)
Explain about String methods( functions ) (or) String operations in Java .
Note : To explain all string methods , consider two example strings as follows :
String s1= “Java” ;
String s2 = “Program” ;
1.concat (): It concatenates or joins two strings and returns a third string as a result.
Ex : String s3 = s1.concat(s2) ;Result : s3=JavaProgram
5. indexof( ‘char‘ ,n ): It returns position of given character in string after nth position.
Ex :int x=s3.indexof( ‘ r ’ , 6) ;
Result : x=8 ( r is located at 8 th position after 6 th position)
6.compareTo() : It compares two strings and to know which string is big or small orequal.
Ex :int x =s1.compareTo(s2) ; Result x = -1
It returns –ve , if s1 is less than s2
It returns +ve , if s1 is greater than s2
It returns zero , if s1 is equals to s2
8. substring ( n ): It returns part of given string from nth position to end of string.
Ex :s3 = “JavaProgram” [ position starts from zero(0) ]
s3.substring( 2 ) ;
Result :vaProgram[ It is part of string s3 from 2nd position ]
12. equals(): It returns true if the two strings are same, otherwise false. This is case sensitive.
Ex : if s1= “JAVA” and s2=”Java” then
s1.equals( s2 ) ; Result : false
13. equalsIgnoreCase(): It returns true if the two strings are same, otherwise false. but not
case sensitive.
Ex : if s1= “JAVA” and s2=”Java” then
s1.equals( s2 ) ; Result : true
for(i=0;i<st.length;i++)
{
for(j=i+1;j<=st.length-1;j++)
{
if(st[i].compareTo(st[j])>0)
{
String t=st[i];
st[i]=st[j];
st[j]=t;
}
}
}
System.out.println("After Sorting :");
for(i=0;i<st.length;i++)
System.out.print(st[i] +” ,”);
}
}
Output:Before Sorting : Delhi , Madras , Hyderabad , Calcutta , Bombay
After Sorting : Bombay ,Calcutta , Delhi , Hyderabad , Madras
------------------------------------------------------------------------------------------------
A) Immutability of Strings : Immutability means “not capable to change”. If Strings are not
able to modify the original content, then it is called “Immutability of Strings” .
- In java, strings are defined by two predefined classes which are “String” and “StringBuffer”
- Strings which are defined by using “String” class are not able to modify.
Now we can change length and content of the string ‘s1’ as we require .To perform these
operations , “StringBuffer” class provides some methods . They are :
StringBufferMethods :
1. s1.setCharAt(n, ‘char’ ) : It modifies the nth position character in ‘s1’ with given character.
2.s1.append(“string”) : It adds the new given string at end of existed string ‘s1’.
3 .s1.insert( n , “string” ) : It inserts the new given string at nth position of existed string ‘s1’.
4. s1.setLength(n) : It modifies the length of the string ’s1’ to ‘n’ .
output:
Original string : Object Programing
Now string modified as :ObjectOriented Programing
Now string modified as :ObjectOriented Programing improves Security
Now string modified as : Object – Oriented Programing improves Security
In this way by using StringBufferclass , we can created and modify the original contents of a
string, But this not possible to strings which are created by class “String”.
-----------------------------------------------------------------------------------------------
Q) Explain String Comparison (or) equals( ) method.
A) We cannot compare two strings by using comparison operator( = =).
Ex: String s1=”Java”;
String s2=”Java”;
if ( s1 = = s2)
System.out.println(“Strings are Equal”) ;
else
System.out.println(“Strings are Not Equal”) ;
The above code gives output as “Strings are Not Equal” even s1 and s2 are equal,
because JVM creates two different references for s1 and s2.
So, Java provides two String class methods to compare two strings. They are :
1. s1.equals(s2) – it returns true if s1 and s2 are equal, otherwise false
2. s1.equalsIgnoreCase(s2) - it returns true if s1 and s2 are equal by ignoring case
Ex :
class StrComp
{
public static void main(String args[])
{
String s1="Hello";
String s2="hello";
System.out.println(s1.equals(s2)); // false
System.out.println(s1.equalsIgnoreCase(s2)); // true
}
}
-------------------------------------------------------------------------------------------------
Chapter-2 INTRODUCTION TO OOP
1. Procedure OrientedProgramming(POP)
2. Object OrientedProgramming(OOP)
1.Procedure Oriented Programming:
Disadvantages:
3. Most of the functions use global data. 3. Each object controls its own data
4.Same data may be transfer from one 4.Data does not possible transfer from
function to another one
object to another
Functions get more importance than data Data gets more importance than
functions
5. there is no perfect way for data hiding 5. Data hiding possible in OOP which
prevent illegal access of function
from outside of it.
6. More data or functions can not be 6. More data or functions can be added
added easily with Program very easily
.
7. Top down process is 7. Bottom up process is
followed for program followed for program
design. design.
8. Example: Pascal, Fortran 8. Example: C++, Java.
____________________________________________________________________
1. Encapsulation
2. Class
3. Object
4. Abstraction
5. Inheritance
6. Polymorphism
7. Dynamic Binding
8. Message passing
Due to this the data in one block is not accessed by another block.
Ex : class Rectangle
{
int length,width ; // variables
System.out.println(“Area=”+(length*width));
By using the object ,we can use the variables and methods of that class.
Here r1 ,r2 are the objects of class “Rectangle ” (i.e. two sets(copies) of variables
and methods of rectangle class)
Object : r1 Object : r2
Data(varaiables) Data(varaiables)
Here the method “area()” does not contain any definition. i.e. we don’t mention
which area is calculated like Tringle or Rectangle or Square etc.
Here the single method ‘area()’ is defined in many forms.i.e. the same method
“area()” calculates the area for circle,Box,Triangle objects seperately.
Dynamic Binding:
It is also known as dynamic dispatch, it is the process of linking function call
to a specific function definition atrun-time.
Message Passing:
Objects communicate with one another by sending and receiving information
much the same way as people pass messages to oneanother.
Ex :employee.salary(name);
Applications of OOP
Real timesystems
Simulation andmodeling
Object- Orienteddatabase
Hypertext, hypermedia andexpert-text
Artificial Intelligence(A I) and expertsystems
Neural networks and parallelprogramming
Decision support and office automationsystems
CAM/CADsystems
_____________________________________________________________________________
Since Java is OOP language , the java code is represented in the form of classes and
objects.
Class : It is the group of variables and methods as single logic unit.
This process of grouping variables & methods as single unit , is called “Encapsulation “
In java, classes are defined as follows :
Syntax : class class_Name [ extends class_name ]
{
Instance variables;
Method definitions ;
}
2.Method definitions :
-Methods are similar to functions in c- language.
-Method is block of statements to peform a well defined task. These are defined as :
Syntax : returntype method_name ( [ parameter list ] )
{
[ local variables ; ]
Statements ; ( Body of method )
}
Here ,returntype : is datatype of value return by method when it executed.
Method_name :is name of the method.
Parameter_list : these are values given to method.
Local variables : these variables declared and used (if required) in that method only
Staements: statements which are to be executed.
Ex : class Rectangle
{
int length,width; // instance variables
void area (int x , int y) // area is method and x, y are parameters
{
length=x;
width=y;
int a; // a is local variable
a = length * width ;
System.out.println(“ Area = “ + a );
}
}
Here “class “ is the keyword which is used to define class . “Rectangle” is the class
name, “extends” is the keyword used in Inheritance.
r1.area(10,20);
r2.area(7,5);
}
}
Above program , Saved as : OOP1.java
Compile as :javac OOP1.java
Run as : java OOP1
Output : Area = 200 // r1 used length,width variables and calculate area using area() method
Area = 35 // r2 also used length,width and calculate area using area() method.
i.e. the variables and methods of a class are used by all objects of that class individually and at the
same time.
_____________________________________________________________________________
void area()
{
Normal int a;
method a = length * width ;
System.out.println(“ Area = “ + a );
}
}
class OOP3
{
public static void main(String args[])
{
Rectangle r=new Rectangle (10,20); /* initialize variables length,width at
time of object creation */
r.area();
}
}
Above program , Saved as : OOP3.java
Compile as :javac OOP3.java
Run as : java OOP3
Output : Area = 200
Types of constructors :
There are two types of constructors
1.Default constructor : It is a constructor which have no parameters.
2.Parameterised Constructor : It is a constructor which have parameters
Example program :
class Values
{
int v1,v2,v3 ;
Values( ) // Default constructor
{
v1=0;
}
Values(int y , int z ) // parameterisd constructor
{
v2=y;
v3=z;
}
}
Constructor Overloading: It is the process of defining same constructor with different
parameter lists.
Example Program:
class Values
{
int v1,v2,v3 ;
Values(int p) // one parameter
{
v1=p;
}
Example Program :
class Sample
{
int num = 10 ;
void display( )
{
System.out.println(“Given value for num = “ + num ) ;
}
}
class var_init
{
public static void main(String args[])
{
Sample s = new Sample( ) ;
s.num = 7 ; /* Now 7 is replaced insteadof 10 in variable num */
s.display();
}
}
output : Given value for num = 7
------------------------------------------------------------------------------------------------------
Chapter -3 METHODS IN JAVA
------------------------------------------------------------------------------------------------------------
Instance Methods : The methods which used the instance variables are called
“Instance Methods” . These are two types :
1. AccessorMethods: These methods just access instance variables but cannot modify them.
2. Mutator Methods : These methods can access and modify the instance variables.
{
System.out.println("Given n Value = "+n);
n=33; /* access and modify the instance variable “n” */
System.out.println(" Modfied n value = "+n);
}
}
class OOP5
{
public static void main(String args[])
{
methods k=new methods();
k.acce_method(7);
k.muta_method();
}
}
output : Given n value = 7 Modified n value = 3
--------------------------------------------------------------------------------------------
Q) Explain about “ this “ keyword.
A) “ this” is the reserved keyword. It is used to refer to the object of a class(Parent
class) where it is used.
It is default reference of a class when an object is created for that class.
By using “this” , we can refer all instance variables,methods,constrcutors of a class.
Instance Variables
this Constructors
Methods
Object
Example Program:
class Demo
{
int n ;
Demo( )
{
this( 7 ) ;
this.display( );
}
Demo(int n )
{
this.n = n ;
}
void display( )
{
System.out.println(“n value = “ + n );
}
}
class OOP6
{
public static void main(String args[ ])
{
Demo d = new Demo( );
}
}
output : n value = 7
--------------------------------------------------------------------------------------------------------------------
Q ) Explain the following :
a)passing primitive DataTypes to methods
b)passing Arrays to methods
c) passing Objects to methods
Syntax : method_Name(arg1,arg,.....) ;
Ex : class Sample
{
void display(int x, int y )
{
System.out.println(x +” “ +y ) ;
}
}
class oop7
{
public static void main(String args[])
{
int n1=10,n2=20 ;
Sample k =new Sample( );
k.display(n1,n2) ; // Passing Primitve type “int “ values n1,n2 to display() method.
}
}
output : 10 20
Example prog:
class Student
{
int rollno;
String name;
}
void get_data(int rollno,String name)
{
this.rollno=rollno;
this.name=name;
}
}
class Details
{
void display_data(Student k)
{
System.out.println("Student RollNo = "+k.rollno);
System.out.println("Student Name = "+k.name);
}
}
class oop9
{
public static void main(String args[ ])
{
Student k=new Student( ) ; // ‘k’ is object of Student class
k.get_data(7,"Raju");
Details m=new Details( ) ;
m.display_data( k ) ; // object k passed to display_data( ) method
}
}
output : Student RollNo = 7
Student Name = Raju
-----------------------------------------------------------------------------------------------------------------
Q ) Explain Recursion with an Example
A) If a method calls itself , then it is called “Recursive Function “ or “Recursion”.
Ex Prog : class Recursion {
int factorial( int n )
{
if( n = = 1 )
return 1 ;
else
return( n * factorial( n – 1 ) ) ;
}}
class oop10
{
public static void main( String args[ ] )
{
Recursion k = new Recursion( ) ;
int f ;
f = factorial ( 5 ) ;
System.out.println(“ factorial value = “ + f );
}
}
Syntax : method1()
{
…………
………....
method2() ;
………….
}
Example program:
class Nesting
{
void msg()
{
System.out.println(“ Java is OOP language”);
}
void display()
{
System.out.println(“ welcome”);
msg();
}
}
class nest_method
{
public static void main(String args[])
{
Nesting n = new Nesting( );
n.display( );
}
}
In the above program , when display() method is executed automatically msg()
method also executed because msg() is nested in display() method.
Output : welcome
--------------------------------------------------------------------------------
Q) Explain about static variables(static members / class variables ),static
methods inJava
Generally each object of a class maintain its own copy of variables and methods , But static
variables and static methods are used common instance(memory block) for all objects .
If we declare variables with “static” keyword in a class , those are called “Static Variables”.
If we define methods with “static” keyword in a class , those are called ” StaticMethods”.
Similarly, these variables and methods of a class may accessed without any object.
Ex Program :
class Numbers
{
int x ;
static int y ;
n1.x=5;
n3.x=15; but for static variable ‘y’ common block for all objects
Output : 5 , 10 , 15
25 , 25 , 25
--------------------------------------------------------------------------------------------------------
choice Q) Explain Different ways to give values to instance variables:
The variables which are declared in a class are called “instance variables “.we can give values to
these instance variables by using following techniques :
Example :
class Values
v1 = x;
v2 = y;
void display()
class OOP
a.get_value(20);
a.display();
output : 7 20 25
_____________ _________________________________________________________
Chapter – 5 INHERITANCE .
Introduction : A Java program may contain no. of classes , But the properties( variables and
methods) of one class are not accessed by another class . So using Inheritance concept we can
access properties of one class into another class . Since Java is OOP language , it supports
Inheritance.
Types of Inheritance :
In this , a single sub class is derived from single super class. It is represented as follows :
Here class B is derived from class A. So Class B can use ( Inherit ) the variables and methods of
class A.
The following example program shows Single Inheritance :
Note :In programs comments /*……*/ are just for understanding only
classA
{
int x;
void displayA( )
{
System.out.println(x);
}
}
class B extends A /* class B derived from class A */
{
int y;
void displayB( )
{
System.out.println(x +” ,” +y); /* class B use “ x “ which is variable of class A */
}
}
class Single
{
public static void main(String args[ ] )
{
B b=new B( );
b.x=20;
b.y=30; /* class B use the variables and methods of class A */
b.displayA( );
b.displayB( );
}
}
Output : 20
20 30
Note : Super class can use its own properties only , But Sub class can use Superclass properties
and its own properties also.
A Super class
B sub class
C sub class
Here class B is derived from class A. Similarly class C is derived from subclass B. So B can use
theproperties of class A ,But C can use properties of both classes A and B.
classA
{
int x;
void displayA( )
{
System.out.println(x);
}
}
class MultiLevel
{
public static void main(String args[ ] )
{
B b=new B( );
b.x=20;
b.y=30; /* class B use the variables and methods of class A */
b.displayA( );
b.displayB( );
C c=new C( );
c.x=3;
c.y=5;
c.z= 7; /* class C use the variables and methods of class A and class B */
c.displayA( ); Output : 20
c.displayB( );
c.displayC( ); 20 , 30
}}
3,5,7
3 ,5
3.Hierarchical Inheritance :
In this, more than one SubClasses are derived from single Super Class Only. It represented as
Super class A
B C
Sub Class1 Sub Class 2
Here the Sub ClassesBand C are derived from Single Super Class A . So Band Ccan use
theproperties of class A .
class A
{
int x;
voiddisplayA( )
{
System.out.println(x);
}
}
class Hierarchical
{
public static void main(String args[ ] )
{
B b=new B( );
b.x=20;
b.y=30; /* class B use the variables and methods of class A */
b.displayA( );
b.displayB( );
C c=new C( );
c.x=3;
c.z= 7; /* class C use the variables and methods of class A */
c.displayA( ); Output : 20
c.displayC( ); 20 , 30
}
} 3
3,7
3 ,7
4. Multiple Inheritance :
In this, single Sub Class is derived from more than one Super Class . It is represented as :
Sub Class
Here the Sub Class C is derived from two Super Classes A and B .
In Java , the Multiple Inheritance is not possible with classes . But by using “ Interfaces “
concept , we can develop Multiple Inheritance.
3.Hybrid Inheritance :
Single Inheritance
Hierarchical Inheritance
C D
In the above example , two types of Inheritance are combined Single Inheritance (A -> B) and
Hierarchical Inheritance ( B -> C and D) . This is called “Hybrid Inheritance “.
------------------------------------------------------------------------------------------------------------------------
We can initialize the instance variables of super class by using its subclass at time of object
creation. For this java provides a special method called “super( )”.
class A
{
int length , width ;
A(int x , int y )/* Super Class Constructor */
{
length = x ;
width = y ;
}
void area( )
{
System.out.println(“Area =“+(length*width));
} }
}
class B extends A
{
int height;
void volume( )
{
System.out.println(“Volume =”+(length*width*height));
}
}
class SubConst
{
public static void main(String args[ ])
{
B b =new B( 8,5,12 );
b.area( );
b.volume( );
}
}
Output : Area = 40
Volume = 480
In the above program, when object is created for subclass B, three values are passed to Subclass
Constructor. In those three values , two values are passed to Superclass constructor by using
super( )method which is used in subclass constructor.
____________________________________________________________________________________________________