0% found this document useful (0 votes)
22 views20 pages

Ooptj r23 Unit 2

Uploaded by

rahulswarna027
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)
22 views20 pages

Ooptj r23 Unit 2

Uploaded by

rahulswarna027
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/ 20

UNIT – 2

Classes and Objects


Classes and Objects: Introduction, Class Declaration and Modifiers, Class Members, Declaration of
Class Objects, Assigning One Object to Another, Access Control for Class Members, Accessing
Private Members of Class, Constructor Methods for Class, Overloaded Constructor Methods, Nested
Classes, Final Class and Methods, Passing Arguments by Value and by Reference, Keyword this.
Methods: Introduction, Defining Methods, Overloaded Methods, Overloaded Constructor Methods,
Class Objects as Parameters in Methods, Access Control, Recursive Methods, Nesting of Methods,
Overriding Methods, Attributes Final and Static

1. INTRODUCTION TO CLASS
Fundamentals of the class

A class is a group of objects that has common properties. It is a template or blueprint from
which objects are created. The objects are the instances of class. Because an object is an
instance of a class, you will often see the two words object and instance used interchangeably.

A class is used to define new type of the data. Once defined, this new type can be used to create
objects of its type. The class is the logical entity and the object is the logical and physical entity.

1.1 Class Declaration


A class is declared by use of the class keyword. The classes that have been used up to this point
are actually very limited examples of its complete form. Classes can (and usually do) get much
more complex. A simplified general form of a class definition is shown here:

The general form of the class:


modifier class classname
{
modifier datatype variable1;
modifier datatype variable2;
………………………………..
……………………………….
modifier datatype variableN;

modifier returntype method1(parameterlist)


{
//body of the method1
}
modifier returntype method2(parameterlist)
{
//body of the method2
}
……………………………………..
……………………………………..
modifier datatype methodN(parameterlist)
{
//body of the methodN
}
}
 The data or variables, defined within the class are instance variables and static variable.
 The methods also contain the code.
 The methods and variables collectively called as members.
 Variable declared within the methods are called local variables.

A Simple Class

SACET, CSE Department, II CSE I SEM ( R23) Page 1


Let’s begin our study of the class with a simple example. Here is a class called Box that defines
three instance variables: width, height, and depth. Currently, Box does not contain any
methods.

class Box
{ //instance variables
double width;
double height;
double depth;
}
As stated, a class defines new data type. The new data type in this example is, Box. This defines
the template, but does not actually create object.

Note: By convention the First letter of every word of the class name starts with Capital letter, but
not compulsory. For example “box” is written as “Box” The First letter of the word of the
method name begins with small and remaining first letter of every word starts with Capital letter,
but not compulsory. For example “boxVolume()”

1.2 Object Declaration

Creating the Object


There are three steps when creating an object from a class:

 Declaration: A variable declaration with a variable name with an object type.


 Instantiation: The 'new' key word is used to create the object.
 Initialization: The 'new' keyword is followed by a call to a constructor. This call
initializes the new object.

Step 1:
Box b;

Effect: b null

Declares the class variable. Here the class variable contains the value null. An attempt to access
the object at this point will lead to Compile-Time error.

Step 2:
Box b=new Box();

Here new is the keyword used to create the object. The object name is b. The new operator
allocates the memory for the object, that means for all instance variables inside the object,
memory is allocated.
Width
Effect: b Height
Depth

Box Object
Step 3:
There are many ways to initialize the object. The object contains the instance variable.
The variable can be assigned values with reference of the object.

b.width=12.34;
b.height=3.4;
b.depth=4.5;

Here is a complete program that uses the Box class:


BoxDemo.java

SACET, CSE Department, II CSE I SEM ( R23) Page 2


