Java Unit 2
Java Unit 2
Java Unit 2
UNIT II: Classes and objects, class declaration, creating objects, methods, constructors and
constructor overloading, garbage collector, importance of static keyword and examples, this
keyword, arrays, command line arguments, nested classes.
Class:
A class is a user defined data type / non-primitive data type that contains attributes and
methods that operate on data. The attributes or variables defined within a class are called
instance variables and the code that operates on this data is known as methods.
(or)
Class can be defined as a template / blueprint that describe the variables / methods of a
particular entity.
In Java everything is encapsulated under classes. Class is the core of Java language.
A class in java can contain:
attributes / variables / fields
methods
constructor
block
class and interface
Rules for Java Class:
A class can have only public or default (no modifier) access modifier.
It can be either abstract, final or concrete (normal class).
It must have the class keyword, and class must be followed by a legal identifier.
It may optionally implement any number of comma-separated interfaces.
The class attributes and methods are declared within a set of curly braces {}.
Each .java source file may contain only one public class. A source file may contain any
number of default visible classes.
The source file name must match the public class name and it must have a .java suffix.
By naming convention, class names capitalize the initial of each word.
For example: Employee, Boss, DateUtility, PostOffice, RegularRateCalculator.
This type of naming convention is known as Pascal naming convention.
The other convention, the camel naming convention, capitalizes the initial of each word,
except the first word.
Methods and attributes use the camel naming convention.
Syntax:
1
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA
class <class_name>
{
attributes;
methods;
}
Example:
public class Student
{
String name;
int id;
public void readData()
{
}
public void displayData ()
{
}
};
Object:
An object is an instance of a class. It is a reference variable that represents attributes as well as
methods required for operating on the data.
(or)
An object is an entity that exists physically in the real world which requires some memory will be
called as an object.
2
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA
Creating an Object:
As mentioned previously, a class provides the blueprints for objects. So basically, an object is
created from a class. In Java, the new key word is used to create new objects.
There are three steps when creating an object from a class:
Declaration: A variable declaration with a variable name with an object type.
Instantiation: The 'new' key word is used to create the object.
Initialization: The 'new' keyword is followed by a call to a constructor. This call initializes
the new object.
To create object of a class <new> Keyword can be used.
Syntax:
<Class_Name> ClassObjectReference = new <Class_Name>();
Example:
Student std=new Student();
Here constructor of the class(Class_Name) will get executed and object will be
created(ClassObjectRefrence will hold the reference of created object in memory).
Simple Example of Object and Class:
Ex-1: main() inside the class
public class Student {
int id;
String name;
public static void main(String[] args) {
Student s1 = new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Output:
0
null
3
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA
Output:
0
Null
Ex-4:
4
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA
class StudentInfo {
int id;
String name;
}
public class Student
{
public static void main(String[] args) {
System.out.println(new StudentInfo().id);
System.out.println(new StudentInfo().name);
}
}
Output:
0
Null
class Student
{
public static void main(String[] args) {
StudentInfo si = new StudentInfo();
si.id = 100;
si.name = "Java";
System.out.println(si.id+" "+si.name);
}
}
Output:
100 Java
5
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA
Ex-2. We can also create multiple objects and store information in it through reference
Variable
class StudentInfo {
int id;
String name;
}
class Student
{
public static void main(String[] args) {
StudentInfo s1 = new StudentInfo();
StudentInfo s2 = new StudentInfo();
s1.id = 1;
s1.name = "REC";
System.out.println(s1.id+" "+s1.name);
s2.id = 2;
s2.name = "RIT";
System.out.println(s2.id+" "+s2.name);
}
}
Output:
1 REC
2 RIT
s2.insert(2,"RIT");
s1.display();
s2.display();
}
}
Output:
1 REC
2 RIT
Methods in Java
A method is a block of code or collection of statements or a set of code grouped together to
perform a certain task or operation.
Advantages
Code Reusability
Code Optimization
Write once and use it many times
Parts of a Method
Method Declaration (Method Prototype / Method Header)
Method Definition
Method Call
Method Declaration
It contains Access modifier, returntype, method name and method parameters.
Syntax:
Accessmodifier returntype methodName(parameters);
Method Definition
It contains method declaration and body.
Syntax:
Accessmodifier returnType nameOfMethod (parameters)
{
// method body
}
The syntax shown above includes:
Accessmodifier − It defines the access type of the method and it is optional to use.
returnType − Method may return a value.
nameofMethod − This is the method name. The method signature consists of the method
name and the parameter list.
7
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA
Parameters − The list of parameters, it is the type, order, and number of parameters of a
method. These are optional, method may contain zero parameters.
method body − The method body contains statements or code.
Method Call
It is used to transfer control from one place to another place during program execution.
syntax:
methodName(parameters);
Types of Method
There are two types of methods in Java:
Predefined Methods
User-defined Methods (Instance Methods, Static Methods)
Predefined Methods
In Java, predefined methods are the methods that are already defined in the Java class
libraries are known as predefined methods.
It is also known as the standard library method or built-in method.
We can directly use these methods just by calling them in the program at any point.
Ex: print(), println(), length(), equals(), compareTo(), sqrt(), etc.
Ex:
public class Demo
{
public static void main(String[] args)
{
// using the max() method of Math class
System.out.print("The maximum number is: " + Math.max(9,7));
}
}
Output:
The maximum number is: 9
User-defined Methods
The method is created by the user or programmer is known as a user-defined method. These
methods are modified according to the requirement.
Based on the data flow between the calling method and called method, the methods are classified as
follows..
1. Method without parameters and without return value.
2. Method without parameters and with return value.
3. Method with parameters and with return value.
4. Method with parameters and without return value.
8
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA
9
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA
Instance Methods
The method of the class is known as an instance method. It is a non-static method defined in the
class. Before calling or invoking the instance method, it is necessary to create an object of its class.
Syntax:
objectname. methodname ();
10
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA
Static Methods:
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.
We cannot access instance variables (non-static) and instance methods (non-static methods)
inside the static method.
It is invoked by using the classname , objectname, and through the instance method.
Ex-1:
class Display
{
void display()
{
System.out.println("Welcome To JAVA");
display1(); // static method calling
}
static void display1()
{
System.out.println("Hello World");
}
}
public class ClassDemo {
public static void main(String[] args) {
Display d = new Display(); // Object Creation
d.display(); // instance method calling
}
}
Output:
Welcome To JAVA
Hello World
Hello World
Hello World
11
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA
Ex-2:
class Student{
int rollno; //instance variable
String name;
static String college ="REC"; //static variable
//we can change the college of all objects by the single line of code
public class StaticDemo{
public static void main(String args[]){
s1.display();
s2.display();
}
}
Output:
1 JAVA RIT
2 C++ RIT
Method Overloading:
Two or more methods can have the same name inside the same class if they accept different
12
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA
Ex:
public class Overloading
{
public static int sum(int i, int j)
{
return i+j;
}
public static float sum(float a, float b)
{
return a+b;
}
public static double sum(double d, double e)
{
return d+e;
}
public static String sum(char c1, String c2)
{
return c1+c2;
}
public static String sum(String s1, String s2)
{
return s1+s2;
}
public static void main(String[] args)
{
System.out.println("Sum of two ints = "+sum(10,20));
System.out.println("Sum of two floats = "+sum(10.1f,20.2));
System.out.println("Sum of two doubles = "+sum(10.1,20.2));
System.out.println("Sum of char and string = "+sum('A',"B"));
System.out.println("Sum of two strings = "+sum("Raghu"," College"));
}
}
Output:
Constructor
It is a special type of method which is used to initialize the object.
Every time an object is created using the new () keyword, at least one constructor is called.
It calls a default constructor if there is no constructor available in the class. In such case, Java
compiler provides a default constructor by default.
13
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA
RULES/PROPERTIES/CHARACTERISTICS OF A CONSTRUCTOR:
Default Constructor
Syntax:
<class name>()
{
Ex:
class Sample
{
Sample()
{
System.out.println("Default Constructor Called");
}
public static void main(String[] args)
{
Sample s1 = new Sample();
Sample s2 = new Sample();
}
}
Output:
Default Constructor Called
Default Constructor Called
The default constructor is used to provide the default values to the object like 0, null, etc.,
depending on the type.
14
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA
Ex:
class Sample
{
int i;
String s;
Sample()
{
System.out.println("Default Constructor Called");
System.out.println(i+" "+s);
}
public static void main(String[] args)
{
Sample s1 = new Sample();
}
}
Output:
NOTE:
Whenever we create an object only with default constructor, defining the default constructor is
optional. If we are not defining default constructor of a class, then JVM will call automatically
system defined default constructor (SDDC). If we define, JVM will call user/programmer defined
default constructor (UDDC).
Parameterized Constructor
Syntax:
The parameterized constructor is used to provide different values to distinct objects. However, you
can provide the same values also.
Ex:
class Constructor
{
int i;
String s;
15
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA
Output:
NOTE:
Whenever we create an object using parameterized constructor, it is mandatory for the JAVA
programmer to define parameterized constructor otherwise we will get compile time error.
Overloaded constructor is one in which constructor name is similar but its signature is different.
Signature represents number of parameters, type of parameters and order of parameters. Here, at least
one thing must be differentiated.
Ex:
class Sample
{
int i;
String s;
Sample()
{
System.out.println("Default Constructor Called");
System.out.println(i+" "+s);
}
Sample(int i,String name)
{
System.out.println("Parameterized Constructor Called");
System.out.println(i+" "+name);
}
public static void main(String[] args)
{
16
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA
Output:
NOTE:
Whenever we define/create the objects with respect to both parameterized constructor and default
constructor, it is mandatory for the JAVA programmer to define both the constructors.
NOTE:
When we define a class, that class can contain two categories of constructors they are single default
constructor and ‘n’ number of parameterized constructors (overloaded constructors).
A constructor is used to initialize the state A method is used to expose the behaviour of an
of an object. object.
A constructor must not have a return type. A method must have a return type.
The Java compiler provides a default The method is not provided by the compiler in
constructor if you don't have any any case.
constructor in a class.
The constructor name must be same as the The method name may or may not be same as
class name. the class name.
17
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA
Garbage Collector:
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.
Advantages
It makes java memory efficient because garbage collector removes the unreferenced objects
from heap memory.
It is automatically done by the garbage collector (a part of JVM) so we don't need to make
extra efforts.
An object is unreferenced in the following ways.
By nulling the reference
By assigning a reference to another
By anonymous object etc.
18
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA
1) By nulling a reference:
new Employee();
In order to call the garbage collector explicitly, we use finalize() method and gc() method.
finalize() method
The finalize() method is invoked each time before the object is garbage collected. This method can
be used to perform cleanup processing.
Protected / public void finalize(){}
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.
new GcDemo();
System.gc();
}
}
Output:
Object Memory Destroyed
Object Memory Destroyed
19
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA
Output:
10
10
10
20
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA
Ex-2:
class Student{
int rollno; //instance variable
String name;
static String college ="REC"; //static variable
//constructor to initialize the variable
Student(int r, String n){
rollno = r;
name = n;
}
//method to display the values
void display (){
System.out.println(rollno+" "+name+" "+college);
}
}
public class StaticDemo{
public static void main(String args[]){
Student s1 = new Student(1,"RAGHU");
Student s2 = new Student(2,"RAHUL");
//we can change the college of all objects by the single line of code
//Student.college="RECA";
s1.display();
s2.display();
}
Output:
1 RAGHU REC
2 RAHUL REC
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.
We cannot access instance variables(non-static) and instance methods(non-static methods) in
side the static method.
21
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA
It is invoked by using the classname , objectname, and through the instance method.
Ex-1:
class Display
{
void display()
{
System.out.println("Welcome To JAVA");
display1(); // static method calling
}
static void display1()
{
System.out.println("Hello World");
}
}
public class ClassDemo {
public static void main(String[] args) {
Display d = new Display(); // Object Creation
d.display(); // instance method calling
}
}
Output:
Welcome To JAVA
Hello World
Hello World
Hello World
Ex-2:
class Student{
int rollno; //instance variable
String name;
static String college ="REC"; //static variable
}
}
//we can change the college of all objects by the single line of code
public class StaticDemo{
public static void main(String args[]){
s1.display();
s2.display();
}
}
Output:
1 RAGHU RIT
2 RAHUL RIT
Ex-1:
class OuterClass {
static class InnerClass{
void innerClassMethod()
{
System.out.println("inner Class Method");
}
}
public static void main(String[] args) {
InnerClass ic = new InnerClass();
ic.innerClassMethod();
}
}
Output:
inner Class Method
Ex-2:
class OuterClass {
int a =10;
static int b=20;
static class InnerClass{
void innerClassMethod()
{
System.out.println("inner Class Method");
//System.out.println(a); // invalid
System.out.println(b); // valid
}
}
public static void main(String[] args) {
InnerClass ic = new InnerClass();
ic.innerClassMethod();
}
}
Output:
inner Class Method
20
24
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA
There are two main restrictions for the static method. They are:
1. The static method cannot use non static data member or call non-static method directly.
2. this and super keywords cannot be used in static context.
Ex:
class A{
int a=40; //non static variable or instance variable
public static void main(String args[]){
System.out.println(a);
}
}
this is an internal or implicit object created by JAVA for the following purposes. They are
‘this’ object is internally pointing to current class object.
this (): this () is used for calling current class default constructor from current class
parameterized constructors.
this (…): this (…) is used for calling current class parameterized constructor from other
category constructors of the same class.
Usage of Java this keyword:
1. this can be used to refer current class instance variable.
2. Whenever the formal parameters and attributes of the class are similar, to differentiate the
attributes of the class from formal parameters, the attributes of class must be preceded by
‘this’.
3. this can be used to invoke current class method (implicitly)
4. this() can be used to invoke current class constructor.
25
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA
NOTE:
• If any method called by an object, then that object is known as source object.
• If we pass an object as a parameter to the method then that object is known as target object.
Ex-1:
In this program, we are printing the reference variable and this, output of both variables are same.
class Sample{
void m(){
System.out.println(this); //prints same reference ID
}
public static void main(String args[]){
Sample obj=new Sample();
System.out.println(obj); //prints the reference ID
obj.m();
}
}
Output
Sample@379619aa
Sample@379619aa
26
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA
Example:
class ThisDemo
{
int a = 10;
void display()
{
int a = 20;
System.out.println(this.a);
System.out.println(a);
}
public static void main(String[] args)
{
ThisDemo td = new ThisDemo();
td.display();
}
}
Output:
10
20
2. Whenever the formal parameters and attributes of the class are similar, to differentiate the
attributes of the class from formal parameters, the attributes of class must be preceded by
„this‟.
Example:
class ThisDemo
{
int i;
String s;
ThisDemo(int i,String s)
{
this.i=i;
this.s=s;
}
void print()
{
System.out.println(i+" "+s);
}
public static void main(String[] args)
{
ThisDemo td = new ThisDemo(1,"REI");
td.print();
}
}
Output:
1 REI
27
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA
class A{
void m()
{
System.out.println("Instance Method m");
}
void n(){
System.out.println("Instance Method n");
//m(); //same as this.m()
this.m();
}
}
class ThisDemo{
public static void main(String args[]){
A a=new A();
a.n();
}
}
Output:
Instance Method m
Instance Method n
}
void display()
{
System.out.println(i+" "+s);
28
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA
}
public static void main(String[] args)
{
Sample s1 = new Sample(1,"REC");
s1.display();
}
}
Output:
Default Constructor Called
1 REC
}
void display()
{
System.out.println(i+" "+s);
}
public static void main(String[] args)
{
Sample s1 = new Sample();
s1.display();
}
}
Output:
Default Constructor Called
1 REC
29
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA
Java Arrays:
An array is a collection of similar data values with a single name. An array can also be
defined as, a special type of variable that holds multiple values of the same data type at a
time.
In java, arrays are objects and they are created dynamically using new operator. Every array
in java is organized using index values. The index value of an array starts with '0' and ends
with 'size-1'. We use the index value to access individual elements of an array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on.
Advantages
Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
Random access: We can get any data located at an index position.
Disadvantages
Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework is used in Java which grows automatically.
Types of Arrays
There are two types of arrays.
Single Dimensional Array
Multidimensional Array
Single Dimensional Array:
In Java, single dimensional arrays are used to store list of values of same datatype.
In other words, single dimensional arrays are used to store a row of values.
In single dimensional array, data is stored in linear form.
Single dimensional arrays are also called as one-dimensional arrays, Linear Arrays or
simply 1-D Arrays.
30
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA
arrayRefVar=new datatype[size];
Ex-1:
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;
//traversing 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
Ex-2:
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5}; //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:
33
3
4
5
31
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA
Multidimensional Array:
An array of arrays is called as multi-dimensional array. In simple words, an array created with more
than one dimension (size) is called as multi-dimensional array. Multi-dimensional array can be
of two-dimensional array or three-dimensional array or four-dimensional array or more...
Most popular and commonly used multi-dimensional array is two-dimensional array. The 2-D
arrays are used to store data in the form of table. We also use 2-D arrays to create
mathematical matrices.
Syntax to Declare Multidimensional Array:
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
Example:
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
33
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA
class CommandLineExample{
public static void main(String args[]){
System.out.println("Your first argument is: "+args[0]);
}
}
Output:
E:\>javac CommandLineExample.java
E:\>java CommandLineExample RECCSE
Your first argument is: RECCSE
Example of command-line argument that prints all the values
In this example, we are printing all the arguments passed from the command-line.
For this purpose, we have traversed the array using for loop.
class A{
public static void main(String args[]){
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
Output:
E:\>javac A.java
E:\>java A 1 2 3 Rec Cse
1
2
3
Rec
Cse
Nested Class / Inner class:
Java nested class or inner class is a class that is declared inside other class is known as nested
class.
Advantage of Java inner classes
it can access all the members (attributes and methods) of the outer class, including private.
Nested classes are used to develop more readable and maintainable code.
Code Optimization: It requires less code to write.
Types of Nested classes
1. non-static nested class (inner class)
Member inner class (Regular inner class)
Local inner class (Method local inner class)
Anonymous inner class
34
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA
Ex-1:
class OuterClass {
void outerClassMethod()
{
System.out.println("Outer Class Method");
InnerClass i = new InnerClass();
i.innerClassMethod();
}
class InnerClass
{
void innerClassMethod()
{
System.out.println("inner Class Method");
}
}
public static void main(String[] args) {
OuterClass oc = new OuterClass();
oc.outerClassMethod();
//oc.innerClassMethod(); // invalid
35
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA
Ex-2
class OuterClass {
private int a=10;
void outerClassMethod()
{
System.out.println("Outer Class Method");
}
class InnerClass // Inner Class
{
void innerClassMethod()
{
System.out.println(a); // Outer Class variable
outerClassMethod(); // Outer Class Method
System.out.println("inner Class Method");
}
}
public static void main(String[] args) {
OuterClass oc = new OuterClass();
oc.outerClassMethod();
}
}
Output:
Outer Class Method
10
Outer Class Method
inner Class Method
Output:
inner Class Method
Output:
REC
CSE
37
RAGHU ENGINEERING COLLEGE OOP THROUGH JAVA
Output:
inner Class Method
38