0% found this document useful (0 votes)
12 views34 pages

JAVA (SEM 4) Unit 2

This document covers concepts of Object-Oriented Programming (OOP) using Java, including strings, string methods, and the distinction between String and StringBuffer classes. It explains the principles of OOP such as encapsulation, inheritance, and polymorphism, and contrasts OOP with Procedure Oriented Programming (POP). Additionally, it provides examples and methods for string manipulation and sorting in Java.

Uploaded by

kvdc2005
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)
12 views34 pages

JAVA (SEM 4) Unit 2

This document covers concepts of Object-Oriented Programming (OOP) using Java, including strings, string methods, and the distinction between String and StringBuffer classes. It explains the principles of OOP such as encapsulation, inheritance, and polymorphism, and contrasts OOP with Procedure Oriented Programming (POP). Additionally, it provides examples and methods for string manipulation and sorting in Java.

Uploaded by

kvdc2005
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/ 34

II BSC(sem-4)-All Comp Groups- OOP using Java Unit - II

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 .

String :It is a sequence of characters.


In java , a string is an object for the predefined class called “String” .

In Java , strings are created in different ways as shown below :


1. We can declare a String variable and directly store a string value by assignment op .
Syntax : String string_object ;
Ex : String s1 ; // declaring the string type variable
Syntax : string_object = value

Ex : s1=”Hello java”; //assign a group of characters to it


The above two statements may write in single statement as follows :
String s1 =“Hello java” ;
2. We can create an object to String class by allocating memory using new Operator.
This is like creating an object to any class.

Ex :String s1 = new String (" Hello Java");

String Methods (string operations ):


 The “String” class contains some special methods which are called “String Methods”.
 These methods are used to perform string related operations. They are :

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

2.length( ) :It gives number of characters in a string.

Krishnaveni Degree College :: Narasaropet Page 1


II BSC(sem-4)-All Comp Groups- OOP using Java Unit - II

Ex :intn = s3.length( ); Result : n=11

3.charAt() : It returns particular character in a string at the specified location.


Ex :char x =s3.charAt(5) ;
Result :x = r ( r is at index (5+1) =6 in string s3 since index starts from 0)

4. indexof( ‘char‘ ) : It returns position of the given character in the string.


Ex :int x=s3.indexof( ‘ r ’ ) ;
Result : x=5 ( r is located at 5 th position (4+1) in s3)

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

7. replace ( ‘x’ , ’ y’ ): It replaces all ‘x’ characters with ‘y’.


Ex : s1.replace( ‘a’ , ’e’ ) ; Result : “Java” changed as “Jeve”

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 ]

9. substring( n , m ): It returns part of string from n th position to upto m th position.


Ex : s3.substring( 2 , 7 ) ;
Result :vaPro[ It is part string s3 from 2nd positionupto 7th pos]

10. toUpperCase() : It converts all the characters in String to upper case.


Ex : s3.toUpperCase( ) ; Result : JAVAPROGRAM

11. toLowerCase( ) : It converts all the characters in String to lower case.


Ex : s3.toLowerCase( ) ; Result : javaprogram

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

Krishnaveni Degree College :: Narasaropet Page 2


II BSC(sem-4)-All Comp Groups- OOP using Java Unit - II

14.trim( ) : It removes the white spaces at beginning and ending of a string.

15.String.Valueof(variable) : Converts the parameter value to string representation .

String Array (Array of Strings ) : It is an array which contains a collection of strings .

Syntax : String str_arrayName [ ] = { “str1”, “str2” , …….. };