class Box
{
double width;
double height;
double depth;
}
// This class declares an object of type Box.
class BoxDemo
{
public static void main(String args[])
{
//declaring the object (Step 1) and instantiating (Step 2) object
Box mybox = new Box();
double vol;
// assign values to mybox's instance variables (Step 3)
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
// compute volume of box
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
}

When you compile this program, you will find that two .class files have been created, one for
Box and one for BoxDemo. The Java compiler automatically puts each class into its own .class
file. It is not necessary for both the Box and the BoxDemo class to actually be in the same source
file.
To run this program, you must execute BoxDemo.class.

OUTPUT:
Volume is 3000.0

1.3 Assigning One Object to Another

Assigning Object Reference Variables


Object reference variables act differently than you might expect when an assignment takes
place. For example,
Box b1 = new Box();
Box b2 = b1;

After this fragment executes, b1 and b2 will both refer to the same object. The assignment of b1
to b2 did not allocate any memory or copy any part of the original object. It simply makes b2
refer to the same object as does b1. Thus, any changes made to the object through b2 will affect
the object to which b1 is referring, since they are the same object.
This situation is depicted here:

2. MODIFIERS
There are two types of modifiers in Java: access modifiers and non-access modifiers.

Access Modifiers
There are four types of Java access modifiers:
 private
 default/No Modifier

SACET, CSE Department, II CSE I SEM ( R23) Page 3


