Java
Java
Introduction to JAVA
Different Programming Paradigms
• Functional/procedural programming:
– program is a list of instructions to the
computer
• Object-oriented programming
– program is composed of a collection objects
that communicate with each other
Why Java ?
• Portable
• Easy to learn
myprog.c myprog.exe
gcc machine code
C source code
OS/Hardware
Platform Independent
myprog.java myprog.class
javac bytecode
Java source code
JVM
OS/Hardware
08/22/2021
Hello World
Hello.java
class Hello {
public static void main(String[] args) {
System.out.println(“Hello World !!!”); }
}
08/22/2021 8
An object is a thing. A class is a category of things.
8/22/21
8/22/21
8/22/21
Object
Any entity that has state and behavior is known as an object.
For example: chair, pen, table, keyboard, bike etc. It can be
physical and logical.
Object can be defined as an instance of a class. An object
contains an address and takes up some space in memory.
Objects can communicate without knowing details of each
other's data or code, the only necessary thing is that the type
of message accepted and type of response returned by the
objects.
Example: A dog is an object because it has states i.e. color,
name, breed etc. as well as behaviors i.e. wagging the tail,
barking, eating etc.
08/22/2021 12
Creating Objects
8/22/21
Class
• Collection of objects is called class.
• It is a logical entity.
• A class can also be defined as a blueprint from
which you can create an individual object.
• Class does not store any space.
A class can contain any of the following variable
types.
Local variables
Variables defined inside methods, constructors
or blocks are called local variables. The variable
will be declared and initialized within the method
and the variable will be destroyed when the
method has completed.
08/22/2021 15
Instance variables
Instance variables are variables within a
class but outside any method. These variables
are initialized when the class is instantiated.
Instance variables can be accessed from
inside any method, constructor or blocks of
that particular class.
Class variables
Class variables are variables declared
within a class, outside any method, with the
static keyword.
08/22/2021 16
Types of Classes
class Lamp {
boolean isOn;
void turnOn() {
isOn = true;
}
void turnOff() {
isOn = false;}
void displayLightStatus() {
System.out.println("Light on? " + isOn);
}}
class ClassObjectsExample {
public static void main(String[] args) {
Lamp l1 = new Lamp(), l2 = new Lamp();
l1.turnOn();
l2.turnOff();
l1.displayLightStatus();
l2.displayLightStatus();}}
Output:
Light on? true
Light on? False
In the above program,
• Lamp class is created.
• The class has an instance variable isOn and three
methods turnOn(), turnOff() and displayLightStatus().
• Two objects l1 and l2 of Lamp class are created in
the main() function.
• Here, turnOn() method is called using l1 object: l1.turnOn();
• This method sets isOn instance variable of l1 object to true.
• And, turnOff() method is called using l2 object: l2.turnOff();
Methods
• A Java method defines a group of statements as
performing a particular operation
• static indicates a static or class method
• A method that is not static is an instance method
• All method arguments are call-by-value
– Primitive type: value is passed to the method
– Method may modify local copy but will not affect caller’s
value
– Object reference: address of object is passed
– Change to reference variable does not affect caller
– But operations can affect the object, visible to caller
Example Program:
class Main
{
public static void main(String[] args)
{
System.out.println("About to encounter a method.");
myMethod(); // method call
System.out.println("Method was executed successfully!");
}
private static void myMethod() // method definition
{
System.out.println("Printing from inside myMethod()!");
}
}
Output:
About to encounter a method.
Printing from inside myMethod().
Method was executed successfully!
08/22/2021 51
• Member data - Same data is used for all the
instances (objects) of some Class.
Assignment performed
Class A {
on the first access to the
public int y = 0;
Class.
public static int x_ = 1;
Only one instance of ‘x’
};
exists in memory
A a = new A();
A b = new A(); a b
System.out.println(b.x_); Output: 0 0
a.x_ = 5; y y
System.out.println(b.x_);
A.x_ = 10;
1
System.out.println(b.x_); 5 1
10 A.x_
• Member function
– Static member function can access only static members
– Static member function can be called without an
instance.
Class TeaPot {
private static int numOfTP = 0;
private Color myColor_;
public TeaPot(Color c) {
myColor_ = c;
numOfTP++;
}
public static int howManyTeaPots()
{ return numOfTP; }
// error :
public static Color getColor()
{ return myColor_; }
}
Constructors in Java
In Java, a constructor is a block of codes similar to the method. It is
called when an instance of the object is created, and memory is allocated
for the object.
It is a special type of method which is used to initialize the object.
When is a constructor called
Every time an object is created using new() keyword, at least one
constructor is called. It calls a default constructor.
Note: 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
There are two rules defined for the constructor.
1. Constructor name must be the same as its class name
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized
Types of Java constructors
There are two types of constructors in Java:
1. Default constructor (no-arg constructor)
2. Parameterized constructor
1. Default constructor (no-arg constructor)
A constructor is called "Default Constructor" when it doesn't have any parameter.
Example of default constructor
//Java Program to create and call a default constructor
class Bike1
{
//creating a default constructor
Bike1(){System.out.println("Bike is created");
}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
} }
In this example, we are creating the no-arg
constructor in the Bike class. It will be invoked at the
time of object creation.
Output:
Bike is created
2. Parameterized constructor :
A constructor which has a specific number of
parameters is called a parameterized constructor.
Why use the parameterized constructor?
The parameterized constructor is used to provide
different values to the distinct objects. However, you
can provide the same values also.
Example Program:
//Java Program to demonstrate the use of parameterized constructor
class Student4
{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n; Output:
} 111 Karan
//method to display the values 222 Aryan
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
} }
Garbage Collection
•In java, garbage means unreferenced objects.
•Garbage Collection is process of reclaiming the runtime unused
memory automatically. In other words, it is a way to destroy the
unused objects.
•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
•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.
08/22/2021 58
finalize() method
Before an object is garbage collected, the runtime system invokes the objects finalize()
method.
The finalize() can be used to perform clean up activities such as release system file
resources (or) close sockets (or) close database connections etc.
The finalize() method is declared in the java.lang.Object class,
Example
protected void finalize(){
//close resource }