0% found this document useful (0 votes)
2 views69 pages

Java Unit2

This document covers programming constructs in Java, focusing on arrays (both single and multi-dimensional), command line arguments, and the Scanner class for input. It details the syntax, advantages, and disadvantages of arrays, along with example programs demonstrating their usage. Additionally, it introduces wrapper classes for converting between primitive data types and objects.

Uploaded by

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

Java Unit2

This document covers programming constructs in Java, focusing on arrays (both single and multi-dimensional), command line arguments, and the Scanner class for input. It details the syntax, advantages, and disadvantages of arrays, along with example programs demonstrating their usage. Additionally, it introduces wrapper classes for converting between primitive data types and objects.

Uploaded by

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

UNIT - 2

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.

Single Dimensional Array:


 A one dimensional (1D) or single dimensional array represents a row or a column of elements.
 Syntax to Declare single dimensional array:
1) dataType[] arr; (or)
2) dataType []arr; (or)
3) dataType arr[];
 Instantiation of an Array in java
- datatype arrayRefVar = new datatype[size];
 Examples:
1) int marks[ ]; //declare marks array of integer type
2) marks = new int [5];// allocate memory for storing 5 elements

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

Program 2: A java program of single dimensional array with declaration, instantiation


and Initialization

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 3: A java program of to find minimum value using array


class Testarray2
{
static void min(int arr[])
{
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
public static void main(String args[])
{
int a[]={6,3,2,9};
min(a);//passing array to method
}
}
OUTPUT:
2

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:

Marks j=0 j=1 j=2 j=3 j=4


i=0 50 60 55 67 70
i=1 62 65 70 74 70
i=2 72 66 77 0 69
 Another way of creating a two dimensional array is by declaring the array first and then allocating
memory for it by using new operator.
int marks[ ] [ ] = new int [3] [5];
 Here, JVM allots memory for storing 15 integer elements into the array. But there are no actual
elements stored in the array, we can store these elements by accepting them from the keyboard.

Program 65: A java program on multi-dimensional array


class Testarray3
{
public static void main(String args[])
{
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println( );
}
}
}
OUTPUT:
123
245
445

Program 6: A java program Transpose of Matrix


import java.io.*;
import java.util.Scanner;
class Matrix
{
public static void main(String args[ ] ) throws IOException
{
Scanner sc = new Scanner(Sytem.in);
System.out.println(“Enter rows and column? “);
int r = sc.nextInt( );
int c = sc.nextInt( );
//creating an array
int arr[ ][ ] = new int [r][c];
//accept a matrix from keyboard
System.out.println(“Enter elements of matrix”);
for(int i=0; i<r; i++)
for(int j=0; j<c; j++)
arr[i][j] = sc.nextInt( );
System.out.println(“The transpose matrix:”);
for(int i=0; i<r; i++)
{
for(int j=0; j<c; j++)
{
System.out.println(arr[j][i] +“ ”);
}
System.out.println(“\n”);
}
}
}

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

//creating another matrix to store the sum of two matrices


int c[][]=new int[2][3];

//adding and printing addition of 2 matrices


for(int i=0;i<2;i++)
{
for(int j=0;j<3;j++)
{
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println( );//new line
}
}
}
OUTPUT:
2 6 8
6 8 10

Program 8: A java program Multiplication of Matrix


 In case of matrix multiplication, one row element of first matrix is multiplied by all columns of second
matrix.
//Multiplication Program
public class MatrixMultiplication
{
public static void main(String args[])
{
//creating two matrices
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};

//creating another matrix to store the multiplication of two matrices


int c[][]=new int[3][3]; //3 rows and 3 columns

//multiplying and printing multiplication of 2 matrices


for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{ c[i]
[j]=0;
for(int k=0;k<3;k++)
{
c[i][j]=c[i][j] + a[i][k]*b[k][j];
}//end of k loop
//printing matrix element
System.out.print(c[i][j]+" ");
}//end of j loop
System.out.println( );//new line
}
}
}

Reading input values dynamically


 Java supports reading the input values dynamically in following 2 ways:
1) Using “Command Line Arguments”.
2) Using “Scanner” class.

Command Line Arguments:


 Generally argument means value and the java command-line argument is an argument i.e. passed at
the time of running the java program.
 If any input value is passed through command prompt or console at the time of running of java