Ex : String st[ ]={"Delhi","Madras","Hyderabad","Calcutta","Bombay"};
Here the string array “st” contains 5 strings
_________________________________________________________________________________________
Example program on Strings and String Array :
/* Write a program to sort the given names in ascending order */
classstr_sort
{
public static void main(String args[ ])
{
String st[ ]={"Delhi","Madras","Hyderabad","Calcutta","Bombay"};
int i,j;
System.out.println("Before Sorting : ");
for( i=0;i<st.length;i++)
System.out.print(st[i]+” ,”);

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
------------------------------------------------------------------------------------------------

Krishnaveni Degree College :: Narasaropet Page 3


II BSC(sem-4)-All Comp Groups- OOP using Java Unit - II

Q) Explain Immutability of Strings. (or)


Explain about StringBuffer class and its methods. (or)
Explain difference between “String” class and “StringBuffer” class.

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.

Example : String s="Hello";


s = s +"Java";
System.out.println(s1);
The above code prints “HelloJava” on output screen only , but original value in variable “s” is
not changed. This is Immutablity of String.
StringBuffer: It is a predefined class in java. It is used to create strings of flexible length .
i.e. we can change the size and content of a string.
This is not possible strings which are created using “String” class.

creating strings using “StringBuffer “ class :


Syntax :StringBufferstring_Name = new StringBuffer( “string_value ” ) ;
Ex :StringBuffer s1 = new StringBuffer( “ hello ” ) ;

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’ .

Example Program StringBuffer class methods :


class SB
{
public static void main ( String args[ ] )
{
StringBufferstr=new StringBuffer("Object Programing");
System.out.println("Original string : "+str);
str.insert(7," Oriented"); /* inserting a string at 6th position*/
System.out.println("Now string modified as : "+ str ) ;
str.append("improves Security "); /* inserting a string at last*/
System.out.println("Now string modified as : "+ str ) ;
str.setCharAt(6,'-'); /* inserting a character at 6th position*/

Krishnaveni Degree College :: Narasaropet Page 4


II BSC(sem-4)-All Comp Groups- OOP using Java Unit - II

System.out.println("Now string modified as : "+ str);


}
}

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[])

Krishnaveni Degree College :: Narasaropet Page 5


II BSC(sem-4)-All Comp Groups- OOP using Java Unit - II

{
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

Q) Need of Object-Oriented Programming (or)


Problems in POP(Procedure Oriented Prog.)
Explain difference b/w POP and OOP
Depending on the organization of code(data and operations), the high level language
programming is divided into two types. Theyare

1. Procedure OrientedProgramming(POP)
2. Object OrientedProgramming(OOP)
1.Procedure Oriented Programming:

In this, the data(variables) and operations(functions) are represented in the form of


functions(Procedures). Example: C – language

Disadvantages:

1.Program modification and extension is difficult.


2.Data security is not provided

Krishnaveni Degree College :: Narasaropet Page 6


II BSC(sem-4)-All Comp Groups- OOP using Java Unit - II

2.Object Oriented Programming: In this, the data(variables) and operations(functions)


are represented

in the form of classes and objects. Example : C++, Java languages.

Advantages: 1.It allows the reusability of the code.

2.It allows the programmer to build secure programs.

Procedure Oriented Programming-POP Object Oriented Programming_OOP


1. Main program is divided into small 1. Main program is divided into small
parts object
depending on the functions depending on the problem
2.POP does not have any access 2. OOP has access specifiers named
specifier. Public, Private, and protected

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.

Krishnaveni Degree College :: Narasaropet Page 7


II BSC(sem-4)-All Comp Groups- OOP using Java Unit - II

____________________________________________________________________

Q) Explain Basic Concepts (or) Principles of OOP (Object Oriented


Programing). Benefits and applications of OOP.
Ans :Object Oriented Programming: In this, the data(variables) and
operations(functions) are represented in the form of classes and objects. Example :
C++, Java languages.

Object-oriented programming languages provides and satisfy the following


principles(concepts) :

1. Encapsulation
2. Class
3. Object
4. Abstraction
5. Inheritance
6. Polymorphism
7. Dynamic Binding
8. Message passing

Encapsulation: Binding of data(variables) and operations(methods) performs on


that data into single block in a program is called “Encapsulation”.

Due to this the data in one block is not accessed by another block.

In Java, defning a “class” is example of Encapsulation.

Class : It is user defined datatype. It is collection of variables and methods as single


Unit.

