0% found this document useful (0 votes)
2 views58 pages

Java Unit 2

Unit II covers methods and classes in Java, detailing how to define and use methods, constructors, and object-oriented principles such as encapsulation and method overloading. It explains the significance of access modifiers, garbage collection, and the 'this' keyword, as well as how to pass objects and arguments to methods. The unit also emphasizes the importance of constructors, including default and parameterized constructors, in initializing objects.

Uploaded by

sarveshyogi2005
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)
2 views58 pages

Java Unit 2

Unit II covers methods and classes in Java, detailing how to define and use methods, constructors, and object-oriented principles such as encapsulation and method overloading. It explains the significance of access modifiers, garbage collection, and the 'this' keyword, as well as how to pass objects and arguments to methods. The unit also emphasizes the importance of constructors, including default and parameterized constructors, in initializing objects.

Uploaded by

sarveshyogi2005
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

UNIT-II

Methods and classes


Unit – II Contact Hours = 8 Hours

Methods and classes: methods, returning from a method,


returning a value, using parameters, constructors, parameterized
constructors, the new operator revisited, garbage collection and
finalizers, this keyword, controlling access to class members, pass
objects to methods, argument passing, returning objects, method
overloading.
Methods
• In Java, a method is a block of code that performs a specific task and
can optionally return a value.
• Methods are used to encapsulate and reuse code, making it easier to
read and maintain. They can be defined within a class or interface and
can be called by other parts of the program.
• Methods can also take parameters, which are values passed to the
method when it is called, and can have different access levels, such as
public or private.
•Methods are defined using the following syntax:
type name(parameter-list) {
// body of method
}
Adding the method to the class
• To add a method to a class in Java, the method must be defined
within the class using the proper syntax.
• The method's access level, return type, name, and parameter list
are specified, followed by the method's code block
• Here is an example of how a method called "add" can be added
to a class called "Calculator":