 protected
 public

Non Access Modifiers


There are many non-access modifiers
For classes:
 final
 abstract
For variable and methods:
 final
 static
 abstract
 synchronized
 native,
 transient
 volatile

3. ACCESS MODIFIERS/ ACCESS CONTROL FOR CLASS


MEMBERS

The access modifiers in Java specifies the accessibility or scope of a field, method, constructor,
or class. We can change the access level of fields, constructors, methods, and class by applying
the access modifier on it.

There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default/No Modifier: 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.
3. 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.
4. 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.

Access Modifier within class within package outside package by subclass only outside package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

Example:
class AccessDemo
{
private Int a;
int b;
public int c;
}
class AccessDemoMain
{
public static void main(String[]args)
{
a=10; //compile time error
SACET, CSE Department, II CSE I SEM ( R23) Page 4
b=20;
c=30;
}
}

4. METHOD DEFINITION/ DEFINING METHODS


Classes usually consist of two things: variables and methods.
This is the general form of a method:
type name(parameter-list)
{
// body of method
}
Here, type specifies the type of data returned by the method. This can be any valid type,
including class types that you create. If the method does not return a value, its return type must
be void. The name of the method is specified by name. This can be any legal identifier other than
those already used by other items within the current scope. The parameter-list is a sequence of
type and identifier pairs separated by commas. Parameters are essentially variables that receive
the value of the arguments passed to the method when it is called. If the method has no
parameters, then the parameter list will be empty.

Methods that have a return type other than void return a value to the calling routine using the
following form of the return statement:

return value;

Here, value is the value returned.

Adding a method to the Box class


Box.java
class Box
{
double width, height, double depth;
// display volume of a box
void volume()
{
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}
Here the method name is "volume()". This methods contains some code fragment for computing
the volume and displaying. This method cane be accessed using the object as in the following
code:
BoxDemo3.java
class BoxDemo3
{
public static void main(String args[])
{
Box mybox1 = new Box();
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's

// display volume of first box


mybox1.volume();
// display volume of second box
}
}

Returning a Value
A method can also return the value of specified type. In this case the type of the method should
be clearly mentioned. The method after computing the task returns the value to the caller of the
method.

SACET, CSE Department, II CSE I SEM ( R23) Page 5


BoxDemo3.java
Box
{
double width, height, depth;

double volume()
{
return (width*height*depth);
}
}

class BoxDemo3
{
public static void main(String args[])
{
Box mybox1 = new Box();
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
double vol;
/* assign different values to mybox2's
//calling the method
vol= mybox1.volume();
System.out.println("the Volume is:"+vol);
}
}

Method that takes the parameters


We can also pass arguments to the method through the object. The parameters separated with
comma operator. The values of the actual parameters are copied to the formal parameters in the
method. The computation is carried with formal arguments, the result is returned to the caller of
the method, if the type is mentioned.

double volume(double w, double h, double d)


{
width=w;
height=h;
depth=d;
return (width*height*depth);
}

5. METHOD OVERLOADING
In Java it is possible to define two or more methods within the same class that share the
same name, as long as their parameter declarations are different. When this is the case, the
methods are said to be overloaded, and the process is referred to as method overloading.
Method overloading is one of the ways that Java supports polymorphism.

When an overloaded method is invoked, Java uses the type and/or number of arguments as its
guide to determine which version of the overloaded method to actually call. When Java
encounters a call to an overloaded method, it simply executes the version of the method
whose parameters match the arguments used in the call.

Here is a simple example that illustrates method overloading:


// Demonstrate method overloading.

class OverloadDemo
{
void test()
{
System.out.println("No parameters");
}

SACET, CSE Department, II CSE I SEM ( R23) Page 6


// Overload test for one integer parameter.
void test(int a)
{
System.out.println("a: " + a);
}
}
class Overload
{
public static void main(String args[])
{
OverloadDemo ob = new OverloadDemo();
double result;

// call all versions of test()


ob.test();
ob.test(10);
}
}
The test() method is overloaded two times, first version takes no arguments, second version
takes one argument. When an overloaded method is invoked, Java looks for a match between
arguments of the methods.

6. CONSTRUCTORS
It can be tedious to initialize all of the variables in a class each time an instance is
created. Even if we use some method to initialize the variables, it would be better this
initialization is done at the time of the object creation.

 A constructor is a method that initializes an object immediately at the time of object


creation.
 It has the same name as the class in which it resides and is syntactically similar to a
method.
 It is automatically called immediately after the object is created, before the new operator
completes.
 They have no return type, not even void.

Example Program:
class Box
{
double width;
double height;
double depth;

// This is the constructor for Box.


Box()
{
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}

// compute and return volume


double volume()
{
return width * height * depth;
}
}
class BoxDemo6 {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box();
double vol;

// get volume of first box


vol = mybox1.volume();

SACET, CSE Department, II CSE I SEM ( R23) Page 7


System.out.println("Volume is " + vol);
// get volume of second box
}
}

Parameterized Constructors
Constructor can have parameters. Constructor with parameters is called Parameterized
Constructor.

/* Here, Box uses a parameterized constructor to initialize the dimensions of a box. */


class Box
{
double width;
double height;
double depth;

// This is the parameterized constructor for Box.


Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}

class BoxDemo7 {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;

// get volume of first box


vol = mybox1.volume();
System.out.println("Volume is " + vol);

// get volume of second box


vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}

7. CONSTRUCTOR OVERLOADING
In Java it is possible to define two or more class constructors that share the same name, as
long as their parameter declarations are different. This is called constructor overloading.
When an overloaded constructor is invoked, Java uses the type and/or number of
arguments as its guide to determine which version of the overloaded constructor to actually call.
Thus, overloaded constructors must differ in the type and/or number of their parameters.

Example: All the constructors names will be same, but their parameter list is different.
OverloadCons.java
class Box {
double width;
double height;
double depth;

// constructor used when all dimensions specified

SACET, CSE Department, II CSE I SEM ( R23) Page 8


Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}

// constructor used when no dimensions specified


Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}

// constructor used when cube is created


Box(double len) {
width = height = depth = len;
}

// compute and return volume


double volume() {
return width * height * depth;
}
}

class OverloadCons
{
public static void main(String args[])
{
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;

// get volume of first box


vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);

// get volume of second box


vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);

// get volume of cube


vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}

The output produced by this program is shown here:

Volume of mybox1 is 3000.0


Volume of mybox2 is -1.0
Volume of mycube is 343.0

8. GARBAGE COLLECTION
Objects are dynamically allocated in Java by using the new operator. In some languages,
such as C++, dynamically allocated objects must be manually released by use of a delete
operator. But, Java takes a different approach; it handles deallocation automatically. The
technique that accomplishes this is called garbage collection.
There are Two Techniques: 1) Reference Counter 2) Mark and Sweep.
Reference Counter: In the Reference Counter technique, when an object is created along with it
a reference counter is maintained in the memory. When the object is referenced, the reference
counter is incremented by one. If the control flow is moved from that object to some other
object, then the counter value is decremented by one. When the counter reaches to zero (0), then
it's memory is reclaimed.
Mark and Sweep: In the Mark and Sweep technique, all the objects that are in use are marked
and are called live objects and are moved to one end of the memory. This process we call it as

SACET, CSE Department, II CSE I SEM ( R23) Page 9


compaction. The memory occupied by remaining objects is reclaimed. After these objects are
deleted from the memory, the live objects are placed in side by side location in the memory. This
is called copying.
It works like this: when no references to an object exist, that object is assumed to be no
longer needed, and the memory occupied by the object can be reclaimed. There is no need to
destroy objects explicitly.
Garbage collection only occurs during the execution of your program. The main job of
this is to release memory for the purpose of reallocation