Ex : class Rectangle
{
int length,width ; // variables

void display( ) //method

System.out.println(“Area=”+(length*width));

Krishnaveni Degree College :: Narasaropet Page 8


II BSC(sem-4)-All Comp Groups- OOP using Java Unit - II

Object : It is instance(occurance) of a particular class .

By using the object ,we can use the variables and methods of that class.

Ex : Rectangle r1=new Rectangle();

Rectangle r2=new Rectangle();

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)

r1.length , r1.width r2.length , r2.width


Method(operation)
Method(operation)
r2.area( )
r1.area( )

Abstraction : It is the process of hiding internal details and showing functionality


of particular object.Ex : float calculate_area();

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.

Inheritance:It is the process of accessing one class properties(attributes) into


another class.Here theattributes of class “Bird” are used by its derived classes
“Flyingbirds”, “NonFlyingBirds” and so on.

Krishnaveni Degree College :: Narasaropet Page 9


II BSC(sem-4)-All Comp Groups- OOP using Java Unit - II

Polymorphism : It means “one can have many forms”.In java it is satisfied by


“Method Overloading”.

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);

Here employee is object, salary is message and name is information

Advantages (benefits) of OOP


 Using inheritance we can extend the program very easily and can eliminate the
duplication ofcode.
 Object-Oriented systems can be easily upgraded from small to largesystems.
 It is easy to partition the work in a project based onobjects.
 The concept of data hiding helps the programmer to develop secureprograms.
 Software complexity can be easilymanaged
Disadvantages ( demerits) of OOP
 Simple programs are more complex.
 Programmer should have Programming Skills and Planing.
 Execution of programs is slow.

Krishnaveni Degree College :: Narasaropet Page 10


II BSC(sem-4)-All Comp Groups- OOP using Java Unit - II

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
_____________________________________________________________________________

Q) Differences between C and JAVA

C language Java language


C isprocedural-oriented programing(POP) Java is Object-Oriented programing (OOP)
C is a compiled language Java is compiled and Interpreted language
C uses the top-down approach Java uses the bottom-Up approach
C support pointers Java does not support pointers
C does not support method overloading Java support method overloading
C support Preprocessor Directives Does not support Preprocessor Directives
difficult to handle run time errors. Java can handle exceptions
Security is low Security is high
………………………………………………………………………………..

chapter-2 Classes ,Objects and methods

Q) Explain about creating Classes , Methods and Objects .

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 ;
}

Krishnaveni Degree College :: Narasaropet Page 11


II BSC(sem-4)-All Comp Groups- OOP using Java Unit - II

As shown above , the class definition contains the following :


1.Instance variables declaration:
 Instance variables are declared inside of the class and outside of the methods of
that class.
 These are used to store different values for different objects. These are declared as
Syntax : datatype variable1,variable2,……..variable n;

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.

 Object : After class is defined , we need to create Objects . It is the instance


(occurrence ) of the class.

Krishnaveni Degree College :: Narasaropet Page 12


II BSC(sem-4)-All Comp Groups- OOP using Java Unit - II

By creating the objects , we can do the following :


 We can create memory for the instance variables of that class.
 we can access the variables and methods of that class.
Objects are created as follows :
Syntax : Class_Name object_name = new Class_Name ();
Ex : Rectangle r = new Rectangle();
The above statement can be written as two statements also as follows :
Rectangle r ;
r = new Rectangle ( );
Example program to calculate Area of Rectangle using by creating a Class and
Object in java program :
class Rectangle
{
int length , width ;
void area(intx,int y)
{
length=x;
width=y;
int a;
a = length * width ;
System.out.println(“ Area = “ + a );
}
}
class OOP1 // main method class
{
public static void main(String args[])
{
Rectangle r=new Rectangle();
r.area(10,20);
}
}
Above program , Saved as: OOP1.java
( file name should be same main method class name “OOP1”)
Compile as :javac OOP1.java
Run as : java OOP1
Output : Area = 200

Krishnaveni Degree College :: Narasaropet Page 13


