0% found this document useful (0 votes)
9 views49 pages

Chapter 2.1

The document provides an overview of methods and constructors in Java, explaining their definitions, usage, and types such as default and parameterized constructors. It also covers concepts like method nesting, command-line arguments, argument passing, and the 'this' keyword. Additionally, it introduces varargs for handling variable-length arguments in methods.

Uploaded by

yash gavali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views49 pages

Chapter 2.1

The document provides an overview of methods and constructors in Java, explaining their definitions, usage, and types such as default and parameterized constructors. It also covers concepts like method nesting, command-line arguments, argument passing, and the 'this' keyword. Additionally, it introduces varargs for handling variable-length arguments in methods.

Uploaded by

yash gavali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 49

Unit II

Derived Syntactical
Constructs in Java

Mr. R. M. Patil
SY CO, JPR
2023-2024
Methods in Java
 A method is a block of code which only runs when it is called.
 You can pass data, known as parameters, into a method.
 Methods are used to perform certain actions, and they are also
known as functions.
 Why use methods?
To reuse code: define the code once, and use it many times.
public class test
{
void myMethod()
{
// code to be executed
}
}
Methods in Java

public class test


{
void myMethod()
{
// code to be executed
}
}

• myMethod() is the name of the method

• void means that this method does not have a return value.
Methods in Java - Call a Method (Without Object)
public class test
{
static void myMethod()
{
System.out.println("I just got executed!");
}
public static void main(String[] args)
{
myMethod();
myMethod();
myMethod(); OUTPUT:
} I just got executed!
} I just got executed!
I just got executed!
Methods in Java - Call a Method (With Object)
public class test
{
void myMethod()
{
System.out.println("I just got executed!");
}
public static void main(String[] args)
{
test t1 = new test();
t1.myMethod();
t1.myMethod(); OUTPUT:
t1.myMethod(); I just got executed!
} I just got executed!
} I just got executed!
2.1. Nesting of Methods in Java
 When a method in java calls another method in the
same class, it is called Nesting of methods.

method2()
{
class Test // statements
{ method1();
method1() }
{ method3()
// statements {
} // statements
method2();
}
}
2.1. Nesting of Methods in Java - Example
class Test void display()
{ {
int m,n; int lagre=largest();
Test(int x, int y) System.out.println(“Largest=”+large);
{ }
m=x; }
n=y; class Demo
} {
int largest() public static void main(String args[])
{ {
if(m>=n) Test t=new Test(50,40);
return(m); t.display();
else }
return(n); }
}
2.1. Constructors in Java
 In Java, a constructor is a block of codes similar to the
method.
 It is called when an instance of the class is created.

 At the time of calling constructor, memory for the object is


allocated in the memory.
 It is a special type of method which is used to initialize the
object.
 Every time an object is created using the new() keyword, at
least one constructor is called.
2.1. Constructors in Java – Rules for creating Constructor

1. Constructor name must be the same as its class name

2. A Constructor must have no explicit return type

3. A Java constructor cannot be abstract, static, final, and


synchronized
2.1. Constructors in Java – Types of JAVA Constructor
2.1. Constructors in Java – 1. Default Constructor
A constructor is called "Default Constructor" when it
doesn't have any parameter.
class Bike
{
Bike()
{
System.out.println("Bike is created"); Output :
}
Bike is created
public static void main(String args[])
{
Bike b=new Bike();
}
}
2.1. Constructors in Java – 1. Default Constructor

Rule: If there is no constructor in a class, compiler


automatically creates a default constructor.

Q) What is the purpose of a default constructor?


The default constructor is used to provide the default values
to the object like 0, null, etc., depending on the type.
2.1. Constructors in Java – 1. Default Constructor
class Student
{
In the above
int id;
class, you are
String name;
not creating
void display()
any constructor
{
so compiler
System.out.println(id+" "+name);
provides you a
}
default
public static void main(String args[])
constructor.
{
Here 0 and null
Student s1=new Student();
values are
Student s2=new Student();
provided by
s1.display();
default
s2.display();
constructor.
}
}
2.1. Constructors in Java – 2. Parameterized Constructor

 A constructor that has parameters is known as