program is known as “command line argument”.
 Syntax:
> javac filename.java
> java filename value1, value2, value3,…
 In the above syntax, value1, value2, value3 are known as command line arguments.
 Command line arguments should be separated with ‘spaces’, by default all these values are stored
in ‘String’ array of main method.
 By default, every command line argument is ‘String’ type.
 The java command-line argument is an argument i.e. passed at the time of running the java program.

Program1: A Java program on command-line arguments


 In the below example program 42, we are receiving only one argument and printing it.
 To run this java program, you must pass at least one argument from the command prompt.
class CommandLineExample
{
public static void main(String args[])
{
System.out.println("Your first argument is: "+args[0]);
}
}
OUTPUT:
>javac CommandLineExample.java
> java CommandLineExample hellojava
Output: Your first argument is: hellojava

Reading inputs using ‘Scanner’ class:


 ‘Scanner’ is a predefined class in “java.util” package used to read the input values from any input
component like ‘keyboard’, ‘file’, ‘client machine’ etc.
Syntax: Scanner sn = new Scanner(System.in);
 The Java Scanner class breaks the input into tokens using a delimiter that is whitespace by default. It
provides many methods to read and parse various primitive values.
 System.in represents standard input device and System.out represents standard output device.

Scanner class methods:


1) nextByte( ) - It used to read byte value.
2) nextShort( ) - It used to read short value.
3) nextInt( ) - It used to read int value.
4) nextLong( ) - It used to read long value.
5) nextFloat( ) - It used to read float value.
6) nextDouble( ) - It used to read double value.
7) nextBoolean( ) - It used to read boolean value.
8) next( ) - It used to read a ‘single string’ value. It doesn’t consider spaces.
9) nextLine( ) - It used to read It used to read a ‘single string’ value. It doesn’t consider spaces.

- 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

Program 2: A java program to read the student details dynamically


import java.util.Scanner;
class ScannerTest
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter your rollno");
int rollno=sc.nextInt( );
System.out.println("Enter your name");
String name=sc.next( );
System.out.println("Enter your fee");
double fee=sc.nextDouble( );
System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
sc.close( );
}
}
OUTPUT:
Enter your rollno
111
Enter your name
Ratan
Enter your fee
450000
Rollno:111 name: Ratan fee:450000
WRAPPER CLASSES
 These are the predefined classes in “java.lang” package used to:
1) Represent the primitive data type into object type.
2) Convert string to primitive data and primitive data to string type.
 The below shows various wrapper classes and its methods for parsing.
Wrapper Class Method Description
1) Byte parseByte(String) It used to convert string to byte value.
2) Short parseShort(String) It used to convert string to short value.
3) Integer parseInt(String) It used to convert string to Integer value.
4) Long parseLong(String) It used to convert string to Long value.
5) Float parseFloat(String) It used to convert string to float value.
6) Double parseDouble(String) It used to convert string to double value.
7) Boolean parseBoolean(String) It used to convert string to boolean value.

Program : A java program to work with command line arguments


class CmdDemo
{
public static void main(String args[ ])
{
System.out.println(“Before Converting”);
System.out.println(args[0] + args[1]);
System.out.println(“After Converting”);
int x = Integer.parserInt(args[0]);
int y = Integer.parserInt(args[1]);
int z = x + y;
System.out.println(“Sum =” +z);
}

}
OUTPUT:
>javac CmdDemo.java
>java CmdDemo 10 20
Before Converting
1020
After Converting
30

Accept input form the keyboard:


 A stream is required to accept input from the keyboard.
 A stream represents flow of data from one place to another place.
 A stream can carry data form keyboard to memory or memory to printer or from memory to a file.
 A stream is always required if we want to move data from one place to another.
 Basically there are two types of streams:
1) Input Streams
2) Output Streams
 Input streams are those streams which receive or read data coming from some other place.
 Output steams are those streams which send or write data to some other place.
 All streams of input and output are represented by classes in “java.io” package.
 This package contains a lot of classes, all of which can be classified into input and output streams.
 Keyboard is represented by a field, called ‘in’ in ‘System’ class. When we write “System.in”
