Java Unit2
Java Unit2
SYLLABUS
PROGRAMMING CONSTRUCTS
Arrays-one dimensional and multidimensional -command line arguments. Introducing classes –
class fundamentals –methods -objects -constructors –this keyword –-garbage collection-Nested
Classes – Polymorphism
Arrays
An array is a data structure which represents a group of elements of same type.
By using arrays we can store group of int values or a group of float values or group of strings in the
array. But we cannot store all data type values in the same array.
In Java, arrays are created on dynamic memory allocated by JVM at runtime.
Types of arrays:
1) Single dimensional array
2) Multi-dimensional array(2D, 3D, .. arrays)
Advantage of Java Array:
1) Code Optimization: It makes the code optimized; we can retrieve or sort the data easily.
2) Random access: We can get any data located at any index position.
Disadvantage of Java Array:
1) Size Limit: We can store only fixed size of elements in the array.
2) It doesn't grow its size at runtime. To solve this problem, collection framework is used in java.
Program 1: A java program of single dimensional array with declaration and instantiation
class Testarray
{
public static void main(String args[])
{
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
OUTPUT:
10
20
70
40
50
class Testarray1
{
public static void main(String args[])
{
int a[]={9,13,6,3};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
OUTPUT:
9
13
6
3
Program 4: A java program to find out total marks and percentage of student with 1D array
import java.io.*;
class OneArray
{
public static void main(String args[ ])
{
BufferedReader br = new BufferedReader(new InputStream(System.in));
Sysytem.out.println(“How many subjects: ?”);
int n = Integer.parseInt(br.readLine( ));
int[ ] marks = new int[n];
//store elements into array
for(int i=0; i<n; i++)
{
System.out.println(“Enter marks”);
Mraks[i] = Integer.parseInt(br.readLine( ));
}
//find total marks
int tot = 0;
for(int i=0;i<n;i++)
{
tot = tot + marks[i];
}
System.out.println(“Total marks =” +tot);
// find percent
float percent = (float)tot/n;
System.out.println(“Percentage =”+percent);
}
}
Multi-Dimensional Array:
Multi-dimensional arrays represents 2D, 3D,.. arrays which are combinations of several types of
arrays.
In this, data is stored in row and column based index also known as matrix form.
For example, a two dimensional array is a combination of two or more 1D arrays and 3D arrays means
a combination of two or more 2D arrays.
Syntax for two dimensional:
1. dataType[][] arrayRefVar; (or)
2. dataType [][]arrayRefVar; (or)
3. dataType arrayRefVar[][]; (or)
4. dataType []arrayRefVar[];
Example to instantiate Multidimensional Array:
int[][] arr=new int[3][3];//3 row and 3 column
Example to initialize Multidimensional
Array arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
We can declare a two dimensional array and directly store elements at the time of its declaration
as: int marks [ ] [ ] = { { 50, 60, 55, 67, 70}, { 62, 65, 70, 74, 70}, { 72, 66, 77, 80, 69}};
Here ‘int’ represents integer type elements stored into array, and the array name is ‘marks’. To
represent a two dimensional array, we should use two pairs of square braces [ ] and [ ] after the array
name.
Each row of elements should be written inside the curly braces { }.
The rows in each row should be separated by commas.
So there are 3 rows and 5 columns in each row then the JVM creates 3X5 = 15 blocks of memory as
there are 15 elements being stored into the array.
These blocks of memory can be individually referenced to as mentioned here:
marks[0][0], marks[0][1], marks[0][2], marks[0][3], marks[0][4]
marks[1][0], marks[1][1], marks[1][2], marks[1][3], marks[1][4]
marks[2][0], marks[2][1], marks[2][2], marks[2][3], marks[2][4]
The elements in the array can be referred as “marks[i][j]”, where ‘i’ represents row position and ‘j’
represents column position.
The memory arrangement of elements in a 2D array as follows:
OUTPUT:
Enter rows, columns? 3 4
Enter elements of matrix:
1 2 3 4
5 6 7 8
9 9 -1 2
The transpose matrix:
1 5 9
2 6 9
3 7 -1
1 2
Program 7: A java program Addition of Matrix
class MatrixAdd
{
public static void main(String args[])
{
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
- Above all methods are non-static methods, so we must access with object.
Program 1: A java program to read the input values using ‘Scanner’ class
import java.util.Scanner;
class Demo
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
System.out.println(“Enter first number:”);
int x = sc.nextInt( );
System.out.println(“Enter second number:”);
int y = sc.nextInt( );
int z = x + y;
System.out.println(“Result is:”+z);
}
}
OUTPUT:
Enter first number:
25
Enter second number:
10
Result is:
35
}
OUTPUT:
>javac CmdDemo.java
>java CmdDemo 10 20
Before Converting
1020
After Converting
30
Program : A java program to accept and display a character from the keyboard
import java.io.*;
class Accept
{
public static void main (String args[ ]) throws IOException
{
//create BufferedReader object to accept data from keyboard
BufferedReader br = new BufferedReader( new InputStreamReader(System.in));
System.out.println(“Enter a character:”);
Char ch = (char)br.read( );
System.out.println(“You entered:” +ch);
}
}
OUTPUT:
Enter a character: A
You entered: A
Program : A java program to accept and display a String of characters from the keyboard
import java.io.*;
class Accept
{
public static void main (String args[ ]) throws IOException
{
BufferedReader br = new BufferedReader( new InputStreamReader(System.in));
System.out.println(“Enter a name:”);
Stringname =br.readLine( );
System.out.println(“You entered:” +name);
}
}
OUTPUT:
Enter a name: Java
You entered: Java
To accept an integer value from the keyboard, follow the below steps:
1) First, accept the integer number from the keyboard as a string using readLine( ) method.
String str = br.readLine( );
2) The readLine( ) method return type is Integer. So this should be converted into an int by using
parseInt( ) method of Integer class in ‘java.lang’ package and parseInt( ) is a static method in
Integer class so it can be called by using classname, as follows:
int n = Integer.parseInt(str);
3) We can combine the above two steps in a single statement as follows:
int n = Integer.parseInt(br.readLine( ));
OUTPUT:
Enter a value: 1234
You entered: 1234
OUTPUT:
Enter a float: 12.34
You entered: 12.34
OUTPUT:
Enter a double value: 123456.789
You entered: 123456.789
Similarly, we can write different statements to accept many other data types from the keyboard as
follows:
1) To accept a byte value.
byte n = Byte.parseByte(br.readLine( ));
2) To accept a short value.
short n = Short.parseShort(br.readLine( ));
3) To accept a long value.
long n = Long.parseLong(br.readLine( ));
4) To accept a boolean value.
boolean n = Boolean.parseBoolean(br.readLine( ));
The classes like Byte, Short, Integer, Long, Float, Double and Boolean belongs to “java.lang”
package. These classes are called as WRAPPER CLASSES.
Program : A java program that accepting and displaying employee details
import java.io.*;
import java.lang.*;
class a
{
public static void main (String args[ ]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Emp id:");
int id = Integer.parseInt(br.readLine( ));
System.out.println("Enter Emp name:");
String name = br.readLine( );
System.out.println("Enter Emp salary:");
float sal = Float.parseFloat(br.readLine( ));
//display the employee details
System.out.println("Emp Id is:" +id);
System.out.println("Emp name:" +name);
System.out.println("Emp sal is:" +sal);
}
}
Objects in Java:
Class in Java:
A class is a group of objects which have common properties. It is a logical entity. It can't be physical.
A class in Java can contain:
1. variable
2. methods
3. constructors
4. blocks
5. nested class and interface
Variable in Java:
A variable which is created inside the class but outside the method is known as instance variable.
Instance variable doesn't get memory at compile time. It gets memory at run time when
object(instance) is created. That is why, it is known as instance variable.
Method in Java:
In java, a method is like function i.e. used to expose behavior of an object.
Advantages of method are: Code Reusability and Code Optimization.
OUTPUT:
0
null
OUTPUT
0
null
class Student
{
int id;
String name;
}
class TestStudent2
{
public static void main(String args[])
{
Student s1=new Student( );
s1.id=101;
s1.name="Abc";
System.out.println(s1.id+" "+s1.name);//printing members with a white space
}
}
OUTPUT:
101 Abc
class Student
{
int id;
String name;
}
class TestStudent3
{
public static void main(String args[])
{
//Creating objects
Student s1=new Student( );
Student s2=new Student( );
//Initializing objects
s1.id=101;
s1.name="Abc";
s2.id=102;
s2.name="Xyz";
System.out.println(s1.id+" "+s1.name);
System.out.println(s2.id+" "+s2.name);
}
}
OUTPUT:
101 Abc
102 Xyz
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
Program : A java program to store employee records
class Employee
{
int id;
String name;
float salary;
void insert(int i, String n, float s) {
id=i;
name=n;
salary=s
;
}
void display( ){System.out.println(id+" "+name+" "+salary);}
}
public class TestEmployee
{
public static void main(String[] args)
{
Employee e1=new Employee( );
Employee e2=new Employee( );
Employee e3=new Employee( );
e1.insert(101,"ajeet",45000);
e2.insert(102,"irfan",25000);
e3.insert(103,"nakul",55000);
e1.display( );
e2.display( );
e3.display( );
}
}
OUTPUT:
101 ajeet 45000.0
102 irfan 25000.0
103 nakul 55000.0
Example Program:
class Calculation
{
void fact(int n)
{
int fact=1;
for(int i=1;i<=n;i++)
{
fact=fact*i;
}
System.out.println("factorial is "+fact);
}
public static void main(String args[])
{
new Calculation( ).fact(5);//calling method with anonymous object
}
}
OUTPUT:
Factorial is 120
Access Specifiers:
An access specifier is a keyword that specifies how to access the members of class or a class itself.
We can use access specifiers before a class and its members.
There are 4 access specifiers mainly available in java are as follows.
Private: ‘private’ members of a class are not accessible anywhere outside the class. They are
accessible only within the methods of the same class.
Public: ‘public’ members of a class are accessible everywhere outside the class. So any other
program can read them and use them.
Protected: ‘protected’ members of a class are accessible outside the class, but generally within the
same directory.
default: If no access specifier is written by the programmer, then the java compiler uses a
‘default’ access specifier. ‘default’ members are accessible outside the class but within the same
directory.
Note:
In real time, we generally use ‘private’ for instance variables and ‘public’ for methods.
In java, classes cannot be declared by using ‘private’.
Access Modifier:
These are the keywords in java language used to change the current behavior of methods (or)
variables.
Every access modifier is a ‘keyword’ but every keyword is not an access modifier.
In java language there are 4 types of access specifiers:
1) default
2) private
3) protected
4) public
If any variable or method is not preceded by “private/protected/public” then that properties are treated
as ‘default’ properties.
//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
}
}
OUTPUT:
Compile time error
//save by A.java
package pack;
public class A
{
public 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( );
obj.msg( );
}
}
OUTPUT:
Hello
Methods in Java:
Def: A method represents a group of statements that performs a task. A task represents a calculation or
processing of data or generating a report etc.
A method has two parts:
1) Method header or Method prototype
2) Method body
The method header contains method return datatype, method name, method parameter.
The method body contains business logic.
Method Syntax:
returntype methodName (parameter 1, parameter 2, …)
{
// method body
}
In the above syntax, ‘methodname’ can be any user defined name and the main business logic must
be written inside the method body.
Parameters:
The ‘parameters’ represents the “input”, it can be any of following 3 types:
1) No parameter (empty):Method performs an operation without accepting any input.
2) Primitive datatype: Method performs an operation by accepting single input value.
3) Reference datatype: Method performs an operation by accepting multiple input values in the form
of “object”.
Returntype:
‘returntype’ represents “output”, it can be any of following 3 types:
1) No return type (void):Method does not return the output to other method from where it is calling.
2) Primitive datatype: Method returns a single output value to the other method.
3) Reference data type: Method returns multiple output values in the form of ‘object’ to the other
method.
Primitive data type: This is a data type whose variable can handle maximum one value at a time. For
example: byte, short, int, long, float, double, char and Boolean
Reference data type: It is a data type whose variable can handle more than one value in the form of
‘object’.
Note: If the result (output) of one method wants to be used inside the other method then the return
type of the first method should be either ‘primitive’ (or) ‘reference’ data type.
Types of method:
1. Non-static/ Instance method
2. Static method
Instance Method:
If any method is not preceded by ‘static’ keyword is known as ‘Non-static’ or ‘Instance’ method.
Syntax:
returntype methodname( )
{
-----
-----
}
In real time, it is highly recommended to define instance methods onlyif any method wants to perform
an operation only on ‘Instance variables’.
Non-static method should be accessed with ‘object’.
For non-static method memory is allocated only once at that time of object calling.
Static Method:
If any method is preceded by ‘static’ method known as static method.
Syntax:
static returntype methodname( )
{
-----
-----
}
In real time, it is highly recommended to define the static methods to perform an operation only on
static variables.
Static methods should be accessed with ‘class name’.
For static method, memory is allocated only once at that time of loading of class.
If any method definition is preceded by ‘static’ keyword is known as “static method”, it must be
accessed with ‘classname’.
If any method definition is not preceded by ‘static’ keyword is known as “non-static method” or
“instance method”, it must be accessed with ‘object’.
Syntax No 1:
void methodname( )
{
-----
-----
}
- In the above syntax 1, it is use to perform an operation without accepting any input values and
does not returns any output to the other method
- Syntax to call a non-static method:
object.methodname( );
- Syntax to call a static method:
classname.methodname( );
Syntax No 2:
void methodname( primitivedatatype variable)
{
-----
-----
}
- In the above syntax 2, it is use to perform an operation by accepting single input value and does
not returns any output to the other method.
- Syntax to call a non-static method:
object.methodname( value);
- Syntax to call a static method:
classname.methodname( value);
Syntax No 3:
void methodname( Referencedatatype variable)
{
-----
-----
}
- In the above syntax 3, it is use to perform an operation by accepting multiple input values in the
form of object and does not returns any output to the other method.
- Syntax to call a non-static method:
object.methodname( object);
- Syntax to call a static method:
classname.methodname(object);
Syntax No 4:
primitivedatatype methodname( )
{
-----
-----
return value;
}
- In the above syntax 4, it is use to perform an operation without accepting any input values and
returns a single output value to the other method.
- Syntax to call a non-static method:
primitivedatatype variablename = object.methodname( );
- Syntax to call a static method:
primitivedatatype variablename = classname.methodname( );
Syntax No 5:
primitivedatatype methodname( primitivedatatype variable)
{
-----
-----
return value;
}
- In the above syntax 5, it is use to perform an operation by accepting single input value and returns
single output value to the other method.
- Syntax to call a non-static method:
primitivedatatype variablename= object.methodname( value);
- Syntax to call a static method:
primitivedatatype variablename = classname.methodname( value);
Syntax No 6:
primitivedatatype methodname( referencedatatype variable)
{
-----
-----
return value;
}
- In the above syntax 6, it is use to perform an operation by accepting multiple input values in the
form of object and returns single output value to the other method.
- Syntax to call a non-static method:
Classname objectreference = object.methodname( object);
- Syntax to call a static method:
Classname objectreference = classname.methodname(object);
Syntax No 7:
Referencedatatype methodname( )
{
-----
-----
return object;
}
- In the above syntax 7, it is use to perform an operation without accepting any input values and
returns multiple output values in the form of object to the other method.
- Syntax to call a non-static method:
Classname objectreference = object.methodname( );
- Syntax to call a static method:
Classname objectreference = classname.methodname( );
Syntax No 8:
Referencedatatype methodname(primitivedatatype variable )
{
-----
-----
return object;
}
- In the above syntax 8, it is use to perform an operation by accepting single input value and returns
multiple output values in the form of object to the other method.
- Syntax to call a non-static method:
Classname objectreference = object.methodname(value);
- Syntax to call a static method:
Classname objectreference = classname.methodname( value);
Syntax No 9:
Referencedatatype methodname(Referencedatatype variable )
{
-----
-----
return object;
}
- In the above syntax 9, it is use to perform an operation by accepting multiple input value and
returns multiple output values in the form of object to the other method.
- Syntax to call a non-static method:
Classname objectreference = object.methodname(object);
- Syntax to call a static method:
Classname objectreference = classname.methodname( object);
Following table shows how to access both static and non-static properties within the non-static and
static methods of same class or other class:
Within the non- Within the Within the non- Within the static
Type of
static method of static method static method of method of other
Property
same class of same class other class class
1. Non-static Can be used Can be accessed Can be accessed Can be accessed
method/variable directly by using object by using object by using object
Can be accessed Can be accessed Can be accessed Can be accessed
2. Static
directly / using directly / using by using class by using class
method/variable
class name class name name name
}
}
class B
{
void f4( ) //non-static method
{
new A( ).f1( );
A.f3( );
}
static void f5( )
{
new A( ).f1( );
A.f3( );
}
}
class MethodDemo
{
public static method(String args[ ])
{
A.f3( );
new B( ).f4( );
B.f5( );
B.f4( );//Not possible because f4( ) is a non-static method so we cannot call by class
//name. If requires we can access the f4( ) by creating an object.
}
}
Program 5: A java program for a method without parameters and without return type
class Sample
{
private double, num1, num2;
void sum( )
{
double res = num1 + num2;
System.out.println(“Sum=” +res);
}
}
class Methods
{
public static void main(String a[ ])
{
Sampe s = new Sample( );
s.sum( );
}
}
Program6 : A java program for a method without parameters and with return type
class Sample
{
private double num1, num2;
double sum( )
{
double res = num1 + num2;
return res;
}
}
class Methods
{
public static void main(String a[ ])
{
Sample s = new Sample( );
double x = s.sum( );
System.out.println(“Sum=” +x);
}
}
Program 7: A java program for a method with two parameters and with return type
class Sample
{
double sum(int num1, double num2)
{
double res = num1 + num2;
return res;
}
}
class Methods
{
public static void main(String a[ ])
{
Sample s = new Sample( );
double x = s.sum(10, 22.5);
System.out.println(“Sum =” +x);
}
}
Program 8: A java program for a static method that accepts data and return the result
class Sample
{
static double sum(double num1, double num2)
{
double res = num1 + num2;
return res;
}
class Methods
{
public static void main(String a[ ])
{
double x = Sample.sum(10, 22.5);
System.out.println(“Sum=” +x);
}
}
Program 9: A java program to test whether a static method can access the instance variable or not
class Test
{
int x;
static void access( )
{
System.out.println(“x =”+x);
}
}
class Demo
{
public static void main(String args[ ])
{
Test.access( );
}
}
Program 10: A java program to test whether a static method can access the static variable or not
class Test
{
static int x = 55;
static void access( )
{
System.out.println(“X =” +x);
}
}
class Demo
{
public static void main(String args[ ])
{
Test.access( );
}
}
Program 11: A java program by taking an instance variable x in the Test class
class Test
{
int x = 10;
void display( )
{
System.out.println(x);
}
}
class InstanceDemo
{
public static void main(String args[ ])
{
Test obj1, obj2;
obj1= new Test( );
obj2= new Test( );
++obj1.x;
System.out.println(“X in obj1: “);
obj1.display( );
System.out.println(“X in obj2: “);
obj2.display( );
}
}
OUTPUT:
X in obj1: 11
X in obj2: 10
Program 12: A java program by taking a static variable x in the Test class
class Test
{
static int x = 10;
static void display( )
{
System.out.println(x);
}
}
class StaticDemo
{
public static void main(String args[ ])
{
Test obj1, obj2;
obj1= new Test( );
obj2= new Test( );
++obj1.x;
System.out.println(“X in obj1: “);
obj1.display( );
System.out.println(“X in obj2: “);
obj2.display( );
}
}
OUTPUT:
X in obj1: 11
X in obj2: 11
In the program 30, we have created two methods, first add( ) method performs addition of two
numbers and second add method performs addition of three numbers.
In this example, we are creating static methods so that we don't need to create instance for calling
methods.
Class sample
{
//method
void add(int a ,int b)
{
System.out.println(“sum of two numbers=”+(a+b));
}
//method
void add(float a,float b,float c)
{
System.out.println(“sum of three numbers=”+(a+b+c));
}
}
class poly
{
//main method
Public static void main(String args[])
{
//creating object
sample s=new sample();
s.add(10,20);
s.add(1.5f,2.5f,3.5f);
}
}
OUTPUT:
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
Method Overloading: changing data type of arguments
In the above program , we have created two methods that differ in data type. The first add method
receives two integer arguments and second add method receives two double arguments.
In method overloading, is not possible by changing the return type of the method only because of
ambiguity.
Example program:
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:
Compile Time Error: method add(int,int) is already defined in class Adder
Program : A Java Program with Type Promotion in case of ambiguity in method overloading
class OverloadingCalculation3
{
void sum(int a, long b)
{
System.out.println("a method invoked");
}
void sum(long a, int b)
{
System.out.println("b method invoked");
}
public static void main(String args[])
{
OverloadingCalculation3 obj=new OverloadingCalculation3( );
obj.sum(20,20);//now ambiguity
}
}
OUTPUT:
Compile Time Error
Parameterized Constructor:
If any constructor contains list of parameters in its signature is known as ‘parameterized constructor’.
Syntax:
classname (list of parameters)
{
//Initialization code
}
Syntax to call the parametrized constructor:
- classname objreference = new classname(arguments); // constructor calling with referenced object
- new classname(arguments); //constructor calling without referenced object
//parameterized constructor
rectangle(int l,int b)
{
length=l;
breadth=b;
}
//method
void area()
{
System.out.println("The area of rectangle="+(length*breadth));
}
}
class parameterized
{
public static void main(String args[])
{
rectangle r=new rectangle(5,10);
r.area();
}
}
OUTPUT:
class rectangle
{
//instance variable
int length;
int breadth;
//default constructor
rectangle()
{
length=5;
breadth=6;
}
//method
void area()
{
System.out.println("The area of rectangle="+(length*breadth));
}
}
class constructoroverloading
{
public static void main(String args[])
{
rectangle r=new rectangle();
r.area();
}
}
OUTPUT:
Program : A java program on 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
Program : A java program for a method with two parameters and with return type with constructor
class Sample
{
Private double num1, num2;
Sample(double x, double y)
{
num1 = x;
num2 = y;
}
double sum(int num1, double num2)
{
double res = num1 + num2;
return res;
}
}
class Methods
{
public static void main(String a[ ])
{
Sample s = new Sample(10.9,23.6 );
double x = s.sum(10, 22.5);
System.out.println(“Sum =” +x);
}
}
OUTPUT:
Sum = 23.5
Constructor overloading:
Same constructor name but different parameters is called constructor overloading.
class rectangle
{
//instance variable
int length;
int breadth;
//default constructor
rectangle()
{
length=5;
breadth=6;
}
//parameterized constructor
rectangle(int l,int b)
{
length=l;
breadth=b;
}
//method
void area()
{
System.out.println("The area of rectangle="+(length*breadth));
}
}
class constructoroverloading
{
public static void main(String args[])
{
rectangle r=new rectangle();
r.area();
rectangle r1=new rectangle(6,70);
r1.area();
}
}
OUTPUT:
Difference between Method and Constructor in java:
Method Constructor
1) Method is used to expose behavior of an 1) Constructor is used to initialize the state
object. of an object.
2) Method must have return type. 2) Constructor must not have return type.
3) Method is invoked explicitly. 3) Constructor is invoked implicitly.
4) The java compiler provides a default
4) Method is not provided by compiler in any
constructor if you don't have any
case.
constructor.
5) Method name may or may not be same as 5) Constructor name must be same as the
class name. class name.
this.
It is used to differentiate “instance variables” with “formal parameters” of either method (or)
constructor if both are existing with same name.
Syntax: this.variablename;
class rectangle
{
int length;
int breadth;
//method
void getdata(int length,int breadth)
{
this.length=length;
this.breadth=breadth;
}
//method
void area()
{
System.out.println("Area of rectangle is:"+(length*breadth));
}
}
class thisdemo
{
public static void main(String args[])
{
rectangle r=new rectangle();
r.getdata(6,10);
r.area();
}
}
OUTPUT:
OUTPUT:
Emp id: 1
Emp name: abc
Emp sal: 76.24
Emp id: 2
Emp name: xyz
Emp sal: 960.24
this( )
1) It is used to call one constructor inside another constructor same class.
2) The main advantage with this( ) is to call multiple constructors by creating single object.
3) The scope of ‘this’ keyword is within the same class.
4) This( ) must be the first statement while calling method or constructor.
5) Syntax:
o this(arguments) //used to call parameterized constructor
o this( ); //used to call no-parameterized constructor
By nulling a reference:
Employee e=new
Employee( ); e=null;
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
By anonymous 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.
Syntax: 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.
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
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
OUTPUT:
static block is invoked
Hello main
Nested Classes