parameterized constructor.

 Parameterized constructor is used to provide different


values to distinct objects.
2.1. Constructors in Java – 2. Parameterized Constructor

class demo public class test


{ {
int x; public static void main(String args[])
{
demo(int i ) demo d1 = new demo( 10 );
{ demo d2 = new demo( 20 );
x = i; System.out.println(d1.x + " " + d2.x);
} }
} }

Output : 10 20
2.1. Constructors in Java – 2. Parameterized Constructor
class Student {
{ public static void main(String args[])
int id; {
String name; Student s1=new Student(01,”XYZ”);
Student s2=new Student(02, “abc”);
Student (int a, String nm) s1.display();
{ s2.display();
id = a; }
name = nm; }
}

void display()
{
System.out.println(id+" "+name);
}
}

public class test


2.1. Constructors in Java – Constructor Overloading

 Constructor overloading in Java is a technique of


having more than one constructor with different
parameter lists.

 They are arranged in a way that each constructor


performs a different task.

 They are differentiated by the compiler by the number


of parameters in the list and their types.
2.1. Constructors in Java – Constructor Overloading
2.1. Constructors in Java – Constructor Overloading

class demo public class test


{ {
int x ; public static void main(String args[])
String y; {
demo(int i) demo d1 = new demo( 10 );
{ demo d2 = new demo( “sit” );
x = i; System.out.println(d1.x + " " + d2.y);
} }
demo(String n) }
{
y = n;
} Output : 10 sit
}
2.1. Constructors in Java – Diff. b/w Constructor & Methods
Java Constructor Java Method
A constructor is used to initialize the A method is used to expose the
state of an object. behavior of an object.

A constructor must not have a return A method must have a return type.
type.

The constructor is invoked implicitly. The method is invoked explicitly.

The Java compiler provides a default The method is not provided by the
constructor if you don't have any compiler in any case.
constructor in a class.

The constructor name must be same as The method name may or may not be
the class name. same as the class name.
Homework
1. What is Constructor? Or Define Constructor.
W14, W15, S16 – 02 M
2. Enlist types of Constructor. Explain any two with Example.
S18 - 04 M
3. Create a class with 3 data members. Define a constructor to set
values of first two data members. Define a method to calculate
addition of numbers and print the result. – 04 M
4. Demonstrate the use of parameterized constructor with suitable
example.
W14, W15, S16 – 02 M
5. How to overload constructor? Explain with suitable example. 04M
2.1. Command Line Arguments in Java

 The java command-line argument is an argument i.e.


passed at the time of running the java program.
 The arguments passed from the console can be
received in the java program and it can be used as an
input.
 So, it provides a convenient way to check the behavior
of the program for the different values.
 You can pass N (1,2,3 and so on) numbers of
arguments from the command prompt.
2.1. Command Line Arguments in Java - Example

class CommandLineExample
{
public static void main(String args[])
{
System.out.println("Your first argument is: "+args[0]);
System.out.println("Your second argument is: "+args[1]);
}
}

compile by > javac CommandLineExample.java


run by > java CommandLineExample sit poly
Output: Your first argument is: sit
Your second argument is: poly
2.1. Command Line Arguments in Java - Example
class A
{
public static void main(String args[]) Output:
{ sit
for(int i=0;i<args.length;i++)
{ poly
System.out.println(args[i]); 1
}
} 5
} co

compile by > javac A.java


run by > java A sit poly 1 5 co
2.1. Argument Passing in Java – Call by Value

 There is only call by value in java, not call by reference.

 If we call a method passing a value, it is known as call


by value.

 The changes being done in the called method, is not


affected in the calling method.
2.1. Argument Passing in Java – Call by Value
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[]) Output:


