CORE JAVA NOTES Up To Exception Handling
CORE JAVA NOTES Up To Exception Handling
set of programs.
In IT we develop two types of applications. They are stand alone applications and distributed
applications.
A stand alone application is one which runs in the context of local disk. All stand alone
applications are not sharable. System software and application software comes under stand alone
applications.
System software is used for developing functionality of hardware devices. Examples are C and
ALP (Assembly Language Programming).
Application software is used for developing organizations oriented applications. This is also
known as backend software’s. Examples are dbase, dbase III plus, FoxPro, oracle versions
released till now.
Internet software is used for developing distributed applications.
A distributed application is one which can be accessed across the globe. Distributed application is
also one which runs in the contest of the World Wide Web. To develop distributed applications we
must use client-server architecture.
In client-server architecture we must hare at least two programs they are client program and server
program. A client program is one which always makes a request to get the service from the server. A
server program is one which will do three operations receiving the request from client, processing
the client request and sending the response to the client.
All the above three operations are performed by the server concurrently. In order to exchange
the data between client and server we must use a protocol called http (hypertext transfer protocol).
Protocol is a set of values which are defined to exchange the data between client and server either
locally or remotely.
In order to develop distributed applications, two software companies came forward whose
names are Microsoft System and Sun Micro System.
Microsoft System has developed a technology called DOT NET and Sun Micro System has
developed a technology called JAVA. Both this technologies are called distributed technologies.
The technology DOT NET will run only on that operating system’s which are provided by
Microsoft (as on today). Hence DOT NET technology is platform dependent technology. Whereas, the
technology called JAVA will run on all operating system’s irrespective of their providers hence JAVA is
called platform independent technology.
History of JAVA:
JAVA is a distributed technology developed by James Gosling, Patric Naugton, etc., at Sun
Micro System has released lot of rules for JAVA and those rules are implemented by JavaSoft Inc, USA
(which is the software division of Sun Micro System) in the year 1990. The original name of JAVA is
OAK (which is a tree name). In the year 1995, OAK was revised and developed software called JAVA
(which is a coffee seed name).
JAVA released to the market in three categories J2SE (JAVA 2 Standard Edition), J2EE (JAVA 2
Enterprise Edition) and J2ME (JAVA 2 Micro/Mobile Edition).
J2SE is basically used for developing client side applications/programs.
J2EE is used for developing server side applications/programs.
J2ME is used for developing server side applications/programs.
If you exchange the data between client and server programs (J2SE and J2EE), by default JAVA is
having on internal support with a protocol called http. J2ME is used for developing mobile
applications and lower/system level applications. To develop J2ME applications we must use a
protocol called WAP (Wireless Applications Protocol).
FEATURES of java:
Simple
Platform independent
Architectural neutral
Portable
Multi threading
Distributed
Networked
Robust
Dynamic
Secured
High performance
Interpreted
Object Oriented Programming Language
Simple: JAVA is simple because of the following factors:
JAVA is free from pointers hence we can achieve less development time and less execution
time [whenever we write a JAVA program we write without pointers and internally it is
converted into the equivalent pointer program].
Rich set of API (application protocol interface) is available to develop any complex application.
The software JAVA contains a program called garbage collector which is always used to collect
unreferenced (unused) memory location for improving performance of a JAVA program.
[Garbage collector is the system JAVA program which runs in the background along with
regular JAVA program to collect unreferenced memory locations by running at periodical
interval of times for improving performance of JAVA applications.
JAVA contains user friendly syntax’s for developing JAVA applications.
Platform Independent:
A program or technology is said to be platform independent if and only if which can run on all
available operating systems.
The languages like C, Cpp are treated as platform dependent languages since these languages
are taking various amount of memory spaces on various operating systems [the operating system
dos understands everything in the form of its native format called Mozart (MZ) whereas the
operating system Unix understands everything in its negative format called embedded linking
format (elf). When we write a C or Cpp program on dos operating and if we try to transfer that
program to Unix operating system, we are unable to execute since the format of these operating
systems are different and more over the C, Cpp software does not contain any special programs
which converts one format of one operating system to another format of other operating
system].
The language like JAVA will have a common data types and the common memory spaces on
all operating systems and the JAVA software contains the special programs which converts the
format of one operating system to another format of other operating system. Hence JAVA
language is treated as platform independent language.
[JAVA language is also treated as server independent language since the server side program
can run on any of the server which is available in the real world (web server or application
server). JAVA can retrieve or store the data in any one of the data base product which is available
in rest world irrespective of their vendors (developers) hence JAVA language is product
independent language.
In order to deal with server side program from the client side, we can use C language client
program, Cpp client program, DOT NET client program, etc. hence JAVA language is a simple,
platform independent, server independent, data base/product independent and language
independent programming language].
Architectural Neutral:
A language or technology is said to be architectural neutral which can run on any available
processors in the real world. The languages like C, Cpp are treated as architectural dependent.
The language like JAVA can run on any of the processor irrespective of their architecture and
vendor.
Portable:
A portable language is one which can run on all operating systems and on all processors
irrespective their architectures and providers. The languages like C, Cpp are treated as non-
portable languages whereas the language JAVA is called portable language.
Multi Threading:
Definitions:
A flow of control is known as thread.
A multi threaded program is one in which there exists multiple flow of controls i.e., threads.
A program is said to be multi threaded program if and only of there exists n number of sub-
programs. For each and every sub-program there exists a separate flow of control. All such
flow of controls are executing concurrently. Such flow of controls is known as threads. Such
type of applications is known as multi threading applications.
The languages like C, Cpp are treated as threads as single threaded modeling languages
(STML). SMTL are those in which there exists single flow of control.
The languages like JAVA and DOT NET are treated as multi threaded modeling languages
(MTML). MTML are those in which there exist multiple flows of controls.
Whenever we write a JAVA program there exists by threads. They are
default two
Distributed:
A service is a said to be a distributed service which runs in multiple servers and that service
can be accessed by n number of clients across the globe. In order to develop distributed
applications we must require architecture called trusted network architecture. To develop these
applications we require a technology called J2EE. Distributed applications are preferred by large
scale organizations.
Networked:
In real world we have two types of networks. They are un-trusted networks and trusted
networks.
Un-trusted networks:
A network is said to be un-trusted network in which n number of inter
there exists
connected non-autonomous architecture. Un-trusted network is also known as LAN. Using this
network architecture, we develop centralized applications. A centralized application is one which
runs on single server and it can be access in limited graces. In order to develop centralized
applications we may use a technology called J2SE and these kinds of applications are preferred
by small scale organization.
Trusted network:
A network is said to be trusted network in which there exists n number of inter connected
autonomous architecture. Trusted network is also known as WAN. Using this network, we can
develop distributed applications. A distributed application is one which runs on multiple servers
and it can be access in unlimited graces. In order to develop distributed applications we may use
a technology called J2EE organization. and these kinds of applications are preferred by
large scale
When we represent the data in object oriented programming language we get the security.
Examples of object oriented programming languages are LISP, ADA, ALGOL, SMALLTALK, OBJECT
COBOL, OBJECT PASCAL, Cpp, JAVA, DOT NET, etc. In order to say any language is an object oriented
programming language it has to satisfy 8 principles of OOPs.
OOPs Principles:
Class.
Object.
Data Abstraction.
Data Encapsulation.
Inheritance.
Polymorphism.
Dynamic Binding.
Message Passing.
CLASS: “A class is a way of binding the data and associated methods in a single unit”.
Any JAVA program if we want to develop then that should be developed with respective
class only i.e., without class there is no JAVA program.
In object oriented programming’s, methods. They are
generally we write two types of
member methods and non-member methods.
A member method is one which is comes under the scope of the class. In JAVA we use only
member methods.
Non-member methods are those which are not comes under the scope of the class. JAVA
does not allow non-member methods at all.
Here, class is a keyword which is used for developing or creating user defined datatypes.
Clsname represents a JAVA valid variable name and it is treated as name of the class. Class names are
used for creating objects.
Class contains two parts namely variable declaration and method definitions. Variable
declaration represents what type of data members which we use as a part of the class. Method
definition represents the type of methods which we used as the path of the class to perform an
operation.
By making use of the variables, which are declared inside the class? Every operation in JAVA
must be defined with in the class only i.e., outside definition is not possible
Whenever we define a class there is no memory space for data members of the class. Memory
space will be created for the data members of the class when we create object.
NOTE:
In JAVA memory space for the data members will be creating on heap memory (Dynamic
memory).
Memory space for methods will be creating on stack memory (that too when we call the
methods).
All constants of any JAVA program is available in associative memory (retrieving data from
associative memory is negligible).
The class definition exists only one time but whose objects can exists many number of times i.e.,
a class is acting as a formula form.
OBJECT: In order to store the data for the data members of the class, we must create an object.
Instance (instance is a mechanism of allocating sufficient amount of memory space for data
members of a class) of a class is known as an object.
Class variable is known as an object.
Grouped item (grouped item is a variable which allows us to store more than one value) is known
as an object.
Value form of a class is known as an object.
Blue print of a class is known as an object.
Logical runtime entity is known as an object.
Real world entities are called as objects.
NOTE:
JAVA always follows dynamic memory allocation but not static memory allocation.
In order to create a memory space in JAVA we must use an operator called new. This new
operator is known as dynamic memory allocation operator.
Syntax-1 for defining an OBJECT:
<Clsname> objname = new <clsname ()>
Clsname () represents constructor. The new operator will perform two standard actions.
They are:
It allocates sufficient amount of memory space for the data members of the class.
It takes an address of the class and stored in the left hand side variable of syntax-1.
When an object is declared where value is null. Since, there is no memory space for data
members of the class. When the object is referenced the value of the object is not null. Since,
memory space is created for the data members of the class.
“The difference between class and object..?”
Class Object
A class is a way of binding the data and Class variable is known as an object.
associated methods in a single unit.
Whenever we start executing a JAVA After loading the class into main
program, the class will be loaded into memory, objects can be created in
main memory with the help of class n number.
loader subsystem (a part of JVM) only
once.
When the class id defined there is no 3) When an object is created we get the
memory space for data members of a memory space for data members of
class. the class.
Data Abstraction:
“Data abstraction is a mechanism of retrieving the essential details without dealing with
background details”.
NOTE:
In real world we have three levels of abstractions. They are physical level abstraction,
conceptual/logical level abstraction and view level abstraction.
Physical level abstraction is one; it always deals with physical organization architecture of the
application. For example, in real world an application designing of any problem comes under
physical level abstraction.
Conceptual/logical level abstraction is one it always deals with what kind of data we are entering
without dealing with physical architecture of the application. For example, entering the data
into the database, writing the coding and applying testing principle comes under conceptual
level abstraction.
View level abstraction deals with what kind of data we are retrieving without dealing with both
conceptual level abstraction and physical level abstraction. For example, retrieving the data
from the data base in various combinations. All internet users come under view level
abstraction.
Data Encapsulation:
“Data encapsulation is the process of wrapping up on data and associated methods in a
single unit”.
Data encapsulation is basically used for achieving data/information hiding i.e., security.
When we want to send the data from client to the server we must always send in the form of
JAVA object only. Since, by default the JAVA object is in encrypted form (we should not
send the data from client to the server in the form of fundamental data).
Inheritance:
Inheritance is the process of taking the features (data members + methods) from one class to
another class.
The class which is giving the features is known as base/parent class.
The class which is taking the features is known as derived/child/sub class.
Instance is known as sub classing or derivation or extendable classes or reusability.
Advantages of INHERITANCE:
Application development time is very less.
Redundancy (repetition) of the code is reducing. Hence we can get less memory cost and
consistent results.
Instrument cost towards the project is reduced.
We can achieve the slogan write one’s reuse/run anywhere (WORA) of JAVA.
An intermediate base class is one, in one context it acts as bass class and in another context
it acts as derived class.
Hierarchical Inheritance:
Hierarchical inheritance is one in which there exists single base class and n number of
derived classes.
Multiple Inheritances:
Multiple inheritance is one in which there exists n number of bass classes and single derived
classes.
Multiple inheritances are not supported by JAVA through classes but it is supported by JAVA
through the concept of interfaces.
Hybrid Inheritance:
Hybrid inheritance = combination of any available inheritances types.
Polymorphism:
Polymorphism is a process of representing “one form in many forms”.
In object oriented programming’s, we have two types of polymorphism. They are compile time
polymorphism and run time polymorphism.
JAVA does not support compile time polymorphism but JAVA supports only run time
polymorphism.
In the above diagram we have a single sum method but it is defined in many forms hence that
method is known as polymorphic method.
Dynamic Binding:
“Dynamic binding is a mechanism of binding an appropriate version of a derived class which
is inherited from base class with base class object”.
Every real time application will be developed with concept of polymorphism and executed
with the concept of dynamic binding.
Dynamic binding is basically used to reduce the amount of memory space for improving the
performance of JAVA applications.
1) C1 O1 = new C1();
2) O1.sum();
3) O1 = new C2();
4) O1.sum();
5) O1 = new C3();
6) O1.sum();
In the line numbers 1, 3 and 5 the object oven contains address of c1, c2 and c3 classes
respectively one at a time. Hence that object is known as polymorphic object. In the line numbers 2,
4 and 6 the statement O1.sum () is known as polymorphic statement.
NOTE:
Function overriding = function heading is same but function definition is different.
A function is said to be overloaded function if and only if function name is same but its signature
(signature represents number of parameters, type of parameters and order of parameters) is
different.
Message Passing:
Definitions:
Exchanging the data between multiple objects is known as message passing.
Message passing is the process of exchanging the data between two remote/local objects for a
period of time across the network (trusted) for generating multiple requests for obtaining
multiple responses for performing a meaningful operation.
“Data types are used for representing the data in main memory of the computer”.
In JAVA, we have eight data types which are organized in four groups. They are integer
category data types, float category data types, types and Boolean
character category data category data types.
Whatever the data type we use that should not exceed predefined value.
NOTE: Range of any data type = (A) number of bits occupied by a data type
Where, A = number of bits available in the language which is understand by computer i.e., 2
bits.
For example:
Range of byte = 28 256
= 1 to 2
= 0 to 5
= 0 to 5
(
2
5
5
/
2
)
= (127.5 - 0.5 = +127) (127.5 + 0.5 = -128)
“A variable is an identifier whose value will be changed during execution of the program”.
CONSTANTS in java
“Constant is an identifier whose value cannot be changed during execution of the program”.
In JAVA to make the identifiers are as constants, we use a keyword called final.
Final is a keyword which is playing an important role in three levels. They are at variable level, at
method level and at class level.
When we don’t want to change the value of the variable, then that variable must be declared as
final.
For example:
Final int a=10;
a=a+20;
//invalid a=30;
//invalid
When the final variable is initialized, no more modifications or assignments are possible.
For example:
Final int a;
a=a+1; //invalid
a=30+2; //invalid
a=400; //valid for 1st
time a=500; //invalid
Whenever a final variable is declared first time assignment is possible and no more modification
and further assignments are not possible. Hence, final variables cannot be modified.
PROGRAMMIG BASIC’S
System.out.println (“”);
This statement is used for displaying the data or messages on to the consol (monitor).
Here, println is the predefined instance method of print stream class.
To call this method we require an object called print stream class.
The object of print stream class is called out is created as a static data member in system class
(system is a predefined class).
Hence to call the println method we must use the following statement:
System.out.println (“WELCOME TO JAVA”);
Print stream class is a predefined class which contains nine overloaded instance println methods
and nine overloaded instance print methods and whose prototypes are as follows: Public
void println (byte);
Public void println (short);
Public void println (int);
Public void println (long);
Public void println (float);
Public void println
(double); Public void
println (char);
Public void println
(Boolean); Public void
println (string);
For example 1:
Int a=40000;
System.out.println (a); //40000
System.out.println (“value of a=” + a); //value of a=40000
System.out.println (a + “is the value of a”); //40000 is the value of a
For example 2:
Int a=10, b=20,
c; C = a + b;
System.out.println (c); //30
System.out.println (“sum=” + c);
//sum=30
System.out.println (c + “is the sum”); // 30 is the sum
System.out.println (“sum of” + a + “and” + b + “=” + c); //sum of 10 and 20 is 30
For example 3:
System.out.println (“WELCOME TO JAVA”);
Package details:
class <clsname>
{
Data member’s
methods;
NOTE:
While giving the file name to a JAVA program we must give the file name as name of the class
with an extension “.java” in which ever the class main method presents.
Whenever we give println it will prints in the new line whereas print prints in the same line.
Steps for COMPILING and RUNNING the java program
Write a JAVA program which illustrates the concept of instance methods and static methods?
Answer:
class Second
{
Void disp1 ()
{
System.out.println (“disp1-instance”);
}
Static void disp2 ()
{
System.out.println (“disp2-static”);
}
Public static void main (string k [])
{
System.out.println (“main-beginning”);
Second so = new Second ();
s
o
.
} d
} //second i
s
p
1
(
)
;
S
e s
c p
o 2
n (
d )
. ;
d System.out.println (“main-end”);
i
NOTE:
One static method can call another static method directly provide both the static method
belongs to same class.
One instance method can call another instance method directly provide both the static instance
method belongs to same class.
HUNGARIAN NOTATION:
Hungarian Notation is the naming convention followed by SUN (Stanford University Network)
micro system to develop their predefined classes, interfaces, methods and data members.
All the data members in the predefined classes and interfaces are belongs to public static
final XXX data members. XXX represents data type, variable name and variable value. Every final data
member must belong to static data member but reverse may or may not be applicable.
Write a JAVA program to generate the multiplication table for the given number?
Answer:
class Mul //Business Logic Class (BLC)
{
int n;
void set (int x)
{
n=x;
}
void table ()
{
for (int i=1; i<=10; i++)
{
int res=n*i;
System.out.println (n + “*” + i + “=” + result);
}
}
};
class MulDemo //Execution Logic Class (ELC)
{
Public static class main (string k [])
{
Mul mo = new Mul
(); mo.set (4);
mo.table ();
}
};
NOTE:
The data members of a class can be used in all the functions of the class.
The variable which we use as a part of function heading is known as formal parameters and they
can be used within the function only.
The variables which we use as a part of function definition/body then those variables known as
local variables and they can be used within its scope i.e., function definition.
The variables which we use within the function call then those variables are known as actual
parameters.
For example:
int n=4;
mo.set (n);
Where ’n’ is the actual parameter.
The following table gives the details about those classes and methods used for converting
storing data to fundamental data:
parseDouble
(string)
public static char
parseChar (string)
public static
boolean
parseBoolean
(string)
Whenever we develop a JAVA program it is recommended to write ‘n’ number of business logic
classes and single execution logic class. A business logic class is one which contains ‘n’ number of
user defined methods in which we write business logic. Business logic is one which is provided by
JAVA programmer according business rules (requirements) started by customer. Whatever data we
represent in JAVA runtime environment it is by default treated as objects of string data. As a
programmer when we start any JAVA program an object of string class is created depends on number
of values we pass.
Wrapper classes are basically used for converting the string data into fundamental data type.
Each and every wrapper class contains the following generalized parse methods.
public static Xxx parseXxx (String);
here, Xxx represents fundamental data type.
Length is an implicit attribute created by JVM to determine number of elements or size of the array.
For example:
int a [] = {10, 20, 30, 40};
System.out.println (a. length);
//4 String s1 [] = {10, 20, 30};
System.out.println (s1.length); //3
class Data
{
public static void main (String s [])
{
int noa=s.length;
System.out.println ("NUMBER OF VALUES
="+noa); System.out.println (s [0] +s [1]);
int x=Integer.parseInt (s [0]);
//8 int y=Integer.parseInt (s
[1]); //9 int z=x+y;
System.out.println ("SUM ="+z);
}
};
8 and 9 lines used for converting string into int data type.
Write a JAVA program for printing the data which we pass from command prompt?
Answer:
class Print
{
public static void main (String k [])
{
System.out.println ("NUMBER OF VALUES
="+k.length); for (int i=0; i<k.length; i++)
{
System.out.println (k[i] +" ");
}
}
};
Write a JAVA program which computes sum of two numbers by accepting the data from command
prompt (DOS)?
Answer:
class Sum
{
int a, b, c; //a,b,c are data members
void assign (int x, int y) //x,y are formal parameters
{
a=x
;
b=y
;
}
void add () //add () is business logic method
{
c=a+b;
}
void disp () //disp () is business logic method
{
System.out.println ("SUM OF "+a+" AND "+b+" = "+c);
}
};
class SumDemo
{
public static void main (String k [])
{
int x=Integer.parseInt (k
[0]); int y=Integer.parseInt
(k [1]); Sum so=new Sum ();
so. assign(x, y);
so. add ();
so.disp ();
}
};
NOTE: The data which we pass through command prompt is called command line arguments.
Write a JAVA program to check weather the given number is prime or not?
Answer:
class Prime
{
int n;
void set (int x)
{
n=x;
}
String decide ()
{
int i;
for (i=2; i<n; i++)
{
if (n%i==0)
{
break;
}
}
if (i==n)
{
return "PRIME";
}
else
{
return "NOT"+"PRIME";
}
}
};
class PrimeDemo
{
public static void main (String k [])
{
int n=Integer.parseInt (k
[0]); Prime po=new Prime ();
po.set (n);
String so=po.decide ();
System.out.println (so);
}
};
Write a JAVA program which converts an ordinary number into roman number?
Answer:
class Roman
{
int n;
void set (int x)
{
n=x;
}
void convert ()
{
if (n<=0)
{
System.out.print ("NO ROMAN FOR THE
} GIVEN NUMBER");
else
{
while (n>=1000)
{
System.out.print
("M"); n=n-1000;
}
if (n>=900)
{
System.out.print
("CM"); n=n-900;
}
if (n>=500)
{
System.out.print
("D"); n=n-500;
}
if (n>=400)
{
System.out.print
("CD"); n=n-400;
}
while (n>=100)
{
System.out.print
("C"); n=n-100;
}
if (n>=90)
{
System.out.print
("XC"); n=n-90;
}
if (n>=50)
{
System.out.print
("L"); n=n-50;
}
if (n>=40)
{
System.out.print
("XL"); n=n-40;
}
while (n>=10)
{
System.out.print
("X"); n=n-10;
}
if (n>=9)
{
System.out.print
("IX"); n=n-9;
}
if (n>=5)
{
System.out.print
("V"); n=n-5;
}
if (n>=4)
{
System.out.print
("IV"); n=n-4;
}
while (n>=1)
{
System.out.print
("I"); n=n-1;
}
System.out.println ();
}
}
};
class RomanDemo
{
public static void main (String k [])
{
int n=Integer.parseInt (k
[0]); Roman r=new Roman ();
r.set (n);
r.convert ();
}
};
CONSTRUCTORS in java
A constructor is a special member method which will be called by the JVM implicitly
(automatically) for placing user/programmer defined values instead of placing default values.
Constructors are meant for initializing the object.
ADVANTAGES of constructors:
A constructor eliminates placing the default values.
A constructor eliminates calling the normal method implicitly.
RULES/PROPERTIES/CHARACTERISTICS of a constructor:
Constructor name must be similar to name of the class.
Constructor should not return any value even void also (if we write the return type for the
constructor then that constructor will be treated as ordinary method).
Constructors should not be static since constructors will be called each and every time whenever
an object is creating.
Constructor should not be private provided an object of one class is created in another class
(constructor can be private provided an object of one class created in the same class).
Constructors will not be inherited at all.
Constructors are called automatically whenever an object is creating.
TYPES of constructors:
Based on creating objects in JAVA we have two types of constructors. They are
default/parameter less/no argument constructor and parameterized constructor.
A default constructor is one which will not take any parameters.
Syntax:
class <clsname>
{
clsname () //default constructor
{
Block of statements;
………………………………;
………………………………;
}
………………………;
………………………;
};
For example:
class Test
{
int a,
b; Test
()
{
System.out.println ("I AM FROM DEFAULT
CONSTRUCTOR..."); a=10;
b=20;
System.out.println ("VALUE OF a =
"+a); System.out.println ("VALUE OF b
= "+b);
}
};
class TestDemo
{
public static void main (String [] args)
{
Test t1=new Test ();
}
};
RULE-1:
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).
For example:
class Test
{
int a, b;
Test (int n1, int n2)
{
System.out.println ("I AM FROM PARAMETER CONSTRUCTOR...");
a=n1
;
b=n2
;
System.out.println ("VALUE OF a =
"+a); System.out.println ("VALUE OF b
= "+b);
}
};
class TestDemo1
{
public static void main (String k [])
{
Test t1=new Test (10, 20);
}
};
RULE-2:
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.
For example:
Test t1=new Test (10, 20);
Test t2=new Test (10, 20, 30);
Test t3=new Test (10.5, 20.5);
Test t4=new Test (10, 20.5);
Test t5=new Test (10.5, 20);
RULE-3:
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).
Write a JAVA program which illustrates the concept of default constructor, parameterized constructor
and overloaded constructor?
Answer:
class Test
{
int a,
b; Test
()
{
System.out.println ("I AM FROM DEFAULT
CONSTRUCTOR..."); a=1;
b=2;
System.out.println ("VALUE OF a
="+a); System.out.println ("VALUE OF
b ="+b);
}
Test (int x, int y)
{
System.out.println ("I AM FROM DOUBLE PARAMETERIZED CONSTRUCTOR...");
a=x
;
b=y
;
System.out.println ("VALUE OF a
="+a); System.out.println ("VALUE OF
b ="+b);
}
Test (int x)
{
System.out.println ("I AM FROM SINGLE PARAMETERIZED CONSTRUCTOR...");
a=x
;
b=x
;
System.out.println ("VALUE OF a
="+a); System.out.println ("VALUE OF
b ="+b);
}
Test (Test T)
{
System.out.println ("I AM FROM OBJECT PARAMETERIZED CONSTRUCTOR...");
a=T.a;
b=T.b;
System.out.println ("VALUE OF a
="+a); System.out.println ("VALUE OF
b ="+b);
}
};
class TestDemo2
{
public static void main (String k [])
{
Test t1=new Test ();
Test t2=new Test (10,
20); Test t3=new Test
(1000); Test t4=new Test
(t1);
}
};
‘this ‘: ‘this’ is an internal or implicit object created by JAVA for two purposes. They are
‘this’ object is internally pointing to current class object.
i. Whenever the formal parameters and data members of the class are similar, to differentiate
the data members of the class from formal parameters, the data members of class must be
proceeded by ‘this’.
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.
For example:
class Test
{
int a,
b; Test
()
{
🡪 this (10); //calling current class single parameterized constructor
System.out.println ("I AM FROM DEFAULT
CONSTRUCTOR..."); a=1;
b=2;
System.out.println ("VALUE OF a =
"+a); System.out.println ("VALUE OF b
= "+b);
}
Test (int x) ---2
{
🡪 this (100, 200); //calling current class double parameterized constructor
System.out.println ("I AM FROM SINGLE PARAMETERIZED CONSTRUCTOR...");
a=b=x;
System.out.println ("VALUE OF a =
"+a); System.out.println ("VALUE OF b
= "+b);
}
Test (int a, int b) ---3
{
System.out.println ("I AM FROM DEFAULT CONSTRUCTOR...");
this.a=a
;
this.b=b
;
System.out.println ("VALUE OF a = "+this.a);
System.out.println ("VALUE OF b = "+this.b);
System.out.println ("VALUE OF a = "+a);
System.out.println ("VALUE OF b = "+b);
}
};
class TestDemo3
{
public static void main (String k [])
{
🡪 Test t1=new Test ();
}
};
NOTE:
Whenever we refer the data members which are similar to formal parameters, the JVM
gives first preference to formal parameters whereas whenever we write a keyword this before the
variable name of a class then the JVM refers to data members of the class.
this methods are used for calling current class constructors.
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.
For example:
SOURCE OBJECT. METHOD NAME (TARGET OBJECT);
t1. display (t2); // written in main
In the definition of display method t1 data members are referred by this. Data member names
(this. a & this. b) whereas t2 object data members are referred by formal object name. Data member
names (T. a & T. b).
Write a JAVA program which computes sum of two objects by accepting the data from command
prompt?
Answer:
class Test
{
int
a,b;
Test ()
{
a=b=0;
}
Test (int a, int b)
{
this.a=a
;
this.b=b
;
}
Test sum (Test T)
{
Test T11=new Test
();
T11.a=this.a+T.a;
T11.b=this.b+T.b;
return (T11);
}
void display ()
{
System.out.println ("VALUE OF a =
"+a); System.out.println ("VALUE OF b
= "+b);
}
};
class SumDemo1
{
public static void main (String k[])
{
int n1=Integer.parseInt
(k[0]); int
n2=Integer.parseInt (k[1]);
int n3=Integer.parseInt
(k[2]); int
n4=Integer.parseInt (k[3]);
Test t1=new Test (n1,n2);
Test t2=new Test
(n3,n4); Test t3=new
Test ();
// t3=t1+t2; invalid statement
t3=t1.sum (t2);
System.out.println ("t1 VALUES ARE AS
FOLLOWS..."); t1.display ();
System.out.println ("t2 VALUES ARE AS
FOLLOWS..."); t2.display ();
System.out.println ("t3 VALUES ARE AS
FOLLOWS..."); t3.display ();
}
};
Based on reusing the data members from one class to another class in JAVA we have three types
of relationships. They are is-a relationship, has-a relationship and uses-a relationship.
Is-a relationship is one in which data members of one class is obtained into another class
through the concept of inheritance.
Has-a relationship is one in which an object of one class is created as a data member in
another class.
Uses-a relationship is one in which a method of one class is using an object of another class.
Inheritance is the technique which allows us to inherit the data members and methods from
base class to derived class.
Base class is one which always gives its features to derived classes.
Derived class is one which always takes features from base class.
A Derived class is one which contains some of features of its own plus some of the data members
from base class.
Syntax for INHERITING the features from base class to derived class:
class <clsname-2> extends <clsname-1>
{
Variable
declaration; Method
definition;
};
Here, clsname-1 and clsname-2 represents derived class and base class respectively.
Extends is a keyword which is used for inheriting the data members and methods from base class to
the derived class and it also improves functionality of derived class.
NOTE:
Final classes cannot be inherited.
If the base class contains private data members then that type of data members will not be
inherited into derived class.
One class can extend only one class at a time. Since, JAVA does not support multiple inheritance.
Whenever we inherit the base class members into derived class, when we creates an object of
derived class, JVM always creates the memory space for base class members first and later memory
space will be created for derived class members.
For example:
class c1;
{
int a;
void
f1()
{
…………;
}
};
class c2 extends c1
{
int b;
void
f2()
{
…………;
}
};
NOTE:
Whatever the data members are coming from base class to the derived class, the base class
members are logically declared in derived class, the base class methods are logically defined
in derived class.
Private data members and private methods of the base class will not be inherited at all.
For every class in JAVA we have a super class called object class. The purpose of object class
is that it provides garbage collector for collecting unreferenced memory locations from the derived
classes.
‘Super’ keyword:
Super keyword is used for differentiating the base class features with derived class features.
Super keyword is placing an important role in three places. They are at variable level, at method level
and at constructor level.
Super at variable level
Whenever we inherit the base class members into derived class, there is a possibility that
base class members are similar to derived class members.
In order to distinguish the base class members with derived class members in the derived
class, the base class members will be preceded by a keyword super.
Syntax for super at VARIABLE LEVEL:
super. base class member name
For example:
class Bc
{
int a;
};
class Dc extends Bc
{
int a;
void set (int x, int y)
{
super.a=x;
a=y; //by default 'a' is preceded with 'this.' since 'this.' represents current class
}
void sum ()
{
System.out.println ("SUM = "+(super.a+a));
}
};
class InDemo1
{
public static void main (String k [])
{
int n1=Integer.parseInt
(k[0]); int
n2=Integer.parseInt (k[1]); Dc
do1=new Dc ();
do1.set (n1, n2);
do1.sum ();
}
};
Syntax for super at method level: super. base class method name
For example:
class Bc
{
void display ()
{
System.out.println ("BASE CLASS - DISPLAY...");
}
};
class Dc extends Bc
{
void display ()
{
super.display (); //refers to base class display
method System.out.println ("DERIVED CLASS -
DISPLAY...");
}
};
class InDemo2
{
public static void main (String k [])
{
Dc do1=new Dc ();
do1.display ();
}
};
Super () is used for calling super class default constructor from default constructor or from
parameterized constructor of derived class. It is optional.
Super (…) is used for calling super class parameterized constructor either from default
constructor or from parameterized constructor of derived class. It is always mandatory.
RULES:
Whenever we use either super () or super (…) in derived class constructors they must be
used as first statement.
Whenever we want to call default constructor of base class from default constructor of derived
class using super () in default constructor of derived class is optional.
For example:
class Bc
{
Bc ()
{ System.out.println ("I AM FROM BASE
CLASS...");
}
};
class InDemo3
{
public static void mai
{
Dc o1=new Dc n
}
}; (St
rin
g k [])
();
Whenever we want to call the super class parameterized class from parameterized class of the
derived class using super (…) in parameterized class of derived class is mandatory.
For example:
class C1
{
int a;
C1 (int a)
{
System.out.println ("PARAMETERIZED CONSTRUCTOR -
C1"); this.a=a;
System.out.println ("VALUE OF a = "+a);
}
};
class C2 extends C1
{
int b;
C2 (int a, int b)
{
super (a);
System.out.println ("PARAMETERIZED CONSTRUCTOR –
C2"); this.b=b;
System.out.println ("VALUE OF b = "+b);
}
};
class InDemo4
{
public static void main (String k [])
{
C2 o2=new C2 (10, 20);
}
};
Whenever we want to call default constructor of base class from parameterized class of derived
class using super () in parameterized class of derived class is optional.
For example:
class C1
{
int a; C1 ()
{
System.out.println
("PARAMETERIZED
CONSTRUCTOR - C1");
} this.a=a;
}; System.out.println ("VALUE OF a = "+a);
class C2 extends C1
{
int b;
C2 (int b)
{
super (); //optional
System.out.println ("PARAMETERIZED CONSTRUCTOR -
C2"); this.b=b;
System.out.println ("VALUE OF b = "+b);
}
};
class InDemo5
{
public static void main (String k [])
{
C2 o2=new C2 (20);
}
};
Whenever we want to call parameterized class of base class from default constructor of derived
class using super (…) in default constructor of derived class is mandatory.
For example:
class C1
{
int a;
C1 (int a)
{
System.out.println ("PARAMETERIZED CONSTRUCTOR -
C1"); this.a=a;
System.out.println ("VALUE OF a = "+a);
}
};
class C2 extends C1
{
int b; C2 ()
{
super (10);
System.out.println
("DEFAULT
CONSTRUCTOR - C2");
} this.b=20;
}; System.out.println ("VALUE OF b = "+b);
class InDemo6
{
public static void main (String k [])
{
C2 o2=new C2 ();
}
};
Bc (int x)
{
this ();
System.out.println ("BASE CLASS - PARAMETERIZED CONSTRUCTOR");
}
};
class Ibc extends Bc
{
Ibc ()
{ super (100);
System.out.println ("INTERMEDIATE BASE CLASS
- DEFAULT CONSTRUCTOR");
}
Ibc (int x)
{
this ();
System.out.println ("INTERMEDIATE BASE CLASS - PARAMETERIZED CONSTRUCTOR");
}
};
class Dc extends Ibc
{
Dc ()
{ this (10);
System.out.println ("DERIVED CLASS -
DEFAULT CONSTRUCTOR");
}
Dc (int x)
{
super (10);
System.out.println ("DERIVED CLASS - PARAMETERIZED CONSTRUCTOR");
}
};
class StDemo
{
public static void main (String k [])
{
Dc do1=new Dc ();
}
};
ABSTRACT CLASSES:
In JAVA we have two types of classes. They are concrete classes and abstract classes.
A concrete class is one which contains fully defined methods. Defined methods are also known as
implemented or concrete methods. With respect to concrete class, we can create an object
of that class directly.
For example:
class C1
{
int a,b;
void f1 ()
{
…………;
…………;
}
void f2 ()
{
…………;
…………;
}
};
An abstract class is one which contains some defined methods and some undefined methods.
Undefined methods are also known as unimplemented or abstract methods. Abstract
method is one which does not contain any definition. To make the method as abstract we
have to use a keyword called abstract before the function declaration.
For example:
Abstract void sum ();
The abstract methods make us to understand what a method can do but it does not give how
the method can be implemented. Every abstract method belongs to a class under class is known as
abstract class, to make the class as abstract we use a keyword called abstract before the class
specification.
For example:
abstract class Op
{
abstract void sum ();
};
With respect to abstract class we cannot create an object direct but we can create indirectly.
An object abstract class is equal to an object of that class which extends that abstract class.
For example:
class CC extends AC
{
…………;
…………;
};
AC Ao=new AC ();
//invalid AC Ao=new CC
();
or
AC Ao;
Ao=new CC ();
Write a JAVA program for computing sum of two integers and floats using abstract classes?
Answer:
abstract class Op
{
abstract void sum ();
};
class isum extends Op
{
void sum ()
{
int
a,b,c;
a=10;
b=20;
c=a+b;
System.out.println ("INT VALUE = "+c);
}
};
class fsum extends Op
{
void sum ()
{
float
f1,f2,f3;
f1=10.26f;
f2=20.32f;
f3=f1+f2;
System.out.println ("FLOAT VALUE = "+f3);
}
};
class AbDemo
{
public static void main (String k [])
{
// Op o1=new Op ();
invalid Op o2;
o2=new isum
(); o2.sum ();
o2=new fsum
(); o2.sum ();
}
};
Abstract classes should not be final, since, they are always reusable. Abstract classes are
basically used to implement polymorphism; we use the concept of dynamic binding. Hence, abstract
classes, polymorphism and dynamic binding will improve the performance of JAVA J2EE applications
by reducing amount of memory space.
Whenever we inherit ‘n’ number of abstract methods from abstract base class to derived
class, if the derived class defines all ‘n’ number of abstract methods then the derived class is
concrete class. If the derived class is not defining at least one abstract method out of ‘n’ abstract
methods then the derived class is known as abstract derived class and to make that class abstract, we
use a keyword called abstract.
An abstract base class is one which contains physical representation of abstract methods. An
abstract derived class is one which contains logical declaration of abstract methods which are
inherited from abstract base class.
Implement the above diagram by using abstract class’s polymorphism and dynamic binding.
Answer:
abstract class C1
{
abstract void f1
(); abstract void
f2 ();
};
abstract class C2 extends C1
{
void f1 ()
{
System.out.println ("f1-C2-original");
}
};
class C3 extends C2
{
void f1 ()
{
super.f1 ();
System.out.println ("f1-C3-OVERRIDDEN");
}
void f2 ()
{
System.out.println ("f2-C3");
}
void f3 ()
{
System.out.println ("f3-C3-SPECIALLY DEFINED");
}
};
class AbDemo1
{
public static void main (String k [])
{
C3 o3=new C3
(); o3.f1 ();
o3.f2 ();
o3.f3 ();
// C2 o2=new C2 ();
invalid C2 o2=new C3
();
o2.f1 ();
o2.f2 ();
// o2.f3 (); invalid
C1 o1=new C3 (); // or
o2 o1.f1 ();
o1.f2 ();
// o1.f3 ();
}
};
Output:
With respect to Concrete Class:
C3 o3=new C3 ();
o3.f1 (); // f1 - overridden -
C3 o3.f2 (); // f2 - C3
o3.f3 (); // f3 - defined in - C3
An object of either concrete base class or abstract base class contains the details about those
methods which are available in that class only but this object (concrete base class or abstract base
class) does not contains details of those methods which are specially defined in derived class’s.
Application:
Write a JAVA program to display the fonts of the system?
Answer:
import
java.awt.GraphicsEnvironment; class
Fonts
{
public static void main (String k [])
{
GraphicsEnvironment
ge=GraphicsEnvironment.getLocalGraphicsEnvironment
(); String s []=ge.getAvailableFontFamilyNames ();
System.out.println ("NUMBER OF FONTS = "+s.length);
for (int i=0; i<s.length; i++)
{
System.out.println (s [i]);
}
}
};
A factory method is one whose return type is similar to name of the class where it presents.
For example:
getLocalGraphicsEnvironment ();
Factory methods are used for creating an object without using new operator. Every predefined
abstract class contains at least one factory method for creating an object of abstract class.
Whenever we define a concrete class, that concrete class also can be made it as abstract
and it is always further reusable or extendable by further classes.
When we define only concrete class we may extend or we may not extend by derived
classes.
Interfaces:
Interfaces are basically used to develop user defined data types.
With respect to interfaces we can achieve the concept of multiple inheritances.
With interfaces we can achieve the concept of polymorphism, dynamic binding and hence we can
improve the performance of a JAVA program in turns of memory space and execution time.
Interface is a keyword which is used for developing user defined data types. Interface name
represent a JAVA valid variable name and it is treated as name of the interface. With respect to
interface we cannot create an object directly but we can create indirectly.
Variable declaration represents the type of data members which we use a part of interface.
Whatever the variables we use in the interface are meant for general purpose (the variables like PI,
e, etc.).
Whatever the variables we write in the interface, they are by default belongs to:
public static final xxx data members
xxx represents data type, variable name and variable value.
All variables must be initialized (otherwise it will be compilation error). Method declaration
represents the type of methods we use as a part of interface. All the methods of interface are
undefined methods and to make those methods as abstract, the JAVA programmer need not to write
a keyword abstract explicitly before the declaration of interface method.
Since all the methods of interface are meant for general purpose hence they must give
universal access. To make it as universal access the JAVA programmer need not to write a keyword
public explicitly before the method declaration. Hence, by default all the methods of interfaces
belong to public abstract methods.
For example:
Interface i1
{
Int a; //invalid since, initializing is
mandatory Int b=20;
Void f1 ();
Void f2 ();
}
NOTE:
Whenever we compile an interface, we get <interface name>.class as an
intermediate file, if no errors are present in interface.
Syntax-1 for reusing the features of interface(s) to class:
[abstract] class <clsname> implements <intf 1>,<intf 2>.........<intf n>
{
variable declaration;
method definition or declaration;
};
In the above syntax clsname represents name of the class which is inheriting the features
from ‘n’ number of interfaces. ‘Implements’ is a keyword which is used to inherit the features of
interface(s) to a derived class.
NOTE:
When we inherit ‘n’ number of abstract methods from ‘n’ number of interfaces to the
derived class, if the derived class provides definition for all ‘n’ number of abstract methods then the
derived class is known as concrete class. If the derived class is not providing definition for at least
one abstract class and it must be made as abstract by using a keyword abstract.
For example:
interface I1
{
int
a=10;
void f1
();
};
interface I2 extends I1
{
int
b=20;
void f2
();
};
If one interface is taking the features of another interface then that inheritance is known as
interface inheritance
Syntax-3:
[abstract] class <derived class name> extends <base class
name> implements <intf 1>,<intf 2>.........<intf n>
{
variable declaration;
method definition or declaration;
};
Whenever we use both extends and implements keywords as a part of JAVA program we
must always write extends keyword first and latter we must use implements keyword.
Important points:
An object of interface cannot be created directly since it contains ‘n’ number of abstract methods.
An object of interface can be created indirectly. An object of interface = an object of that class
which implements that interface.
An object of base interface contains the details about those methods which are declared in that
interface only but it does not contain details about those methods which are specially available
in either in derived classes or in derived interfaces.
Interfaces should not be final.
An interface does not contain Constructors.
PACKAGE
PREDEFINED PACKAGES
Predefined packages are those which are developed by SUN micro systems and supplied as a
part of JDK (Java Development Kit) to simplify the task of java programmer.
NOTE:
Core packages of java starts with java. (For example: java.lang.*) and Advanced packages of
java starts with javax. (For example: java.sql.*)
java.io.* This package is used for developing file handling applications, such as, opening
the file in read or write mode, reading or writing the data, etc.
java.awt.* This package is used for developing GUI (Graphic Unit Interface) components such
(abstract as buttons, check boxes, scroll boxes, etc.
windowing toolkit)
java.awt.event.* Event is the sub package of awt package. This package is used for providing the
functionality to GUI components, such as, when button is clicked or when check
box is checked, when scroll box is adjusted either vertically or
horizontally.
java.applet.* This package is used for developing browser oriented applications. In other words
this package is used for developing distributed programs.
An applet is a java program which runs in the context of www or browser.
java.net.* This package is used for developing client server applications.
java.util.* This package is used for developing quality or reliable applications in java or J2EE.
This package contains various classes and interfaces which improves the
performance of J2ME applications. This package is also known as collection
framework (collection framework is the standardized mechanism of grouping of
similar or different type of objects into single object. This single object is
known as collection object).
java.text.* This package is used for formatting date and time on day to day business
operations.
java.lang.reflect.* Reflect is the sub package of lang package. This package is basically used to study
runtime information about the class or interface. Runtime information represents
data members of the class or interface, Constructors of the class,
types of methods of the class or interface.
java.sql.* This package is used for retrieving the data from data base and performing
various operations on data base.
A user defined package is one which is developed by java programmers to simplify the task
of the java programmers to keep set of classes, interfaces and sub packages which are commonly
used. Any class or interface is commonly used by many java programmers that class or interface
must be placed in packages.
Syntax:
package pack1[.pack2[.pack3……[.packn]…..]];
Here, package is a keyword which is used for creating user defined packages, pack1 represents
upper package and pack2 to packn represents sub packages.
For example:
package p1; 🡪 statement-1
package p1.p2; 🡪
statement-2
The statements 1 and 2 are called package statements.
RULE:
Whenever we create user defined package statement as a part of java program, we must use
package statement as a first executable statement.
NOTE:
Whenever we develop any JAVA program it contains ‘n’ number of classes and interfaces.
Each and every class and interface which are developed by the programmer must belong to a
package (according to industry standards). If the programmer is not keeping the set of classes and
interfaces in a package, JVM will assume its own package called NONAME package.
NONAME package will exist only for a limited span of time until the program is completing.
For example:
// Test.java
package tp;
public class
Test
{
public Test ()
{
System.out.println ("TEST - DEFAULT CONSTRUCTOR");
}
public void show ()
{
System.out.println ("TEST - SHOW");
}
}
//ITest.
java
package
tp;
public interface ITest
{
void disp ();
}
For example:
javac –d . Test.java
Here, -d is an option or switch which gives an indication to JVM saying that go to Test.java
program take the package name and that package name is created as directory automatically
provides no errors are present in Test.java. When Test.java is not containing any errors we get Test.
class file and it will be copied automatically into current directory which is created recently i.e., tp
(package name). The above program cannot be executed since it doesn’t contain any main method.
For example:
Import p1.*; 1
Import p1.p2.*; 2
Import p1.p2.p3.*; 3
When statement 1 is executing we can import or we can access all the classes and interfaces
of package p1 only but not its sub packages p2 and p3 classes and interfaces.
When statement 2 is executing we can import as the classes and interfaces of package p2
only but not p1 and p3 classes and interfaces.
When statement 3 is executing we can import as the classes and interfaces of package p3
only but not p1 and p2 classes and interfaces.
Syntax-2:
Import pack1 [.pack2 [.…………[.packn]]].class name/interface name;
For example:
Import p1.c1; 4
Import p1.p2.c3; 5
When statement 4 is executing can import c1 class of package p1 only but not other classes
and interfaces of p1 package, p2 package and p3 package.
When we compile the above program we get the following error “package tp does not exist”. To
avoid the above error we must set the classpath as., SET CLASSPATH =
%CLASSPATH%;.;
When two classes or an interface belongs to the same package and if they want to refer
those classes or interfaces need not to be referred by its package name.
For example:
// I1.java
// javac -d . I1.java
package ip;
public interface I1
{
public void f1
(); public
void f2 ();
};
// C01.java
// javac -d . C01.java
package cp;
public abstract class C01 implements ip.I1
{
public void f1 ()
{
System.out.println ("F1 - C01");
}
};
// C02.java
// javac -d . C02.java
package cp;
public class C02 extends C01
{
public void f2 ()
{
System.out.println ("F2 - C02");
}
public void f1 ()
{
super. f1 ();
System.out.println ("F1 - C02 - OVER RIDDEN");
}
};
// PackDemo.java
// javac PackDemo.java
import
ip.I1;
class
PackDemo
{
public static void main (String [] args)
{
System.out.println ("CP.C02");
cp.C02 o2=new cp.C02 ();
o2.f1 ();
o2.f2 ();
System.out.println ("CP.C01");
cp.C01 o1=new cp.C02 ();
o1.f1 ();
o1.f2 ();
I1 io;
io=o1; //new cp.C02
(); io.f1 ();
io.f2 ();
}
};
In order to run the above program we must run with respect to package name.
1🡪 javac –d . PackDemo1.java
mp/PackDemo1
2🡪 java mp.PackDemo1 or java
In order to use the data from one package to another package or within the package, we
have to use the concept of access specifiers. In JAVA we have four types of access specifiers. They
are private, default (not a keyword), protected and public.
Access specifiers makes us to understand how to access the data within the package (class
to class, interface to interface and interfaces to class) and across the package (class to class,
interface to interface and interfaces to class). In other words access specifiers represent the visibility
of data or accessibility of data.
Syntax for declaring a variable along with access specifiers:
[Access specifiers] [Static] [Final] data type v1 [=val1], v2 [=val2] …vn [=valn];
For example:
Public static final int
a=10; Protected int d;
Int x; [If we are not using any access specifier it is by default treated as default access specifier]
Private int e;
Private Default Protected Public
Other package
derived class × √ √
×
Other package
independent class × × × √
NOTE:
Private access specifier is also known as native access specifier.
Default access specifier is also known as package access specifier.
Protected access specifier is also known as inherited access specifier.
Public access specifier is also known as universal access specifier.
package sp;
public class
Sbc
{
private int
N_PRI=10; int
N_DEF=20;
protected int
N_PRO=30; public
int N_PUB=40;
public Sbc()
{
System.out.println ("VALUE OF N_PRIVATE =
"+N_PRI); System.out.println ("VALUE OF N_DEFAULT
= "+N_DEF); System.out.println ("VALUE OF
N_PROTECTED = "+N_PRO); System.out.println ("VALUE
OF N_PUBLIC = "+N_PUB);
}
};
// Sdc.java
// javac -d . Sdc.java
package sp;
public class Sdc extends Sbc //(is-a relation & within only)
{
public Sdc()
{
// System.out.println ("VALUE OF N_PRIVATE =
"+N_PRI); System.out.println ("VALUE OF N_DEFAULT
= "+N_DEF); System.out.println ("VALUE OF
N_PROTECTED = "+N_PRO);
System.out.println ("VALUE OF N_PUBLIC = "+N_PUB);
}
};
// Sic.java
// javac -d . Sic.java
package sp;
public class
Sic
{
Sbc so=new Sbc(); // (has-a relation & within
only) public Sic()
{
// System.out.println ("VALUE OF N_PRIVATE =
"+so.N_PRI); System.out.println ("VALUE OF N_DEFAULT
= "+so.N_DEF); System.out.println ("VALUE OF
N_PROTECTED = "+so.N_PRO); System.out.println
("VALUE OF N_PUBLIC = "+so.N_PUB);
}
};
// Odc.java
// javac -d .
Odc.java package
op;
public class Odc extends sp.Sbc // (is-a relation & across)
{
public Odc ()
{
// System.out.println ("VALUE OF N_PRIVATE = "+N_PRI);
// System.out.println ("VALUE OF N_DEFAULT =
"+N_DEF); System.out.println ("VALUE OF
N_PROTECTED = "+N_PRO); System.out.println
("VALUE OF N_PUBLIC = "+N_PUB);
}
};
// Oic.java
// javac -d . Oic.java
package op;
public class
Oic
{
sp.Sbc so=new sp.Sbc (); // (has-a relation &
across) public Oic ()
{
// System.out.println ("VALUE OF N_PRIVATE = "+so.N_PRI);
// System.out.println ("VALUE OF N_DEFAULT = "+so.N_DEF);
// System.out.println ("VALUE OF N_PROTECTED =
"+so.N_PRO); System.out.println ("VALUE OF N_PUBLIC
= "+so.N_PUB);
}
};
// ASDemo.java
// javac ASDemo.java
import
sp.Sbc;
import
sp.Sdc;
import
sp.Sic;
class
ASDemo
{
public static void main (String [] args)
{
// import approach
To convert the above statements into nameless object approach follow the following statements.
For example:
// nameless object approach
new Test ().display ();
EXCEPTIONAL HANDLING
Whenever we develop any project in real time it should work in all circumstances (mean in
any operation either in error or error free). Every technology or every programming language, if we
use for implementing real time applications and if the end user commits a mistake then by default
that language or technology displays system error messages which are nothing but run time errors.
Exceptional handling is a mechanism of converting system error messages into user friendly
messages.
Errors are of two types. They are compile time errors and run time errors.
Compile time errors are those which are occurring because of poor understanding of the language.
Run time errors are those which are occurring in a program when the user inputs invalid data.
The run time errors must be always converted by the JAVA programmer into user friendly
messages by using the concept of exceptional handling.
In JAVA run time environment, to perform any kind of operation or task or an action that will
be performed with respect to either class or an interface.
Whenever we pass invalid data as an input to the JAVA program then JAVA run time environment
displays an error message, that error message is treated as a class.
Types of exceptions:
In JAVA we have two types of exceptions they are predefined exceptions and user or custom
defined exceptions.
Predefined exceptions are those which are developed by SUN micro system and supplied as a part of
JDK to deal with universal problems. Some of the universal problems are dividing by zero, invalid
format of the number, invalid bounce of the array, etc.
Predefined exceptions are divided into two types. They are asynchronous exceptions and
synchronous exceptions.
Asynchronous exceptions are those which are always deals with hardware problems. In
order to deal with asynchronous exceptions there is a predefined class called java.lang.Error.
java.lang.Error class is the super class for all asynchronous exceptions.
Synchronous exceptions are one which always deals with programmatic errors. In order to
deal with synchronous exceptions we must use a predefined class called java.lang.Exception class.
java.lang.Exception is the super class for all synchronous exceptions. Synchronous exceptions are divided
into two types. They are checked exceptions and unchecked exceptions.
A checked exception is one which always deals with compile time errors regarding class not found
and interface not found.
Unchecked exceptions are those which are always deals with programmatic run time errors such as
ArithmeticException, NumberFormatException, ArrayIndexOutOfBoundsException, etc.
An exception is an object which occurs at run time which describes the nature of the message.
The nature of the message can be either system error message or user friendly message.
Whenever we pass irrelevant input to a JAVA program, JVM cannot process the irrelevant input.
Since JVM is unable to process by user input, hence it for getting an
can contact to JRE appropriate exception class.
JRE contacts to java.lang.Throwable for finding what
type of exception it is.
java.lang.Throwable decides what type of exception it is and pass the message to JRE.
JRE pass the type of exception to JAVA API.
[6.1 & 6.2] From the JAVA API either java.lang.Error class or java.lang.Exception class will found an
appropriate sub class exception.
Either java.lang.Error class or java.lang.Exception class gives an appropriate exception class to JRE.
JRE will give an appropriate exception class to JVM.
JVM will create an object of appropriate exception class which is obtained from JRE and it generates
system error message.
In order to make the program very strong (robust), JAVA programmer must convert the system error
messages into user friendly messages by using the concept of exceptional handling.
User friendly messages are understand by normal user effectively hence our program is robust.
try
{ are to be monitored by JVM at run time
Block of statements which problematic (or
errors);
}
finally
{
Block of statements which releases the resources;
}
Try block:
This is the block in which we write the block of statements which are to be monitored by JVM at run
time i.e., try block must contain those statements which causes problems at run time.
If any exception is taking place the control will be jumped automatically to appropriate catch block.
If any exception is taking place in try block execution will be terminated and the rest of the
statements in try block will not be executed at all and the control will go to catch block.
For every try block we must have at least one catch block. It is highly recommended to write ‘n’
number of catch’s for ‘n’ number of problematic statements.
Catch block:
This is used for providing user friendly messages by catching system error messages.
In the catch we must declare an object of the appropriate execution class and it will be internally
referenced JVM whenever the appropriate situation taking place.
If we write ‘n’ number of catch’s as a part of JAVA program then only one catch will be executing at
any point.
After executing appropriate catch block even if we use return statement in the catch block the
control never goes to try block.
Finally block:
This is the block which is executing compulsory whether the exception is taking place or not.
This block contains same statements which releases the resources which are obtained in try block
(resources are opening files, opening databases, etc.).
Writing the finally block is optional.
For example:
class Ex1
{
public static void main (String [] args)
{
try
{ S
t
r
i
n
g
s
} 1
=
a
r
g
s
[
0
]
;
S
t
r
i
n
g
s
2
=
a
r
g
s
[
1
]
;
int
n1=I
nteg
er.p
arse
Int
(s1)
;
int
n2=I
nteg
er.p int
arse n3=n
Int 1/n2
(s2) ;
; System.out.println ("DIVISION VALUE =
"+n3);
catch (ArithmeticException Ae)
{
System.out.println ("DONT ENTER ZERO FOR DENOMINATOR...");
}
catch (NumberFormatException Nfe)
{
System.out.println ("PASS ONLY INTEGER VALUES...");
}
catch (ArrayIndexOutOfBoundsException Aioobe)
{
System.out.println ("PASS DATA FROM COMMAND PROMPT...");
}
finally
{
System.out.println ("I AM FROM FINALLY...");
}
}
};
Throws block: This is the keyword which gives an indication to the calling function to keep the
called function under try and catch blocks.
Syntax:
<Return type> method name (number of parameters if any) throws type of
exception1,type of exception2,………type of exception;
Write a JAVA program which illustrates the concept of throws keyword?
Answer:
(CALLED FUNCTION)
package ep;
public class
Ex2
{
public void div (String s1, String s2) throws ArithmeticException, NumberFormatException
{
int n1=Integer.parseInt
(s1); int
n2=Integer.parseInt (s2);
int n3=n1/n2;
System.out.println ("DIVISOIN = "+n3);
}
};
(CALLING FUNCTION)
import
ep.Ex2;
class Ex3
{
public static void main (String [] args)
{
try
{ String s1=args [0];
S
t
r
i
} n
g
s
2
=
a
r
g
s
[
1
]
;
E
x
2
e
o
=
n
e
w
E
x
2
(
)
;
e
o
.
d
i
v
(
s
1
,
s )
2 ;
catch (ArithmeticException Ae)
{
System.out.println ("DONT ENTER ZERO FOR DENOMINATOR");
}
catch (NumberFormatException Nfe)
{
System.out.println ("PASS INTEGER VALUES ONLY");
}
catch (ArrayIndexOutOfBoundsException Aioobe)
{
System.out.println ("PASS VALUES FROM COMMAND PROMPT");
}
}
};
Using an object of java.lang.Exception: An object of Exception class prints the name of the exception
and nature of the message.
For example:
try
{
int x=Integer.parseInt ("10x");
}
catch (Exception e)
{
System.out.println (e); // java.lang.NumberFormatException : for input string 10x
} name of the exception nature of the message
Using printStackTrace method: This is the method which is defined in java.lang.Throwable class and
it is inherited into java.lang.Error class and java.lang.Exception class. This method will display
name of the exception, nature of the message and line number where the exception has taken
place.
For example:
try
{
......;
int x=10/0;
......;
}
catch (Exception e)
{
e.printStackTrace (); // java.lang.ArithmeticException : / by zero : at line no: 4
} name of the exception nature of the message line number
Using getMessage method: This is also a method which is defined in java.lang.Throwable class and it
is inherited into both Error and Exception classes. This method will display only nature of the
message.
For example:
try
{
......;
int x=10/0;
......;
}
catch (Exception e)
{
System.out.println (e.getMessage ()); // / by zero
} nature of the message
User defined exceptions are those which are developed by JAVA programmer as a part of
application development for dealing with specific problems such as negative salaries, negative ages,
etc.
For example:
package na; // step1
public class Nage extends Exception // step2 & step3
{
public Nage (String s) // step4
{
super (s);// step5
}
};
Write a JAVA program which illustrates the concept of user defined exceptions?
Answer:
package na;
public class Nage extends Exception
{
public Nage (String s)
{
super (s);
}
};
package ap;
import
na.Nage;
public class
Age
{
public void decide (String s) throws NumberFormatException, Nage
{
int ag= Integer.parseInt
(s); if (ag<=0)
{
Nage na=new Nage ("U HAV ENTERED INVALID
AGE..!");
} throw (na);
else
{
import
na.Nage;
import
ap.Age;
class CDemo
{
public static void main(String[] args)
{
try
{ S
t
r
i
} n
g
s
1
=
a
r
g
s
[
0
]
;
a
p
.
A )
g ;
e A
A o
o .
= d
n e
e c
w i
a d
p e
. (
A s
g 1
e )
( ;
catch (Nage na)
{
System.out.println (na);
}
catch (NumberFormatException nfe)
{
System.out.println ("PASS ONLY INTEGER VALUES..!");
}
catch (ArithmeticException ae)
{
System.out.println ("PASS INTEGER VALUES ONLY..!");
}
catch (ArrayIndexOutOfBoundsException aioobe)
{
System.out.println ("PASS VALUES THROUGH COMMAND PROMPT..!");
}
catch (Exception e)
{
System.out.println (e);
}
}
};
NOTE: Main method should not throw any exception since the main method is called by JVM and JVM
cannot provide user friendly message.