II BSC(sem-4)-All Comp Groups- OOP using Java Unit - II

choice( Q)Explain Creating Multiple(more than one) objects for a class


we can create any number of objects for a class.For each object , it create its own instance(set)
of variables and methods of that class.
For Example consider the as same above class “Rectangle”
class Rectangle
{
int length,width;
void area(intx,int y)
{
length=x;
width=y;
int a;
a = length * width ;
System.out.println(“ Area = “ + a );
}
}
class OOP1 // main method class “OOP1 “is the class name given by programer
{
public static void main(String args[])
{
Rectangle r1=new Rectangle ();
Rectangle r2=new Rectangle (); // r1 and r2 are two objects of class “Rectangle “

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.
_____________________________________________________________________________

Krishnaveni Degree College :: Narasaropet Page 14


II BSC(sem-4)-All Comp Groups- OOP using Java Unit - II

Q) Explain Constructor , Types of Constructors and constructor overloading.


A ) Constructor : It is a special method which is used to initialize the objects itself.
i.e.Instance variables are initialized at the time of object creation.
The constructor is method but having the following special characteristics:
 Class name and method name should be same
 Does not have return type
 It automatically execute when object is created
Example Program :
class Rectangle
{
int length , width ;
Rectangle(int x, int y)
{
length=x;
Constructor width=y;
method }

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

Krishnaveni Degree College :: Narasaropet Page 15


II BSC(sem-4)-All Comp Groups- OOP using Java Unit - II

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;
}

Krishnaveni Degree College :: Narasaropet Page 16


II BSC(sem-4)-All Comp Groups- OOP using Java Unit - II

Values(int x, int y , int z) // three parameters


{
v1=x ;
v2=y;
v3=z;
}
void display( )
{
System.out.println(v1 +”, “+v2+”, “+v3);
}
}
class col
{
public static void main(String args [])
{
Values a =new Values(10);
Values b = new Values(5,7,9);
a.display( ); // displays only one value
b.display( ) ; // displays three values
}
}
output : 10 , 0 , 0
5,7,9
As shown above we pass the different parameters to the same constructor.This is
called Constructor Overloading.
-------------------------------------------------------------------------------------------------------------

Krishnaveni Degree College :: Narasaropet Page 17


II BSC(sem-4)-All Comp Groups- OOP using Java Unit - II

Q) Explain Initialisation of Instance variables .


A) After declaring the instance variables in a class, we can initialise those variables with
some value. But this value is not permanent, when we give new value to that variable
by using method (or) Dot operator (or) constructor, the initialised value is
overwritten(changed).

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
------------------------------------------------------------------------------------------------------------

Q) Define Method(or) Instance Method. Explain types of methods in Java. (or)


Explain Method Header(Prototype),Method Body(definition),Method calling.

A) Method :-Methods are similar to functions in C- language.


-Method is block of statements to perform a well defined task.
- Every method contains three parts :
1. Method Header(ProtoType): It is Method declaration(Signature) which represented as
follows
Syntax : returnType method_name ( [ parameter list ] )
Ex : void area(int l, int w ) ;

Krishnaveni Degree College :: Narasaropet Page 18


II BSC(sem-4)-All Comp Groups- OOP using Java Unit - II

2.Method Body(Definition) : It is block os statements which are to be executed. It is


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
Statements: statements which are to be executed.

Ex : void area(int l, int w)


{
int a = l*w ;
System.out.println(“Area = “ + a) ;
}

3. Method calling : It is invoking the method to execute.


Ex : r.area(10,20) ;

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.

Example Program on Types of methods :


class methods
{
int n ;

void acce_method(int n) /* Accessor method */


{
this.n=n; /* just access instance variable “n” */
}

void muta_method() /* Mutator method */

Krishnaveni Degree College :: Narasaropet Page 19


II BSC(sem-4)-All Comp Groups- OOP using Java Unit - II

{
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( );
}

Krishnaveni Degree College :: Narasaropet Page 20


II BSC(sem-4)-All Comp Groups- OOP using Java Unit - II

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

a) passing primitive DataTypes to methods : It is the process of passing Primitive