represents a standard input device i.e. keyboard by default. System class is found in
“java.lang” package and has three fields as follows:
1) System.in: This represents “InputStream” class object, by default represents standard input device
i.e. keyboard.
2) System.out: This represents “OutputStream” class object, by default represents standard output
i.e. monitor. It is used to display normal messages and results.
3) System.err: This filed also represents “PrintStream” object, which by default represents monitor.
It is used to display error messages.
 To accept the data from the keyboard i.e. “System.in”, we need to connect the keyboard to an input
stream object. Here we can use “InputStreamReader” that can read data from the keyboard.
InputStreamReader obj = new InputStreamReader (System.in);
 Now, connect “InputStreamReader” to “BufferedReader”, which is another input type of stream. By
using this we can read data properly coming from the stream in two ways:
1) BufferedReader br = new BufferedReader(obj);
- Here we are creating “BufferedReader” object (br) and connecting the “InputStream” object (obj) to
it.
2) Buffer Reader br = new BufferedReader(new InputStreamReader(System.in));
- Here we can be combined object (br) and object (obj).
 Now we can read the data coming from the keyboard using read( ) and readLine( ) methods available
in “BufferedReader” class.
Accepting a single character from the Keyboard:
 Now, the following steps are required to accept a single character from the keyboard:
1) Create a “BufferedReader” class object (br).
2) Then, read a single character from the keyboard using “read( )” method.
 The read( ) method return type is Integer. So we need to do “type casting” for converting int data
type to char type.
 The read( ) method could not accept a character due to insufficient memory or illegal character, then it
gives rise to a runtime error which is called by the name IOException class. Where IO standards for
input/output and Exception represents runtime error.
 When read( ) method is giving IOException. Then we are identifying by using Exception Handling.

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

Accepting a String of characters from the Keyboard:

 To read string a characters from the keyboard we required readLine( ) method in


‘BufferedReader’ class.
 The readLine( ) method accepts a string from the keyboard and returns the string.
 Here type casting not required because accepting and returning the same data type.
 But this method can give to the runtime error: IOException.

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

Accepting a Integer value from the Keyboard:

 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( ));

Program : A java program to accept an integer from 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 value:”);
int num = Integer.parseInt(br.readLine( ) );
System.out.println(“You entered:” +num);
}
}

OUTPUT:
Enter a value: 1234
You entered: 1234

Accepting a Float value from the Keyboard:

 To accept an float value from the keyboard in the following way:


Float n = Float.parseFloat(br.readLine( ));

Program : A java program to accept an integer from 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 float value:”);
float num = Float.parseFloat(br.readLine( ) );
System.out.println(“You entered:” +num);
}
}

OUTPUT:
Enter a float: 12.34
You entered: 12.34

Accepting a Double value from the Keyboard

 To accept an double value from the keyboard in the following way:


double n = Double.parseDouble(br.readLine( ));

Program : A java program to accept a double from 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 double value:”);
double num = Double.parsedouble(br.readLine( ) );
System.out.println(“You entered:” +num);
}
}

OUTPUT:
Enter a double value: 123456.789
You entered: 123456.789

Accepting byte, long, short and boolean types of values:

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

Program : A java program to perform Fibonacci series


import java.io.*;
class Fib
{
public static void main(String args [ ]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println(“How many fibonaccis?”);
int n = Integer.parseInt(br.readLine( ));
long f1 = 0, f2 = 1;
System.out.println(f1);
System.out.println(f2);
long f = f1+f2;
System.out.println(f);
//Already 3 fibonaccis are displayed. So count will start at 3
int count = 3;
while(count<n)
{
f1 = f2;
f2 = f;
f = f1+f2;
System.out.println(f);
count++;
}
}
}
OUTPUT:
How many fibonaccies? 5
0
1
1
2
3

Classes and objects


 In object-oriented programming every program is developed by using objects and classes.
 Object is the physical as well as logical entity whereas class is the logical entity only.

Objects in Java:

 An entity that has state and behavior is known as an object.


 An object has three characteristics:
1) State: represents data (value) of an object.
2) Behavior: represents the behavior (functionality) of an object such as deposit, withdraw etc.
3) Identity: Object identity is typically implemented via a unique ID. The value of the ID is not
visible to the external user. But, it is used internally by the JVM to identify each object uniquely.
 For example, ‘student’ is an object. His name, student id, branch, etc. represents the state. He used to
renewal books in library, knowing his current academic percentage, etc. represents the behavior.
 So object is called as instance of class.

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

Syntax to declare a class:


class <class_name>
{
field;
method;
}

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.

