IT2301 – Java Programming
UNIT - I
Features of Java
There is given many features of java. They are also known as java buzzwords.
1. Simple
2. Object-Oriented
3. Platform independent
4. Network savvy
5. Secured
6. Robust
7. Architecture neutral
8. Portable
9. Dynamic
10. Interpreted
11. High Performance
12. Multithreaded
13. Distributed
Simple
According to Sun, Java language is simple because:
syntax is based on C++ (so easier for programmers to learn it after C++).
removed many confusing and/or rarely-used features e.g., explicit pointers,
operator overloading etc.
removed many confusing and/or rarely-used features e.g., explicit pointers,
operator overloading etc.
Object-oriented
Object-oriented means we organize our software as a combination of different
types of objects that incorporates both data and behaviour.
Object-oriented programming(OOPs) is a methodology that simplify software
development and maintenance by providing some rules.
Platform Independent
A platform is the hardware or software environment in which a program runs.
There are two types of platforms software-based and hardware-based. Java provides
software-based platform. The Java platform differs from most other platforms in the
sense that it's a software-based platform that runs on top of other hardware-based
platforms.It has two components:
1
IT2301 – Java Programming
1. Runtime Environment
2. API(Application Programming Interface)
Java code can be run on multiple platforms e.g.Windows,Linux,Sun Solaris,Mac/OS etc.
Java code is compiled by the compiler and converted into bytecode.This bytecode is a
platform independent code because it can be run on multiple platforms i.e. Write Once
and Run Anywhere(WORA).
Network Savvy
Java has an extensive library of routines for coping with TCP/IP protocols like
HTTP and FTP. Java applications can open and access objects across the Net via
URLs with the same ease as when accessing a local file system.
Secured
Java is secured because:
No explicit pointer
Programs run inside virtual machine sandbox.
Classloader- adds security by separating the package for the classes of the
local file system from those that are imported from network sources.
Bytecode Verifier- checks the code fragments for illegal code that can violate
access right to objects.
Security Manager- determines what resources a class can access such as
reading and writing to the local disk.
These security are provided by java language. Some security can also be
provided by application developer through SSL,JAAS,cryptography etc..
Robust
Robust simply means strong. Java uses strong memory management. There are lack of
pointers that avoids security problem. There is automatic garbage collection in java.
There is exception handling and type checking mechanism in java. All these points
makes java robust.
Architecture-neutral
There is no implementation dependent features e.g. size of primitive types is set.
Portable
We may carry the java bytecode to any platform
2
IT2301 – Java Programming
High-performance
Java is faster than traditional interpretation since byte code is "close" to native code
still somewhat slower than a compiled language (e.g., C++)
Distributed
We can create distributed applications in java. RMI and EJB are used for creating
distributed applications. We may access files by calling the methods from any
machine on the internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java
programs that deal with many tasks at once by defining multiple threads. The main
advantage of multi-threading is that it shares the same memory. Threads are important
for multi-media, Web applications etc.
Simple Program of Java
In this page, we will learn how to write the hello java program. We can write a simple
hello java program easily.
To create a simple java program, you need to create a class that contains main method.
Let's understand the requirement first.
Creating hello java example
class Simple
public static void main(String args[])
System.out.println("Hello Java");
3
IT2301 – Java Programming
OOPs (Object Oriented Programming System) Concepts
Object means a real word entity such as pen, chair, table etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and
objects. It simplifies the software development and maintenance by providing some
concepts:
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Object
An entity that has state and behavior is known as an object e.g. chair, bike,
marker, pen, table, car etc. It can be physical or logical (tengible and
intengible). The example of integible object is banking system.
Object is an instance of a class
An object has three characteristics:
state: represents data (value) of an object.
behavior: represents the behavior (functionality) of an object such as deposit,
withdraw etc.
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: Pen is an object. Its name is Reynolds, color is white etc. known as its
state. It is used to write, so writing is its behavior.
Class
A class is a group of objects that has common properties. It is a template or blueprint
from which objects are created.
A class in java can contain:
data member
method
constructor
block
class and interface
4
IT2301 – Java Programming
Inheritance
When one object acquires all the properties and behaviours of parent object i.e.
known as inheritance.
It provides code reusability.
It is used to achieve runtime polymorphism.
Polymorphism
When one task is performed by different ways i.e. known as polymorphism.
For example: to convense the customer differently, to draw something e.g. shape or
rectangle etc.
In java, we use method overloading and method overriding to achieve polymorphism.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For
example: phone call, we don't know the internal processing.
In java, we use abstract class and interface to achieve abstraction.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as
encapsulation.
For example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.
Abstract class
A class that is declared as abstract is known as abstract class. It needs to be extended
and its method implemented. It cannot be instantiated.
Syntax to declare the abstract class
abstract class <class_name>
{ }
Abstract method
5
IT2301 – Java Programming
A method that is declared as abstract and does not have implementation is known as
abstract method.
Syntax to define the abstract method
abstract return_type <method_name>();
Example of abstract class that have abstract method
In this example, Shape is the abstract class, its implementation is provided by the
Rectangle and Circle classes. Mostly, we don't know about the implementation class (i.e.
hidden to the end user) and object of the implementation class is provided by the factory
method.
A factory method is the method that returns the instance of the class. We will learn
about the factory method later.
In this example, if you create the instance of Rectangle class, draw method of Rectangle
class will be invoked.
abstract class Shape
{
abstract void draw();
}
class Rectangle extends Shape
{
void draw()
{
System.out.println("drawing rectangle");
}
}
class Circle extends Shape
{
void draw()
{
System.out.println("drawing circle");
}
}
class Test
{
public static void main(String args[])
{
Shape s=new Circle();
s.draw();
6
IT2301 – Java Programming
}
}
Object and Classes in Java
Class
A class is a group of objects that has common properties. It is a template or blueprint
from which objects are created.
A class in java can contain:
data member
method
constructor
block
class and interface
Object
An entity that has state and behavior is known as an object e.g. chair, bike,
marker, pen, table, car etc. It can be physical or logical (tengible and
intengible). The example of integible object is banking system.
Object is an instance of a class
An object has three characteristics:
state: represents data (value) of an object.
behavior: represents the behavior (functionality) of an object such as deposit,
withdraw etc.
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: Pen is an object. Its name is Reynolds, color is white etc. known as its
state. It is used to write, so writing is its behavior.
Defining Classes
Syntax to declare a class:
class <class_name>
data member;
method;
7
IT2301 – Java Programming
}
Example of Object and Class
In this example, we have created a Student class that have two data members id and
name. We are creating the object of the Student class by new keyword and printing the
objects value.
class Student
int id; //data member (also instance variable)
String name;//data member(also instance variable)
public static void main(String args[])
Student s1=new Student(); //creating an object of Student
System.out.println(s1.id+" "+s1.name);
Another Example
class Rectangle
int length;
int width;
void insert(int l,int w)
length=l;
width=w;
8
IT2301 – Java Programming
void calculateArea()
System.out.println(length*width);
public static void main(String args[])
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
Output:55
45
Methods
Private Methods
To implement a private method in Java, simply change the public keyword to
private.
By making a method private, you are under no obligation to keep it available if
you change to another implementation. The method may well be harder to
implement or unnecessary if the data representation changes: this is irrelevant.
The point is that as long as the method is private, the designers of the class can be
assured that it is never used outside the other class operations and can simply drop
it. If a method is public, you cannot simply drop it because other code might rely
on it.
Static Methods
Static methods are methods that do not operate on objects.
9
IT2301 – Java Programming
For example, the pow method of the Math class is a static method. The expression
Math.pow(x, a) computes the power xa. It does not use any Math object to carry
out its task.
Because static methods don’t operate on objects, you cannot access instance fields
from a static method. But static methods can access the static fields in their class.
Here is an example of such a static method:
Class Employee
{
public static int getNextId()
{
return nextId; // returns static field
}
}|
To call this method, you supply the name of the class:
int n = Employee.getNextId();
You use static methods in two situations:
• When a method doesn’t need to access the object state because all needed
parameters are supplied as explicit parameters (example: Math.pow)
• When a method only needs to access static fields of the class (example:
Employee.getNextId)
Factory Methods
Here is another common use for static methods. The NumberFormat class uses factory
methods that yield formatter objects for various styles.
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();
NumberFormat percentFormatter = NumberFormat.getPercentInstance();
double x = 0.1;
System.out.println(currencyFormatter.format(x)); // prints $0.10
System.out.println(percentFormatter.format(x)); // prints 10%
The main Method
Note that you can call static methods without having any objects. For example, you
never construct any objects of the Math class to call Math.pow.
For the same reason, the main method is a static method.
public class Application
{
public static void main(String[] args)
{
// construct objects here. . .
}
}
The main method does not operate on any objects. In fact, when a program starts, there
aren’t any objects yet. The static main method executes, and constructs the objects that
the program needs.
Method Parameters
10
IT2301 – Java Programming
There are, however, two kinds of method parameters:
• Primitive types (numbers, boolean values)
• Object references
Access Specifiers
There are 4 types of access modifiers:
1. private
2. default
3. protected
4. public
There are many non-access modifiers such as static, abstract, synchronized, native,
volatile, transient etc. Here, we will learn access modifiers.
1) private
The private access modifier is accessible only within class
Example of 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
}
11
IT2301 – Java Programming
Role of Private Constructor:
If you make any class constructor private, you cannot create the instance of that class
from outside the class
class A
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
Note: A class cannot be private or protected except nested class.
2) default
If you don't use any modifier, it is treated as default bydefault. The default modifier is
accessible only within package.
Example of default access modifier
In this example, we have created two packages pack and mypack. We are accessing
the A class from outside its package, since A class is not public, so it cannot be
accessed from outside the package.
12
IT2301 – Java Programming
package pack;
class A{
void msg(){System.out.println("Hello");}
package mypack;
import pack.*;
class B
public static void main(String args[])
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
In the above example, the scope of class A and its method msg() is default so it cannot
be accessed from outside the package.
3) protected
The protected access modifier is accessible within package and outside the package
but through inheritance only.
The protected access modifier can be applied on the data member, method and
constructor. It can't be applied on the class.
Example of protected access modifier
In this example, we have created the two packages pack and mypack. The A class of
pack package is public, so can be accessed from outside the package. But msg method
of this package is declared as protected, so it can be accessed from outside the class
only through inheritance.
package pack;
13
IT2301 – Java Programming
public class A
protected void msg(){System.out.println("Hello");}
package mypack;
import pack.*;
class B extends A
public static void main(String args[])
B obj = new B();
obj.msg();
Output:Hello
4) public
The public access modifier is accessible everywhere. It has the widest scope among all
other modifiers.
Example of public access modifier
package pack;
public class A
public void msg(){System.out.println("Hello");}
14
IT2301 – Java Programming
package mypack;
import pack.*;
class B
public static void main(String args[]){
A obj = new A();
obj.msg();
Output:Hello
Understanding all java access modifiers
Access within within outside outside
Modifier class package package by package
subclass
only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
static members
The static keyword is used in java mainly for memory management. We may apply
static keyword with variables, methods, blocks and nested class. The static keyword
belongs to the class than instance of the class.
The static can be:
1. variable (also known as class variable)
2. method (also known as class method)
3. block
4. nested class
1) static variable
If you declare any variable as static, it is known static variable.
15
IT2301 – Java Programming
The static variable can be used to refer the common property of all objects
(that is not unique for each object) e.g. company name of employees,college
name of students etc.
The static variable gets memory only once in class area at the time of class
loading.
Advantage of static variable
It makes your program memory efficient (i.e it saves memory).
Program of counter without static variable
In this example, we have created an instance variable named count which is
incremented in the constructor. Since instance variable gets the memory at the time of
object creation, each object will have the copy of the instance variable, if it is
incremented, it won't reflect to other objects. So each objects will have the value 1 in
the count variable.
class Counter
int count=0;//will get memory when instance is created
Counter()
count++;
System.out.println(count);
public static void main(String args[])
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
16
IT2301 – Java Programming
}
Output:1
Program of counter by static variable
As we have mentioned above, static variable will get the memory only once, if any
object changes the value of the static variable, it will retain its value.
class Counter
static int count=0;//will get memory only once and retain its value
Counter()
count++;
System.out.println(count);
public static void main(String args[])
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
17
IT2301 – Java Programming
Output:1
2) 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.
//Program to get cube of a given number by static method
class Calculate
static int cube(int x)
return x*x*x;
public static void main(String args[])
int result=Calculate.cube(5);
System.out.println(result);
Output:125
Restrictions for static method
There are two main restrictions for the static method. They are:
1. The static method can not use non static data member or call non-static method
directly.
18
IT2301 – Java Programming
2. this and super cannot be used in static context.
3) static block
Is used to initialize the static data member.
It is executed before main method at the time of classloading.
Example of static block
class A
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
Constructors
Constructor is a special type of method that is used to initialize the object.
Constructor is invoked at the time of object creation. It constructs the values i.e.
provides data for the object that is why it is known as constructor.
Rules for creating constructor
There are basically two rules defined for the constructor.
1. Constructor name must be same as its class name
2. Constructor must have no explicit return type
Types of constructors
19
IT2301 – Java Programming
There are two types of constructors:
1. default constructor (no-arg constructor)
2. parameterized constructor
1) Default Constructor
A constructor that have no parameter is known as default constructor
Syntax of default constructor:
<class_name>()
{}
Example of default constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be
invoked at the time of object creation.
class Bike
Bike()
System.out.println("Bike is created");
public static void main(String args[])
Bike b=new Bike();
Output: Bike is created
20
IT2301 – Java Programming
Rule: If there is no constructor in a class, compiler automatically creates a default
constructor.
Parameterized constructor
A constructor that have parameters is known as parameterized constructor
Example of parameterized constructor
In this example, we have created the constructor of Student class that have two
parameters. We can have any number of parameters in the constructor.
class Student
int id;
String name;
Student(int i,String n)
id = i;
name = n;
void display()
System.out.println(id+" "+name);
public static void main(String args[])
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
s1.display();
21
IT2301 – Java Programming
s2.display();
Output:111 Karan
222 Aryan
Constructor Overloading
Constructor overloading is a technique in which a class can have any number of
constructors that differ in parameter lists.The compiler differentiates these
constructors by taking into account the number of parameters in the list and their type.
Example of Constructor Overloading
class Student
int id;
String name;
int age;
Student(int i,String n)
id = i;
name = n;
Student(int i,String n,int a)
id = i;
name = n;
age=a;
22
IT2301 – Java Programming
void display()
System.out.println(id+" "+name+" "+age);
public static void main(String args[])
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan",25);
s1.display();
s2.display();
Output:111 Karan 0
222 Aryan 25
Initialization Blocks
There are two ways to initialize a data field:
• By setting a value in a constructor
• By assigning a value in the declaration
There is actually a third mechanism in Java; it’s called an initialization block. Class
declarations can contain arbitrary blocks of code. These blocks are executed whenever an
object of that class is constructed.
Example:
class Employee
{
public Employee(String n, double s)
{
name = n;
salary = s;
}
public Employee()
{
23
IT2301 – Java Programming
name = "";
salary = 0;
}
...
private static int nextId;
private int id;
private String name;
private double salary;
...
Chapter 4. Objects and Classes
Object Construction 149
// object initialization block
{
id = nextId;
nextId++;
}
}
In this example, the id field is initialized in the object initialization block, no matter
which constructor is used to construct an object. The initialization block runs first, and
then the body of the constructor is executed.
Finalize Method
You can add a finalize method to any class. The finalize method will be called before the
garbage collector sweeps away the object.
Declaration
The finalize() method has this general form:
protected void finalize()
// finalization code here
Here, the keyword protected is a specifier that prevents access to finalize() by
code defined outside its class.
24