(fundamental) datatypes like int,float,char,…etc. values as parameters to a method.

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[])
{

Krishnaveni Degree College :: Narasaropet Page 21


II BSC(sem-4)-All Comp Groups- OOP using Java Unit - II

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

b) passing Arrays to methods : It is the process of passing Array(group of elements


as parameter to a method.
Syntax : method_name(Array_Name ,....... ) ;
Ex : class Array
{
void display(int arr[ ], int n )
{
for(int i = 0 ; i < n ; i ++ )
System.out.println( arr [ i ] +” , “ ) ;
}
}
class oop8
{
public static void main(String args[])
{
int arr [ ] = { 7,5,3,2,8 } ;
Array k =new Array ( );
k.display( arr , arr.length ) ; // Passing 1D-Array “arr” to display() method.
}
}
Output : 7 , 5 , 3 , 2, 8

c) passing Objects to methods : It is the process of passing an object as a


parameter to a method.
Syntax : method_Name(object_Name) ;

Example prog:

class Student
{
int rollno;
String name;

Krishnaveni Degree College :: Narasaropet Page 22


II BSC(sem-4)-All Comp Groups- OOP using Java Unit - II

}
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 ) ) ;

}}

Krishnaveni Degree College :: Narasaropet Page 23


II BSC(sem-4)-All Comp Groups- OOP using Java Unit - II

class oop10
{
public static void main( String args[ ] )
{
Recursion k = new Recursion( ) ;
int f ;
f = factorial ( 5 ) ;
System.out.println(“ factorial value = “ + f );
}
}

output : factorial value = 120


---------------------------------------------------------------------------------------------------
Q ) Explain about Nested Methods (or) Nesting of Methods.

If a method used in another method (or) a method called by another method ,


then it is called “Nested methods “.

Syntax : method1()
{
…………
………....
method2() ;
………….
}
Example program:
class Nesting
{
void msg()
{
System.out.println(“ Java is OOP language”);
}
void display()
{
System.out.println(“ welcome”);
msg();
}
}

Krishnaveni Degree College :: Narasaropet Page 24


II BSC(sem-4)-All Comp Groups- OOP using Java Unit - II

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

Java is OOP language

--------------------------------------------------------------------------------
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 ;

static void display( )


{
System.out.println(“ This is Example for static methods”);
}
}
class oop12

public static void main(String args[])

Krishnaveni Degree College :: Narasaropet Page 25


II BSC(sem-4)-All Comp Groups- OOP using Java Unit - II

Numbers n1= new Numbers() ;

Numbers n2= new Numbers() ;

Numbers n3= new Numbers() ;

n1.x=5;

n2.x=10 ; n1,n2,n3 objects creates three memory blocks for’ x’

n3.x=15; but for static variable ‘y’ common block for all objects

n1.y=7 ; n1.y n1.x 5

n2.y=10; n2.y 25 n2.x 10

n3.y=25; n3.y n3.x 15

( static variable y ) ( normal instance variable x)

System.out.println(n1. x + “, ”+n2. x+” ,” +n3. x ) ;

System.out.println(n1. y +”,”+n2. y+”,” +n3. y ) ;

Numbers.display( ); // static methods accessed by class name also(without object)

Output : 5 , 10 , 15

25 , 25 , 25

This is Example for Static methods

--------------------------------------------------------------------------------------------------------
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 :

1.by using constructor

2.by using userdefinedmethod

3.by using Dot( . ) operator

Example :

Krishnaveni Degree College :: Narasaropet Page 26


II BSC(sem-4)-All Comp Groups- OOP using Java Unit - II

class Values

int v1,v2,v3; // instance variables

Values(int x) //giving value for v1 by using constructor

v1 = x;

voidget_value(int y) // giving value for v2 by using userdefined method

v2 = y;

void display()

System.out.println(v1 +” “+ v2+” “ + v3);

