Download Example of default constructor - Vivek-IT

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Iteration Statement:
The process of repeatedly executing a statements and is called as looping. The
statements may be executed multiple times (from zero to infinite number). If a loop
executing continuous then it is called as Infinite loop. Looping is also called as
iterations.
In Iteration statement, there are three types of operation:
for loop
while loop
do-while loop
The for loop is entry controlled loop. It means that it provide a more conscious
loop control structure.
Syntax:
for(initialization; condition; iteration)//iteration means increment/decrement
{
Statement block;
}
When the loop is starts, first part(i.e. initialization) is execute. It is just like a counter
and provides the initial value of loop. But the thing is, Initialization is executed only
once. The next part( i.e. condition) is executed after the initialization. The important
thing is, this part provide the condition for looping. If the condition will satisfying then
loop will execute otherwise it will terminate.
Third part(i.e. iteration) is executed after the condition. The statements that
incremented or decremented the loop control variables.
while loop:
The while loop is entry controlled loop statement. The condition is evaluated, if the
condition is true then the block of statements or statement block is executed otherwise
the block of statement is not executed.
Syntax:
While(condition)
{
Statement block;
}
do-while loop:
In do-while loop, first attempt of loop should be execute then it check the condition.
The benefit of do-while loop/statement is that we get entry in loop and then condition
will check for very first time. In while loop, condition will check first and if condition
will not satisfied then the loop will not execute.
Syntax:
do
{
Statement block;
}
While(condition);
In program, when we use the do-while loop, then in very first attempt, it allows us
to get enter in loop and execute that loop and then check the condition.
Arrays:-> Array is a collection of similar type of data elements
-> Array is a references data type
-> A variable of type array is called reference variable
-> Java array is an object the contains elements of similar data type. It is a data
structure where we store similar elements. We can store only fixed set of elements
in a java array.
-> Reference variable hold address of array object
Advantage:1.avoiding declaring number of variables
2.grouping and referring all the values with one name
Disadvantage:1.Array is fixed in size once array is created the size cannot be
decreased or increased.
2.lots of wastage of memory.
Types of arrays:1.single dimensional array
2.multi dimensional array
3.Jagged array
1.Single dimensional array:An array with one subscript is called single dimensional array, in this
array data is organized by dividing into rows and multiple columns or
columns and multiple rows.
i)Declare Array
ii)Create Array
i)Declaring Array:On declaring of array memory is allocated for reference
variable,reference variable hold address of array.
SYNTAX:----<datatype><arrayname>[];
int a[];
int []a;
int[] a;
all methods are valid
'a' is a reference variable which hold address of array object..
ii)Creating Array:Arrays in java are dynamic, dynamic memory allocation is done
using new keyword or operator.
->Heap area is called dynamic memory area
->It is managed memory area
->Array is a object in java
->this object are created in heap area.
Example 1:
class Array1
{
public static void main(String args[])
{
int a[]=new int[10];//creates an array of size ten
System.out.println(a.length);//it is used to find the length of the array
System.out.println(a[0]);//a[index] is used to read the contents of the array
System.out.println(a[1]);
}
}
Example 2:
class Array2
{
public static void main(String args[])
{
int a[]=new int[0];
float b[]=new float[3];
char c[]=new char[3];
double d[]=new double[3];
String s[]=new String[3];
boolean j[]=new boolean[10];
System.out.println(a);
System.out.println(b);
System.out.println(c);//Character array reference doesn't print address
System.out.println(a.length);
System.out.println(c.length);
c[0]='a';
c[1]='b';
c[2]='c';
System.out.println(c);
System.out.println(d);
System.out.println(s);
System.out.println(j);
}
}
2. Multi dimensional array:An array with more than one subscript is called multi dimensional array, in this
array data is organized by dividing into multiple rows and multiple columns.
Example 1:
class TwoDimensionalDemo1
{
public static void main(String args[])
{
int a[][]=new int[3][3];
System.out.println(a);
System.out.println(a[0]);
System.out.println(a[1]);
System.out.println(a[0][0]);
System.out.println(a[0][1]);
System.out.println(a[1][0]);
System.out.println(a[1][1]);
a[1][1]=20;
System.out.println(a[1][1]);
System.out.println(a[0].length);
System.out.println(a[1].length);
System.out.println(a[2].length);
System.out.println(a.length);
}
}
Example 2:
//Write a program to read 3 Student subject and marks and display
import java.util.Scanner;
class ArrayDemo2
{
public static void main(String args[])
{
Scanner scan=new Scanner(System.in);
System.out.println("enter row size");
int a=scan.nextInt();
System.out.println("enter column size");
int b=scan.nextInt();
float marks[][]=new float[a][b];
String subject[][]=new String[a][b];
int i,j;
for(i=0;i<marks.length;i++)
{
for(j=0;j<marks.length;j++)
{
System.out.println("Enter subject Name");
subject[i][j]=scan.next();
System.out.println("input marks");
marks[i][j]=scan.nextFloat();
}
}
for(i=0;i<marks.length;i++)
{
for(j=0;j<marks.length;j++)
{
System.out.printf("\nSubjects entered are:%s\t",subject[i][j]);
System.out.print(marks[i][j]);
}
}
}
}
3. Jagged Array:-> Jagged array is multidimensional array with fixed number of rows and
variable length of columns
-> The number of columns hold by each row varies, it changes from one row to
another row.
Advantage:Avoiding wastage of memory
syntax
declare array
<data type> array_name
Example 1:-
import java.util.Scanner;
class ArrayDemo1
{
public static void main(String args[])
{
Scanner scan=new Scanner(System.in);
int scores[][]=new int[3][];
scores[0]=new int[2];
scores[1]=new int[1];
scores[2]=new int[3];
int i,j;
System.out.println("input Scores");
for(i=0;i<scores.length;i++)
{
for(j=0;j<scores[i].length;j++)
{
scores[i][j]=scan.nextInt();
}
}
for(int s[]:scores)
{
for(int r:s)
System.out.printf("%d\t",r);
System.out.println();
}
}
}
Console Input and Output:In Java, there are 3 ways to read input from a console :
1. BufferedReader + InputStreamReader (Classic)
2. Scanner (JDK 1.5)
3. System.console (JDK 1.6)
1. BufferedReader + InputStreamReader
For experienced Java developers, you will miss this classic way to read a system input.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ReadConsole
{
public static void main(String[] args)
{
BufferedReader br = null;
try
{
br = new BufferedReader(new InputStreamReader(System.in));
while (true)
{
System.out.print("Enter something : ");
String input = br.readLine();
if ("q".equals(input))
{
System.out.println("Exit!");
System.exit(0);
}
System.out.println("input : " + input);
System.out.println("-----------\n");
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (br != null)
{
try
{
br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}
Enter something : old and classic
input : old and classic
-----------
Enter something : q
Exit!
2. Scanner
In JDK 1.5, the developer starts to use java.util.Scanner to read system input.
ReadConsole2.java
package com.mkyong;
public class ReadConsole2
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
while (true)
{
System.out.print("Enter something : ");
String input = scanner.nextLine();
if ("q".equals(input))
{
System.out.println("Exit!");
break;
}
System.out.println("input : " + input);
System.out.println("-----------\n");
}
scanner.close();
}
}
Output
Enter something : hello jdk 1.5
input : hello jdk 1.5
-----------
Enter something : scanner example
input : scanner example
-----------
Enter something : q
Exit!
3. System.console
In JDK 1.6, the developer starts to switch to the more simple and
powerful java.io.Console class.
ReadConsole3.java
public class ReadConsole3
{
public static void main(String[] args)
{
while (true)
{
System.out.print("Enter something : ");
String input = System.console().readLine();
if ("q".equals(input))
{
System.out.println("Exit!");
System.exit(0);
}
System.out.println("input : " + input);
System.out.println("-----------\n");
}
}
}
Output
Enter something : hello jdk 1.6
input : hello jdk 1.6
----------Enter something : console example
input : console example
----------Enter something : q
Exit!
Formatting
Stream objects that implement formatting are instances of either PrintWriter, a
character stream class, or PrintStream, a byte stream class.
Like all byte and character stream objects, instances
of PrintStream and PrintWriter implement a standard set of write methods for simple
byte and character output. In addition, both PrintStream and PrintWriter implement the
same set of methods for converting internal data into formatted output. Two levels of
formatting are provided:


print and println format individual values in a standard way.
format formats almost any number of values based on a format string, with
many options for precise formatting.
The print and println Methods
Invoking print or println outputs a single value after converting the value using the
appropriate toString method. We can see this in the Root example:
public class Root {
public static void main(String[] args) {
int i = 2;
double r = Math.sqrt(i);
System.out.print("The square root of ");
System.out.print(i);
System.out.print(" is ");
System.out.print(r);
System.out.println(".");
i = 5;
r = Math.sqrt(i);
System.out.println("The square root of " + i + " is " + r + ".");
}
}
Here is the output of Root:
The square root of 2 is 1.4142135623730951.
The square root of 5 is 2.23606797749979.
The format Method
The format method formats multiple arguments based on a format string. The format
string consists of static text embedded with format specifiers; except for the format
specifiers, the format string is output unchanged.
Format strings support many features. In this tutorial, we'll just cover some basics. For a
complete description, see format string syntax in the API specification.
The Root2 example formats two values with a single format invocation:
public class Root2
{
public static void main(String[] args)
{
int i = 2;
double r = Math.sqrt(i);
System.out.format("The square root of %d is %f.%n", i, r);
}
}
Here is the output:
The square root of 2 is 1.414214.
Like the three used in this example, all format specifiers begin with a % and end with a
1- or 2-character conversion that specifies the kind of formatted output being generated.
The three conversions used here are:



d formats an integer value as a decimal value.
f formats a floating point value as a decimal value.
n outputs a platform-specific line terminator.
Constructor in Java
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e.
provides data for the object that is why it is known as constructor.
Rules for creating java constructor
There are basically two rules defined for the constructor.
1. Constructor name must be same as its class name
2. Constructor must have no explicit return type
Types of java constructors
There are two types of constructors:
1. Default constructor (no-arg constructor)
2. Parameterized constructor
Java Default Constructor
A constructor that have no parameter is known as default constructor.
Syntax of default constructor:
<class_name>(){}
Example of default constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be
invoked at the time of object creation.
class Bike1
{
Bike1()
{
System.out.println("Bike is created");
}
public static void main(String args[])
{
Bike1 b=new Bike1();
}
}
Output:
Bike is created
Rule: If there is no constructor in a class, compiler automatically creates a default
constructor.
Q) What is the purpose of default constructor?
Default constructor provides the default values to the object like 0, null etc. depending
on the type.
Example of default constructor that displays the default values
class Student3
{
int id;
String name;
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student3 s1=new Student3();
Student3 s2=new Student3();
s1.display();
s2.display();
}
}
Output:
0 null
0 null
Java parameterized constructor
A constructor that have parameters is known as parameterized constructor.
Why use parameterized constructor?
Parameterized constructor is used to provide different values to the distinct objects.
Example of parameterized constructor
In this example, we have created the constructor of Student class that have two
parameters. We can have any number of parameters in the constructor.
class Student4{
int id;
String name;
Student4(int i,String n){
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
Output:
111 Karan
222 Aryan
Constructor Overloading in Java
Constructor overloading is a technique in Java in which a class can have any number
of constructors that differ in parameter lists.The compiler differentiates these
constructors by taking into account the number of parameters in the list and their
type.
Example of Constructor Overloading
class Student5
{
int id;
String name;
int age;
Student5(int i,String n) // Parameterized Constructor
{
id = i;
name = n;
}
Student5(int i,String n,int a)
{
id = i;
name = n;
age=a;
}
void display()
{
System.out.println(id+" "+name+" "+age);
}
public static void main(String args[])
{
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
Output:
111 Karan 0
222 Aryan 25
Difference between constructor and method in java
There are many differences between constructors and methods. They are given below.
Java Constructor
Java Method
Constructor is used to initialize the state of an
object.
Method is used to expose behavior of an object.
Constructor must not have return type.
Method must have return type.
Constructor is invoked implicitly.
Method is invoked explicitly.
The java compiler provides a default constructor
if you don't have any constructor.
Method is not provided by compiler in any case.
Constructor name must be same as the class
Method name may or may not be same as class name.
name.
Method Overloading in Java
If a class have multiple methods by same name but different parameters, it is known
as Method Overloading.
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. So, we
perform method overloading to figure out the program quickly.
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
Example of Method Overloading by changing the no. of arguments
In this example, we have created two overloaded methods, first sum method performs
addition of two numbers and second sum method performs addition of three numbers.
class Calculation{
void sum(int a,int b)
{
System.out.println(a+b);
}
void sum(int a,int b,int c)
{
System.out.println(a+b+c);
}
public static void main(String args[])
{
Calculation obj=new Calculation();
obj.sum(10,10,10);
obj.sum(20,20);
}
}
Output: 30
40
Example of Method Overloading by changing data type of argument
In this example, we have created two overloaded methods that differs in data type. The
first sum method receives two integer arguments and second sum method receives two
double arguments.
class Calculation2
{
void sum(int a,int b)
{
System.out.println(a+b);
}
void sum(double a,double b)
{
System.out.println(a+b);
}
public static void main(String args[])
{
Calculation2 obj=new Calculation2();
obj.sum(10.5,10.5);
obj.sum(20,20);
}
}
Output: 21.0
40
Java static keyword
The static keyword in java is used for memory management mainly. We can apply java
static keyword with variables, methods, blocks and nested class. The static keyword
belongs to the class than instance of the class.
The static can be:
1.
2.
3.
4.
variable (also known as class variable)
method (also known as class method)
block
nested class
1) Java static variable
If you declare any variable as static, it is known static variable.
o
o
The static variable can be used to refer the common property of all objects (that
is not unique for each object) e.g. company name of employees,college name of
students etc.
The static variable gets memory only once in class area at the time of class
loading.
Advantage of static variable
It makes your program memory efficient (i.e it saves memory).
Understanding problem without static variable
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 object is created.All student have its unique rollno and name
so instance data member is good.Here, college refers to the common property of all
objects.If we make it static,this field will get memory only once.
Note:- Java static property is shared to all objects
Example of static variable
//Program of static variable
class Student8{
int rollno;
String name;
static String college ="ITS";
Student8(int r,String n)
{
rollno = r;
name = n;
}
void display ()
{
System.out.println(rollno+" "+name+" "+college);
}
public static void main(String args[])
{
Student8 s1 = new Student8(111,"Karan");
Student8 s2 = new Student8(222,"Aryan");
s1.display();
s2.display();
}
}
Output:111 Karan ITS
222 Aryan ITS
Program of counter without static variable
In this example, we have created an instance variable named count which is
incremented in the constructor. Since instance variable gets the memory at the time of
object creation, each object will have the copy of the instance variable, if it is
incremented, it won't reflect to other objects. So each objects will have the value 1 in
the count variable.
class Counter{
int count=0;//will get memory when instance is created
Counter(){
count++;
System.out.println(count);
}
public static void main(String args[]){
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
}
Output:
1
1
1
Program of counter by static variable
As we have mentioned above, static variable will get the memory only once, if any
object changes the value of the static variable, it will retain its value.
class Counter2{
static int count=0;//will get memory only once and retain its value
Counter2(){
count++;
System.out.println(count);
}
public static void main(String args[]){
Counter2 c1=new Counter2();
Counter2 c2=new Counter2();
Counter2 c3=new Counter2();
}
}
Output:
1
2
3
2) Java static method
If you apply static keyword with any method, it is known as static method.
o
o
o
A static method belongs to the class rather than object of a class.
A static method can be invoked without the need for creating an instance of a
class.
static method can access static data member and can change the value of it.
Example of static method
1. //Program of changing the common property of all objects(static field).
class Student9{
int rollno;
String name;
static String college = "ITS";
static void change()
{
college = "BBDIT";
}
Student9(int r, String n)
{
rollno = r;
name = n;
}
void display ()
{
System.out.println(rollno+" "+name+" "+college);
}
public static void main(String args[])
{
Student9.change();
Student9 s1 = new Student9 (111,"Karan");
Student9 s2 = new Student9 (222,"Aryan");
Student9 s3 = new Student9 (333,"Sonoo");
s1.display();
s2.display();
s3.display();
}
}
Output:
111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT
Another example of static method that performs normal calculation
//Program to get cube of a given number by static method
class Calculate
{
static int cube(int x)
{
return x*x*x;
}
public static void main(String args[])
{
int result=Calculate.cube(5);
System.out.println(result);
}
}
Output:125
Restrictions for static method
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
public static void main(String args[])
{
System.out.println(a);
}
}
Output:
Compile Time Error
3) Java static block
o
o
Is used to initialize the static data member.
It is executed before main method at the time of classloading.
Example of static block
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
Access Modifiers in java:There are two types of modifiers in java:
1.access modifiers
2.non-access modifiers.
The access modifiers in java specifies accessibility (scope) of a data member, method,
constructor or class.
There are 4 types of java access modifiers:
1.
2.
3.
4.
private
default
protected
public
There are many non-access modifiers such as static, abstract, synchronized, native,
volatile, transient etc. Here, we will learn access modifiers.
1) private access modifier
The private access modifier is accessible only within class.
Simple example of private access modifier
In this example, we have created two classes A and Simple. A class contains private
data member and private method. We are accessing these private members from
outside the class, so there is compile time error.
class A
{
private int data=40;
private void msg()
{
System.out.println("Hello java");}
}
public class Simple
{
public static void main(String args[])
{
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
Role of Private Constructor
If you make any class constructor private, you cannot create the instance of that class
from outside the class. For example:
class A
{
private A()//private constructor
{
}
void msg()
{
System.out.println("Hello java");}
}
public class Simple
{
public static void main(String args[])
{
A obj=new A();//Compile Time Error
}
}
Note: A class cannot be private or protected except nested class.
2) default access modifier
If you don't use any modifier, it is treated as default by default. The default modifier
is accessible only within package.
Example of default access modifier
In this example, we have created two packages pack and mypack. We are accessing
the A class from outside its package, since A class is not public, so it cannot be
accessed from outside the package.
//save by A.java
package pack;
class A
{
void msg()
{
System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot
be accessed from outside the package.
3) protected access modifier
The protected access modifier is accessible within package and outside the package
but through inheritance only.
The protected access modifier can be applied on the data member, method and
constructor. It can't be applied on the class.
Example of protected access modifier
In this example, we have created the two packages pack and mypack. The A class of
pack package is public, so can be accessed from outside the package. But msg method
of this package is declared as protected, so it can be accessed from outside the class
only through inheritance.
//save by A.java
package pack;
public class A
{
protected void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B extends A
{
public static void main(String args[])
{
B obj = new B();
obj.msg();
}
}
Output: Hello
4) public access modifier
The public access modifier is accessible everywhere. It has the widest scope among
all other modifiers.
Example of public access modifier
//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
Output: Hello
Understanding all java access modifiers
Let's understand the access modifiers by a simple table.
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
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.
Usage of java this keyword
Here is given the 6 usage of java this keyword.
1. this keyword can be used to refer current class instance variable.
2.
3.
4.
5.
6.
this() can be used to invoke current class constructor.
this keyword can be used to invoke current class method (implicitly)
this can be passed as an argument in the method call.
this can be passed as argument in the constructor call.
this keyword can also be used to return the current class instance.
1) The this keyword can be used to refer current class instance
variable.
If there is ambiguity between the instance variable and parameter, this keyword
resolves the problem of ambiguity.
Understanding the problem without this keyword
Let's understand the problem if we don't use this keyword by the example given
below:
class Student10
{
int id;
String name;
Student10(int id,String name)
{
id = id;
name = name;
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student10 s1 = new Student10(111,"Karan");
Student10 s2 = new Student10(321,"Aryan");
s1.display();
s2.display();
}
}
Output: 0 null
0 null
In the above example, parameter (formal arguments) and instance variables are same
that is why we are using this keyword to distinguish between local variable and
instance variable.
Solution of the above problem by this keyword
//example of this keyword
class Student11
{
int id;
String name;
Student11(int id,String name)
{
this.id = id;
this.name = name;
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student11 s1 = new Student11(111,"Karan");
Student11 s2 = new Student11(222,"Aryan");
s1.display();
s2.display();
}
}
Output
111 Karan
222 Aryan
2) this() can be used to invoked current class constructor.
The this() constructor call can be used to invoke the current class constructor
(constructor chaining). This approach is better if you have many constructors in the
class and want to reuse that constructor.
//Program of this() constructor call (constructor chaining)
class Student13{
int id;
String name;
Student13(){System.out.println("default constructor is invoked");}
Student13(int id,String name){
this ();//it is used to invoked current class constructor.
this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student13 e1 = new Student13(111,"karan");
Student13 e2 = new Student13(222,"Aryan");
e1.display();
e2.display();
}
}
Output:
default constructor is invoked
default constructor is invoked
111 Karan
222 Aryan
Where to use this() constructor call?
The this() constructor call should be used to reuse the constructor in the constructor.
It maintains the chain between the constructors i.e. it is used for constructor chaining.
Let's see the example given below that displays the actual use of this keyword.
class Student14{
int id;
String name;
String city;
Student14(int id,String name){
this.id = id;
this.name = name;
}
Student14(int id,String name,String city){
this(id,name);//now no need to initialize id and name
this.city=city;
}
void display(){System.out.println(id+" "+name+" "+city);}
public static void main(String args[]){
Student14 e1 = new Student14(111,"karan");
Student14 e2 = new Student14(222,"Aryan","delhi");
e1.display();
e2.display();
}
}
Output:
111 Karan null
222 Aryan delhi
Rule: Call to this() must be the first statement in constructor
Recursion
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
}
Java Recursion Example 1: Infinite times
public class RecursionExample1
{
static void p()
{
System.out.println("hello");
p();
}
public static void main(String[] args)
{
p();
}
}
Output:
hello
hello
...
Java Recursion Example 2: Finite times
public class RecursionExample2
{
static int count=0;
static void p()
{
count++;
if(count<=5)
{
System.out.println("hello "+count);
p();
}
}
public static void main(String[] args)
{
p();
}
}
Output:
hello 1
hello 2
hello 3
hello 4
hello 5
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.
Advantage of Garbage Collection
o
o
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.
How can an object be unreferenced?
There are many ways:
o
o
o
By nulling the reference
By assigning a reference to another
By annonymous object etc.
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 annonymous object:
new Employee();
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:
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();
}
}
OUTPUT:object is garbage collected
object is garbage collected