‘new’ keyword in Java:


 The new keyword is used to allocate memory at run time. All objects get memory in Heap memory
area.
 There are two types we can create object in java:
Syntax 1:classname reference = new classname( ); // referenced object

Syntax 2:new classname( ); // unreferenced object


 The ‘referenced object’ is available in live state for more time, so that it is recommended to use while
accessing multiple methods of a class or same method multiple times.
 The ‘unreferenced object’ is automatically deallocated by “Garbage Collector (GC)” before
executing the next time. So that it is highly recommended to access a single method of the class at a
time.
 In Garbage Collector point of view, referenced object means ‘Useful object’ and unreferenced means
‘un-useful’ object.
 ‘Referenced object’ and ‘unreferenced object’ is created by JVM in main memory based on its syntax.
 In the above syntax 2, JVM will create a new object for the properties of the given class.
 In the above syntax 1, JVM will create a new object along with class reference name. In this case
reference name acts as a pointer.

Examples of object creation:

1) Person raju = new Person( ); // object creation of syntax 1.

2)new Person( ); // object creation of syntax 2.

Program : A java program to create an object within the class


class Student
{
int id;//field or data member or instance variable
String name;
public static void main(String args[])
{
Student s1=new Student( );//creating an object of Student
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
}}

OUTPUT:
0
null

Program : A java program to create a main outside the class


class Student
{
int id;
String name;
}
class TestStudent1
{
public static void main(String args[])
{
Student s1=new Student( );
System.out.println(s1.id);
System.out.println(s1.name);
}}

OUTPUT
0
null

Object creation and Initialization:


 There are 3 ways to initialize object in java.
a) By reference variable
b) By method
c) By constructor

Program : A java program to Initialization through reference


 Initializing object simply means storing data into object.
 The below example program shows how to initialize object through reference variable.

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

Program : A java program to create multiple objects through reference variable

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

Program : A java program to Initialization through method


class Student
{
int rollno;
String name;
void insertRecord(int r, String n)
{
rollno=r;
name=n;
}
void displayInformation( )
{
System.out.println(rollno+" "+name);
}
}
class TestStudent4
{
public static void main(String args[])
{
Student s1=new Student( );
Student s2=new Student( );
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation( );
s2.displayInformation( );
}
}
OUTPUT:
111 Karan
222 Aryan

Program : A java program to Initialization through 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
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

Anonymous (or) un-reference object:


 Anonymous simply means nameless. An object which has no reference is known as anonymous
object.
 It can be used at the time of object creation only.
 For example: new Calculation( );//anonymous object

Syntax for calling method through anonymous object:

 new Classname( ).methodName( );

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

Program : A java program to store Bank details of customers


class Account
{
int acc_no;
String name;
float amount;
void insert(int a,String n,float amt)
{
acc_no=a;
name=n;
amount=amt;
}
void deposit(float amt)
{
amount=amount+amt;
System.out.println(amt+" deposited");
}
void withdraw(float amt)
{
if(amount<amt)
{
System.out.println("Insufficient Balance");
}
else
{
amount=amount-amt;
System.out.println(amt+" withdrawn");
}
}
void checkBalance( )
{
System.out.println("Balance is: "+amount);
}
void display( )
{
System.out.println(acc_no+" "+name+" "+amount);
}
}
class TestAccount
{
public static void main(String[] args)
{
Account a1=new Account( );
a1.insert(832345,"Ankit",1000);
a1.display( );
a1.checkBalance( );
a1.deposit(40000);
a1.checkBalance( );
a1.withdraw(15000);
a1.checkBalance( );
}
}
Output:
832345 Ankit 1000.0
Balance is: 1000.0
40000.0 deposited
Balance is: 41000.0
15000.0 withdrawn
Balance is: 26000.0

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

 Following access modifiers represents accessibility of variables and methods.


Within the derived Anywhere in same
Access Within the Within the
class of other and outside the
Modifier same class same package
package package
1) private YES NO NO NO
2) default YES YES NO NO
3) protected YES YES YES NO
4) pubic YES YES YES YES

 If any variable or method is not preceded by “private/protected/public” then that properties are treated
as ‘default’ properties.

private access modifier:


 The private access modifier is accessible only within class.
 In the below program 14, 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.