public class Calculator {


public int add(int a, int b) {
return a + b;
}
// other class members
}
• Once the method is defined within the class, it can be called by other
parts of the program by creating an instance of the class and using the
dot notation to access the method.
Calculator calculator = new Calculator();
int result = [Link](3, 4);
//Add Range to Vehicle class
//assigining values to field in sportscar
class Vehicle{
[Link]=2;
int passengers; [Link]=14;
int fulecap; [Link]=12;
int mpg; [Link]("minivan can
carry" +[Link]+ ".");
//display the range
[Link]();//display range of
void range(){ minivan
[Link]("Range is " + fulecap * mpg); [Link]("minivan can carry"
} + [Link]+ ".");
} [Link]();//display range of
sports car
public class AddMeth { }
public static void main( String[] args){ }
Vehicle minivan= new Vehicle();
Vehicle sportscar =new Vehicle();
int range1,range2; OUTPUT:
//assign values to fields in sportscar minivan can [Link] is 336
[Link]=7; sportscar can [Link] is 168
[Link]=16;
[Link]=21;
Returning from a method:
∙ Two conditions can cause a method to return
1. When the method’s closing brace is encountered
2. When a return statement is executed.

∙ There are 2 forms of return


1. One for use in void methods (which do not return a value)
2. Other for returning values

∙ In a void method, we can terminate a method by using the following form of


return:
return;

∙ When this statement executes, program control returns to the caller,


skipping any remaining code in the method.
•For ex:
void sample( ){
for(int i=0; i<10; i++) {
if(i==5)
return; //stop at 5
[Link](i);
}
}
Returning a Value:
∙ Methods return a value to the calling routing using this
form of return:
return value;

Using Parameters:
∙ Value passed to a method is called an argument. Variable that receives the
argument is called a parameter.
∙ Parameters are declared inside the parentheses that follow the
method’s name.
For ex:
Class Demo{
class ckNum{ public static void main(String[ ] args){
//return true if x is even ckNum e=new ckNum();
boolean isEven(int x){ if([Link](10))
if((x%2)==0) return true; [Link](“10 is even”);
else if([Link](9))
[Link](“9 is even”);
return false; }
} }
}
Constructors
• A constructor in Java is a special type of method that is used to initialize an
object when it is created.
• It has the same name as the class and does not have a return type.

Rules for creating java constructor:


• It has the same name as the class in which it resides and is syntactically
similar to a method.
• They have no explicit return type.

There are two types of constructors:


• Default constructor (no-arg constructor)
• Parameterized constructor
Default Constructor:
• Constructor which does not take any argument is called default constructor.

class MyClass{
int x;
MyClass( ) { //default constructor for MyClass
x=10 ; }
}
Class ConsDemo {
Public static void main(String[ ] args ) {
MyClass t1= new MyClass( );
MyClass t2= new MyClass( );
[Link](t1.x + “ “ +t2.x);
}
}
Parameterized Constructors
• A parameterized constructor in Java is a constructor that accepts one or more arguments/parameters.
• It allows you to initialize an object with specific values when it is created. Here is an example:

class MyClass{
int x;
MyClass( int i ) { // This is a constructor for MyClass which has a parameter
x=i; }
}
Class ParmConsDemo {
Public static void main(String[] args) {
MyClass t1= new MyClass(10);
MyClass t2= new MyClass(88);
[Link](t1.x + “ “ +t2.x);
}
}

• Out Put of the program is:


• 10 88
ADDING Constructors for Vehicle Class
class Vehicle{
int passengers;
int fulecap;
int mpg; gallons=[Link](dist);
Vehicle(int p, int f, int m) { //constructor for Vehicle [Link](“To go ”+ dist + “miles minivan
passangers=p; needs” + gallons + ”gallons of fule”);
fuleCap=f;
mpg=m; }
//Return the range
gallons=[Link](dist);
int range(){ [Link](“To go ”+ dist + “miles
sportscar needs” + gallons + ”gallons of fule”);
return mpg*fuleCap; }
//compute fule needed for a given distance. }
double fuleNeeded(int miles){
return(double) miles/mpg; }
}
class VehicleConstructorDemo{
public static void main(String[] args){
Vehicle minivan= new Vehicle(7, 16, 21);
Vehicle sportscar= new Vehicle(2, 14, 12);
double gallons;
int dist =252;
the new operator revisited
new operator has this general form:
class_var = new class_name(arg_list);
∙ class_var is a variable of the class type being created.

∙ The class_name is the name of the class that is being instantiated

∙ The class_name followed by a parenthesized argument list specifies the constructor for the class.

∙ If a class does not define its own constructor, new will use the default constructor supplied by Java

∙ The new can be used to create an object of any class type.

∙ It returns a reference to the newly created object, which is assigned to class-var


Garbage collection and finalizers
• A you have seen objects are dynamically allocated from a pool of free memory by using the
new operator.

• Memory is not infinite, and free memory can be exhausted, hence memory has to be freed
after its usage.

• In Java, garbage collection is a mechanism that automatically frees objects that are no
longer being used by the program,

• It work 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 is released . This memory can then
be used for a subsequent allocation.
• The garbage collector will usually run only when two conditions are met:
• There are objects to recycle, and there is a need to recycle them..
The Finalize() Method
• Finalizers are a mechanism for releasing resources associated with an
object before it is garbage collected. i.e finalizer will be called just
before an object’s final destruction by the garbage collector.

• They are implemented as a method called "finalize()", and it can be


used in very specialized cases to ensure that object terminates
cleanly.

• However, the use of finalizers is generally discouraged because they


can make it difficult to predict when resources will be released, and
they can lead to performance problems if not used carefully.
∙ To add a finalizer to a class, you simply define the finalize( ) method.

∙ The Java run time calls that method whenever it is about to recycle an object of that class. Inside the
finalize( ) method, actions that must be performed before an object is destroyed will be specified.

∙ The garbage collector runs periodically, checking for objects that are no longer referenced by any
running state or indirectly through other referenced objects

∙ The keyword protected is a specifier that prevents access to finalize( ) by code defined outside its
class

∙ It is important to understand that finalize( ) is only called just prior to garbage collection.
The this Keyword

• this keyword 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

• The use of this is redundant, but perfectly correct. Inside Box( ), this
will always refer to the invoking object. While it is redundant in this
case, this is useful in other contexts
The this Keyword cont…

The this Keyword:


• It is used to refer the current object.
• It is a reference to an object.
• It is used to resolve any Namespace collision between instance variables &
local variables.
• In java , you can have local variables including formal parameters to method
to overlap. When this is the case, local variables hide the instance variables.
• The problem of instance variable hiding can be overcome by the use of this
keyword.
Instance Variable Hiding
• It is illegal in Java to declare two local variables with the same name inside the
same or enclosing scopes
• Interestingly, you can have local variables, including formal parameters to
methods, which overlap with the names of the class’ instance variables
• When a local variable has the same name as an instance variable, the local
variable hides the instance variable
• For example, here is another version of Box( ), which uses width, height, and
depth for parameter names and then uses this to access the instance variables by
the same name

∙ Use this to overcome the instance variable hiding


Controlling access to class members
Controlling Access to Class Members
• A member can be accessed is determined by the access specifier that
modifies its declaration.
• Member access control is achieved through the use of three access
specifiers/modifiers are public, private, and protected. Java also defines a
default access level. protected applies only when inheritance is involved
• When a member of a class is modified by the public specifier, then that
member can be accessed by any other code
• When a member of a class is specified as private, then that member can only
be accessed by other members of its class.
• For example,
• Member c is given private
access. This means that it
cannot be accessed by
code outside of its class.
So, inside the AccessTest
class, c cannot be used
directly. It must be
accessed through its
public methods: setc( )
and getc( )
Pass Objects to Methods
• So far, we have only been using primitive types such as int as parameters to
methods. However, it is both correct and common to pass objects to methods.
• For example,
Output:

Objects are equal


Objects are not equal

∙ The check_equality( ) method


inside Object_Method compares
two objects for equality and
displays the result. That is, it
compares the invoking object with
the one that it is passed. If they
contain the same values, then the
method displays objects are equal.
Otherwise, it displays objects are
not equal
How Arguments are Passed
• There are two ways in which an argument can be passed to a
subroutine/method
• Call-by-value:
• Copies the value of an argument into the formal parameter of the subroutine.
• Therefore, changes made to the parameter of the subroutine have no effect
on the argument.
• Call-by-reference:
• Reference to an argument (not the value of the argument) is passed to the
parameter
• Inside the subroutine, this reference is used to access the actual argument
specified in the call. Changes made to the parameter will affect the argument
used to call the subroutine.
• //Call by value and call by reference.
class a{
int a=5;
int b=7;
int sum(int c , int d) //method header
{
int e= c + d ;
return e ; }
void add( int f, int g)
{
[Link](“sum=“+(f+g));
} }
class b{
public static vid main(String[] args){
a ob=new a();
int h= [Link](15,10);//call by value
System .[Link](h);
[Link](ob.a,ob.b);//call by reference
} }
• Example for call-by-value

Output:
Values of a and b before call 10 20
Values of a and b after call 10 20
∙ The operations that occur inside display( ) have no effect on the
values of a and b used in the call; their values here did not change to
30 and -20.

Example for call-by-reference


Output:
Values of a and b before call 10 20
Values of a and b after call 20 40
∙ In this case, the actions inside display( ) have
affected and changed the actual object used as an
argument, as copy of the reference (not the value)
is passed as the argument. Hence, the reference
variables o and obj are referring to the same object.
Returning Objects
• A method can return any type of data, including class types that you create.
• For example

When display( ) method is invoked, it returns an object of the class Ret_obj class
Method Overloading
• Method overloading in Java allows a class to have multiple methods
with the same name but different parameters. The compiler determines
which method to call based on the number and types of arguments
passed to the method.

• Method overloading is one of the ways that Java supports polymorphism

• Thus, overloaded methods must differ in the type and/or number of their
parameters.
• 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's a simple example demonstrating method overloading
using a DrawShape class:
public class Calculator {

// Method to add two integers


int add(int a, int b) { public class Main{
return a + b; public static void main(String[] args) {
} Calculator c = new Calculator();

// Method to add three integers // Testing addition methods


int add(int a, int b, int c) { [Link]("Sum of 5 and 7: " + [Link](5, 7));
return a + b + c; [Link]("Sum of 3, 8, and 10: " + [Link](3, 8, 10) );
} [Link]("Sum of 2.5 and 3.5: " + [Link](2.5, 3.5) );

// Method to add two doubles }


double add(double a, double b) {
return a + b;
}
}
class DrawShape {

// Method to draw a circle


void draw(int radius) {
[Link]("Drawing a circle with radius: " + radius);
}

// Method to draw a rectangle


void draw(int length, int width) {
[Link]("Drawing a rectangle with length " + length + " and width " + width);
}

// Method to draw a square


void draw(int sideLength, boolean isSquare) {
if (isSquare) {
[Link]("Drawing a square with side length: " + sideLength);
} else {
[Link]("Drawing a rectangle with length " + sideLength + " and width " + sideLength);
// Logic to draw a rectangle (for non-square)
}
}
}
public class MethodOverloadingExample {

public static void main(String[] args) {


DrawShape drawer = new DrawShape();

[Link](5); // Draw a circle


[Link](8, 6); // Draw a rectangle
[Link](4, true); // Draw a square
}
}
Output:

This method doesn't take any parameters


This method takes one integer parameter
This method takes two integer parameters
This method takes one double parameter
The result is 156.25

∙ initialize( ) is overloaded four times


• In some cases, Java’s automatic type conversions can play a
role in overload resolution. Output:

This method takes one double parameter


This method takes two integer parameters
This method takes one double parameter
The result is 156.25
5a) Write a program to demonstrate the implementation of method
overloading
5.1) Create a Stack class having an integer array say elem and top_of_stack as instance variables.
Define three overloaded methods having the following signatures:
a. initStack(int size) to create an array of specified size and initialize the top_of_stack
b. initStack(Stack another) to intialize the Stack object with state of the Stack object "another"
c. initStack(int [] a) to initialize contents of a[] to the instance variable elem.

Write following methods:


a. push(): Pushes the element onto the stack,
b. pop(): Returns the element on the top of the stack, removing it in the process, and
c. peek(): Returns the element on the top of the stack, but does not remove it.

Also write methods that check whether stack is full and stack is empty and return boolean value true
or false appropriately.
Stack Class:
[Link] Variables:
1. int[] ele: An array representing the elements of the stack.
2. int top: An integer indicating the top of the stack.
[Link]:
1. void initStack(int size): Initializes the stack with a specified size.
2. void initStack(Stack another): Initializes the stack using another Stack object. Copies the elements
from the given stack to the current stack.
3. void initStack(int[] a): Initializes the stack using an array. Copies the elements from the array to the
stack.
4. void push(int item): Pushes an element onto the stack if there is space.
5. int pop(): Pops the top element from the stack and returns it.
6. int peek(): Returns the top element of the stack without removing it.
class Stack{

int[] ele;
void initStack(int[] a){
int top; ele=new int[[Link]];
void initStack(int size){ top=-1;
for(int item:a)
ele=new int[size];
push(item);
top=-1; }
}
void initStack(Stack another){

ele=new int[[Link]];

top=-1;

for(int item:[Link])

push(item);

}
void push(int item){
if(top<[Link]){
ele[++top]=item;
[Link]("Pushed element is "+item);
}
else
[Link]("Stack overflow");
}
int pop(){
if(top==-1){
[Link]("Stack underflow");
return -1;
}
else{
int item=ele[top--];
return item;
}
}
int peek(){
return ele[top];
}
}
TW5a Class:
[Link] Method:
1. Creates two Stack objects, s1 and s2.
2. Initializes s1 with a size of 5 and pushes elements onto it.
3. Initializes s2 using the initStack method that takes another Stack object
(s1).
This demonstrates the method overloading feature.
1. Initializes a third Stack object, s3, using an array.
2. Performs some stack operations:
1. Pops an element from s1.
2. Prints the element on top of s1.
3. Prints the element on top of s2.
public class TW5a {
public static void main(String[] args) { [Link] Explanation:
Stack s1=new Stack(); 1. The elements 10, 20, 30, 40, 50 are pushed onto
s1.
Stack s2=new Stack();
2. s2 is initialized using the elements from s1, so s2
[Link](5);
will have the same elements.
[Link](10); 3. The top element of s1 is 40 after popping an
[Link](20); element (50).
[Link](30); 4. The top element of s1 is printed using the peek
[Link](40); method.
[Link](50); 5. The top element of s2 is also printed using the
peek method.
[Link](s1);
6. Note: The code doesn't print the contents of the
int[] array={1,2,3,4};
stack after each operation, but you can modify it to
Stack s3=new Stack(); see the state of the stacks at different points in the
[Link](array); program.
[Link]("Popped element in S1 object is "+[Link]());
[Link]("Element on top of the stack of object s1 is "+[Link]());
[Link]("Element on top of the stack of object s2 is "+[Link]());

}
}
5 b) Overriding.

5 b.1 )Implement the following class hierarchy. In the Cuboid class,


