Java Unit-I
Java Unit-I
UNIT - I
Object-Oriented Thinking- A way of viewing world – Agents and
Communities, messages and methods, Responsibilities, Classes and
Instances, Class Hierarchies- Inheritance, Method binding, Overriding and
Exceptions, Summary of Object-Oriented concepts. Java buzzwords, An
Overview of Java, Data types, Variables and Arrays, operators, expressions,
control statements, Introducing classes, Methods and Classes, String
handling.
Inheritance– Inheritance concept, Inheritance basics, Member access,
Constructors, Creating Multilevel hierarchy, super uses, using final with
inheritance, Polymorphism-ad hoc polymorphism, pure polymorphism,
method overriding, abstract classes, Object class, forms of inheritance
specialization, specification, construction, extension, limitation, combination,
benefits of inheritance, costs of inheritance.
Introduction:
Java is an object-oriented programming language developed by james
goshling in the year 1996 at sun micro systems (which is now a subsidiary of
Oracle Corporation). Much of its syntax is taken from c and c++. Initially it
was called oak and later it is changed to java.
J2SE/JAVASE:
Ex: Notepad
J2EE/JAVAEE:
Servlets and JSP are the technologies provided by the sun for
the development of web application and for developing distributed
applications we are having RMI and EJB technologies.
J2ME/JAVAME:
Versions of JAVA:
Many java versions have been released till now. The current stable release of
Java is Java SE 13.
Object Oriented :
Objects
Class
Data Abstraction
Data Encapsulation
Inheritance
Polymorphism
Dynamic binding
Message passing
Simple :
Pointers
operator overloading
virtual functions
Templates
It also uses same syntax of C and C++, so it is easy for a programmer who is
familiar with C or C++.
Secured:
Once java code compiled on one platform and will run on any platform
without making any changes i.e., write once run any where.
The Java compilers and the JVM are platform dependent and .class file
is platform independent. Because of this feature, java is widely accepted as
internet language.
Architecture Neutral:
The java programs are strong and they don’t crash easily like a c/c++
programs because of the following reasons.
Allocation Deallocation
calloc()
C malloc() Free()
realloc()
C++ new Delete
Java new __
Dynamic:
Interpreted:
Java programs are compiled to generate the byte code. This byte code
can be downloaded and interpreted by the interpreter in JVM. In Java, we use
both compiler and interpreter for the execution.
High Performance:
The problem with interpreter inside the JVM is that it is slow, By this
java programs used to run slow. To overcome this problem, along with the
interpreter, JIT (Just In Time) compiler was introduced which enhances the
speed of execution. So, now in JVM, both interpreter and JIT compiler work
together to run the program.
Multithreaded:
Distributed:
Java Identifiers :
An identifier is a name given to the variable, constant, method, class,
package, etc.,
It starts with a uppercase letter and internal word also starts with
uppercase letter. Rest of the characters are lower case.
{ {
------------ ------------
} }
It starts with a uppercase letter and internal word also starts with
uppercase letter. Rest of the characters are in lower case.
{ {
------------ ------------
} }
It begins with a lowercase letter and internal word also starts with
uppercase letter. Rest of the characters are in lower case.
Ex: int x;
int age;
int myFirstSalary;
int MAX_VALUE=567;
It start with a lowercase letter and internal word also starts with
uppercase letter. Rest of the characters are in lower case.
----------
{ -----------}
Ex : java.lang
java.io
java.net
java.awt
animal
mypack
Reserved Words:
Reserved words are the words that have some specific meaning and
purpose. We cannot change them.
goto: goto is not defined or not used since the readability of the
application decreases or goes down as goto increases the
complexity of the application.
int x=10;
javac First.java
javadoc First.java
Now, there will be HTML files created for your Calculator class in the
current directory. Open the HTML files and see the explanation of Calculator
class provided through documentation comment.
Data Types:
Java supports eight data types out of which four are integral data types,
two are real floating data type, one is character data type and one boolean
type.
The difference between a float and double is float takes 7 digits after the
decimal point where as double takes 16 digits accurately after the decimal
point.
Except boolean and char, all the remaining datatypes are signed
datatypes.
found : int
required : byte
byte b3 = ‘A’;
found : int
required : short
short s3 = ‘+’;
short s4 = ‘ ’;
int i = 10;
float x = 10;
float x = 010;
float x = 0X10;
float x = ‘A’;
float x = 11.2147483648F;
char ch = ‘A’;
char ch = ‘#’;
For unicode values which are not supported by the system we get question
marks.
char ch=‘\uFACE’
Escape Characters:
char ch=‘\b’;
char ch=‘\n’;
char ch=‘\t’;
char ch=‘\f’;
char ch=‘\k’;
‘\u0008’ Backspace
‘\u000c’ Formfeed
boolean Literal:
boolean b = true;
boolean b = false;
String Literal:
String s = “Hello”;
Or
3. OS Requirements
import java.lang.*;
The name of the public class and the name of the java text file should be
same.
To develop a java program we need atleast one class. The allowed access
specifiers for the top level class are public or default.
Output:
Compilation-
javac Demo.java
Execution-
java Demo
Variables:
A variable is a identifier whose value is not fixed.
Local variable
Instance variable
Static variable
Local variable: A variable declared inside a method is called local variable.
A local variable must be initialized before its usage
Default values are not applicable to the local variables.
Scope of the variables is within the method only. It cannot be used
outside the method.
The only modifier that is applied to the local variable is final
import java.lang.*;
public class Demo2
{
public static void main(String args[])
{
int x=10;
int y=20;
int z;
System.out.println(x);
System.out.println(y);
System.out.println(" sum is : "+x+y); // sum is : 1020
System.out.println("sum is : "+(x+y)); // sum is : 30
System.out.println(x+y+ " is sum "); // 30 is sum
// System.out.println(z): // Error: local variable Z might not have been
initialized.
}
}
Output:
10
20
sum is : 1020
sum is : 30
30 is sum
Encapsulation:
Encapsulation is a mechanism where the data (variables) and the code
(methods) that act on the data will bind together.
Class:
A class is declared by using the keyword class. A class is a blue print
of a object.
Declaration:
instance variable
static variable
instance methods
static methods
A class contains set of variables and methods and are integrated into a
single unit.
Object:
Object is an instance of a class. Every object will have state and
behavior. The state is maintained using variables and behavior is changed
using methods.
Creating an object:
(or)
Class_name Object_name;
(or)
Demo d;
d = new Demo();
d is reference to the Demo class object. Using new operator we can allocate
the memory dynamically. In java every memory allocation is dynamic. We can
access the instance variables using the reference name i.e., object name.
Syntax: Object_name.variablename;
Object_name.method_name();
Ex: d.x
d.setData();
Instance variable:
A variable declared inside the class and outside a method is called
instance variable.
The allowed access modifiers for instance variable are final, transient,
volatile and static.
import java.lang.*;
public class Demo2
{
int x,y,z;
public static void main(String args[])
{
Demo2 d = new Demo2();
System.out.println(d.x+"\t"+d.y+"\t"+d.z);
d.x=100;
d.y=200;
d.z=678;
System.out.println(d.x+"\t"+d.y+"\t"+d.z);
Demo2 d1 = new Demo2();
System.out.println(d1.x+"\t"+d1.y+"\t"+d1.z);
d1.x=10;
d1.y=20;
d1.z=67;
System.out.println(d1.x+"\t"+d1.y+"\t"+d1.z);
}
}
Output:
0 0 0
100 200 678
0 0 0
10 20 67
For a static variable the memory will be allocated as soon as .class file
loaded into the JVM.
Only once the memory will be allocated for static variable and it is
shared by every object.
Directly
w.r.t to object name
w.r.t to class name
if a static variable is accessed outside the class there are only two ways
w.r.t to object name
w.r.t to class name
public class S1
{
static int a=9;
int x,y;
public static void main(String args[])
{
Syntax:
return;
1. instance method
2. static method
3. factory method
4. abstract method
instance method :
from one instance method we can call other instance method directly.
class Demo2
{
int x, y, z;
void increment()
{
x++;
y++;
z++;
}
void display()
{
System.out.println(x+"\t"+y+"\t"+z);
Output:
0 0 0
1 1 1
0 0 0
0 0 0
2 2 2
this:
it is a keyword
this is can be used w.r.t instance variable and instance method and can
be used inside the constructors.
class Demo9
{
int a,b,c;
void initialize(int a, int b,int c)
{
this.a=a;
this.b=b;
this.c=c;
this.display();
}
void display()
{
System.out.println(a+"\t"+b+"\t"+c);
}
public static void main(String args[])
{
Demo9 d = new Demo9();
d.initialize(10,20,30);
Demo9 d1 = new Demo9();
d1.initialize(100,200,100);
}
}
Output:
10 20 30
100 200 100
Static method:
Directly
w.r.t object
w.r.t class name
w.r.t object
w.r.t class name.
Answer : 1,3,4
There are two types of blocks: Instance block and static block
Instance block :
Instance blocks are declared inside the class. Instance block is called as
soon as object is created. Any number of instance can be placed inside the
java class.
class Demo2
{
int x,y,z;
}
public static void m1()
{
System.out.println("m1 method Static Variable : "+a);
}
public static void main(String args[])
{
Demo2 d= new Demo2();
}
}
Instance Block 1
Display method
0 0 0
Instance Block 2
Display method
Static block :
A static block is declared inside the java class with static keyword.
A static block is called as soon as .class file is loaded into the JVM.
Any number of static blocks can be placed inside the java class.the order
of execution of static block is from top to bottom
Java program execution starts from main but static blocks are executed
before the main() method.
The name of the publc class and the name of the text file must be same.
A java text file can have any number of default classes but only one public
class.
If a java text file contains only default classes the name of the text file can
be any name.
The no. of .class file is equal to the number of class available in the java
text file.
If java text file contains two public classes then at compile time it gives
error. No two public classes defined. A java program must contain only one
public class.
A java text file can have only one main method.(not a rule)
Java tools
C:\>java Demo
/**
Type casting:
Conversion of one data type into another data type is known as type
casting.
There are two types of type casting: implicit type casting and explicit type
casting.
Syntax: (target_data_type)operand;
int i = (float)f;
class Demo
{
public static void main(String args[])
{
int x;
float y=100.36f; // Explicit type casting
x = (int)y;
System.out.println(x);
System.out.println(y);
int i=67; //Explicit type casting
char ch=(char)i;
System.out.println(ch);
System.out.println(i);
}
}
Output:
100
100.36
C
67
Constructors:
Default constructor
Parameterized Constructor
A java class can have more than one parameterized constructor but they
should differ in the number of parameters or type of parameters or order
of parameters.
If a java class is not having any constructor then the java compiler will
generate the default constructor.
The allowed access specifiers to the constructors are private, protected,
public and <default>.
If a class is having a private constructor then we cannot create the object
outside the class.
A constructor will not have a return type not even a void. If we place a
return type then it is treated as a method.
Using constructors there is no need of explicit method calls.
Demo1(int a,int b)
{
System.out.println("Two Parameterized Constructor ");
x=a;
y=b;
}
Demo1(int a, int b, int c)
{
System.out.println("Three Parameterized Constructor ");
x=a;
y=b;
z=c;
}
void display()
{
System.out.println(x+" "+y+" "+z);
}
}
class D
{
public static void main(String args[])
{
Demo1 d= new Demo1();
d.display();
Demo1 d1= new Demo1(10,20);
d1.display();
Demo1 d2 =new Demo1(1,2,3);
d2.display();
}
}
Default Constructor
5 10 0.0
Two Parameterized Constructor
10 20 0.0
Three Parameterized Constructor
1 2 3.0
Constructor overloading:
class A
{
A()
{
System.out.println("dc");
A(int i)
{
System.out.println(i);
}
A(int i, float j)
{
System.out.println(i+"\t"+j);
}
A(int i, int j)
{
System.out.println(i+"\t"+j);
}
A(float j, int i)
{
System.out.println(i+"\t"+j);
}
}
public class Demo5
{
public static void main(String args[])
{
A a = new A();
A a1 = new A(10);
A a2 = new A(10,20);
A a3 = new A(10.3f,200);
A a4 = new A(100,20.5f);
}
}
dc
10
10 20
200 10.3
100 20.5
this():
class A
{
A()
{
this(10);
System.out.println("dc");
A(int i)
{
this(10,5.3f);
System.out.println(i);
}
A(int i, float j)
{
this(100,200);
System.out.println(i);
}
A(int i, int j)
{
this(10.5f,10);
System.out.println(i+"\t"+j);
}
A(float j, int i)
{
System.out.println(i+"\t"+j);
}
}
public class Demo
{
public static void main(String args[])
{
A a = new A();
}
}
10 10.5
100 200
10
10
dc
Difference between this and this():
Arrays :
Arrays are fixed in size. The array index start from zero
Types of arrays:
Single-dimensional
Multi-dimensional
Two-dimensional
Three-dimensional
We should not specify the size at the time of declaration, if we specify the
size it gives compile time error.
Construction of an array:
int x[];
x=new int[];
Or
In java arrays are objects. So, we can allocate the memory dynamically by
using new operator.
The allowed data types to mention various size of array are byte, short, int,
char because all can be converted into int.
Length:
System.out.println(x.length); //prints 5
Initialization:
x[0]=10;x[1]=20; x[2]=30;
flaot x[]={10.2f,1.4f};
Multidimensional Arrays:
At the declaration we should not specify the size because gives an compile
time error.
String s[][];
float y[][];
byte [][]b;
Construction of 2D Array :
int x[][];
X=new int[2][3];
System.out.println(x[0]); //null
System.out.println(x[1]); //null
System.out.println(x.length); //2
System.out.println(x[0].length);//3
1. String[][] s;
2. String s[][];
3. String []s[];
4. String [][]s;
5. Object [][o;
int[][][] a; or
int [][][]a; or
int[][] a[]; or
int a[][][]; or
int [] a[][];
Construction of 3D Array
Inheritance:
Inheritance is a concept where new classes can be produced from
existing classes. The newly created class acquires all features of existing class
from where it is derived. Inheritance provides the idea of reusability.
The class from which the subclass is derived is called a super class or
base class or parent class.
----------
---------
-----------
-----------
A java class cannot extend more than one class so multiple inheritance is
not achieved through classes and it is possible by using interfaces.
Constructors are not inherited since they are not members of the class.
public, default, protected members are inherited where as private
members are not inherited
Object is the super class of all classes i.e., every class directly or
indirectly inherited from object class
{ {
------------ Demo()
------------ {
} }
Single Inheritance
Multiple Inheritance
Hierarchical inheritance
Multilevel inheritance
Hybrid Inheritance.
Multiple Inheritance :
Hierarchical Inheritance: In this type, there is only one super class but
many subclasses. These subclasses are derived from only one super class.
Specialization
Specification
Construction
Extension
Limitation
Combinations
------
----------
The MyFrame class inheritance all the properties of parent class Frame.
MyApplet is specialized form of Frame class.
The parent class may be abstract class or interface. If the parent class
is abstract class then we need extends that abstract class. If the parent class
is interface then we need implement the interface as follows:
-----------------------------------
-------------------------------------
void mouseClicked(MouseEvent e) ;
void mouseEntered(MouseEvent e) ;
void mouseExited(MouseEvent e) ;
void mousePressed(MouseEvent e) ;
Construction:
The child class inherits all the properties of its parent class even though there
is no common functionality between parent and child class.
Extension:
The child class adds some more additional behavior (methods) to the parent
class without modifying the attributes(variables) that are inherited from
parent class.
Limitation:
Whenever a new class is derived from any class then the sub class restricts
few behaviors to be used that are inherited from the parent class.
Combinations:
Java doesn’t allow creating a class from more than one class. We can create
a class by implementing more than one interface.
interface A
void m1();
void m2();
interface B
void m3();
void m4();
class Demo1
-------------------
Benefits of Inheritance:
Increased Reliability
Reusability
Polymorphism
Extending the Behavior
Public: Public class members i.e methods and field can be accessed in the
classes of same package and also the classes of other packages. Public means
every where.
Private: Private members of a class can be accessed within the class only i.e.,
they cannot be accessed by the classes of same package and also the classes
of other packages.
In the following figure we are taking three classes class A, class B and
class C. whereas class A and class B exists in the same package, class C is
from other package. Let us assume that there are four members with private,
public, protected and default specifiers in class A.
super Uses:
We can create an object of super class, we can access only the super class
members but not the sub class members. If we create sub class object, all the
members of both super and sub classes are available to it. Some times the
super members and sub class members may have same names.
class P
int a=60,b=0;
void m1()
System.out.println("m1 in P");
System.out.println("sum :"+(a+b));
class C extends P
int a=10,b=56;
void m1()
System.out.println("m1 in C");
System.out.println("mul : "+(a*b));
class SDemo
C c1=new C();
c1.m1();
In the above program a method m1() is called w.r.t child class object, hence
this m1() present in both child class as well as parent class. So w.r.t child
class object we are calling m1() method so the method that present in the
child class is called. In this case if we want to access the members of super
class from sub class super keyword is used. super is a keyword. Super is used
to access super class members from sub class. super can be used w.r.t
methods and variables
super.variable;
super.methods();
class P
int a=60,b=0;
void m1()
System.out.println("m1 in P");
System.out.println("sum :"+(a+b));
class C extends P
int a=10,b=56;
void m1()
System.out.println("m1 in C");
super.m1();
class SDemo
C c1=new C();
c1.m1();
super():
this() and super() cannot be used at a time since both must be used
as a first statements.
this() is used to call constructors of same class but super is used call
the super class constructors from sub class.
{ {
Demo()
} {
Super();
class P
P()
System.out.println("default p ");
class C extends P
C()
System.out.println("default C ");
class SF
C c1=new C();
class Demo
Demo(int a)
this(40,20);
System.out.println("a: "+a);
Demo(int a,int b)
Demo1()
super(1);
class SF
}}
final : final is a keyword and is used w.r.t variable , method and classes. A
final variable cannot be modified i.e. it is used to define a constant. Final
methods cannot be overridden in sub class. Final classes cannot be
extended. If we try to change the value of variable that is declared by using
final keyword then the java compiler gives an error. If we try to override the
final methods in sub classes then java compiler gives an error.
If we try to extend the final classed then java compiler gives an error. Let us
consider the following program:
final class P
System.out.println("final method");
class C extends P
void m1()
System.out.println("m1 in C");
class FDemo
System.out.println(x);
System.out.println(x++);
Polymorphism:
Polymorphism word comes from ancient Greek where poly means many so
polymorphic are something which can take many form. In this Java
Polymorphism tutorial we will see what is Polymorphism in Java , How
Polymorphism is implemented in Java e.g method overloading and
overriding,
Method Overridding: Writing two or more methods in super and sub classes
such that methods have same name and same signature is called method
overriding. Overriding exists for only instance methods not for static methods.
Even return type must be same up to java1.4 version. We cannot assign weak
access specifier to the overridden method. Final methods cannot be
overridden. Method overriding is an example of run-time polymorphism. At
the execution time it decides which method is called based on the type of the
object.
class P
class C extends P
class Demo
P p1=new P();
p1.display();
C c1=new C();
c1.display();
p2.display();
c2.display();*/
Case 1 class P
Class C extends P {
{ valid
Case 2 class P
Class C extends P
Public public
No overriding for private methods since they cannot be accessed outside the
class.
Method Hidding: If a sub class defines a static methods with the same
signature as a static method in the super class the method in the sub class
hides the method of super class. Method hiding takes for static methods
where as overriding takes for instance methods. Method hiding is an
example of compile time polymorphisms i.e, the type of the object is not
important only the type of the reference is important.
class P
class C extends P
}}
class MH
P p1 =new P();
p1.m1();
C c1 = new C();
c1.m1();
P p2 =new C();
p2.m1();
Output:
Method Overloading: Two or more methods having the same method name
with different signatures is called method overloading. In case of method
overloading the number of parameters or the type of parameters or the order
of parameters must be differed. Return type may or may not be same.
Method overloading is an example of compile time polymorphism i.e., the
method call is decided at the compile time based on the parameters or
parameter types or order of parameters. Method overloading exists within
the same class where as overriding exists in between the classes. Method
overloading exists for instance and static methods.
class MO
System.out.println(i);
System.out.println(m);
System.out.println(x+"\t"+m);
System.out.println(x+"\t"+m);
MO d = new MO();
d.display();
d.display(10);
d.display(100,200.5f);
d.display(11.12f,222);
d.display(10.99f);
}}
Same method name and different Same method name and same
signature signature
Overloading exists for instance and Overriding exists only for instance
static methods methods
Return type may or may not be Return type must be same upto
same java1.4 version
Void display()
} // concrete method
Abstract method cannot be static & final. For abstract method the
implementation is provided in the sub class Abstract classes:
class AbstractDemo2
cir.display();
rect.display();
tri.display();
System.out.println(" ============");
Shape s;
s=cir;
s.display();
s=rect;
s.display();
s=tri;
s.display();
abstract class A
abstract class B
class AbstractDemo5
System.out.println(A.x);
System.out.println(B.y);
Classes:
Object
Wrapper Classes
String
StringBuffer
System
Runtime
Thread
Reflection
Math
Exception,Error, Throwable
Process
Object: It is the class from java.lang package. Object is the super class of all
classes i.e. Every class directly or indirectly inherited from object class.
Programmers code
compiler code
class A class A
extends java.lang.Object
{ {
} }
hashCode(): returns the address of the Object/ returns distinct integers for
distinct Object
System.out.println(d.toString());
System.out.println(d.hashCode());
System.out.println(d1.hashCode());
System.out.println(d.equals(d1));
d=d1;
System.out.println(d.hashCode());
System.out.println(d1.hashCode());
return "abc";
return 420;
System.out.println(d.toString());
System.out.println(d);
System.out.println(d.hashCode());
System.out.println(d1.hashCode());
System.out.println(d.equals(d1));