Java Basics Unit 2
Java Basics Unit 2
Java Arrays
memory location.
• Array in Java is index-based, the first element of the array is stored at the 0th index,
• Unlike C/C++, we can get the length of the array using the length member. In C/C++,
• Java array inherits the Object class, and implements the Serializable as well as
Cloneable interfaces.
in Java.
available in C/C++.
Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
Disadvantages
o Size Limit: We can store only the fixed size of elements in the array.
automatically.
Let's see the simple example of java array, where we are going to declare, instantiate,
3. class Testarray{
6. a[0]=10;//initialization
7. a[1]=20;
8. a[2]=70;
9. a[3]=40;
10. a[4]=50;
13. System.out.println(a[i]);
14. }}
Output:
10
20
70
40
50
Array
We can declare, instantiate and initialize the java array together by:
3. class Testarray1{
6. //printing array
8. System.out.println(a[i]);
9. }}
Output:
33
• The Java for-each loop prints the array elements one by one.
• It holds an array element in a variable, then executes the body of the loop.
The syntax of the for-each loop is given below:
1. for(data_type variable:array){
3. }
Let us see the example of print the elements of Java array using the for-each loop.
2. class Testarray1{
4. int arr[]={33,3,4,5};
6. for(int i:arr)
7. System.out.println(i);
8. }}
Output:
33
ArrayIndexOutOfBoundsException
The Java Virtual Machine (JVM) throws an ArrayIndexOutOfBoundsException if length
of the array in negative, equal to the array size or greater than the array size while
int arr[]={50,60,70,80};
for(int i=0;i<=arr.length;i++){
System.out.println(arr[i]);
}}
Output:
at TestArrayException.main(TestArrayException.java:5)
50
60
70
80
form).
4. dataType []arrayRefVar[];
1. arr[0][0]=1;
2. arr[0][1]=2;
3. arr[0][2]=3;
4. arr[1][0]=4;
5. arr[1][1]=5;
6. arr[1][2]=6;
7. arr[2][0]=7;
8. arr[2][1]=8;
9. arr[2][2]=9;
2Dimensional array.
2. class Testarray3{
5. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
6. //printing 2D array
7. for(int i=0;i<3;i++){
8. for(int j=0;j<3;j++){
9. System.out.print(arr[i][j]+" ");
10. }
11. System.out.println();
12. }
13. }}
Output:
1 2 3
2 4 5
4 4 5
2. class TestJaggedArray{
14.
19. }
21. }
22. }
23. }
Output:
0 1 2
3 4 5 6
7 8
In Java, an array is an object. For array object, a proxy class is created whose name
class Testarray4{
int arr[]={4,4,5};
Class c=arr.getClass();
String name=c.getName();
System.out.println(name);
}}
2. class Testarray5{
5. int a[][]={{1,3,4},{3,4,5}};
6. int b[][]={{1,3,4},{3,4,5}};
7.
10.
14. c[i][j]=a[i][j]+b[i][j];
15. System.out.print(c[i][j]+" ");
16. }
18. }
19.
20. }}
Output:
2 6 8
6 8 10
In the case of matrix multiplication, a one-row element of the first matrix is multiplied
by all the columns of the second matrix which can be understood by the image given
below.
Let's see a simple example to multiply two matrices of 3 rows and 3 columns.
5. int a[][]={{1,1,1},{2,2,2},{3,3,3}};
6. int b[][]={{1,1,1},{2,2,2},{3,3,3}};
7.
10.
14. c[i][j]=0;
16. {
17. c[i][j]+=a[i][k]*b[k][j];
22. }
23. }}
Output:
6 6 6
12 12 12
18 18 18
Java OOPs Concepts
The popular object-oriented languages are Java, C#, PHP, Python, C++, etc.
Object means a real-world entity such as a pen, chair, table, computer, watch,
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Object
• Any entity that has state and behaviour is known as an object. For example, a
• Objects can communicate without knowing the details of each other's data or
code. Example: A dog is an object because it has states like color, name,
breed, etc. as well as behaviors like wagging the tail, barking, eating, etc.
Class
• A class can also be defined as a blueprint from which you can create an
Inheritance
When one object acquires all the properties and behaviors of a parent object, it is
polymorphism.
Polymorphism
polymorphism.
• Another example can be to speak something; for example, a cat speaks meow,
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example
Binding (or wrapping) code and data together into a single unit are known as
A java class is the example of encapsulation. Java bean is the fully encapsulated class
programming language
size increases.
3) OOPs provides the ability to simulate real-world event much more effectively. We
can provide the solution of real word problem if we are using the Object-Oriented
Programming language.
Objects and Classes in Java
An object in Java is the physical as well as a logical entity, whereas, a class in Java is a
An entity that has state and behavior is known as an object e.g., chair, bike, marker,
pen, table, car, etc. It can be physical or logical (tangible and intangible). The example
withdraw, etc.
o Identity: An object identity is typically implemented via a unique ID. The value
of the ID is not visible to the external user. However, it is used internally by the
For Example, Pen is an object. Its name is Reynolds; color is white, known as its state.
Object Definitions:
blueprint from which objects are created. It is a logical entity. It can't be physical.
o Fields
o Methods
o Constructors
o Blocks
2. field;
3. method;
4. }
• A variable which is created inside the class but outside the method is known
as an instance variable.
Method in Java
In Java, a method is like a function which is used to expose the behavior of an object.
Advantage of Method
o Code Reusability
o Code Optimization
The new keyword is used to allocate memory at runtime. All objects get memory in
In this example, we have created a Student class which has two data members id and
name. We are creating the object of the Student class by new keyword and printing
File: Student.java
class Student{
//defining fields
String name;
System.out.println(s1.name);
}
Output:
null
In real time development, we create classes and use it from another class. It is a
better approach than previous one. Let's see a simple example, where we are having
We can have multiple classes in different Java files or single Java file. If you define
multiple classes in a single Java source file, it is a good idea to save the file name
File: TestStudent1.java
2. //another class
4. class Student{
5. int id;
6. String name;
7. }
8. //Creating another class TestStudent1 which contains the main method
9. class TestStudent1{
12. System.out.println(s1.id);
13. System.out.println(s1.name);
14. }
15. }
Output:
null
1. By reference variable
2. By method
3. By constructor
Initializing an object means storing data into the object. Let's see a simple example
where we are going to initialize the object through a reference variable.
File: TestStudent2.java
1. class Student{
2. int id;
3. String name;
4. }
5. class TestStudent2{
8. s1.id=101;
9. s1.name="Sonoo";
11. }
12. }
Output:
101 Sonoo
We can also create multiple objects and store information in it through reference
variable.
File: TestStudent3.java
1. class Student{
2. int id;
3. String name;
4. }
5. class TestStudent3{
7. //Creating objects
11. s1.id=101;
12. s1.name="Sonoo";
13. s2.id=102;
14. s2.name="Amit";
18. }
19. }
Output:
101 Sonoo
102 Amit
2) Object and Class Example: Initialization through method
In this example, we are creating the two objects of Student class and initializing the
value to these objects by invoking the insertRecord method. Here, we are displaying
1. class Student{
2. int rollno;
3. String name;
5. rollno=r;
6. name=n;
7. }
8. void displayInformation()
9. {
11. }
16. s1.insertRecord(111,"Karan");
17. s2.insertRecord(222,"Aryan");
18. s1.displayInformation();
19. s2.displayInformation();
20. }
21. }
Output:
111 Karan
222 Aryan
As you can see in the above figure, object gets the memory in heap memory area.
The reference variable refers to the object allocated in the heap memory area. Here,
s1 and s2 both are reference variables that refer to the objects allocated in memory.
constructor
1. class Employee{
2. int id;
3. String name;
4. float salary;
6. id=i;
7. name=n;
8. salary=s;
9. }
11. }
17. e1.insert(101,"ajeet",45000);
18. e2.insert(102,"irfan",25000);
19. e3.insert(103,"nakul",55000);
20. e1.display();
21. e2.display();
22. e3.display();
23. }
24. }
Output:
There is given another example that maintains the records of Rectangle class.
File: TestRectangle1.java
1. class Rectangle{
2. int length;
3. int width;
5. length=l;
6. width=w;
7. }
8. void calculateArea(){System.out.println(length*width);}
9. }
14. r1.insert(11,5);
15. r2.insert(3,15);
16. r1.calculateArea();
17. r2.calculateArea();
18. }
19. }
Output:
55
45
Java?
o By new keyword
o By newInstance() method
o By clone() method
o By deserialization
If you have to use an object only once, an anonymous object is a good approach. For
example:
2. c.fact(5);
Calling method through an anonymous object
1. new Calculation().fact(5);
1. class Calculation{
3. int fact=1;
4. for(int i=1;i<=n;i++){
5. fact=fact*i;
6. }
7. System.out.println("factorial is "+fact);
8. }
11. }
12. }
Output:
Factorial is 120
Creating multiple objects by one type only
3. class Rectangle{
4. int length;
5. int width;
7. length=l;
8. width=w;
9. }
11. }
15. r1.insert(11,5);
16. r2.insert(3,15);
17. r1.calculateArea();
18. r2.calculateArea();
19. }
20. }
Output:
55
45
File: TestAccount.java
4. class Account{
5. int acc_no;
6. String name;
7. float amount;
10. acc_no=a;
11. name=n;
12. amount=amt;
13. }
16. amount=amount+amt;
18. }
21. if(amount<amt){
23. }else{
24. amount=amount-amt;
26. }
27. }
37. a1.insert(832345,"Ankit",1000);
38. a1.display();
39. a1.checkBalance();
40. a1.deposit(40000);
41. a1.checkBalance();
42. a1.withdraw(15000);
43. a1.checkBalance();
44. }}
Output:
40000.0 deposited
15000.0 withdrawn
• We write a method once and use it many times. We do not require writing
Method Declaration
visibility, return-type, name, and arguments. It has six components that are known
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
o Protected: When we use protected access specifier, the method is accessible within
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
Method Name: It is a unique name that is used to define the name of a method. It
creating a method for subtraction of two numbers, the method name must
the pair of parentheses. It contains the data type and variable name. If the method
Method Body: It is a part of the method declaration. It contains all the actions to be
Naming a Method
While defining a method, remember that the method name must be a verb and start
with a lowercase letter. If the method name has more than two words, the first name
must be a verb followed by adjective or noun. In the multi-word method name, the
first letter of each word must be in uppercase except the first word. For example:
It is also possible that a method has the same name as another method name in the
Types of Method
o Predefined Method
o User-defined Method
Predefined Method
• In Java, predefined methods are the method that is already defined in the Java
• We can directly use these methods just by calling them in the program at any
sqrt(), etc.
• When we call any of the predefined methods in our program, a series of codes
Demo.java
2. {
3. public static void main(String[] args)
4. {
7. }
8. }
Output:
print(), and max(). We have used these methods directly without declaration
because they are predefined. The print() method is a method of PrintStream class
that prints the result on the console. The max() method is a method of
We can also see the method signature of any predefined method by using the
link https://docs.oracle.com/. When we go through the link and see the max()
name max(), parameter list (int a, int b). In the above example, instead of defining
the method, we have just invoked the method. This is the advantage of a predefined
Similarly, we can also see the method signature of the print() method.
User-defined Method
Let's create a user defined method that checks the number is even or odd. First, we
will define the method.
3. {
4. //method body
5. if(num%2==0)
6. System.out.println(num+" is even");
7. else
8. System.out.println(num+" is odd");
9. }
parameter num of type int. The method does not return any value that's why we
have used void. The method body contains the steps to check the number is even or
odd. If the number is even, it prints the number is even, else prints the number is
odd.
2. {
4. {
9. int num=scan.nextInt();
11. findEvenOdd(num);
12. }
line findEvenOdd(num), the control transfer to the method and gives the output
accordingly.
Let's combine both snippets of codes in a single program and execute it.
EvenOdd.java
1. import java.util.Scanner;
5. {
12. findEvenOdd(num);
13. }
16. {
18. if(num%2==0)
20. else
22. }
23. }
Output 1:
Enter the number: 12
12 is even
Output 2:
99 is odd
Let's see another program that return a value to the calling method.
In the following program, we have defined a method named add() that sum up the
two numbers. It has two parameters n1 and n2 of integer type. The values of n1 and
n2 correspond to the value of a and b, respectively. Therefore, the method adds the
value of a and b and store it in the variable s and returns the sum.
Addition.java
2. {
4. {
5. int a = 19;
6. int b = 5;
7. //method calling
10. }
11. //user defined method
12. public static int add(int n1, int n2) //n1 and n2 are formal parameters
13. {
14. int s;
15. s=n1+n2;
17. }
18. }
Output:
Static Method
• We can also create a static method by using the keyword static before the
method name.
• The main advantage of a static method is that we can call it without creating
an object.
• It can access static data members and also change the value of it. It is used to
Display.java
2. {
4. {
5. show();
6. }
8. {
10. }
11. }
Output:
Instance Method
defined in the class. Before calling or invoking the instance method, it is necessary to
create an object of its class. Let's see an example of an instance method.
InstanceMethodExample.java
2. {
4. {
9. }
10. int s;
13. {
14. s = a+b;
16. return s;
17. }
18. }
Output:
The sum is: 25
o Accessor Method
o Mutator Method
Accessor Method: The method(s) that reads the instance variable(s) is known as the
accessor method. We can easily identify it because the method is prefixed with the
word get. It is also known as getters. It returns the value of the private field. It is
Example
2. {
3. return Id;
4. }
Mutator Method: The method(s) read the instance variable(s) and also modify the
values. We can easily identify it because the method is prefixed with the word set. It
parameter of the same data type that depends on the field. It is used to set the value
2. {
3. this.roll = roll;
4. }
Student.java
2. {
6. {
7. return roll;
8. }
10. {
12. }
14. {
15. return name;
16. }
18. {
20. }
22. {
25. }
26. }
Abstract Method
• The method that does not has method body is known as abstract method. In
• It always declares in the abstract class. It means the class itself must be
Syntax
Demo.java
2. {
5. }
7. {
8. //method impelmentation
9. void display()
10. {
12. }
14. {
18. obj.display();
19. }
20. }
Output:
Abstract method...
Factory method
It is a method that returns an object to the class to which it belongs. All static
NumberFormat.getNumberInstance();
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.
Every time an object is created using the new() keyword, at least one constructor is
called.
There are two types of constructors in Java: no-arg constructor, and parameterized
constructor.
Note: It is called constructor because it constructs the values at the time of object
while declaring a constructor. It controls the object creation. In other words, we can have
2. Parameterized constructor
Java Default Constructor
1. <class_name>(){}
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at
class Bike1{
Bike1()
{
System.out.println("Bike is created");}
//main method
Output:
Bike is created
constructor.
The default constructor is used to provide the default values to the object like 0, null,
values
class Student3{
int id;
String name;
void display(){
System.out.println(id+" "+name);}
//creating objects
s1.display();
s2.display();
Output:
0 null
0 null
Explanation:In the above class,you are not creating any constructor so compiler
provides you a default constructor. Here 0 and null values are provided by default
constructor.
constructor.
In this example, we have created the constructor of Student class that have two
class Student4{
int id;
String name;
id = i;
name = n;
s1.display();
s2.display();
Output:
111 Karan
222 Aryan
Constructor Overloading in Java
• In Java, a constructor is just like a method but without return type. It can also
• 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.
class Student5{
int id;
String name;
int age;
id = i;
name = n;
id = i;
name = n;
age=a;
s1.display();
s2.display();
Output:
111 Karan 0
222 Aryan 25
There are many differences between constructors and methods. They are given
below.
A constructor must not have a return type. A method must have a return type.
The Java compiler provides a default constructor if The method is not provided by the
The constructor name must be same as the class The method name may or may not
There is no copy constructor in Java. However, we can copy the values from one
There are many ways to copy the values of one object into another in Java. They are:
o By constructor
In this example, we are going to copy the values of one object into another using
Java constructor.
//Java program to initialize the values from one object to another object.
class Student6{
int id;
String name;
id = i;
name = n;
Student6(Student6 s){
id = s.id;
name =s.name;
s1.display();
s2.display();
Output:
111 Karan
111 Karan
We can copy the values of one object into another by assigning the objects values to
class Student7{
int id;
String name;
id = i;
name = n;
Student7(){}
s2.id=s1.id;
s2.name=s1.name;
s1.display();
s2.display();
Output:
111 Karan
111 Karan
Java static keyword
• 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.
3. Block
4. Nested class
o The static variable can be used to refer to the common property of all objects
(which is not unique for each object), for example, the company name of
employees, college name of students, etc.
o The static variable gets memory only once in the class area at the time of class
loading.
class Student{
int rollno;
String name;
String college="ITS";
}
Suppose there are 500 students in my college, now all instance data members will
get memory each time when the object is created. All students have its unique rollno
and name, so instance data member is good in such case. Here, "college" refers to
the common property of all objects. If we make it static, this field will get the memory
only once.
Counter(){
count++;//incrementing value
System.out.println(count);
}
Output:
1
1
1
Counter2(){
count++;//incrementing the value of static variable
System.out.println(count);
}
Output:
1
2
3
o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a class.
o A static method can access static data member and can change the value of it.
//Java Program to get the cube of a given number using the static method
class Calculate{
static int cube(int x){
return x*x*x;
}
There are two main restrictions for the static method. They are:
1. The static method can not use non static data member or call non-static method
directly.
2. this and super cannot be used in static context.
class A{
int a=40;//non static
class A2{
static{System.out.println("static block is invoked");}
public static void main(String args[]){
System.out.println("Hello main");
}
}
Output:static block is invoked
Hello main
Ans) No, one of the ways was the static block, but it was possible till JDK 1.6. Since
JDK 1.7, it is not possible to execute a Java class without the main method.
class A3{
static{
System.out.println("static block is invoked");
System.exit(0);
}
}
Output:
Suggestion: If you are beginner to java, lookup only three usages of this keyword.
1) this: to refer current class instance variable
The this keyword can be used to refer current class instance variable. If there is
ambiguity between the instance variables and parameters, this keyword resolves the
problem of ambiguity.
ncepts in Java
Let's understand the problem if we don't use this keyword by the example given
below:
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Output:
0 null 0.0
0 null 0.0
In the above example, parameters (formal arguments) and instance variables are
same. So, we are using this keyword to distinguish local variable and instance
variable.
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();
}}
Output:
class Student{
int rollno;
String name;
float fee;
Student(int r,String n,float f){
rollno=r;
name=n;
fee=f;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis3{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Output:
It is better approach to use meaningful names for variables. So we use same name for
instance variables and parameters in real time, and always use this keyword.
class A{
void m(){System.out.println("hello m");}
void n(){
System.out.println("hello n");
//m();//same as this.m()
this.m();
}
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}}
Output:
hello n
hello m
class A{
A(){System.out.println("hello a");}
A(int x){
this();
System.out.println(x);
}
}
class TestThis5{
public static void main(String args[]){
A a=new A(10);
}}
Output:
hello a
10
class A{
A(){
this(5);
System.out.println("hello a");
}
A(int x){
System.out.println(x);
}
}
class TestThis6{
public static void main(String args[]){
A a=new A();
}}
Output:
5
hello a
class Student{
int rollno;
String name,course;
float fee;
Student(int rollno,String name,String course){
this.rollno=rollno;
this.name=name;
this.course=course;
}
Student(int rollno,String name,String course,float fee){
this(rollno,name,course);//reusing constructor
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}
}
class TestThis7{
public static void main(String args[]){
Student s1=new Student(111,"ankit","java");
Student s2=new Student(112,"sumit","java",6000f);
s1.display();
s2.display();
}}
Output:
class Student{
int rollno;
String name,course;
float fee;
Student(int rollno,String name,String course){
this.rollno=rollno;
this.name=name;
this.course=course;
}
Student(int rollno,String name,String course,float fee){
this.fee=fee;
this(rollno,name,course);//C.T.Error
}
void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}
}
class TestThis8{
public static void main(String args[]){
Student s1=new Student(111,"ankit","java");
Student s2=new Student(112,"sumit","java",6000f);
s1.display();
s2.display();
}}
Output:
Compile Time Error: Call to this must be first statement in constructor
class S2{
void m(S2 obj){
System.out.println("method is invoked");
}
void p(){
m(this);
}
public static void main(String args[]){
S2 s1 = new S2();
s1.p();
}
}
Output:
method is invoked
class B{
A4 obj;
B(A4 obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A4 class
}
}
class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}
Output:10
return_type method_name(){
return this;
}
class A{
A getA(){
return this;
}
void msg(){System.out.println("Hello java");}
}
class Test1{
public static void main(String args[]){
new A().getA().msg();
}
}
Output:
Hello java
class A5{
void m(){
System.out.println(this);//prints same reference ID
}
public static void main(String args[]){
A5 obj=new A5();
System.out.println(obj);//prints the reference ID
obj.m();
}
}
Output:
A5@22b3ea59
A5@22b3ea59
If we have to perform only one operation, having same name of the methods
increases the readability of the program.
Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the method such as a(int,int) for two parameters,
and b(int,int,int) for three parameters then it may be difficult for you as well as other
programmers to understand the behavior of the method because its name differs.
In Java, Method Overloading is not possible by changing the return type of the method
only.
In this example, we are creating static methods so that we don't need to create
instance for calling methods.
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));
}}
Output:
22
33
2) Method Overloading: changing data type of arguments
In this example, we have created two methods that differs in data type. The first add
method receives two integer arguments and second add method receives two
double 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));
}}
Output:
22
24.9
class Adder{
static int add(int a,int b){return a+b;}
static double add(int a,int b){return a+b;}
}
class TestOverloading3{
public static void main(String[] args){
System.out.println(Adder.add(11,11));//ambiguity
}}
Output:
Note: Compile Time Error is better than Run Time Error. So, java compiler renders
compiler time error if you declare the same method having same parameters.
class TestOverloading4{
public static void main(String[] args){System.out.println("main with String[]");}
public static void main(String args){System.out.println("main with String");}
public static void main(){System.out.println("main without args");}
}
Output:
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.
3) By anonymous object:
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:
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.