Program 14: A java program for private access modifier


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
}
}
OUTPUT:
Compile time error

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.
 In the below program 15, 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.
Program : A java program for default access modifier
//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
}
}
OUTPUT:
Compile time error

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.
 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.

Program : A java program for protected access modifier


//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

public access modifier:


 The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.

Program : A java program for 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.*;
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

Rules to be followed while working with methods:


1. Method must be defined inside the class only.
2. One class can have many numbers of methods.
3. No method will be executed without calling.
4. One method should be called inside another method, that maybe main method or user defined method.
5. Method contains only logic to perform an operation.
Program 1: A java program for method concept
class A
{
int x=10, y=20, z;
void add( )
{
z= x + y;
System.out.println(z);
}
}
class B
{
void show( )
{
new A( ).add( );
System.out.println(“In class B”);
}
}
class C
{
void f1( )
{
new B( ).show( );
System.out.println(“In class C”);
}
}
class TestDemo
{
public static void main(String args[])
{
new C( ).f1( );
System.out.println(“In class C”);
}
}
OUTPUT:
30
In class B
In class C
Program 2: A java program to work with all types of variables and methods
Class A
{
int y=8;
static int z = 3;
void f1( )
{
int x=5; //local variable
System.out.println(x);
System.out.println(y);
System.out.println(z);
}
void f2( )
{
System.out.println(x); //local variable cannot be accessed outside the method
System.out.println(y);
System.out.println(z);
System.out.println(A.z);
f1( );
}
static void f3( )
{
A oa = new A( ); System.out.println(oa.y); oa.f1( ); System.out.println(z);

}
}
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 3: A java program to work with methods


class A
{
void f1( )
{
System.out.println(“In f1( ) of class A”);
}
int f2( )
{
return (5);
}
static void f3(String s)
{
System.out.println(“In f3( ) of class A”);
}
}
class Main
{
public static void main(String a[ ])
{
A oa = new A( );
oa.f1( );
int x = oa.f2( );
System.out.println(x);
float y = oa.f2( );//Invalid, because f2( ) is returning integer value but here we are assigning to
float
oa.f2( );
A.f3(Hello);//Invalid, f3( ) is expecting string type value.
A.f3(“Java”);
}
}

Program 4: A java program to work with methods


class Student
{
int rno;
String name;
void display( )
{
System.out.println(rno);
System.out.println(name);
}
}
class A
{
void f1(Student s)
{
System.out.println(“In class A”);
}
static int f2( )
{
return (5);
}
}
class Demo
{
public static void main(String a[ ])
{
new Student( ).display( );
Student s = new Student( );
new A( ).f1(s);
int i = A.f2( );
}
}

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

Method Overloading (or)static polymorphism (or)early binding:


 If the same name is existing multiple times with in a class with different number of parameters,
different type of parameters and different order of parameters is known as “Method Overloading”.
 Advantage of method overloading is “readability of the program”.
 Different ways to overload the method:
1) By changing number of arguments.
2) By changing the data type.

Method Overloading: changing no. of arguments

 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.

Program: write a java program to demonstrate polymorphism or Method overloading.

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:

Program 1: A java program by 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));
}
}
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.

Program 2: A java program by 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));
}
}
OUTPUT:
22
24.9

 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

Can we overload java main( ) method:


 Yes, it is possible by using method overloading.
 You can have any number of main methods in a class by method overloading. But JVM calls main( )
method which receives string array as arguments only.

Program 3: A java program on overloading main( ) method


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:
main with String[ ]

Method overloading with Type Promotion


 One type is promoted to another implicitly if no matching datatype is found. Let's understand the
concept by the figure given below.
 In the above diagram, byte can be promoted to short, int, long, float or double. The short datatype can
be promoted to int, long, float or double. The char datatype can be promoted to int, long, float or
double and so on.

program : A java program with type promotion:


class OverloadingCalculation1
{
void sum(int a, long 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[])
{
OverloadingCalculation1 obj=new OverloadingCalculation1( );
obj.sum(20,20);//now second int literal will be promoted to long
obj.sum(20,20,20);
}
}
OUTPUT:
40
60

Program : A Java program with type promotion if matching found


 If there are matching type arguments in the method, type promotion is not required.