class OOP

public static void main(String args[])

Values a=new Values(7);

a.get_value(20);

a.v3 = 25 ; // giving value for v3 by using Dot(.) operator

a.display();

output : 7 20 25

_____________ _________________________________________________________

Krishnaveni Degree College :: Narasaropet Page 27


II BSC(sem-4)-All Comp Groups- OOP using Java Unit - II

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.

Q) What is Inheritance(Extending Classes) ? Explain Different types of Inheritance.


( OR )
Explain Reusability in Java with Inheritance .

Inheritance : It is the process of deriving a new class from an old(existing) class.


 Due to this , the new class can use(Inherit) the propertiesof the old class. This is also called
“Extending a class”
 The Old class refered as “Super class” and new class refered as “Sub class”.

The general syntax for inherit a class is :

class SubClassName extends SuperClassName


{
variables ;
methods ;
}

Here ,“class” and “extends” are the keywords.

Types of Inheritance :

Inheritance may classified into following types :


1. Single Level (Simple ) Inheritance
2. Multi Level Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance

1.Single Level (Simple ) Inheritance :

In this , a single sub class is derived from single super class. It is represented as follows :

A Super / Old / Base class

B Sub / New / Derived Class

Here class B is derived from class A. So Class B can use ( Inherit ) the variables and methods of

Krishnaveni Degree College :: Narasaropet Page 28


II BSC(sem-4)-All Comp Groups- OOP using Java Unit - II

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.

2.Multi Level Inheritance :


In this , a Sub class is derived from another Sub class. It is represented as follows :

A Super class

B sub class

C sub class

Krishnaveni Degree College :: Narasaropet Page 29


II BSC(sem-4)-All Comp Groups- OOP using Java Unit - II

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.

The following example program shows Multi Level Inheritance :

classA
{
int x;
void displayA( )
{
System.out.println(x);
}
}

classB extends A /* class B derived from class A */


{
int y ;
void displayB( )
{
System.out.println(x +” , “ +y);
}
}

classC extends B /* class C derived from Subclass B */


{
int z;
void displayC( )
{
System.out.println(x +”,” +y+”, “ +z);
}
}

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

Krishnaveni Degree College :: Narasaropet 3 ,5,7 Page 30


II BSC(sem-4)-All Comp Groups- OOP using Java Unit - II

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 .

The following example program shows HierarchicalInheritance :

class A
{
int x;
voiddisplayA( )
{
System.out.println(x);
}
}

class B extends A /* class B derived from class A */


{
int y ;
void displayB( )
{
System.out.println(x +” , “ +y);
}
}

class C extends A /* class C derived from class A */


{
int z;
void displayC( )
{
System.out.println(x +” ,“ +z);
}
}

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 */

Krishnaveni Degree College :: Narasaropet Page 31


II BSC(sem-4)-All Comp Groups- OOP using Java Unit - II

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 :

Super Class A B Super Class

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 :

It is the combination of any two types of Inheritance . It represented as follows :

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 “.

Krishnaveni Degree College :: Narasaropet Page 32


II BSC(sem-4)-All Comp Groups- OOP using Java Unit - II

------------------------------------------------------------------------------------------------------------------------

Q)Explain about Sub class constructor or “super ( )” method


(or)
Explain how super class variables initialized through sub class.

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( )”.

This is super() method is as follows :


 It should be used in subclass constructor only.
 It should be first statement in sub class constructor.
 Parameter list of superclass constructor and super() method should be same.

The following program shows the working of super( ) method :

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;

B(int l,int w,int h) /* Sub Class Constructor */


{
super(l,w); /* super method initializes variables length,width of SuperClassA */
height=h;
}

void volume( )
{
System.out.println(“Volume =”+(length*width*height));
}
}

Krishnaveni Degree College :: Narasaropet Page 33


II BSC(sem-4)-All Comp Groups- OOP using Java Unit - II

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.
____________________________________________________________________________________________________

Krishnaveni Degree College :: Narasaropet Page 34

You might also like