{
before change 50
Operation op=new Operation();
after change 50
System.out.println("before change "+op.data);
op.change(100);
System.out.println("after change "+op.data);
}
}
2.1. Argument Passing in Java – Call by Value
If we pass object in place of any primitive value, original
class Operation
value will be changed.
{
In this example we are passing object as a value
int data=50;
void change(Operation o)
{
o.data=o.data+100; //changes will be in the instance variable
}

public static void main(String args[])


{ Output:
Operation op=new Operation(); before change 50
System.out.println("before change "+op.data); after change 150
op.change(op); //passing object
System.out.println("after change "+op.data);
}
}
2.1. Argument Passing in Java – ‘this’ keyword

 In java, ‘this’ is a reference variable that refers to the


current object.

‘this’ can also be used to:


• Invoke current class constructor
• Invoke current class method
• Return the current class object
• Pass an argument in the method call
• Pass an argument in the constructor call
2.1. Argument Passing in Java – ‘this’ keyword
class Operation
{
int data=50;
void change(int data)
{
this.data=data+100;
} Output:
public static void main(String args[]) before change 50
{ after change 200
Operation op=new Operation();
System.out.println("before change "+op.data);
op.change(100);
System.out.println("after change "+op.data);
}
}
2.1. Argument Passing in Java – ‘this’ keyword (Another Example)
class test
{
int a=100, b=200;
test(int a, int b)
{
a = a; Output:
b = b;
} 100 200
public static void main(String args[])
{
test t = new test(10,20);
System.out.println(t.a+" "+t.b);
}
}
2.1. Argument Passing in Java – ‘this’ keyword (Another Example)
class test
{
int a=100, b=200;
test(int a, int b)
{
this.a = a; Output:
this.b = b;
} 10 20
public static void main(String args[])
{
test t = new test(10,20);
System.out.println(t.a+" "+t.b);
}
}
2.1. Usage of ‘this’ keyword :
2.1. Usage of ‘this’ keyword : - Example (3)

class test
{
test()
{
System.out.println("this method called..");
}
test(int x) Output:
{ this method called..
this(); x=10
System.out.println("x="+x);
}
public static void main(String args[])
{
test t = new test(10);
}
}
2.1. varargs : ‘Variable length arguments’
 Let’s suppose you are creating a Java method.
However, you are not sure how many arguments your
method is going to accept.

 To address this problem, Java 1.5 introduced varargs.

 varargs is a short name for variable arguments.

 In Java, an argument of a method can accept arbitrary


number of values.

 This argument that can accept variable number of


values is called varargs.
2.1. varargs : ‘Variable length arguments’

 The syntax for implementing varargs is as follows:

accessModifier methodName(datatype… arg)


{
// method body
}

 In order to define vararg, ... (three dots) is used in the


formal parameter of a method.

 A method that takes variable number of arguments is


called a variable-arity method, or simply a varargs method.
First, let’s look at the example without using varargs:
class NoVararg
{
public int sumNumber(int a, int b) Output:
{ 3
return a+b;
} 6

public int sumNumber(int a, int b, int c)


{
return a+b+c;
}
What if the
user wants
public static void main( String[] args ) to add 5
{ numbers or
NoVararg obj = new NoVararg(); 10 or 100?
System.out.println(obj.sumNumber(1, 2));
System.out.println(obj.sumNumber(1, 2, 3));
}
}
Now, let’s look at the example using varargs:
Class vararg
{
int sumNumber(int ... args) Output:
{
//System.out.println("argument length: " + args.length); 3
int sum = 0; 6
for(int x: args)
{ 10
sum = sum + x;
}
return sum;
}
public static void main( String[] args )
{
vararg obj = new vararg();
System.out.println(obj.sumNumber(1, 2));
System.out.println(obj.sumNumber(1, 2, 3));
System.out.println(obj.sumNumber(1, 2, 3, 4));
}
}
class VarargsExample2 One more example of varargs
{
static void display(String... values)
{ Output:
System.out.println("display method"); display method
for(String s:values)
{ display method
System.out.println(s); hello
}
display method
}
public static void main(String args[]) my
{ name
display(); //zero argument is
display("hello"); //one argument
display("my","name","is"); //three arguments
}
}
2.1. varargs : ‘Variable length arguments’