class OverloadingCalculation2
{
void sum(int a,int b)
{
System.out.println("int arg method invoked");
}
void sum(long a,long b)
{
System.out.println("long arg method invoked");
}
public static void main(String args[])
{
OverloadingCalculation2 obj=new OverloadingCalculation2( );
obj.sum(20,20);//now int arg sum( ) method gets invoked
}
}
OUTPUT:
int arg method invoked
Method overloading with Type Promotion in case of ambiguity
 If there are no matching type arguments in the method, and each method promotes similar number of
arguments, there will be ambiguity.

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

Rules for Method overloading


1) Method name must be same.
2) Method signature must be different.
3) For overloading methods, ‘return type’ can be any type. There is no compulsion that return type
must be same.
4) Overloaded methods either can be static (or) non-static (or) can be a combination of static and non-
static.
 Example Program:
class A
{
static int f1( )
{
System.out.println(“F1 in class A”);
return (5);
}
static void f1(int x)
{
System.out.println(“F1 with parameter in class A”);
}
}
class MOverloadingDemo
{ A.f1( );
A.f1(5);
}
Constructor in Java:
 In Java, constructor is a block of codes similar to method.
 It is called when an instance of object is created and memory is allocated for the object.
 It is a special type of method which is used to initialize the object.
 Every time an object is created using ‘new’ keyword, at least one constructor is called. It is called a
default constructor.
 It is called constructor because it constructs the values at the time of object creation.
 It is not necessary to write a constructor for a class.
 It is because java compiler creates a default constructor if your class doesn't have any.
 Rules for creating java 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 in java:
1) Default constructor (no parameterized constructor)
2) Parameterized constructor

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

program1:write a java program to implement parameterized constructor.


class rectangle
{
//instance variable
int length;
int breadth;

//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:

Program 2: A java program on parameterized constructor


class Emp
{
int eid;
String ename;
float esal;
Emp(int id, String nm, float sl)
{
eid = id;
ename = nm;
esal = sl;
}
void display( )
{
System.out.println(“emp id:” +eid);
System.out.println(“emp name:” +ename);
System.out.println(“emp sal:” +esal);
}
}
class EmpDemo
{
public static void main(String args[ ])
{
Emp e1 = new Emp(1, “abc”, 75.6f);
e1.display( );
System.out.println(“.....................”);
Emp e2 = new Emp(2, “xyz”, 75.9f);
e1.display( );
System.out.println(“.....................”);
Emp e3 = new Emp(3, “lmn”, 83.7f);
e1.display( );
}
}
 One class can have many number of constructors with different signature, this is technically called as
“Constructor Overloading”.
 The main purpose of defining multiple constructors is to initialize the different objects with different
number of dynamic input values.

Program 2: A java program on multiple parameterized constructors


import java.util.Scanner;
class Emp
{
int eid;
String ename;
float esal;
Emp(int id, String nm, float sl)
{
eid = id;
ename = nm;
easl = sl;
}
Emp(int id, String nm)
{
eid = id;
ename = nm;
}
Emp(int id)
{
eid = id;
}
void display( )
{
System.out.println(“emp id:”,+eid);
System.out.println(“emp name:”,+ename);
System.out.println(“emp sal:”,+esal);
}
}
class EmpDemo
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
System.out.println(“Enter number of inputs:”);
int ni = sn.nextInt( );
if(ni= = 3)
{
System.out.println(“Enter eid, ename, esal:”);
int id = sn.nextInt( );
String nm = sn.nextLine( );
float sl = sn.nextFloat( );
new Emp(id,nm,sl).display( );
}
else if(n= = 2)
{
System.out.println(“Enter eid, ename:”);
int id = sn.nextInt( );
String nm = sn.nextLine( );
new Emp(id,nm).display( );
}
else if(n= = 1)
{
System.out.println(“Enter eid:”);
int id = sn.nextInt( );
new Emp(id).display( );
}
}

Default (No-Parameterized) Constructor:


 If any constructor does not contain list of parameters in its signature is known as “No-
Parameterized Constructor”.
 ‘Java compiler’ creates no-parametrized constructor by default if that class does not contain
parameterized constructors.
 Syntax:
Classname( )
{
//constructor body
}
 Compiler doesn’t creates no-parameterized constructor if that class doesn’t contain atleast one
parameterized constructor.
 The logic is executed only once at that time of creation of object only.
 Syntax to call the no-parameterized constructor:
1) Classname ref = new Classname( );
2) new Classname( );
program1:write a java program to implement default constructor

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:

Program2 : A java program of default constructor


class Bike1
{
Bike1( )
{
System.out.println("Bike is created");
}
public static void main(String args[])
{
Bike1 b=new Bike1( );
}
}
OUTPUT:
Bike is created

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

Program : A java program copying values without constructor


class Student7
{
int id;
String name;
Student7(int i,String n)
{
id = i;
name = n;
}
Student7( )
{
}
void display( )
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student7 s1 = new Student7(111,"Karan");
Student7 s2 = new Student7( );
s2.id=s1.id;
s2.name=s1.name;
s1.display( );
s2.display( );
}
}
OUTPUT:
111 Karan
111 Karan

Constructor overloading:
Same constructor name but different parameters is called constructor overloading.

program: write a program to implement 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’ keyword in Java:


 It is a keyword in java language, represents the current class object, it can be used in following 2 ways:
1) this.
2)this( )

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;

Program1:write a program to implement this keyword at variable level.

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:

Program 2: A java program to work with this.


class Emp
{
int eid;
String ename;
float esal;
Emp(int eid, String ename, float esal)
{
this.eid = eid; //local variable contains highest priority on current class object.
this.ename = ename;
this.esal = esal;
}
void display( )
{
System.out.println("Emp id:" +eid);
System.out.println("Emp name:" +ename);
System.out.println("Emp sal:" +esal);
}
}
class EmpDemo
{
public static void main(String args [ ])
{
Emp e1 = new Emp( 1, "abc", 76.24f);
e1.display( );
Emp e2 = new Emp( 2, "xyz", 960.24f);
e2.display( );
}
}

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

Program : A java program to work with this( ).


class A
{
A( )
{
System.out.println(“No parameterized constructor”);
}
A(int x)
{
this( ); // calls no-parameterized
System.out.println(“Single Parameterized constructor”);
}
A(int x, String y)
{
this(10);// calls single parameterized
System.out.println(“Two parameterized constructor”);
}
}
class TestDemo
{
public static void main(String args[ ])
{
A oa = new A(20, “abc”);
}
}
OUTPUT:
No parameterized constructor
Single parameterized constructor
Two parameterized constructor

Garbage Collector in java


 In java, garbage means unreferenced objects.
 Garbage Collection is process of reclaiming the runtime unused memory automatically. In other
words, it is a way to destroy the unused objects.
 To do so, we were using free( ) function in C language and delete( ) in C++. But, in java it is
performed automatically. So, java provides better memory management.
 Advantage of Garbage Collection:
1) It makes java memory efficient because garbage collector removes the unreferenced objects from
heap memory.
2)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:
1) By nulling the reference
2) By assigning a reference to another
3) By anonymous object etc.

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.

Program : Java 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

Importance of Java static Keyword and examples:


 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 (object).
 The static can be:
1) variable (also known as class variable)
2) method (also known as class method)
3) block

Java static variable

 If you declare any variable as static, it is known static variable.


 The static variable can be used to refer the common property of all objects (that is not unique for each
object).
 Example: 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: It makes your program memory efficient (i.e it saves memory).
 Example program without static variable:
class Student
{
int rollno;
String name;
String college="ITS";
}
 In the above example, all students have its unique ‘rollno’ and ‘name’, so instance data member is
required and for college refer to the common property of all objects. If we make it static, this field will
get memory only once.

Program1 : A java program with 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 2: A java program of counter without static 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
 In the above program 54, 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.

Program 3: A java program of counter by static variable


 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

Java static method:


 If you apply static keyword with any method, it is known as static method.
 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.
 Static method is a method that doesn’t act up on instance variables of a class.
 Static methods are called with ‘classname’ that is the reason static methods are not accessed by JVM
with instance variables.

Program 1: A java program on static method


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

Program 2: A java program on static method that performs normal calculation


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
Program 3: A java program on static method trying to access instance variable
class Test
{
int x;//instance variable
Test(int x)
{
this.x = x;
}
static void access( )
{
System.out.println(“X =” +x);
}
}
class Demo
{
public static void main(String args[ ])
{
Test obj = new Test(10);
Test.access( );
}
}
OUTPUT: Run this program for better understanding

Java static block:


 Is used to initialize the static data member.
 It is executed before main method at the time of class loading.

Program 4: A java program on 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
Nested Classes

You might also like