9. The finalize( ) Method


Sometimes an object will need to perform some action when it is destroyed. To handle
such situations, Java provides a mechanism called finalization. By using finalization, you can
define specific actions that will occur when an object is just about to be destroyed.

To add a finalizer to a class, you simply define the finalize( ) method. Inside the
finalize() method, you will specify those actions that must be performed before an object is
destroyed.

The finalize( ) method has this general form:

protected void finalize( )


{

// finalization code here

Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined
outside its class.

10. NESTED CLASSES


It is possible to define a class within another class; such classes are known as nested classes.
The scope of the nested class (inner class) is bounded by the scope of it’s enclosing class (outer
class). Some important points of nested class are as follow:
 The nested class has right to access members of the enclosing class, including the private
members directly.
 However, the enclosing class has no right to access the members of nested class directly,
but with the help of the inner class object it can access.

Syntax

Following is the syntax to write a nested class. Here, the class Outer_Demo is the outer class
and the class Inner_Demo is the nested class.

class Outer{
class Nested
{
// body of the Inner class
}
//body of the outer class
}

There are two types of nested class: static and non-static.

Static inner class


A static inner class is a nested class which is a static member of the outer class. It can be
accessed without instantiating the outer class, using other static members. Just like static

SACET, CSE Department, II CSE I SEM ( R23) Page 10


members, a static nested class does not have access to the instance variables and methods of the
outer class. The syntax of static nested class is as follows −

Syntax

class MyOuter
{
static class Nested_Demo
{
}
}

Example program:

Outer.java Output
public class Outer
{ D:\>javac Outer.java
//inner static class D:\>java Outer
static class Nested_Demo This is my nested class
{
public void my_method()
{
System.out.println("This is my nested class");
}
}
//body of outer class
public static void main(String args[])
{
//without creating the object of outer class
Outer.Nested_Demo nested = new
Outer.Nested_Demo();
nested.my_method();
}
}

Note: 1. static inner classes are rarely used in programs.


2. IF the static inner class is static method, we can directly call that method in the main()
function with creating the object. As follow: Outer.Nested_Demo.my_method();

Non-static inner class:

Creating an inner class is quite simple. You just need to write a class within a class.
Unlike a class, an inner class can be private and once you declare an inner class private, it
cannot be accessed from an object outside the class.

Following is the program to create an inner class and access it. In the given example, we make
the inner class private and access the class through a method.

Example program:

public class Outer2


{ int outer_x=100;
void test()
{ //creating the object of Inner class
Inner inn=new Inner();
inn.disp();
}

SACET, CSE Department, II CSE I SEM ( R23) Page 11


//inner non-static class
public class Inner
{
public void disp()
{
System.out.println("The value of x is:"+outer_x);
}
}
public static void main(String args[])
{
//creating the out class object
Outer2 out=new Outer2();
out.test();
}
}
Output:

D:\> javac Outer2.java


D:\>java Outer2
The value of x is:100

11. FINAL KEYWORD

The keyword final is a non-access modifier. The java final keyword can be used in many
context. Final can be:

1. variable
2. method
3. class

 the final variable cannot be reinitialized with another value


 the final method cannot be overridden
 the final class cannot be extended

1) Java final variable

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

Example:
class Main {
public static void main(String[] args) {

SACET, CSE Department, II CSE I SEM ( R23) Page 12


// create a final variable
final int AGE = 32;

// try to change the final variable


AGE = 45;
System.out.println("Age: " + AGE);
}
}

n the above program, we have created a final variable named age. And we have tried to change
the value of the final variable.
When we run the program, we will get a compilation error with the following message.

cannot assign a value to final variable AGE


AGE = 45;
^

It is convention to use uppercase to declare final variables in Java.

2) Java final method

If you make any method as final, you cannot override it.

Example:

class FinalDemo {
// create a final method
public final void display() {
System.out.println("This is a final method.");
}
}

class Main extends FinalDemo {


// try to override final method
public final void display() {
System.out.println("The final method is overridden.");
}

public static void main(String[] args) {


Main obj = new Main();
obj.display();
}
}

