0% found this document useful (0 votes)
4 views

Unit2

The document provides an overview of key concepts in Java, including objects, classes, methods, constructors, and garbage collection. It explains the definitions and characteristics of objects and classes, how to create objects, and the significance of methods and method overloading. Additionally, it covers the use of the static keyword, the this keyword, and the garbage collection process in Java, including the finalize() and gc() methods.

Uploaded by

rohitdamer2006
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Unit2

The document provides an overview of key concepts in Java, including objects, classes, methods, constructors, and garbage collection. It explains the definitions and characteristics of objects and classes, how to create objects, and the significance of methods and method overloading. Additionally, it covers the use of the static keyword, the this keyword, and the garbage collection process in Java, including the finalize() and gc() methods.

Uploaded by

rohitdamer2006
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Unit-2

An object in Java is the physical as well as a logical entity, whereas, a class in Java is a logical
entity only.

What is an object in Java


An object is an instance of a class. A class is a template or blueprint from which objects
are created. So, an object is the instance(result) of a class.

Object Definitions:

o An object is a real-world entity.


o An object is a runtime entity.
o The object is an entity which has state and behavior.
o The object is an instance of a class.

What is a class in Java


A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created. It is a logical entity. It can't be physical.

A class in Java can contain:

o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface

Syntax to declare a class:


class <class_name>{
field;
method;
}
new keyword in Java
The new keyword is used to allocate memory at runtime. All objects get memory in Heap
memory area.

//Java Program to illustrate how to define a class and fields


//Defining a Student class.
class Student{
//defining fields
int id;//field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[]){
//Creating an object or instance
Student s1=new Student();//creating an object of Student
//Printing values of the object
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
}
}

What are the different ways to create an object in


Java?
There are many ways to create an object in java. They are:

o By new keyword
o By newInstance() method
o By clone() method
o By deserialization
o By factory method etc
What is a method in Java?
A method is a block of code or collection of statements or a set of code grouped together to
perform a certain task or operation. It is used to achieve the reusability of code. We write a
method once and use it many times. We do not require to write code again and again. It also
provides the easy modification and readability of code, just by adding or removing a chunk of
code. The method is executed only when we call or invoke it. The most important method in Java
is the main() method.

Method Declaration
The method declaration provides information about method attributes, such as visibility, return-
type, name, and arguments. It has six components that are known as method header, as we
have shown in the following figure.

Method Signature: Every method has a method signature. It is a part of the method
declaration. It includes the method name and parameter list.

Access Specifier: Access specifier or modifier is the access type of the method. It specifies
the visibility of the method. Java provides four types of access specifier:

o Public: The method is accessible by all classes when we use public specifier in our
application.
o Private: When we use a private access specifier, the method is accessible only in
the classes in which it is defined.
o Protected: When we use protected access specifier, the method is accessible
within the same package or subclasses in a different package.
o Default: When we do not use any access specifier in the method declaration, Java
uses default access specifier by default. It is visible only from the same package
only.
Return Type: Return type is a data type that the method returns. It may have a primitive
data type, object, collection, void, etc. If the method does not return anything, we use
void keyword.

Method Name: It is a unique name that is used to define the name of a method. It must
be corresponding to the functionality of the method. Suppose, if we are creating a method
for subtraction of two numbers, the method name must be subtraction(). A method is
invoked by its name.

Parameter List: It is the list of parameters separated by a comma and enclosed in the pair
of parentheses. It contains the data type and variable name. If the method has no
parameter, left the parentheses blank.

Method Body: It is a part of the method declaration. It contains all the actions to be
performed. It is enclosed within the pair of curly braces.

Method Overloading in Java


If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.

Advantage of method overloading

Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

1) Method Overloading: changing no. of arguments


class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}

2) Method Overloading: changing data type of arguments


class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}

Passing Objects as argument in methods


Object references can be parameters. Call by value is used, but now the value is
an object reference. This reference can be used to access the object and
possibly change it
**
* This program passes an object as an argument.
* The object is modified by the receiving method.
*/
public class PassObjectDemo
{
public static void main(String[] args)
{
// Create an Rectangle object.
Rectangle rect = new Rectangle(10, 20);

// Display the object's contents.


System.out.println("Length : " + rect.getLength());
System.out.println("Width: " + rect.getWidth());
System.out.println("Area: " + rect.getArea());

// Pass the object to the ChangeRectangle method.


changeRectangle(rect);

// Display the object's contents again.


System.out.println();
System.out.println("Length : " + rect.getLength());
System.out.println("Width: " + rect.getWidth());
System.out.println("Area: " + rect.getArea());
}

/**
* The following method accepts an Rectangle
* object as an argument and changes its contents.
*/
public static void changeRectangle(Rectangle r)
{
r.set(30, 5);
}
}

Recursion in Java
Recursion in java is a process in which a method calls itself continuously. A method in java
that calls itself is called recursive method. It makes the code compact but complex to
understand.

Syntax:

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

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

Rules for creating Java constructor


There are two rules defined for the 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

Types of Java constructors


There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

Java Default Constructor


A constructor is called "Default Constructor" when it doesn't have any parameter.

//Java Program to create and call a default constructor


class Bike1{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
Java Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized
constructor.

//Java Program to demonstrate the use of the parameterized constructor.


class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}
Java static keyword
The static keyword in Java is used for memory management mainly. We can apply static
keyword with variables, methods, blocks and nested classes. The static keyword belongs
to the class than an instance of the class.

The static can be:

1. Variable (also known as a class variable)


2. Method (also known as a class method)
3. Block
4. Nested class

this keyword in Java


There can be a lot of usage of Java this keyword. In Java, this is a reference variable that
refers to the current object.

class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}

Java Garbage Collection


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.

Advantage of Garbage Collection


o It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
o It is automatically done by the garbage collector(a part of JVM) so we don't need to make
extra efforts.

finalize() method
The finalize() method is invoked each time before the object is garbage collected. This
method can be used to perform cleanup processing. This method is defined in Object
class as:

1. protected void finalize(){}


Note: The Garbage collector of JVM collects only those objects that are created by new
keyword. So if you have created any object without new, you can use finalize method
to perform cleanup processing (destroying remaining objects).

gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing.
The gc() is found in System and Runtime classes.

public static void gc(){}

Note: Garbage collection is performed by a daemon thread called Garbage


Collector(GC). This thread calls the finalize() method before object is garbage
collected.

Simple Example of garbage collection in java


public class TestGarbage1{
public void finalize(){System.out.println("object is garbage collected");}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
}
}

You might also like