override the method computeArea() and computePerimeter() of
Rectangle class to compute the surface area and perimeter of a
rectangle cuboid. Add a method computeVolume() in Cuboid class to
compute volume of the cuboid. Assuming length, width and height as l,
w and h respectively,
formula to find the surface area = 2(lw) + 2(hl) + 2(hw)
formula to find the perimeter = 2l + 2w
formula to find the volume = l x w x h
class Cuboid extends Rectangle {
class Rectangle {
double height;
double length;
Cuboid() {
double width;
super();
Rectangle() {
height = 1.0;
length = 1.0;
}
width = 1.0;
Cuboid(double length, double width, double height) {
}
super(length, width);
[Link] = height;
Rectangle(double length, double width) {
}
[Link] = length;
@Override
[Link] = width;
double computeArea() {
}
return 2 * ((length * width) + (width * height) + (length *
height));
double computeArea() { }
return length * width; @Override
} double computePerimeter() {
return 4 * (length + width + height);
double computePerimeter() { }
return 2 * (length + width); double computeVolume() {
} return length * width * height;
} }
}
public class TW5b{
public static void main(String[] args) {
Rectangle r1 = new Rectangle();
[Link]("Rectangle 1:");
[Link]("Area:" + [Link]());
[Link]("Perimeter:" + [Link]());
Rectangle r2 = new Rectangle(10,30);
[Link]("\nRectangle 2:");
[Link]("Area:" + [Link]());
[Link]("Perimeter:" + [Link]());
Cuboid c1=new Cuboid();
[Link]("\nCuboid 1:");
[Link]("Area:" + [Link]());
[Link]("Perimeter:" + [Link]());
[Link]("Volume:" + [Link]());
Cuboid c2=new Cuboid(10,30,40);
[Link]("\nCuboid 2:");
[Link]("Surface area:" + [Link]());
[Link]("Perimeter:" + [Link]());
[Link]("Volume:" + [Link]());
}
}
Previous Year Question for reference..
Q1. Explain with examples the following terms.
a) this
b) finialize() method
c) returning objects.
Q2. Define constructors. Demonstrate the concept of constructor
overloading with an example.
Design a class complex which has real part and imaginary
part as instance variables. include the following in the class.
i) Default constructor.
ii)Parameterized constructor to initialize the instance
variables
iii)A method that add two complex and return a resulting
complex object.
class Complex {
// Method to display the complex number
// Instance variables public void display() {
double real; [Link]([Link] + " + " + [Link] + "i");
double imaginary; }
}
// Default constructor class Main{
Complex() { public static void main(String[] args) {
// Initializes to 0 + 0i // Example usage
[Link] = 0.0; Complex c1 = new Complex(2.0, 3.0);
[Link] = 0.0; Complex c2 = new Complex(1.5, -2.5);
}
// Parameterized constructor // Add two complex numbers
Complex(double real, double imaginary) { Complex sum = [Link](c2);
[Link] = real;
[Link] = imaginary; [Link]("Complex1: ");
} [Link]();
// Method to add two complex numbers
Complex add(Complex other) { [Link]("Complex2: ");
double newReal = [Link] + [Link]; [Link]();
double newImaginary = [Link] +
[Link]; [Link]("Sum: ");
return new Complex(newReal, newImaginary); [Link]();
} }
}
Design a Distance class having feet and inches as
instance variables. include the following in the class.
i) Default constructor.
ii) Parameterized constructor to initialize the instance
variables
iii)A method that add two distance object and returns a
resulting distance object
class Distance {
// Method to add two Distance objects and return the result
// Instance variables public Distance add(Distance other) {
int feet; int newFeet = [Link] + [Link];
int inches; int newInches = [Link] + [Link];

// Default constructor // Adjust if inches exceed 12


Distance() { if (newInches >= 12) {
// Initializes to 0 feet and 0 inches newFeet += newInches / 12;
[Link] = 0; newInches %= 12;
[Link] = 0; }
}
return new Distance(newFeet, newInches);
// Parameterized constructor }
Distance(int feet, int inches) {
[Link] = feet; // Display method
[Link] = inches; public void display() {
} [Link](feet + " feet, " + inches + " inches");
}
}
class Main{
public static void main(String[] args) {
// Example usage
Distance d1 = new Distance(3, 9);
Distance d2 = new Distance(2, 6);

// Add two distances


Distance sum = [Link](d2);

// Display the results


[Link]("Distance1: ");
[Link]();

[Link]("Distance2: ");
[Link]();

[Link]("Sum: ");
[Link]();
}
}
Q3. With example explain the different uses of static keyword in
java
Ans: In Java, the static keyword is used in various contexts, such as with variables, methods, and nested
classes.

1. Static Variables:
Static variables belong to the class rather than to instances of the class. There is only one copy of the
static variable, shared among all instances of the class.
public class ExampleClass {
// Static variable shared among all instances of ExampleClass
static int staticVariable = 0;

public static void main(String[] args) {


ExampleClass obj1 = new ExampleClass();
ExampleClass obj2 = new ExampleClass();

[Link] = 10;

[Link]("[Link]: " + [Link]); // Output: 10


[Link]("[Link]: " + [Link]); // Output: 10
2. Static Method: Static methods belong to the class rather than to instances of the
class. They can be called using the class name without creating an instance of the
class.

public class ExampleClass {


// Static method
static void staticMethod() {
[Link]("This is a static method.");
}

public static void main(String[] args) {


[Link](); // Output: This is a static method.
}
}
3. Static Block: A static block is used to initialize static variables. It runs once when the class is
loaded into the memory.

public class ExampleClass {


// Static variable
static int staticVariable;

// Static block
static {
[Link]("Static block is executed.");
staticVariable = 5;
}

public static void main(String[] args) {


[Link]("staticVariable: " + staticVariable); // Output: 5
}
}

You might also like