Rules:
Examples of varargs that fails to compile:
There can be only
void method(String... a, int... b){ } one variable
argument in the
//Compile time error
method.
void method(int... a, String b){ }
 Variable
//Compile time error argument (varargs)
must be the last
argument.
Example of Varargs that is the last argument in the method:

class VarargsExample3
{
static void display(int num, String... values) Output:
{
number is 500
System.out.println("number is "+num); hello
for(String s:values) number is 1000
{ my
System.out.println(s); name
is
} varargs
}
public static void main(String args[])
{
display(500,"hello"); //one argument
display(1000,"my","name","is","varargs"); //four arguments
}
}
2.1. Garbage collection in java
 In java, garbage means unreferenced objects.

 Garbage Collection is process of reclaiming the runtime


unused memory automatically. In other words, it is a way
to destroy the unused objects.

 To do so, we were using free() function in C language


and delete() in C++.

 But, in java it is performed automatically. So, java


provides better memory management.
2.1. Garbage collection in java

Advantage of Garbage Collection :

 It makes java memory efficient because garbage


collector removes the unreferenced objects from heap
memory.

 It is automatically done by the garbage collector(a part


of JVM) so we don't need to make extra efforts.
2.1. Garbage collection in java
2.1. Garbage collection in java
1) By nulling a reference:
Employee e=new Employee();
e=null;

2) By assigning a reference to another:


Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;
//now the first object referred by e1 is available for
garbage collection

3) By anonymous object:
new Employee();
2.1. Garbage collection in java
We can also request JVM to run garbage collector..

Using System.gc() method: System class contain


static method gc() for requesting JVM to run Garbage
Collector.

 Using Runtime.getRuntime().gc() method: Runtime


class allows the application to interface with the JVM in
which the application is running. Hence by using its gc()
method, we can request JVM to run garbage collector.
2.1. finalize() mathod in java
 The finalize() method of Object class is a method that
the Garbage Collector always calls just before the
deletion/destroying the object which is eligible for
Garbage Collection, so as to perform clean-up activity.

 Clean-up activity means closing the resources


associated with that object like Database Connection,
Network Connection or we can say resource de-
allocation.

 Remember it is not a reserved keyword. Once the


finalize method completes immediately Garbage Collector
destroy that object.
2.1. the Object Class
 The Object class is the parent class of all the classes in java by
default. In other words, it is the topmost class of java.
Method Description
public final Class getClass() returns the Class class object of this object. The
Class class can further be used to get the
metadata of this class.
public int hashCode() returns the hashcode number for this object.
public boolean equals(Object obj) compares the given object to this object.
protected Object clone() throws creates and returns the exact copy (clone) of
CloneNotSupportedException this object.
public String toString() returns the string representation of this object.
public final void notify() wakes up single thread, waiting on this object's
monitor.
public final void notifyAll() wakes up all the threads, waiting on this
object's monitor.
2.1. the Object Class

Method Description

public final void wait(long timeout)throws causes the current thread to wait for the
InterruptedException specified milliseconds, until another thread
notifies (invokes notify() or notifyAll()
method).
public final void wait(long timeout,int causes the current thread to wait for the
nanos)throws InterruptedException specified milliseconds and nanoseconds,
until another thread notifies (invokes
notify() or notifyAll() method).
public final void wait()throws causes the current thread to wait, until
InterruptedException another thread notifies (invokes notify() or
notifyAll() method).
protected void finalize()throws Throwable is invoked by the garbage collector before
object is being garbage collected.
Homework
1. What is ‘this’? Give Example. 02 M
2. Explain ‘varargs’ with suitable example. 04 M
3. What is garbage collection in Java? Explain finalize
method in Java.
S17 - 04 M
4. Explain the importance of object class and explain any
three methods of this class. – 04 M

You might also like