In the above example, we have created a final method named display() inside
the FinalDemo class. Here, the Main class inherits the FinalDemo class.
We have tried to override the final method in the Main class. When we run the program, we will
get a compilation error with the following message.

display() in Main cannot override display() in FinalDemo


public final void display() {
^
overridden method is final

SACET, CSE Department, II CSE I SEM ( R23) Page 13


3) Java final class

If you make any class as final, you cannot extend it.

In Java, the final class cannot be inherited by another class. For example,
// create a final class
final class FinalClass {
public void display() {
System.out.println("This is a final method.");
}
}

// try to extend the final class


class Main extends FinalClass {
public void display() {
System.out.println("The final method is overridden.");
}

public static void main(String[] args) {


Main obj = new Main();
obj.display();
}
}

In the above example, we have created a final class named FinalClass. Here, we have tried to
inherit the final class by the Main class.
When we run the program, we will get a compilation error with the following message.

cannot inherit from final FinalClass


class Main extends FinalClass {
^

12. PASS BY VALUE AND PASS BY REFERENCE


“Java is Pass by Value, Not Pass by Reference”

 If we call a method passing a any primitive value, it is known as pass by value. The
changes being done in the called method, is not affected in the calling method.

 In case of call by reference original value is changed if we made changes in the called
method. If we pass object reference in place of any primitive value, original value will be
changed.

Pass By Value (Passing primitive values )

class Operation
{
int data=50;
void change(int data)
{
data=data+100;//changes will be in the local variable only
}

public static void main(String args[])


{
Operation op=new Operation();
System.out.println("before change "+op.data);

SACET, CSE Department, II CSE I SEM ( R23) Page 14


op.change(500);
System.out.println("after change "+op.data);
}
}
Output:
before change 50
after change 50

Pass by Reference ( Pass by Value by passing Object Reference)

In case of pass by reference original value is changed if we made changes in the called method. If we
pass object reference in place of any primitive value, original value will be changed.

In this example we are passing object reference as a value. Let's take a simple example:

class Operation2
{
int data=50;

void change(Operation2 op)


{
op.data=op.data+100;//changes will be in the instance variable
}
public static void main(String args[])
{
Operation2 op=new Operation2();
System.out.println("before change "+op.data);
op.change(op);//passing object
System.out.println("after change "+op.data);
}
}
Output:
before change 50
after change 150

13. ‘THIS’ KEYWORD

Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines
the this keyword.
this can be used inside any method to refer to the current object. That is, this is always a
reference to the object on which the method was invoked.

Note: This is mainly used to hide the local variables from the instance variable.

Example:
class Box
{
//instance variable
double width, height, depth;
Box(double width, double height, double depth)
{
//local variables are assigned, but not the instance variable
width=width;
height=height;
depth=depth;
}

SACET, CSE Department, II CSE I SEM ( R23) Page 15


}
To avoid the confusion, this keyword is used to refer to the instance variables, as follows:
class Box
{
//instance variable
double width, height, depth;
Box(double width, double height, double depth)
{
//the instance variable are assigned through the this keyword.
this.width=width;
this.height=height;
this.depth=depth;
}
}

14. RECURSIVE METHODS


Recursion in java is a process in which a method calls itself continuously. A method in java that
calls itself is called recursive method.
Syntax:
returntype methodname()
{
//code to be executed
methodname();//calling same method
}

Example:

public class RecursionDemo


{
static int factorial(int n)
{
if (n == 1)
return 1;
else
return(n * factorial(n-1));
}
public static void main(String[] args)
{
System.out.println("Factorial of 5 is: "+factorial(5));
}
}

Output:

Factorial of 5 is: 120

Working of above program:

factorial(5)
factorial(4)
factorial(3)
factorial(2)
factorial(1)
return 1
return 2*1 = 2
return 3*2 = 6
return 4*6 = 24

SACET, CSE Department, II CSE I SEM ( R23) Page 16


return 5*24 = 120

15. STATIC KEYWORD

When a member is declared static, it can be accessed without reference to any object.
You can declare both methods and variables to be static.

Static Variables: Static variables are shared by all the objects. These variables are also called as
"Class Variable".

Static Methods: Methods declared as static have several restrictions:


• They can only call other static methods. These are called without object.
• They must only access static data.
• They cannot refer to this or super in any way.

Static block: If you need to do computation in order to initialize your static variables, you can
declare a static block that gets executed exactly once, when the class is first loaded.

The following example shows a class that has a static method, some static variables, and
a static initialization block:

class UseStatic
{
//static variable
static int a = 3;
static int b;
//static method
static void meth(int x)
{
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
//static block
static
{
System.out.println("Static block initialized.");
b = a * 4;
}
public static void main(String args[])
{
//static methods are called without object
meth(42);
}
}
Note: Static blocks are executed first, even than the static methods. Static methods can be
called without object.
static variables a and b, as well as to the local variable x. Here is the output of the program:
Static block initialized.

x = 42
a=3
b = 12

ATM Example Using the static variable and static method

import java.util.*;
class ATM
{
static float balance;
void deposit()

SACET, CSE Department, II CSE I SEM ( R23) Page 17


{
Scanner in=new Scanner(System.in);
System.out.println("Enter the Deposit amount");
balance=in.nextFloat();
}
void withdraw()
{
Scanner in=new Scanner(System.in);
System.out.println("Enter the Withdrawl amount");
float w=in.nextFloat();
balance=balance-w;
}
static void dispbal()
{
System.out.println("The Balance in your account is:"+balance);
}
public static void main(String args[])
{
ATM a1=new ATM();
a1.deposit();
System.out.println(" Balance at ATM1");
ATM.dispbal();
ATM a2=new ATM();
a2.withdraw();
System.out.println(" Balance at ATM2");
ATM.dispbal();
System.out.println(" Balance at ATM1");
ATM.dispbal();
}
}

16. RECURSIVE METHODS

Recursion in java is a process in which a method calls itself continuously. A method in java that
calls itself is called recursive method.

Syntax:

returntype methodname(){
//code to be executed
methodname();//calling same method
}

Example : Factorial Number


public class RecursionExample3 {
static int factorial(int n){
if (n == 1)
return 1;
else
return(n * factorial(n-1));
}

public static void main(String[] args) {


System.out.println("Factorial of 5 is: "+factorial(5));
}
}

Output:

Factorial of 5 is: 120

SACET, CSE Department, II CSE I SEM ( R23) Page 18


Working of above program:

factorial(5)
factorial(4)
factorial(3)
factorial(2)
factorial(1)
return 1
return 2*1 = 2
return 3*2 = 6
return 4*6 = 24
return 5*24 = 120

17. PASSING OBJECT TO METHOD IN JAVA

Java is strictly pass-by-value language. When we pass a primitive type to a method, the method
receives a copy of the value. However, when we pass an object to a method, the method receives
a reference to the object. When we made changes to the object inside the method will be
reflected in the object outside the method.

Basically, a parameter cannot be changed by the function, but the function can ask the parameter
to change itself via calling some method within it.

o While creating a variable of a class type, we only create a reference to an object. Thus,
when we pass this reference to a method, the parameter that receives it will refer to the
same object as that referred to by the argument.
o It means that objects act as if they are passed to methods by use of call-by-reference.
o Changes to the object inside the method do reflect the object used as an argument.

ObjectPassing.java

class ObjectPassDemo {
int a, b;
// Constructor
ObjectPassDemo(int i, int j)
{
a = i;
b = j;
}
boolean equalTo(ObjectPassDemo o)
{
// Returns true if o is equal to the invoking
// object notice an object is passed as an
// argument to method
return (o.a == a && o.b == b);
}
}
public class ObjectPassing {
public static void main(String args[])
{
// Creating object of above class inside main()
ObjectPassDemo ob1 = new ObjectPassDemo(100, 22);
ObjectPassDemo ob2 = new ObjectPassDemo(100, 22);
ObjectPassDemo ob3 = new ObjectPassDemo(-1, -1);
// Checking whether object is equal as custom values
// above passed and printing corresponding boolean value
System.out.println("ob1 == ob2: " + ob1.equalTo(ob2));
System.out.println("ob1 == ob3: " + ob1.equalTo(ob3));
}
}

SACET, CSE Department, II CSE I SEM ( R23) Page 19


Output:
ob1 == ob2: true
ob1 == ob3: false

******************************************

SACET, CSE Department, II CSE I SEM ( R23) Page 20

You might also like