Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

CS3391 Object Oriented Programming Lecture Notes Watermark

The document provides an overview of Object-Oriented Programming (OOP) concepts such as abstraction, encapsulation, inheritance, and polymorphism, specifically in the context of Java. It details the structure of Java programs, the Java environment including JRE, JDK, and JVM, and highlights the features of Java that contribute to its popularity, such as portability, security, and robustness. Additionally, it contrasts OOP with procedure-oriented programming and explains fundamental programming structures in Java.

Uploaded by

latag16024
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

CS3391 Object Oriented Programming Lecture Notes Watermark

The document provides an overview of Object-Oriented Programming (OOP) concepts such as abstraction, encapsulation, inheritance, and polymorphism, specifically in the context of Java. It details the structure of Java programs, the Java environment including JRE, JDK, and JVM, and highlights the features of Java that contribute to its popularity, such as portability, security, and robustness. Additionally, it contrasts OOP with procedure-oriented programming and explains fundamental programming structures in Java.

Uploaded by

latag16024
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 174

UNITI

INTRODUCTIONTO OOPAND JAVAFUNDAMENTALS


Object Oriented Programming - Abstraction – objects and classes - Encapsulation- Inheritance-
Polymorphism- OOP inJava – Characteristics of Java – The Java Environment -Java Source File- Structure
Compilation.Fundamental Programming Structures in Java – Defining classes in Java –
constructors,methods- access specifiers-staticmembers- Comments,DataTypes,Variables, Operators, Control
Flow, Arrays, Packages - JavaDoc comments.

OBJECT-ORIENTEDPROGRAMMING
Object-OrientedProgramming(OOP)isaprogramminglanguagemodelorganized
aroundobjectsrather than actions and data. An object-oriented program can be characterized as data
controlling access to code. Concepts of OOPS
 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation
OBJECT
Objectmeans arealword entitysuch aspen, chair,tableetc.Anyentitythat hasstateandbehavioris known
as an object. Object can be defined as an instance of a class. An object contains an address and takes up
some space in memory. Objects can communicate without knowing details of each other's data or code, the
only necessary thing is that the type of message accepted and type of response returned by the objects.
Anobject hasthreecharacteristics:
 state:representsdata(value)ofan object.
 behavior:representsthe behavior(functionality)ofanobjectsuch asdeposit,withdrawetc.
 identity: Object identity is typically implemented via a unique ID. The value of the ID is not
visible to the external user. But, it is used internallybythe JVM to identifyeach object uniquely.
CLASS
Collection of objectsis called class. It is a logical entity. A class can also be defined as a blueprint
fromwhich you cancreateanindividualobject. AclassconsistsofDatamembersandmethods.The primary
purposeofaclassistoholddata/information.Thememberfunctionsdeterminethebehavioroftheclass,
i.e.provide adefinitionfor supportingvariousoperationsondataheldintheformofanobject.Classdoesn’t
store anyspace.
INHERITANCE
Inheritance can be defined as the procedure or mechanism of acquiring all the properties and
behavior of one class to another, i.e., acquiring the properties and behavior of child class from the parent
class. When one object acquires all the properties and behaviours of another object, it is known as
inheritance. It provides code reusability and establishes relationships between different classes. A class
which inherits the properties is known as Child Class(sub-class or derived class) whereas a class whose
properties are inherited is known as Parent class(super-class or base class). Types of inheritance in java:
single, multilevel and hierarchical inheritance. Multiple and hybrid inheritance is supported through
interface only.
1
POLYMORPHISM
Whenone task is performed by different ways i.e. known as polymorphism. For example: to
convince the customer differently, to draw something e.g. shape or rectangle etc.

Polymorphismisclassifiedintotwo ways:
MethodOverloading(CompiletimePolymorphism)
MethodOverloadingisafeaturethatallowsaclasstohavetwoormoremethods havingthesamenamebut
theargumentspassedtothemethodsaredifferent.Compiletimepolymorphismreferstoaprocessinwhich a call to
an overloaded method is resolved at compile time rather than at run time.
MethodOverriding(RuntimePolymorphism)
If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in java.In other words, If subclass provides the specific implementation of the method that has
been provided by one of its parent class, it is known as method overriding.
ABSTRACTION
Abstractionis a process of hiding the implementation details and showing only functionality to the
user. For example: phone call, we don't know the internal processing.In java, we use abstract class and
interface to achieve abstraction.
ENCAPSULATION
Encapsulation in javais aprocess of wrapping code and data together into a single unit, for example
capsule i.e. mixed of several medicines.A java class is the example of encapsulation.

DIFFERENCEBETWEENPROCEDURE-ORIENTEDANDOBJECT-ORIENTED
PROGRAMMING
Procedure-OrientedProgramming Object-OrientedProgramming
InPOP,programisdividedintosmallparts In OOP, program is divided into parts
calledfunctions calledobjects.
InPOP,Importanceisnotgiventodatabutto InOOP,Importanceisgiventothedatarather

2
functionsaswellassequenceofactionstobe thanproceduresorfunctionsbecauseitworksas
done. areal world.
POPfollows Top Down approach. OOPfollows BottomUpapproach.
POP does nothaveanyaccessspecifier. OOPhasaccessspecifiersnamedPublic,Private,
Protected,etc.
InPOP,Datacanmovefreelyfromfunctionto InOOP,objectscanmoveandcommunicatewith
functioninthesystem. eachotherthroughmember functions.
ToaddnewdataandfunctioninPOPisnotso OOPprovidesaneasywaytoaddnewdataand
easy. function.
InPOP,MostfunctionusesGlobaldataforsharingthat In OOP, data can not move easily from
canbeaccessedfreelyfromfunction functiontofunction,itcanbekeptpublicorprivatesow
tofunction inthesystem. e
cancontrolthe accessof data.
POPdoesnothaveanyproperwayforhiding OOPprovidesDataHidingsoprovidesmore
dataso it isless secure. security.
InPOP,Overloadingisnot possible. InOOP,overloadingispossibleintheformof
FunctionOverloadingandOperatorOverloading.
ExampleofPOPare:C,VB,FORTRAN, ExampleofOOPare:C++,JAVA,VB.NET,
Pascal. C#.NET.

FEATURESOF JAVA
The main objective of Java programminglanguage creation was to make it portable, simple and secure
programming language. Apart from this, there are also some awesome features which playimportant role in
the popularity of this language. The features of Java are also known as java buzzwords.
AlistofmostimportantfeaturesofJavalanguage aregivenbelow.
Simple
Javaisveryeasytolearnanditssyntaxissimple,cleanandeasytounderstand.AccordingtoSun,Java language is a simple
programming language because:
 Javasyntax is basedonC++(soeasierfor programmerstolearn itafter C++).
 Javahasremovedmanyconfusingandrarely-usedfeaturese.g.explicitpointers,operator overloading etc.
 There is no need to remove unreferenced objects because there is Automatic Garbage Collection in
java.
Object-oriented
Java isobject-orientedprogramming language. Everything in Java is an object. Object-oriented means we
organize our software as a combination of different types of objects that incorporates both data and
behaviour.
Object-oriented programming (OOPs) is a methodology that simplifies software development and
maintenance by providing some rules.
Basicconceptsof OOPsare:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
PlatformIndependent
3
Java is platform independent because it is different from other languages like C,C++etc. which are compiled
into platform specific machines while Java is a write once, run anywhere language. A platform is the
hardware or software environment in which a program runs.
There are two types of platforms software-based and hardware-based. Java provides software-based
platform.

The Java platform differs from most other platforms in the sense that it is a software-based platform that
runs on the top of other hardware-based platforms. It has two components:
1. Runtime Environment
2. API(ApplicationProgrammingInterface)
Java code can be run on multiple platforms e.g. Windows, Linux, Sun Solaris, Mac/OS etc. Java code is
compiled by the compiler and converted into bytecode. This bytecode is a platform-independent code
because it can be run on multiple platforms i.e. Write Once and Run Anywhere(WORA).
Secured
Javais best knownfor its security.WithJava, we candevelop virus-freesystems.Javais secured because:
o No explicit pointer
o JavaProgramsruninsidevirtualmachinesandbox

4
 Classloader:Classloader in Java is a part of the Java Runtime Environment(JRE) which is used to
dynamically load Java classes into the Java Virtual Machine. It adds security by separating the
package for the classes of the local file system from those that are imported from network sources.
 Bytecode Verifier: It checks the code fragments for illegal code that can violate access right to
objects.
 Security Manager:It determines what resources a class can access such as reading and writing to
the local disk.
These security are provided by java language. Some security can also be provided by application developer
through SSL, JAAS, Cryptography etc.
Robust
 Robustsimplymeans strong. Javais robustbecause:
 It usesstrongmemorymanagement.
 Therearelackof pointers thatavoids securityproblems.
 ThereisautomaticgarbagecollectioninjavawhichrunsontheJavaVirtualMachinetogetridof objects which
are not being used by a Java application anymore.
 Thereis exception handlingand typecheckingmechanism in java. Allthesepoints makes java robust.
Architecture-neutral
Javaisarchitectureneutralbecausethereisnoimplementationdependentfeaturese.g.sizeofprimitive types is
fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of memory
for 64-bit architecture. But in java, it occupies 4 bytes of memory for both 32 and 64 bit architectures.
Portable
Java is portable because it facilitatesyou to carry the java bytecode to any platform. It doesn't require
anytype of implementation.
High-performance
Java is faster than other traditional interpreted programming languages because Java bytecode is "close" to
native code. It is still a little bit slower than a compiled language (e.g. C++). Java is an interpreted language
that is why it is slower than compiled languages e.g. C, C++ etc.
Distributed
Java is distributed because it facilitates users to create distributed applications in java. RMI and EJB areused
for creating distributed applications. This feature of Java makes us able to access files by calling the
methods from any machine on the internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that deal with
many tasks at once by defining multiple threads. The main advantage of multi-threading is that it doesn't
occupy memory for each thread. It shares a common memory area. Threads are important for multi-media,
Web applications etc.
Dynamic
Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded on demand.
It also supports functions from its native languages i.e. C and C++.
Javasupports dynamiccompilationand automaticmemorymanagement(garbagecollection).

GARBAGECOLLECTION
Objects are dynamically allocated by using the new operator, dynamically allocated objects must be
manually released by use of a delete operator. Java takes a different approach; it handles deallocation
automaticallythis is called garbage collection. When no references to an object exist, that object is assumed
to be no longer needed, and the memory occupied by the object can be reclaimed. Garbage collection only
occurs sporadically (if at all) during the execution of your program. It will not occur simply because one or
more objects exist that are no longer used.
5
THEJAVAENVIRONMENT
JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java Runtime
Environment is a set of software tools which are used for developing java applications. It is used to provide
runtime environment. It is the implementation of JVM. It physically exists. It contains set of libraries +other
files that JVM uses at runtime.
ImplementationofJVMsarealsoactivelyreleased byother companies besides Sun Micro Systems.

JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software development
environment which is used to develop java applications and applets. It physically exists. It contains JRE +
development tools.
JDKis an implementation of anyoneof thebelowgiven JavaPlatforms released byOraclecorporation:
 StandardEditionJavaPlatform
 EnterpriseEditionJavaPlatform
 MicroEdition JavaPlatform
The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an
interpreter/loader (Java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc) etc. to
complete the development of a Java Application.

6
JVM(Java Virtual Machine)
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment
in which java bytecode can be executed.
JVMsareavailableformanyhardwareandsoftwareplatforms(i.e.JVMisplatformdependent). The JVM
performs following operation:
 Loadscode
 Verifiescode
 Executescode
 Providesruntimeenvironment
JVM provides definitions for the:
 Memoryarea
 Classfileformat
 Register set
 Garbage-collectedheap
 Fatalerrorreporting etc.
InternalArchitectureof JVM

1. Classloader
Classloaderis asubsystem ofJVM that is usedtoload class files.
2. Class(Method)Area
Class(Method) Area stores per-class structures such as the runtime constant pool, field and method data, the
code for methods.
3. Heap
Itistheruntime dataarea in whichobjectsareallocated.
4. Stack
Java Stack stores frames. It holds local variables and partial results, and plays a part in method
invocationand return.
Eachthreadhasaprivate JVMstack,createdatthesametimeas thread.
Anewframeiscreatedeachtimeamethodisinvoked.Aframeisdestroyedwhenitsmethodinvocation completes.

7
5. ProgramCounterRegister
PC (program counter) register contains the address of the Java virtual machine instruction currently being
executed.
6. NativeMethodStack
Itcontainsall thenativemethodsused inthe application.
7. Execution Engine
Contains a virtual processor, Interpreter to read bytecode stream then execute the instructions and Just-In-
Time(JIT) compiler is used to improve the performance. JIT compiles parts of the byte code that have
similar functionality at the same time, and hence reduces the amount of time needed for compilation. Here,
the term "compiler" refers to a translator from the instruction set of a Java virtual machine (JVM) to the
instruction set of a specific CPU.

STRUCTUREOFJAVAPROGRAM
AfirstSimpleJavaProgram
classSimple
{
publicstaticvoid main(String args[])
{
System.out.println("JavaWorld");
}
}
To compile:
javacSimple.java
To execute:
java Simple
classkeywordisusedtodeclareaclassin java.
publickeywordisanaccessmodifierwhichrepresentsvisibility,itmeansitisvisibletoall.
staticis a keyword, if we declare any method as static, it is known as static method. The core advantage of
staticmethodisthatthereisnoneedtocreateobjecttoinvokethestaticmethod.Themainmethodis executed by the
JVM, so it doesn't require to create object to invoke the main method. So it saves memory. void is the return
type of the method, it means it doesn't return any value.
mainrepresentsthestartingpointoftheprogram.
String[]argsisusedforcommandlineargument.
System.out.println() is used print statement.

A programiswritten inJAVA, the javaccompiles it. The resultof the JAVA compileristhe .classfile or the
bytecode and not the machine native code (unlike C compiler).
Thebytecodegeneratedisanon-executablecodeandneedsaninterpretertoexecuteonamachine.This interpreter is the
JVM and thus the Bytecode is executed by the JVM.
Andfinallyprogramrunstogive thedesired output.

8
DEFININGCLASSESIN JAVA
TheclassisatthecoreofJava.Aclassisatemplateforanobject,andanobjectisan instanceofaclass.A class is
declared by use of the class keyword
Syntax:
classclassname{
typeinstance-variable1;
typeinstance-variable2;
// ...
typeinstance-variableN;
typemethodname1(parameter-list){
// bodyofmethod
}
...
typemethodnameN(parameter-list) {
// bodyofmethod
}
The data, or variables, defined within a class are called instance variables. The code is contained within
methods. The methods and variables defined within a class are called members of the class. In most classes,
the instance variables are acted upon and accessed by the methods defined for that class.
Variablesdefinedwithinaclassarecalledinstancevariablesbecause each instanceof theclass(that is,each object
of the class) contains its own copy of these variables. Thus, the data for one object is separate and unique
from the data for another.

ASimple Class
classcalledBoxthat
definesthreeinstancevariables:width,height,anddepth.
class Box {
double width;
doubleheight;
double depth;
}
ThenewdatatypeiscalledBox.ThisnameisusedtodeclareobjectsoftypeBox.Theclassdeclaration only creates a
template. It does not create an actual object.

Tocreatea Box object

Box mybox=newBox();//createaBox objectcalledmybox

myboxwill bean instanceof Box.


9
Each time you create an instance of a class, you are creating an object that contains its own copy of each
instance variable defined by the class. To access these variables, you will use the dot (.) operator. The dot
operator links the name of the object with the name of an instance variable.
Example1:
/*AprogramthatusestheBoxclass. Call
this file BoxDemo.java
*/
class Box {
double width;
doubleheight;
double depth;
}
//ThisclassdeclaresanobjectoftypeBox. class
BoxDemo {
publicstaticvoidmain(Stringargs[]){ Box
mybox = new Box();
double vol;
//assignvaluestomybox'sinstancevariables
mybox.width = 10;
mybox.height=20;
mybox.depth=15;
//computevolumeof box
vol=mybox.width*mybox.height*mybox.depth;
System.out.println("Volume is " + vol);
}
}
Output:
Volume is 3000.0

Example2:
//ThisprogramdeclarestwoBoxobjects. class
Box {
double width;
doubleheight;
double depth;
}
classBoxDemo2{
publicstaticvoidmain(Stringargs[]){ Box
mybox1 = new Box();
Boxmybox2=newBox();
double vol;
//assignvaluestomybox1'sinstancevariables mybox1.width
= 10;
mybox1.height=20;
mybox1.depth=15;
/*assigndifferentvaluestomybox2's
instance variables */
mybox2.width= 3;
mybox2.height=6;

10
mybox2.depth=9;
// computevolumeof first box
vol=mybox1.width*mybox1.height*mybox1.depth;
System.out.println("Volume is " + vol);
//computevolumeof second box
vol=mybox2.width*mybox2.height*mybox2.depth;
System.out.println("Volume is " + vol);
}
}
Output:
Volume is 3000.0
Volume is 162.0
DeclaringObjects
First,declareavariableoftheclasstype.Thisvariabledoesnotdefineanobject.Instead,itissimplya variable that can refer
to an object.
Second, you must acquire an actual, physical copy of the object and assign it to that variable. This is done
using the new operator. The new operator dynamically allocates (that is, allocates at run time) memory for
an object and returns a reference to it. This reference is then stored in the variable. Thus, in Java, all class
objects must be dynamically allocated.
Syntax:
Box mybox =newBox();
Box mybox; // declare reference to object
mybox=newBox();//allocateaBoxobject

The first line declares mybox as a reference to an object of type Box. At this point, mybox does not yetrefer
to an actual object. The next line allocates an object and assigns a reference to it to mybox. After the second
line executes, we can use mybox as if it were a Box object. But in reality, mybox simply holds, in essence,
the memory address of the actual Box object.

AssigningObjectReferenceVariables
Syntax:
Boxb1=newBox(); Box
b2 = b1;
b2isbeingassignedareferencetoacopyoftheobjectreferredtobyb1.b1andb2willbothrefertothe
sameobject.Theassignmentofb1tob2didnotallocateanymemoryorcopyanypartoftheoriginal

11
object.Itsimplymakesb2refertothesameobjectasdoesb1.Thus,anychangesmadetotheobject through b2 will affect
the object to which b1 is referring, since they are the same object.

CONSTRUCTORS
 Constructorsarespecialmemberfunctions whose taskistoinitializetheobjectsofits class.
 Itisaspecialmemberfunction,it hasthesameastheclass name.
 Javaconstructorsareinvokedwhentheirobjectsarecreated. Itisnamedsuchbecause,itconstructs the
value, that is provides data for the object and are used to initialize objects.
 Everyclasshasaconstructorwhenwedon'texplicitlydeclareaconstructorforanyjavaclassthe compiler
creates a default constructor for that class which does not have any return type.
 TheconstructorinJavacannotbeabstract,static,finalorsynchronizedandthesemodifiersarenot allowed
for the constructor.
Thereare two typesof constructors:
1. Defaultconstructor(no-argconstructor)
2. Parameterizedconstructor

Defaultconstructor(no-argconstructor)
Aconstructorhavingnoparameterisknownasdefault constructor andno-argconstructor.
Example:
/*Here,Boxusesaconstructortoinitializethe
dimensions of a box.
*/
class Box {
double width;
doubleheight;
double depth;
//ThisistheconstructorforBox.
Box() {
System.out.println("ConstructingBox");
width = 10;
height=10;
depth= 10;
}
//computeandreturnvolume
double volume() {
returnwidth*height*depth;
}
}
12
classBoxDemo6{
publicstatic void main(Stringargs[]) {
//declare,allocate,andinitializeBoxobjects
Box mybox1 = new Box();
Boxmybox2=newBox();
double vol;
//getvolumeoffirstbox vol=
mybox1.volume();
System.out.println("Volumeis"+vol);
//getvolumeofsecondbox vol
= mybox2.volume();
System.out.println("Volumeis"+vol);
}
}

Output:
ConstructingBox
ConstructingBox
Volume is 1000.0
Volume is 1000.0
new Box( ) is calling the Box( ) constructor. When the constructor for a class is not explicitlydefined , then
Java creates a default constructor for the class. The default constructor automatically initializes all instance
variables to their default values, which are zero, null, and false, for numeric types, reference types, and
boolean, respectively.

ParameterizedConstructors
Aconstructorwhichhasaspecificnumberofparametersiscalledparameterizedconstructor. Parameterized constructor
is used to provide different values to the distinct objects.
Example:
/*Here,Boxusesaparameterizedconstructorto
initialize the dimensions of a box.
*/
class Box {
double width;
doubleheight;
double depth;
// This is the constructor for Box.
Box(doublew,doubleh,doubled){ width
= w;
height=h;
depth = d;
}
//computeandreturnvolume
double volume() {
returnwidth*height*depth;
}
}
classBoxDemo7{
publicstatic void main(Stringargs[]) {

13
//declare,allocate,andinitializeBoxobjects
Box mybox1 = new Box(10, 20, 15);
Boxmybox2=newBox(3,6,9);
double vol;
//getvolumeoffirstbox vol=
mybox1.volume();
System.out.println("Volumeis"+vol);
//getvolumeofsecondbox vol
= mybox2.volume();
System.out.println("Volumeis"+vol);
}
}

Output:
Volume is 3000.0
Volume is 162.0
Boxmybox1=newBox(10,20, 15);
Thevalues 10, 20, and15 are passedto theBox( ) constructorwhen newcreates theobject.Thus,mybox1’s
copyof width,height, anddepthwill containthe values10, 20,and 15respectively.

OverloadingConstructors
Example:
/*Here,Boxdefinesthreeconstructorstoinitialize the
dimensions of a box various ways.
*/
class Box {
double width;
doubleheight;
double depth;
//constructorusedwhenalldimensionsspecified Box(double
w, double h, double d) {
width=w;
height=h;
depth = d;
}
//constructorusedwhennodimensionsspecified
Box() {
width=-1;//use-1toindicate height
= -1; // an uninitialized depth = -1;
// box
}
//constructorusedwhencubeiscreated
Box(double len) {
width=height=depth=len;
}
//computeandreturnvolume
double volume() {
returnwidth*height*depth;
}

14
}
classOverloadCons
{
publicstatic void main(Stringargs[])
{
//createboxesusingthevariousconstructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Boxmycube=newBox(7);
double vol;
//getvolumeoffirstbox
vol=mybox1.volume();
System.out.println("Volumeofmybox1 is"+vol);
//getvolumeofsecondbox vol
= mybox2.volume();
System.out.println("Volumeofmybox2 is"+vol);
// get volume of cube
vol=mycube.volume();
System.out.println("Volumeofmycubeis" +vol);
}
}
Output:
Volumeofmybox1is3000.0
Volume of mybox2 is -1.0
Volume of mycube is 343.0

METHODS
Syntax:
typename(parameter-list) {
// bodyofmethod
}
 typespecifiesthetypeofdatareturnedby themethod.Thiscanbeanyvalidtype,includingclass types that
you create.
 Ifthe methoddoes not returnavalue,its return type must bevoid.
 Thename ofthe methodis specified byname.
 The parameter-list is a sequence of type and identifier pairs separated by commas. Parameters are
essentiallyvariablesthatreceivethevalueoftheargumentspassedtothemethodwhenitiscalled. If the
method has no parameters, then the parameter list will be empty.
 Methods that have a return type other than void return a value to the calling routine using the
following form of the return statement:
Syntax:
returnvalue;
Example:
//Thisprogramincludesamethodinsidetheboxclass. class
Box {
double width;
doubleheight;
double depth;
// displayvolumeofabox
15
void volume() {
System.out.print("Volumeis");
System.out.println(width*height*depth);
}}
classBoxDemo3{
publicstaticvoidmain(Stringargs[]){ Box
mybox1 = new Box();
Box mybox2=newBox();
//assignvaluestomybox1'sinstancevariables mybox1.width
= 10;
mybox1.height=20;
mybox1.depth=15;
/*assigndifferentvaluestomybox2's
instance variables */
mybox2.width= 3;
mybox2.height=6;
mybox2.depth=9;
//displayvolumeoffirstbox
mybox1.volume();
//displayvolumeofsecondbox
mybox2.volume();
}
}
Output:
Volume is 3000.0
Volumeis 162.0
Thefirstlinehereinvokesthevolume()methodonmybox1.Thatis,itcallsvolume()relativetothe
mybox1object,using theobject’snamefollowedby thedotoperator.Thus,thecalltomybox1.volume ( )
displays the volume of the box defined by mybox1, and the call to mybox2.volume( ) displays the volume
of the box defined by mybox2. Each time volume( ) is invoked, it displays the volume for the specified
box.
ReturningaValue
Example:
//Now,volume()returnsthevolumeofabox. class
Box {
double width;
doubleheight;
double depth;
//computeandreturnvolume
double volume() {
returnwidth*height*depth;
}
}
classBoxDemo4{
publicstaticvoidmain(Stringargs[]){ Box
mybox1 = new Box();
Boxmybox2=newBox();
double vol;
//assignvaluestomybox1'sinstancevariables

16
mybox1.width= 10;
mybox1.height=20;
mybox1.depth=15;
/*assigndifferentvaluestomybox2's
instance variables */
mybox2.width= 3;
mybox2.height=6;
mybox2.depth=9;
//getvolumeoffirstbox vol
= mybox1.volume();
System.out.println("Volumeis"+vol);
//getvolumeofsecondbox vol
= mybox2.volume();
System.out.println("Volumeis"+vol);
}
}
Output:
Volume is 3000
Volume is 162

whenvolume()iscalled,itisputontherightsideofanassignment statement.Ontheleftisavariable,in this case vol,


that will receive the value returned by volume( ).
Syntax:
vol= mybox1.volume();
executes,thevalue ofmybox1.volume( )is 3,000and thisvalue thenis storedinvol.

Therearetwo importantthings tounderstandaboutreturningvalues:


• Thetypeof datareturned byamethod must be compatiblewith thereturntypespecified bythemethod.
• Thevariablereceivingthevaluereturnedbyamethod(suchas vol,inthiscase)mustalsobecompatible with the
return type specified for the method.

AddingaMethodThatTakesParameters
Example:
//Thisprogramusesaparameterizedmethod.
class Box {
double width;
doubleheight;
double depth;
//computeandreturnvolume
double volume() {
returnwidth*height *depth;
}
//sets dimensions of box
voidsetDim(doublew,doubleh,doubled){
width = w;
height=h;
depth = d;
}
}

17
classBoxDemo5{
publicstaticvoidmain(Stringargs[]){ Box
mybox1 = new Box();
Boxmybox2=newBox();
double vol;
// initialize each box
mybox1.setDim(10,20,15);
mybox2.setDim(3,6,9);
//getvolumeoffirstbox vol=
mybox1.volume();
System.out.println("Volumeis"+vol);
//getvolumeofsecondbox vol
= mybox2.volume();
System.out.println("Volumeis"+vol);
}
}
Output:
Volume is 3000
Volume is 162

Thethis Keyword
this keyword is used to to refer to the object that invoked it. this can be used inside any method to refer to
the current object. That is, this is always a reference to the object on which the method was invoked. this()
can be used to invoke current class constructor.
Syntax:
Box(doublew,doubleh,doubled){
this.width = w;
this.height=h;
this.depth = d;
}
Example:
classStudent
{
int id;
Stringname;
student(int id, Stringname)
{
this.id = id;
this.name=name;

}
void display()
{
System.out.println(id+""+name);
}
publicstatic void main(Stringargs[])
{
Studentstud1=newStudent(01,"Tarun");
Studentstud2 =new Student(02,"Barun");

18
stud1.display();
stud2.display();
}
}
Output:
01 Tarun
02 Barun

Overloading Methods
When two or more methods within the same class that have the same name, but their parameter declarations
are different. The methods are said to be overloaded, and the process is referred to as method overloading.
Method overloading is one of the ways that Java supports polymorphism.
Therearetwo waystooverload themethodin java
1. Bychangingnumberofarguments
2. Bychangingthe datatype
Example:
//Demonstratemethodoverloading. class
OverloadDemo {
voidtest() {
System.out.println("Noparameters");
}
//Overloadtestforoneintegerparameter. void
test(int a) {
System.out.println("a:"+a);
}
//Overloadtestfortwointegerparameters. void
test(int a, int b) {
System.out.println("a and b:"+a +"" +b);
}
//Overloadtestforadoubleparameter
double test(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
classOverload{
public static void main(String args[]) {
OverloadDemoob=newOverloadDemo();
double result;
//callallversionsoftest()
ob.test();
ob.test(10);
ob.test(10,20);
result= ob.test(123.25);
System.out.println("Resultofob.test(123.25):"+ result);
}
}
Output:
No parameters

19
a:10
aand b: 10 20
doublea:123.25
Resultofob.test(123.25):15190.5625
Method Overriding
When a method in a subclass has the same name and type signature as a method in its superclass, then the
method in the subclass is said to override the method in the superclass. When an overridden method iscalled
from within its subclass, it will always refer to the version of that method defined by the subclass.The
version of the method defined by the superclass will be hidden.
Example:
//Methodoverriding.
class A {
int i, j;
A(inta,intb) {
i = a;
j = b;
}
//displayiandj
void show() {
System.out.println("iandj:"+i+""+j);
}
}
classBextendsA{ int
k;
B(inta,intb,intc){
super(a, b);
k =c;
}
//displayk–thisoverridesshow()inA void
show() {
System.out.println("k: "+k);
}
}
classOverride{
publicstaticvoidmain(Stringargs[]){ B
subOb = new B(1, 2, 3);
subOb.show();//thiscallsshow()inB
}
}
Output:
k: 3

Whenshow()isinvokedonanobjectoftypeB,theversionofshow()definedwithinBisused.Thatis,the version of
show( ) inside B overrides the version declared in A. If you wish to access the superclass version of an
overridden method, you can do so by using super. For example, in this version of B, the superclass
versionofshow()isinvokedwithinthesubclass’version.Thisallowsallinstancevariablestobedisplayed. class B
extends A {
int k;
B(inta,int b,intc) {
20
super(a,b);
k = c;
}
voidshow(){
super.show();//thiscallsA'sshow()
System.out.println("k: " + k);
}
}
Ifyousubstitutethisversionof Aintothepreviousprogram,youwillseethe following
Output:
i and j: 1 2
k: 3
Here,super.show( )callsthe superclass versionof show( ).

ACCESSPROTECTION
Theaccessmodifiersinjavaspecifiesaccessibility(scope)ofadatamember,method,constructororclass. There are
4 types of java access modifiers:
1. private
2. default
3. protected
4. public
1) PrivateAccessModifier
Theprivateaccessmodifierisaccessibleonlywithinclass.
Simple example of private access modifier
In this example, we have created two classes A and Simple. A class contains private data member and
private method. We are accessing these private members from outside the class, so there is compile time
error.
classA{
privateintdata=40;
privatevoidmsg(){System.out.println("Hellojava");}
}
publicclassSimple{
publicstaticvoidmain(Stringargs[]){ A
obj=new A();
System.out.println(obj.data);//CompileTimeError
obj.msg();//Compile Time Error
}
}
RoleofPrivateConstructor
If youmake anyclassconstructorprivate, you cannotcreatetheinstanceof thatclassfromoutsidetheclass. For
example:
classA{
privateA(){}//private constructor
voidmsg(){System.out.println("Hellojava");}
}
publicclassSimple{
publicstaticvoid main(String args[]){
21
Aobj=newA();//CompileTime Error
}
}

If youmake anyclassconstructorprivate, you cannotcreatetheinstanceofthatclassfromoutsidetheclass. For


example:
classA{
privateA(){}//private constructor
voidmsg(){System.out.println("Hellojava");}
}
publicclassSimple{
public static void main(String args[]){
Aobj=newA();//CompileTime Error
}
}

2) DefaultAccessModifier
Ifyoudon'tuseanymodifier,itistreatedas defaultbydefault.Thedefaultmodifierisaccessibleonly within package.
Example:
Inthisexample,wehavecreatedtwopackagespackandmypack.WeareaccessingtheAclassfromoutside its
package, since A class is not public, so it cannot be accessed from outside the package.
//savebyA.java
package pack;
class A{
voidmsg(){System.out.println("Hello");}
}
//save by B.java
packagemypack;
import pack.*;
class B{
public static void main(String args[]){
Aobj=newA();//CompileTimeError
obj.msg();//Compile Time Error
}
}
Intheaboveexample,thescopeofclassAanditsmethodmsg()isdefaultsoitcannotbeaccessedfrom outside the package.

3) ProtectedAccess Modifier
Theprotected access modifieris accessible within package and outside the package but through inheritance
only.

22
Theprotectedaccessmodifiercanbeappliedonthedatamember,methodandconstructor.Itcan'tbe applied on the class.
Example:
Inthisexample,wehave createdthetwopackagespackandmypack.The Aclassofpackpackageispublic, so can be
accessed from outside the package. But msg method of this package is declared as protected, so it can be
accessed from outside the class only through inheritance.
//savebyA.java
package pack;
public class A{
protectedvoidmsg(){System.out.println("Hello");}
}
//save by B.java
packagemypack;
import pack.*;

class Bextends A{
publicstaticvoidmain(Stringargs[]){ B
obj = new B();
obj.msg();
}
}
Output:
Hello

4) PublicAccessModifier
Thepublicaccess modifierisaccessible everywhere.Ithasthewidestscopeamongallother modifiers.
Example:
//savebyA.java
package pack;
public class A{
publicvoid msg(){System.out.println("Hello");}
}
//save by B.java
packagemypack;
import pack.*;
class B{
publicstaticvoidmain(Stringargs[]){ A
obj = new A();
obj.msg();
}
}
Output:
Hello

Access Modifier WithinClass WithinPackage Outside Package Outside Package

23
BySubclassOnly
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y

Javaaccessmodifierswithmethodoverriding
If youareoverridinganymethod,overriddenmethod(i.e.declaredinsubclass)mustnotbemorerestrictive. class A{
protectedvoidmsg(){System.out.println("Hellojava");}
}
publicclassSimpleextends A{
voidmsg(){System.out.println("Hellojava");}//C.T.Error
public static void main(String args[]){
Simpleobj=newSimple();
obj.msg();
}
}
Thedefault modifier ismorerestrictivethan protected.That is whythereis compile timeerror.

STATICMEMBERS
Staticisa non-accessmodifierin Javawhichis applicableforthe following:
1. blocks
2. variables
3. methods
4. nestedclasses
Static blocks
If you need to do computation in order to initialize your static variables, you can declare a static block that
gets executed exactly once, when the class is first loaded.
Example:
//Javaprogramtodemonstrateuseofstaticblocks class
Test
{
//staticvariable
staticinta=10;
static int b;

//staticblock static
{
System.out.println("Staticblockinitialized.");
b = a * 4;
}

publicstaticvoidmain(String[]args)
{
System.out.println("from main");
System.out.println("Valueofa:"+a);
System.out.println("Valueofb:"+b);

24
}
}
Output:
Staticblockinitialized.
from main
Valueofa:10
Valueofb: 40

Static variables
When a variable is declared as static, then a single copy of variable is created and shared among all objects
at class level. Static variables are, essentially, global variables. All instances of the class share the same
static variable.
Importantpointsforstaticvariables:-
 Wecancreatestaticvariablesatclass-level only.
 staticblock and staticvariablesare executed in order theyarepresent in aprogram.
Example:
//Demonstratestaticvariables,methods,andblocks.
class UseStatic {
staticinta=3;
static int b;
static void meth(int x) {
System.out.println("x="+x);
System.out.println("a="+a);
System.out.println("b ="+b);
}
static {
System.out.println("Staticblockinitialized."); b
= a * 4;
}
publicstaticvoidmain(Stringargs[]){
meth(42);
}
}
Output:
Staticblockinitialized. x
= 42
a=3
b =12

Staticmethods
When a method is declared with statickeyword, it is known as static method. When a member is declared
static, it can be accessed before anyobjects ofits class arecreated, and without referenceto anyobject. The
most common example of a static method is main( )method. Methods declared as static have several
restrictions:
 Theycanonlydirectlycallotherstaticmethods.
 Theycanonlydirectlyaccessstatic data.
 Theycannot refer to this orsuperin anyway.
Syntax:
classname.method()
25
Example:
//Insidemain( ),thestaticmethodcallme()and thestaticvariable bareaccessedthroughtheir class name
//StaticDemo.class
StaticDemo{ static
int a = 42; static
int b = 99;
static void callme() {
System.out.println("a="+a);
}
}
classStaticByName{
public static void main(String args[]) {
StaticDemo.callme();System.out.println("b
="+StaticDemo.b);
}
}
Output:
a=42
b =99

JAVACOMMENTS
The java comments are statements that are not executed by the compiler and interpreter. The comments can
be used to provide information or explanation about the variable, method, class or anystatement. It can also
be used to hide program code for specific time.
Thereare3 typesof comments in java.
1. SingleLineComment
2. MultiLine Comment
3. DocumentationComment
1) Java Single LineComment
Thesingle linecommentis used tocomment onlyoneline.
Syntax:
//This issinglelinecomment
Example:
publicclassCommentExample1
{
publicstaticvoidmain(String[]args)
{
inti=10;//Here,iisavariable
System.out.println(i);
}
}
Output:
10

2) JavaMulti LineComment
Themultilinecommentis usedto commentmultiple linesofcode.
Syntax:
/*
26
This
is
multiline
comment
*/
Example:
publicclassCommentExample2
{
publicstaticvoidmain(String[]args)
{
/* Let's declare
andprintvariableinjava.
*/ int i=10;
System.out.println(i);
}
}
Output:
10

3) JavaDocumentation Comment
The documentation comment is used to create documentation API. To create documentation API, you need
to use javadoc tool.
Syntax:
/**
This
is
documentation
comment
*/

Example:
/**TheCalculatorclassprovidesmethodstogetadditionandsubtractionofgiven2numbers.*/ public class
Calculator
{
/**Theadd()methodreturnsadditionofgivennumbers.*/
public static int add(int a, int b)
{
returna+b;
}
/**Thesub()methodreturnssubtractionofgivennumbers.*/ public
static int sub(int a, int b)
{
returna-b;
}
}
ThistypeofcommentisusedtoproduceanHTMLfilethatdocuments yourprogram.Thedocumentation comment begins
with a /** and ends with a */.

27
DATATYPESINJAVA
Datatypesspecify thedifferentsizesandvaluesthatcanbestoredinthevariable.Therearetwotypesof data types in
Java:
1. Primitivedatatypes:TheprimitivedatatypesincludeInteger,Character,Boolean,andFloating Point.
2. Non-primitivedatatypes: Thenon-primitivedatatypesincludeClasses,Interfaces,andArrays.

Javadefineseightprimitivetypesofdata:byte,short,int,long,char,float,double,andboolean.Thesecan be put in
four groups:
• IntegersThisgroupincludesbyte,short,int,andlong,whichareforwhole-valuedsignednumbers.
• Floating-pointnumbersThisgroupincludesfloatanddouble,whichrepresentnumberswithfractional
precision.
• CharactersThisgroupincludeschar,whichrepresentssymbolsinacharacterset,likeletters andnumbers.
• BooleanThisgroupincludesboolean,whichisaspecialtypeforrepresentingtrue/falsevalues.
Example:
//Computedistancelighttravelsusinglongvariables.
class Light {
publicstaticvoidmain(Stringargs[]){ int
lightspeed;
long days;
longseconds;
longdistance;
//approximatespeedoflightinmilespersecond lightspeed =
186000;
days = 1000; // specify number of days
hereseconds=days*24*60*60;//converttoseconds
distance=lightspeed*seconds;//computedistance
System.out.print("In " + days);
System.out.print("dayslightwilltravelabout");
System.out.println(distance + " miles.");
}
}

28
Output:
In 1000 days light will travel about 16070400000000 miles.
Clearly,theresultcouldnothavebeenheldinanintvariable.

VARIABLES
A variable is a container which holds the value and that can be changed durig the execution of the program.
A variable is assigned with a datatype. Variable is a name of memory location. All the variables must be
declared before theycan be used. There are three types of variables in java: local variable, instance variable
and static variable.

20

1) LocalVariable
Avariabledefined withinablockormethodorconstructoris calledlocal variable.
 Thesevariablearecreatedwhentheblockinenteredorthefunctioniscalledanddestroyedafter exiting from
the block or when the call returns from the function.
 Thescopeofthesevariablesexistsonly withintheblockinwhichthevariableisdeclared.i.e.we can access
these variable only within that block.
Example:
import java.io.*;
publicclass StudentDetails
{
publicvoid StudentAge()
{//localvariableage
int age = 0;
age= age+5;
System.out.println("Studentageis:"+age);
}
publicstatic void main(Stringargs[])
{
StudentDetailsobj=newStudentDetails();
obj.StudentAge();
}
}
Output:
Studentageis:5

2) Instance Variable
Instancevariablesarenon-staticvariablesandaredeclaredinaclassoutsideanymethod,constructoror block.
 As instance variables are declared in a class, these variables are created when an object of the classis
created and destroyed when the object is destroyed.

29
 Unlike local variables, we may use access specifiers for instance variables. If we do not specify any
access specifier then the default access specifier will be used.
Example:
importjava.io.*;
class Marks{
intm1;
int m2;
}
classMarksDemo
{
publicstatic void main(Stringargs[])
{//firstobject
Marksobj1=newMarks();
obj1.m1 = 50;
obj1.m2 =80;
//second object
Marksobj2=newMarks();
obj2.m1 = 80;
obj2.m2 =60;
//displaying marks for first object
System.out.println("Marksforfirstobject:");
System.out.println(obj1.m1);
System.out.println(obj1.m2);
//displaying marks for second object
System.out.println("Marksforsecondobject:");
System.out.println(obj2.m1);
System.out.println(obj2.m2);
}}
Output:
Marksforfirst object:
50
80
Marksforsecondobject:
80
60
3) Static variable
StaticvariablesarealsoknownasClass variables.
 These variables are declared similarly as instance variables, the difference is that static variables are
declared using the static keyword within a class outside any method constructor or block.
 Unlikeinstancevariables,wecanonlyhaveonecopyofastaticvariableperclassirrespectiveof how many
objects we create.
 Staticvariablesarecreatedatstartofprogramexecutionanddestroyedautomaticallywhen execution ends.
Example:
importjava.io.*;
class Emp {

// static variable salary


publicstaticdoublesalary;

30
publicstatic Stringname ="Vijaya";
}
publicclass EmpDemo
{
publicstaticvoid main(Stringargs[]){

//accessingstaticvariablewithoutobject
Emp.salary = 1000;
System.out.println(Emp.name+ "'saveragesalary:"+ Emp.salary);
}
}
Output:
Vijaya’saveragesalary:10000.0

DifferencebetweenInstancevariableandStaticvariable
INSTANCE VARIABLE STATIC VARIABLE
Eachobjectwillhaveitsowncopyofinstance Wecanonlyhaveonecopyofastaticvariableper
variable classirrespectiveofhowmanyobjects wecreate.
Changesmadeinaninstancevariableusingoneobjectwill Incaseofstaticchanges willbereflectedinother
notbereflected inotherobjectsaseach objectsasstaticvariablesarecommontoallobject
object has its own copyof instancevariable of a class.
Wecanaccessinstancevariablesthroughobject StaticVariables canbe accesseddirectlyusingclass
references name.
Class Sample Class Sample
{ {
int a; static int a;
} }

OPERATORSINJAVA
Javaprovidesarichsetofoperatorstomanipulatevariables.WecandividealltheJavaoperatorsintothe following groups –
 Arithmetic Operators
 Incrementand Decrement
 BitwiseOperators
 RelationalOperators
 Boolean Operators
 Assignment Operator
 TernaryOperator
ArithmeticOperators
Arithmeticoperatorsareusedtomanipulatemathematical expressions
OperatorResult

31
Example:
//Demonstratethebasicarithmeticoperators.
class BasicMath
{
publicstatic void main(Stringargs[])
{
// arithmetic using integers
System.out.println("IntegerArithmetic");
int a = 1 + 1;
intb=a*3;
int c = b / 4;
int d = c - a;
int e = -d;
System.out.println("a="+a);
System.out.println("b="+b);
System.out.println("c="+c);
System.out.println("d="+d);
System.out.println("e= "+e);
// arithmetic using doubles
System.out.println("\nFloatingPointArithmetic");
double da = 1 + 1;
doubledb=da*3;
double dc = db / 4;
double dd = dc - a;
double de = -dd;
System.out.println("da="+da);
System.out.println("db="+db);
System.out.println("dc="+dc);
System.out.println("dd="+dd);
System.out.println("de= "+de);
}}
Output:
IntegerArithmetic
a=2
b =6
c=1
32
d=-1
e=1
FloatingPointArithmetic
da = 2.0
db =6
dc=1.5
dd=-0.5
de=0.5

Modulus Operator
The modulus operator, %, returns the remainder of a division operation. It can be applied to floating-point
types as well as integer types.
Example:
//Demonstratethe%operator. class
Modulus {
publicstaticvoidmain(Stringargs[]){ int
x = 42;
doubley=42.25;
System.out.println("xmod10="+x%10);
System.out.println("ymod 10 =" +y% 10);
}
}
Output:
xmod 10 = 2
ymod 10 = 2.25

ArithmeticCompoundAssignmentOperators
Javaprovidesspecialoperatorsthatcanbeusedtocombineanarithmeticoperationwith anassignment. a = a +
4;
InJava,youcanrewritethisstatementasshownhere: a +=
4;
Syntax:
varop=expression;
Example:
//Demonstrateseveralassignmentoperators.
class OpEquals
{
publicstatic void main(Stringargs[])
{
inta=1;
intb=2;
int c=3;
a+=5;
b *=4;
c+=a* b;
33
c%=6;
System.out.println("a="+a);
System.out.println("b="+b);
System.out.println("c= "+c);
}
}
Output:
a=6
b =8
c=3

IncrementandDecrementOperators
The++ andthe––areJava’sincrementanddecrementoperators.Theincrementoperatorincreasesits
operandbyone. Thedecrement operator decreasesits operand byone.
Example:
//Demonstrate++.
class IncDec
{
publicstatic void main(Stringargs[])
{
inta=1;
intb=2;
int c;
int d;
c=++b;
d=a++;
c++;
System.out.println("a="+a);
System.out.println("b="+b);
System.out.println("c="+c);
System.out.println("d ="+d);
}
}
Output:
a=2
b =3
c=4
d =1

BitwiseOperators

34
Javadefinesseveral bitwiseoperators thatcanbe applied totheintegertypes:long,int,short,char, and
byte.Theseoperatorsactupontheindividualbitsoftheir operands.

Bitwise Logical Operators


Thebitwiselogicaloperatorsare&,|,^,and~.thebitwiseoperatorsare applied to
each individual bit within each operand.

Example:
//Demonstratethebitwiselogicaloperators.
class BitLogic
{
publicstatic void main(Stringargs[])
{
Stringbinary[]={"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111",
"1000","1001", "1010","1011","1100", "1101","1110","1111"};
int a=3; // 0 +2 +1 or0011 inbinary
intb=6;//4+2+0or0110inbinary int c = a |
b;
intd=a&b; int
e = a ^ b;
intf=(~a&b)|(a&~b); int g
= ~a & 0x0f;
System.out.println(" a = " + binary[a]);
System.out.println(" b = " + binary[b]);
System.out.println(" a|b = " + binary[c]);
System.out.println("a&b="+binary[d]);
System.out.println(" a^b = " + binary[e]);
35
System.out.println("~a&b|a&~b="+binary[f]);
System.out.println(" ~a = " + binary[g]);
}
}
Output:
a=0011
b =0110
a|b=0111
a&b =0010
a^b=0101
~a&b|a&~b=0101
~a=1100

LeftShift Operator
The Java left shift operator << is used to shift all of the bits in a value to the left side of a specified number
of times.
Example:
classOperatorExample
{
publicstaticvoid main(String args[])
{
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(10<<3);//10*2^3=10*8=80
System.out.println(20<<2);//20*2^2=20*4=80
System.out.println(15<<4);//15*2^4=15*16=240
}
}
Output:
40
80
80
240

RightShift Operator
The Java right shift operator >> is used to move left operands value to right by the number of bits specified
by the right operand.
Example:
classOperatorExample
{
publicstaticvoid main(String args[])
{
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}
}
Output:
2
5

36
2
Relational Operators
Therelationaloperatorsdeterminetherelationshipthatoneoperandhastotheother.Specifically,they determine equality
and ordering. The outcome of these operations is a boolean value.
BooleanOperators
TheBooleanlogicaloperatorsshownhereoperateonlyonbooleanoperands.Allofthebinarylogical operators combine
two boolean values to form a resultant boolean value.

Example:
//Demonstratethebooleanlogicaloperators.
class BoolLogic
{
publicstatic void main(Stringargs[])
{
boolean a = true;
booleanb=false;
boolean c = a | b;
booleand=a&b;
booleane= a^ b;
boolean f = (!a & b) | (a & !b);
boolean g = !a;
System.out.println(" a = " + a);
System.out.println(" b = " + b);
System.out.println(" a|b = " + c);
System.out.println("a&b="+d);
System.out.println(" a^b = " + e);
System.out.println("!a&b|a&!b="+f); System.out.println("
!a = " + g);
}
}
Output:
a=true
b = false
a|b = true
a&b=false

37
a^b=true
!a&b|a&!b=true
!a=false
Intheoutput,thestringrepresentationofaJavabooleanvalueisoneoftheliteralvaluestrueorfalse.Java AND
Operator Example: Logical && and Bitwise &
Thelogical&&operatordoesn'tchecksecondconditioniffirstconditionisfalse.Itcheckssecond condition only if first
one is true.
Thebitwise&operator alwayschecksbothconditions whetherfirst conditionis trueor false.
Example:
classOperatorExample
{
publicstaticvoid main(String args[])
{
inta=10;
int b=5;
intc=20;
System.out.println(a<b&&a<c);//false&&true=false
System.out.println(a<b&a<c);//false & true = false
}
}
Output:
false
false

AssignmentOperator
Theassignmentoperatoris thesingleequalsign,=.
Syntax:
var= expression;
Here,thetypeofvarmustbecompatiblewiththetypeofexpression. int x, y,
z;
x=y=z=100; //set x,y,and zto 100
Thisfragment setsthevariables x, y,and zto 100usingasingle statement.

TernaryOperator
Ternaryoperatorinjavaisusedasonelinerreplacementforif-then-elsestatementandusedalotinjava programming. it is
the only conditional operator which takes three operands.
Syntax:
expression1?expression2:expression3
Example:
classOperatorExample
{
publicstaticvoid main(String args[])
{
inta=2;
intb=5;
int min=(a<b)?a:b;
System.out.println(min);
}
}

38
Output:
2

CONTROLSTATEMENTS
SelectionStatementsinJava
Aprogramminglanguageusescontrolstatementstocontroltheflowofexecutionofprogrambasedon certain conditions.
Java’sSelectionstatements:
 if
 if-else
 nested-if
 if-else-if
 switch-case
 jump–break,continue,return

ifStatement
ifstatementisthemostsimpledecisionmakingstatement.Itisusedtodecidewhetheracertainstatementor block of
statements will be executed or not that is if a certain condition is true then a block of statement is executed
otherwise not.
Syntax:
if(condition)
{
//statementstoexecute if
//conditionis true
}
Condition after evaluation will be either true or false. If the value is true then it will execute the block of
statements under it. If there are no curly braces ‘{‘ and ‘}’ after if( condition )then by default if statement
will consider the immediate one statement to be inside its block.

Example:
classIfSample
{
publicstatic void main(Stringargs[])
{
intx,y;
x=10;
y=20;

39
if(x<y)
System.out.println("xislessthany"); x
= x * 2;
if(x== y)
System.out.println("xnowequaltoy"); x
= x * 2;
if(x>y)
System.out.println("xnowgreaterthany");
//thiswon'tdisplayanything
if(x == y)
System.out.println("you won'tseethis");
}
}
Output:
xisless thany
xnowequaltoy
xnowgreaterthany

if-elseStatement
TheJavaif-elsestatementalsoteststhecondition.Itexecutesthe ifblockifconditionistrueelseifitisfalse the else
block is executed.
Syntax:.
If(condition)
{
//Executesthisblock if
//conditionis true
}
else
{
//Executesthisblock if
//conditionis false
}

Example:

40
publicclassIfElseExample
{
publicstaticvoidmain(String[]args)
{
int number=13;
if(number%2==0){
System.out.println("evennumber");
}else
{
System.out.println("odd number");
}}}
Output:
odd number

NestedifStatement
Nestedif-elsestatements, isthat usingoneiforelse ifstatement inside anotheriforelse if statement(s).

Example:
//Javaprogramtoillustratenested-ifstatement class
NestedIfDemo
{
publicstatic void main(Stringargs[])
{
int i = 10;

if(i ==10)
{
if(i <15)
System.out.println("iissmallerthan15"); if
(i < 12)
System.out.println("iissmallerthan12too"); else
System.out.println("iisgreaterthan 15");

41
}
}
}
Output:
iissmallerthan15
iis smallerthan 12 too

if-else-ifladder statement
The if statements are executed from the top down. The conditions controlling the if is true, the statement
associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true,
then the final else statement will be executed.
Syntax:
if(condition)
statement;
elseif(condition)
statement;
elseif(condition)
statement;
.
.
else
statement;

Example:
publicclassIfElseIfExample{
publicstaticvoidmain(String[]args){ int
marks=65;
if(marks<50){
System.out.println("fail");
}
elseif(marks>=50&&marks<60){

42
System.out.println("D grade");
}
elseif(marks>=60&&marks<70){ System.out.println("C
grade");
}
elseif(marks>=70&&marks<80){ System.out.println("B
grade");
}
elseif(marks>=80&&marks<90){ System.out.println("A
grade");
}elseif(marks>=90&&marks<100){
System.out.println("A+ grade");
}else{
System.out.println("Invalid!");
}
}
}
Output:
C grade

SwitchStatements
TheswitchstatementisJava’smultiwaybranchstatement.Itprovidesaneasywaytodispatchexecutionto
differentpartsofyour codebasedonthevalueofanexpression.
Syntax:
switch(expression){
case value1:
//statementsequence
break;
casevalue2:
//statementsequence
break;
.
.
casevalueN:
//statementsequence
break;
default:
//defaultstatementsequence
}
Example:
//Asimpleexampleoftheswitch.
class SampleSwitch {
publicstaticvoidmain(Stringargs[]){
for(int i=0; i<6; i++)
switch(i){
case 0:
System.out.println("iiszero.");
break;
case 1:

43
System.out.println("iisone.");
break;
case 2:
System.out.println("iistwo.");
break;
case 3:
System.out.println("iisthree.");
break;
default:
System.out.println("iis greaterthan3.");
}}}
Output:
iiszero.
i is one.
i is two.
i is three.
iisgreaterthan3.
iisgreaterthan3.

ITERATIVESTATEMENTS
In programming languages, loops are used to execute a set of instructions/functions repeatedly when some
conditions become true. There are three types of loops in java.
44
 while loop
 do-whileloop
 Forloop
whileloop
Awhileloopisacontrolflowstatementthatallowscodetobeexecutedrepeatedlybasedonagiven Boolean condition. The
while loop can be thought of as a repeating if statement.
Syntax:
while(condition){
// bodyofloop
}

 While loop starts with the checking of condition. If it evaluated to true, then the loop bodystatements
are executed otherwise first statement followingthe loop is executed. It is called asEntry controlled
loop.
 Normally the statements contain an update value for the variable being processed for the next
iteration.
 Whenthe condition becomes false, theloop terminates which marks the end of its life cycle.
Example:
//Demonstratethewhileloop.
class While {
publicstaticvoidmain(Stringargs[]){ int
n = 5;
while(n > 0) {
System.out.println("tick"+n);
n--;
}
}
}
Output:
tick5
tick4
tick3
tick2
tick1

45
do-whileloop:
dowhileloopchecksforconditionafterexecutingthestatements,andthereforeitiscalledasExit Controlled Loop.
Syntax:
do {
// bodyofloop
}while (condition);

 do whileloop starts with theexecution ofthestatement(s).There is no checkingof anycondition for the


first time.
 After the execution of the statements, and update of the variable value, the condition is checked for
true or false value. If it is evaluated to true, next iteration of loop starts. 
 Whenthe condition becomesfalse, theloop terminateswhich marks theendof its life cycle.
 Itisimportanttonotethatthedo-whileloopwillexecuteitsstatementsatleastoncebeforeany condition is
checked, and therefore is an example of exit control loop. 
Example
public class DoWhileExample
{publicstaticvoidmain(String[]args){
inti=1;
do{
System.out.println(i);
i++;
}while(i<=5);
}
}
Output:
1
2
3
4
5

for loop

46
for loop provides a concise way of writing the loop structure.A for statement consumes the initialization,condition
and increment/decrement in one line.
Syntax
for(initialization;condition;iteration){
// body
}

 Initialization condition:Here, we initialize the variable in use. It marks the start of a for loop. An
already declared variable can be used or a variable can be declared, local to loop only. 
 Testing Condition:It is used fortestingtheexit condition foraloop. It must returnaboolean value. It is
also anEntry Control Loop as the condition is checked prior to the execution of the loop statements.
 Statement execution:Once the condition is evaluated to true, the statements in the loop body are
executed.
 Increment/Decrement:Itisusedforupdatingthevariable fornextiteration.
 Looptermination:Whentheconditionbecomesfalse,theloopterminatesmarkingtheendofitslife cycle.
Example
publicclassForExample{
publicstaticvoidmain(String[]args){
for(int i=1;i<=5;i++){
System.out.println(i);
}
}}
Output:
1
2
3
4
5

for-eachLoop

47
The for-each loop is used to traverse array or collection in java. It is easier to use than simple for loop
because we don't need to increment value and use subscript notation.It works on elements basis not index.It
returns element one by one in the defined variable.
Syntax:
for(typeitr-var:collection)statement-block

Example:
//Useafor-eachstyleforloop. class
ForEach {
publicstatic void main(Stringargs[]) {
int nums[] ={ 1, 2, 3, 4,5, 6, 7, 8, 9, 10 };
int sum =0;
//usefor-eachstylefortodisplayandsumthevalues for(int x :
nums) {
System.out.println("Valueis:"+x); sum
+= x;
}
System.out.println("Summation:"+ sum);
}
}
Output:
Valueis:1
Valueis:2
Valueis:3
Valueis:4
Valueis:5
Valueis:6
Valueis: 7
Valueis:8
Valueis:9
Valueis:10
Summation:55

NestedLoops
Javaallows loops to benested. That is, oneloopmaybeinsideanother.
Example:
//Loopsmaybenested.
class Nested {
publicstaticvoidmain(Stringargs[]){ int
i, j;
for(i=0; i<10; i++) {
for(j=i; j<10; j++)
System.out.print(".");
System.out.println();
}}
}
Output:

48
..........
.........
........
.......
......
.....
....
...
..
.
JUMPSTATEMENTS
JavaBreakStatement
 Whenabreakstatementisencounteredinsidealoop,theloopisimmediatelyterminatedandthe program
control resumes at the next statement following the loop.
 TheJavabreakisusedto break looporswitchstatement. Itbreaks thecurrentflowoftheprogram at
specified condition. In case of inner loop, it breaks only inner loop.

Example:
//Usingbreaktoexitaloop. class
BreakLoop {
publicstaticvoidmain(Stringargs[]){
for(int i=0; i<100; i++) {
if(i==10)break;//terminateloopifiis10
System.out.println("i: " + i);
}
System.out.println("Loopcomplete.");
}
}
Output:
i: 0
i: 1
i: 2
i: 3
i: 4
i: 5
i: 6
i: 7
49
i: 8
i: 9
Loopcomplete.

Java ContinueStatement
 The continue statement is used in loop control structure when you need to immediately jump to the
next iteration of the loop. It can be used with for loop or while loop. 
 The Javacontinue statement is used to continue loop. It continues the current flow of the program
and skips the remaining code at specified condition. In case of inner loop, it continues only inner
loop.

Example:
//Demonstratecontinue.
class Continue {
publicstaticvoidmain(Stringargs[]){
for(int i=0; i<10; i++) {
System.out.print(i + "");
if(i%2==0)continue;
System.out.println("");
}
}
}
Thiscodeusesthe%operatortocheckifiiseven.Ifitis,theloopcontinueswithout printing a
newline.
Output:
01
23
45
67
89

Return
Thelastcontrolstatementisreturn.Thereturnstatementisusedtoexplicitlyreturnfromamethod.Thatis, it causes
program control to transfer back to the caller of the method.
Example:
//Demonstratereturn.
class Return {
public static void main(String args[]) {
boolean t = true;
System.out.println("Before the return.");
if(t) return; // return to caller
System.out.println("Thiswon'texecute.");
}
}
Output:
Beforethe return.

ARRAYS
 Arrayis acollection ofsimilartypeof elementsthat havecontiguous memorylocation.
50
 InJavaallarraysaredynamicallyallocated.
 Sincearraysareobjects inJava,wecanfindtheirlengthusingmember length.
 AJavaarrayvariable canalso bedeclaredlike othervariables with[] afterthedata type.
 Thevariables inthearrayareorderedand eachhavean index beginningfrom 0.
 Javaarraycan bealso beused as astatic field, a local variableor amethodparameter.
 Thesizeofan arraymustbespecifiedbyan int value and not longor short.
 Thedirect superclass ofan arraytypeisObject.
 Everyarraytypeimplements theinterfacesCloneable and java.io.Serializable.

AdvantageofJavaArray
 CodeOptimization:It makesthecodeoptimized,wecanretrieveorsort thedataeasily.
 Randomaccess: Wecangetanydata located at anyindexposition.
DisadvantageofJava Array
 Size Limit:We can store onlyfixed size of elements in the array. It doesn't grow its size at runtime.
To solve this problem, collection framework is used in java.

Typesof Arrayin java


1. One-DimensionalArray
2. MultidimensionalArray

One-DimensionalArrays
An arrayis a group of like-typed variables that are referred to by a common name. An array declaration has
two components: the type and the name. typedeclares the element type of the array. The element type
determines the data type of each element that comprises the array. We can also create an array of other
primitive data types like char, float, double..etc or user defined data type(objects of a class).Thus, the
element type for the array determines what type of data the array will hold.
Syntax:
typevar-name[ ];
InstantiationofanArrayinjava
array-var = new type [size];
Example:
classTestarray{
publicstaticvoid main(String args[]){
inta[]=newint[5];//declarationandinstantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;

51
//printing array
for(inti=0;i<a.length;i++)//lengthisthepropertyofarray
System.out.println(a[i]);
}}
Output:
10
20
70
40
50
Declaration,InstantiationandInitializationofJavaArray
Example:
classTestarray1{
publicstaticvoid main(String args[]){
inta[]={33,3,4,5};//declaration,instantiationand initialization
//printing array
for(inti=0;i<a.length;i++)//lengthisthepropertyofarray
System.out.println(a[i]);
}}
Output:
33
3
4
5

PassingArray tomethodin java


Wecan pass thejavaarraytomethod so that we can reusethe samelogiconanyarray.
Example:
classTestarray2{
staticvoidmin(intarr[]){ int
min=arr[0];
for(inti=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
publicstaticvoidmain(Stringargs[]){ int
a[]={33,3,4,5};
min(a);//passingarraytomethod
}}
Output:
3

MultidimensionalArrays
Multidimensional arrays arearrays of arrayswith each element of the array holding the reference of other
array. These are also known as Jagged Arrays. A multidimensional array is created by appending one set of
square brackets ([]) per dimension.
52
Syntax:
typevar-name[][]=new type[row-size][col-size];
Example:
//Demonstrateatwo-dimensionalarray.
class TwoDArray {
publicstaticvoidmain(Stringargs[]){ int
twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0;j<5;j++){
twoD[i][j] = k;
k++;
}
for(i=0;i<4;i++){
for(j=0; j<5; j++)
System.out.print(twoD[i][j]+"");
System.out.println();
}
}
}
Output:
01234
56789
10 11 12 13 14
15 16 17 18 19

When you allocate memory for a multidimensional array, you need only specify the memory for the first
(leftmost) dimension. You can allocate the remaining dimensions separately. For example, this following
code allocates memory for the first dimension of twoD when it is declared. It allocates the seconddimension
manually.
Syntax:
inttwoD[][]=newint[4][];
twoD[0] = new int[5];
twoD[1] = new int[5];
twoD[2] = new int[5];
53
twoD[3] =new int[5];
Example:
//Manuallyallocatedifferingsizeseconddimensions.
class TwoDAgain {
publicstaticvoidmain(Stringargs[]){ int
twoD[][] = new int[4][];
twoD[0]=newint[1];
twoD[1]=newint[2];
twoD[2]=newint[3];
twoD[3]=newint[4];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0;j<i+1;j++){
twoD[i][j] = k;
k++;
}
for(i=0;i<4;i++){
for(j=0;j<i+1;j++)
System.out.print(twoD[i][j]+"");
System.out.println();
}
}
}
Output:
0
12
345
6789
Thearraycreated bythisprogram looks likethis:

PACKAGES
Ajava packageis a group of similar types of classes, interfaces and sub-packages. Package in java can be
categorized in two form, built-in package and user-defined package.There are many built-in packages such
as java, lang, awt, javax, swing, net, io, util, sql etc.

54
AdvantageofJavaPackage
1) Javapackageisused tocategorizetheclasses and interfacesso thattheycanbeeasilymaintained.
2) Javapackageprovides accessprotection.
3) Javapackageremovesnamingcollision.

Defining aPackage
To create a package include a package command as the first statement in a Java source file. Any
classes declared withinthatfilewillbelongtothe specifiedpackage. The packagestatementdefinesaname space
in which classes are stored. If package statement is omitted, the class names are put into the default
package, which has no name.
Syntax:
package<fullyqualifiedpackagename>;
packagepkg;
Here,pkgisthenameofthepackage.Forexample,thefollowingstatementcreatesapackagecalled MyPackage.
package MyPackage;
Java uses file system directories to store packages. For example, the .class files for any classes you declare
to be part of MyPackage must be stored in a directory called MyPackage.

Itispossibletocreateahierarchyofpackages.Thegeneralformofamultileveledpackagestatementis shown here:


package pkg1[.pkg2[.pkg3]];

A package hierarchy must be reflected in the file system of your Java development system. For example, a
package declared as
package java.awt.image;
needstobestoredinjava\awt\imageinaWindowsenvironment.Wecannotrenameapackagewithout renaming the
directory in which the classes are stored.

FindingPackagesand CLASSPATH

55
First, by default, the Java run-time system uses the current working directory as its starting point. Thus, if
your package is in a subdirectory of the current directory, it will be found. Second, you can specify a
directory path or paths by setting the CLASSPATH environmental variable. Third, you can use the -
classpath option with java and javac to specify the path to your classes.

considerthefollowingpackagespecification:
package MyPack
In order for a program to find MyPack, one of three things must be true. Either the program can be
executedfromadirectoryimmediatelyabove MyPack,ortheCLASSPATHmustbesettoincludethepath to
MyPack, or the -classpath option must specify the path to MyPack when the program is run via java.
Whenthesecondtwooptionsareused,theclasspathmustnotincludeMyPack,itself.Itmustsimply specify the path
to MyPack. For example, in a Windows environment, if the path to MyPack is
C:\MyPrograms\Java\MyPack
thentheclasspathtoMyPackis
C:\MyPrograms\Java
Example:
//Asimplepackage
package MyPack;
class Balance {
String name;double
bal;
Balance(Stringn,doubleb){
name = n;
bal= b;
}
voidshow(){
if(bal<0)
System.out.print("-->");
System.out.println(name+":$"+bal);
}
}
classAccountBalance{
publicstaticvoidmain(Stringargs[]){
Balance current[] = new Balance[3];
current[0]=newBalance("K.J.Fielding",123.23);
current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33);
for(int i=0; i<3; i++) current[i].show();
}
}
CallthisfileAccountBalance.javaandput itina directorycalledMyPack.
Next, compile the file. Make sure that the resulting .class file is also in the MyPack directory. Then, try
executing the AccountBalance class, using the following command line:
javaMyPack.AccountBalance
Remember, you will need to be in the directory above MyPack when you execute this command.
(Alternatively, you can use one of the other two options described in the preceding section to specify the
path MyPack.)
As explained, AccountBalance is now part of the package MyPack. This means that it cannot be executed
by itself. That is, you cannot use this command line:
56
java AccountBalance
AccountBalancemustbequalifiedwithitspackage name.

Example:
packagepck1;
class Student
{
private int rollno;
private String name;
privateStringaddress;
publicStudent(int rno,Stringsname, Stringsadd)
{
rollno = rno;
name=sname;
address= sadd;
}
publicvoid showDetails()
{
System.out.println("Roll No :: " + rollno);
System.out.println("Name :: " + name);
System.out.println("Address::"+address);
}
}
publicclass DemoPackage
{
publicstatic void main(Stringar[])
{
Studentst[]=newStudent[2];
st[0]=newStudent(1001,"Alice","NewYork");
st[1]=newStudent(1002,"BOb","Washington");
st[0].showDetails();
st[1].showDetails();
}
}
Therearetwo waystocreatepackagedirectoryasfollows:
1. Createthefolderordirectoryatyourchoicelocationwiththesamenameaspackagename.After compilation of
copy .class (byte code file) file into this folder.
2. Compile thefile with following syntax.
javac-d <targetlocationofpackage> sourceFile.java

The above syntax will create the package given in the sourceFile at the<target location of pacakge>if it is
not yet created. If package already exist then only the .class(byte code file) will be stored to thepackage
given in sourceFile.

Stepsto compilethegiven examplecode:


Compilethecodewiththecommandonthecommandprompt. javac -
d DemoPackage.java
1. The command will create the package at the current location with the name pck1, and contains the file
DemoPackage.class and Student.class

57
2. Torunwritethecommandgivenbelow
java pckl.DemoPackage

Note:TheDemoPackate.classisnowstoredinpck1package.Sothatwe'vetouse fullyqualifiedtype name to run or


access it.

Output:
Roll No :: 1001
Name :: Alice
Address::NewYork
Roll No :: 1002
Name :: Bob
Address::Washington

58
UNITII INHERITANCEANDINTERFACES
Inheritance – Super classes- sub classes –Protected members – constructors in sub classes- the
Object class – abstract classes and methods- final methods and classes – Interfaces – defining an
interface,implementinginterface,differences betweenclassesandinterfacesandextending
interfaces-Objectcloning-innerclasses,ArrayLists–Strings

INHERITANCE
Inheritancecanbe definedas theprocedure ormechanismofacquiringalltheproperties
andbehaviorsofoneclasstoanother,i.e.,acquiringthepropertiesandbehaviorofchildclass from the
parent class.
Whenoneobjectacquiresallthepropertiesandbehavioursofanotherobject,itisknown as
inheritance. Inheritance represents the IS-A relationship, also known as parent-childrelationship.
Usesofinheritanceinjava
 ForMethodOverriding(soruntimepolymorphismcanbeachieved).
 ForCodeReusability.
Typesofinheritanceinjava:single,multilevelandhierarchicalinheritance.Multipleandhybrid
inheritance is supported through interface only.
Syntax:
classsubClassextendssuperClass
{
//methodsandfields
}
TermsusedinInheritence
 Class: A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created.
 Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a
derived class, extended class, or child class.
 Super Class/Parent Class: Superclass is the class from where a subclass inherits thefeatures.
It is also called a base class or a parent class.
 Reusability:Asthenamespecifies,reusabilityisamechanismwhichfacilitatesyouto
reusethefieldsandmethodsoftheexistingclasswhenyoucreateanewclass.Youcan
usethesamefieldsandmethodsalreadydefinedinpreviousclass.

SINGLEINHERITANCE
InSingleInheritanceoneclassextendsanotherclass(oneclassonly).
Example:
publicclassClassA
{
publicvoiddispA()
{
System.out.println("disp()methodofClassA");
}
}
publicclassClassBextendsClassA
{
publicvoiddispB()
{
System.out.println("disp()methodofClassB");
}
publicstaticvoidmain(Stringargs[])
{
//AssigningClassBobjecttoClassBreference
ClassB b = new ClassB();
//call dispA() method of ClassA
b.dispA();
//calldispB()methodofClassB
b.dispB();
}
}
Output:
disp()methodofClassA
disp()methodofClassB
MULTILEVEL INHERITANCE
InMultilevelInheritance,oneclasscaninherit fromaderivedclass.Hence,thederivedclass becomes the
base class for the new class.
Example:
publicclassClassA
{
publicvoiddispA()
{
System.out.println("disp()methodofClassA");
}
}
publicclassClassBextendsClassA
{
publicvoiddispB()
{
System.out.println("disp()methodofClassB");
}
}
public class ClassC extends ClassB
{
publicvoiddispC()
{
System.out.println("disp()methodofClassC");
}
publicstaticvoidmain(Stringargs[])
{
//Assigning ClassC object to ClassC reference
ClassC c = new ClassC();
//call dispA() method of ClassA
c.dispA();
//call dispB() method of ClassB
c.dispB();
//call dispC() method of ClassC
c.dispC();
}
}
Output:
disp()method ofClassA
disp() method of ClassB
disp() method of ClassC

HIERARCHICALINHERITANCE
InHierarchicalInheritance,oneclassisinheritedbymanysubclasses.
Example:
publicclassClassA
{
publicvoiddispA()
{
System.out.println("disp()methodofClassA");
}
}
publicclassClassBextendsClassA
{
publicvoiddispB()
{
System.out.println("disp()methodofClassB");
}
}
public class ClassC extends ClassA
{
publicvoiddispC()
{
System.out.println("disp()methodofClassC");
}
}
publicclassClassDextendsClassA
{
publicvoiddispD()
{
System.out.println("disp()methodofClassD");
}
}
publicclassHierarchicalInheritanceTest
{
publicstaticvoidmain(Stringargs[])
{
//AssigningClassBobjecttoClassBreference
ClassB b = new ClassB();
//calldispB()methodofClassB
b.dispB();
//call dispA() method of ClassA
b.dispA();
//Assigning ClassC object to ClassC reference
ClassC c = new ClassC();
//call dispC() method of ClassC
c.dispC();
//call dispA() method of ClassA
c.dispA();

//Assigning ClassD object to ClassD


referenceClassD d = new ClassD();
//call dispD() method of ClassD
d.dispD();
//call dispA() method of ClassA
d.dispA();
}
}
Output:
disp() method of ClassB
disp()method ofClassA
disp() method of ClassC
disp()method ofClassA
disp()methodofClassD
disp()methodofClassA

Hybrid Inheritance is the combination of both Single and Multiple Inheritance. Again Hybrid
inheritanceisalsonotdirectlysupportedinJavaonlythroughinterfacewecanachievethis.
FlowdiagramoftheHybridinheritancewilllooklikebelow.AsyoucanClassAwillbeactingas
theParentclassforClassB&ClassCandClassB&ClassCwillbeactingasParentforClassD.

MultipleInheritanceisnothingbutoneclassextendingmorethanoneclass.Multiple
InheritanceisbasicallynotsupportedbymanyObjectOriented Programminglanguagessuch as
Java,SmallTalk,C#etc..(C++SupportsMultipleInheritance). Asthe Child classhas tomanage the
dependency of morethan one Parentclass. But you canachieve multiple inheritance in Java using
Interfaces.

“super”KEYWORD
Usageofsuperkeyword
1. super()invokestheconstructoroftheparentclass.
2. super.variable_namereferstothevariableintheparentclass.
3. super.method_namereferstothemethodoftheparentclass.

1. super()invokestheconstructoroftheparentclass
super()will invoketheconstructoroftheparentclass.Evenwhenyoudon’t
addsuper()keywordthecompilerwilladdoneandwillinvoketheParentClassconstructor.
Example:
classParentClass
{
ParentClass()
{
System.out.println("ParentClassdefaultConstructor");
}
}
publicclassSubClassextendsParentClass
{
SubClass()
{
System.out.println("ChildClassdefaultConstructor");
}
publicstaticvoidmain(Stringargs[])
{
SubClasss=newSubClass();
}
}
Output:
ParentClassdefaultConstructor
Child Class default Constructor

Evenwhenweaddexplicitlyalsoitbehavesthesamewayasitdidbefore. class
ParentClass
{
publicParentClass()
{
System.out.println("ParentClassdefaultConstructor");
}
}
publicclassSubClassextendsParentClass
{
SubClass()
{
super();
System.out.println("Child ClassdefaultConstructor");
}
publicstaticvoidmain(Stringargs[])
{
SubClasss=newSubClass();
}
}
Output:
ParentClassdefaultConstructor
Child Class default Constructor
Youcanalso call theparameterizedconstructoroftheParent Class.For example,super(10) will call
parameterized constructor of the Parent class.
classParentClass
{
ParentClass()
{
System.out.println("ParentClassdefaultConstructorcalled");
}
ParentClass(intval)
{
System.out.println("ParentClassparameterizedConstructor,value:"+val);
}
}
publicclassSubClassextendsParentClass
{
SubClass()
{
super();//Has to be thefirst statement in the constructor
System.out.println("ChildClassdefaultConstructorcalled");
}
SubClass(intval)
{
super(10);
System.out.println("ChildClassparameterizedConstructor,value:"+val);
}
publicstaticvoidmain(Stringargs[])
{
//Callingdefaultconstructor
SubClass s = new SubClass();
//Calling parameterized constructor
SubClass s1 = new SubClass(10);
}
}
Output
ParentClassdefaultConstructorcalled
Child Class default Constructor called
ParentClassparameterizedConstructor,value:10
ChildClassparameterizedConstructor,value:10

2. super.variable_namereferstothevariableintheparentclass
When we have the same variable in both parent and
subclassclass ParentClass
{
intval=999;
}
publicclassSubClassextendsParentClass
{
intval=123;

voiddisp()
{
System.out.println("Valueis:"+val);
}

publicstaticvoidmain(Stringargs[])
{
SubClass s = new SubClass();
s.disp();
}
}
Output
Valueis:123
Thiswillcallonlythevalofthesubclassonly.Withoutsuperkeyword,youcannotcalltheval
whichispresentintheParentClass.
classParentClass
{
intval=999;
}
publicclassSubClassextendsParentClass
{
intval=123;

voiddisp()
{
System.out.println("Valueis:"+super.val);
}

publicstaticvoidmain(Stringargs[])
{
SubClass s = new SubClass();
s.disp();
}
}

Output
Valueis:999
3. super.method_naereferstothemethodoftheparentclass
WhenyouoverridetheParentClassmethodintheChildClasswithoutsuperkeywordssupport you will
not be able to call the Parent Class method. Let’s look into the below example
classParentClass
{
voiddisp()
{
System.out.println("ParentClassmethod");
}
}
publicclassSubClassextendsParentClass
{

voiddisp()
{
System.out.println("Child Classmethod");
}

voidshow()
{
disp();
}
publicstaticvoidmain(Stringargs[])
{
SubClass s = new SubClass();
s.show();
}
}
Output:
ChildClassmethod
Here wehaveoverriddenthe Parent Class disp() method in theSubClass and henceSubClass
disp() method is called. If we want to call the Parent Class disp() methodalso means then wehave
to use the super keyword for it.
classParentClass
{
voiddisp()
{
System.out.println("ParentClassmethod");
}
}
publicclassSubClassextendsParentClass
{
voiddisp()
{
System.out.println("ChildClassmethod");
}

voidshow()
{
//Calling SubClass disp() method
disp();
//Calling ParentClass disp()
method super.disp();
}
publicstaticvoidmain(Stringargs[])
{
SubClass s = new SubClass();
s.show();
}
}
Output
Child Class method
ParentClassmethod

Whenthereis nomethodoverriding thenby defaultParent Class disp()methodwillbe called. class


ParentClass
{
publicvoiddisp()
{
System.out.println("ParentClassmethod");
}
}
publicclassSubClassextendsParentClass
{
publicvoidshow()
{
disp();
}
publicstaticvoidmain(Stringargs[])
{
SubClass s = new SubClass();
s.show(); }}

Output:
ParentClassmethod
TheObjectClass
Thereisonespecialclass,Object,definedbyJava.AllotherclassesaresubclassesofObject.That
is,Objectisasuperclassofallotherclasses.This meansthatareferencevariableoftype Object can
referto an object of anyother class. Also,since arraysareimplemented as
classes, a variable of typeObjectcan also refer to any array.Objectdefines the following
methods, which means that they are availablein every object.

The methodsgetClass( ),notify( ),notifyAll( ), andwait( )are declared asfinal. You may
override the others. These methods are described elsewhere in this book. However, notice two
methods now:equals()and toString(). The equals()method compares two objects. It returns
trueif the objects are equal, andfalseotherwise. The precise definition of equality can vary,
depending on the type of objects being compared. ThetoString( ) method returns a string that
containsadescriptionoftheobjectonwhichitiscalled.Also,thismethodisautomaticallycalled when
an object is output usingprintln( ). Many classes override this method. Doing so allows
themtotailoradescriptionspecificallyforthetypesofobjectsthattheycreate.
ABSTRACT CLASS
A class that is declared with abstract keyword, is known as abstract class in java. It can have
abstract and non-abstract methods (method with body).Abstraction is a process of hiding the
implementationdetailsand showingonlyfunctionalitytotheuser. Abstractionletsyoufocuson what
the object does instead of how it does it. It needs to be extended and its method implemented. It
cannot be instantiated.
Exampleabstract class:
abstractclassA{}
abstract method:
Amethodthat is declaredas abstract and doesnot haveimplementationis knownas abstract method.
abstractvoidprintStatus();//nobodyandabstract
Inthisexample,Shapeistheabstractclass,itsimplementationisprovidedbytheRectangleand Circle
classes.
IfyoucreatetheinstanceofRectangleclass,draw()methodofRectangleclasswillbeinvoked.
Example1:
File:TestAbstraction1.java
abstract class Shape{
abstract void draw();
}
//Inrealscenario,implementationisprovidedbyothersi.e.unknownbyend user
class Rectangle extends Shape{
voiddraw(){System.out.println("drawingrectangle");}
}
classCircle1extendsShape{
voiddraw(){System.out.println("drawingcircle");}
}
//In real scenario, method is called by programmer or
userclass TestAbstraction1{
publicstaticvoidmain(Stringargs[]){
Shapes=newCircle1();//Inrealscenario,objectisprovidedthroughmethode.g.getShape()met hod
s.draw();
}
}
Output:
drawingcircle
Abstractclass havingconstructor,datamember,methods

Anabstract classcanhave datamember, abstract method,methodbody, constructorandeven main()


method.
Example2:
File:TestAbstraction2.java
//exampleofabstractclassthathavemethodbody
abstract class Bike{
Bike(){System.out.println("bikeiscreated");}
abstract void run();
voidchangeGear(){System.out.println("gearchanged");}
}
classHondaextendsBike{
voidrun(){System.out.println("runningsafely..");}
}
classTestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.changeGear();
}
}
Output:
bike is created
runningsafely..
gear changed

Theabstract classcan also be used to provide someimplementationofthe interface. Insuch case,


theendusermaynotbe forcedtooverrideall themethodsoftheinterface.
Example3:
interface A{
void a();
voidb();
voidc();
voidd();
}
abstractclassBimplementsA{
publicvoidc(){System.out.println("Iamc");}
}
classMextendsB{
public void a(){System.out.println("I am a");}
public void b(){System.out.println("I am b");}
publicvoidd(){System.out.println("Iamd");}
}
classTest5{
public static void main(String args[]){
A a=new M();
a.a();
a.b();
a.c();
a.d();
}}
Output:
I ama
Iamb
I am c
Iamd
INTERFACE IN JAVA
An interface in java is a blueprint of a class. It has static constants and abstract methods.The
interfacein javais amechanism toachieve abstraction and multipleinheritance.
Interface is declared by using interface keyword. It provides total abstraction; means all
themethodsininterface are declared withempty body andarepublicandall fieldsarepublic, static
andfinalbydefault.Aclassthatimplementinterfacemustimplementallthemethodsdeclared in the
interface.

Syntax:
interface<interface_name>
{

//declareconstantfields
//declaremethodsthatabstract
//bydefault.
}

Relationshipbetweenclassesandinterfaces

Example:interface
printable{ void
print();
}
classA6implementsprintable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
}
}
Output:
Hello
Example:interface
Drawable
{
voiddraw();
}
classRectangleimplementsDrawable{
publicvoiddraw(){System.out.println("drawingrectangle");}
}
classCircleimplementsDrawable{
publicvoiddraw(){System.out.println("drawingcircle");}
}
classTestInterface1{
publicstaticvoidmain(Stringargs[]){
Drawabled=newCircle();//Inrealscenario,objectisprovidedbymethode.g.getDrawable() d.draw();
}
}
Output:
drawingcircle

MultipleinheritanceinJavabyinterface
Ifa classimplementsmultiple interfaces,or aninterface extendsmultiple interfaces i.e. knownas multiple
inheritance.

Example:interface
Printable{ void
print();
}
interface Showable{
void show();
}
class A7 implements
Printable,Showable{public void
print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

public static void main(String args[]){


A7 obj = new A7();
obj.print();
obj.show();
}
}
Output:
Hello
Welcome
Interfaceinheritance

Aclassimplementsinterfacebutoneinterfaceextendsanotherinterface.Exam
ple:
interfacePrintable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){ TestInterface4
obj = new TestInterface4(); obj.print();

obj.show();
}}
Output:
Hello
Welcome

NestedInterfacein Java
An interface can have another interface i.e. known as nested
interface.interface printable{
voidprint();
interface MessagePrintable{
void msg();
}
}
Keypointstorememberaboutinterfaces:
1) Wecan’tinstantiateaninterfaceinjava.Thatmeanswecannotcreatetheobjectofaninterface
2) Interfaceprovidesfullabstractionasnoneofitsmethodshavebody.Ontheotherhand
abstractclassprovidespartialabstractionasitcanhaveabstractandconcrete(methodswith body)
methods both.
3) “implements”keywordisusedbyclassestoimplementaninterface.
4) Whileprovidingimplementationinclassofanymethodofaninterface,itneedstobementioned as
public.
5) Classthatimplementsanyinterfacemustimplementallthemethodsofthatinterface,elsethe class
should be declared abstract.
6) Interfacecannotbedeclaredasprivate,protectedortransient.
7) Alltheinterfacemethodsarebydefaultabstractandpublic.
8) Variablesdeclaredininterfacearepublic,staticandfinalbydefault.
interface Try
{
int a=10; public
int a=10;
public static final int a=10;
final int a=10;
staticinta=0;
}
Alloftheabovestatementsareidentical.
9) Interfacevariablesmustbeinitializedatthetimeofdeclarationotherwisecompilerwillthrow an error.
interfaceTry
{
intx;//Compile-timeerror
}
Above code will throw a compile time error as the value of the variable x is notinitialized at the
time of declaration.
10) Inside any implementation class, you cannot change the variables declared in interface
because by default, they are public, static and final. Here we are implementing the interface
“Try” which has a variable x. When we tried to set the value for variable x we got compilation
errorasthevariablexispublicstaticfinalbydefaultandfinalvariablescannotbere-initialized. class
Sample implements Try
{
publicstaticvoidmain(Stringargs[])
{
x=20;//compiletimeerror
}
}
11) Aninterfacecanextendanyinterfacebutcannotimplementit.Classimplementsinterface and
interface extends interface.
12) Aclasscanimplementanynumberofinterfaces.
13) Iftherearetwoormoresamemethodsintwointerfacesandaclassimplementsboth interfaces,
implementationof themethodonceisenough.
interfaceA
{
publicvoidaaa();
}
interfaceB
{
publicvoidaaa();
}
classCentralimplementsA,B
{
publicvoidaaa()
{
//AnyCodehere
}
publicstaticvoidmain(Stringargs[])
{
//Statements
}
}
14) Aclasscannotimplementtwointerfacesthathavemethodswithsamenamebutdifferent return
type.
interfaceA
{
publicvoidaaa();
}
interfaceB
{
publicintaaa();
}
classCentralimplementsA,B
{
publicvoidaaa()//error
{
}
publicint aaa()// error
{
}
publicstaticvoidmain(Stringargs[])
{
}
}
15) Variable names conflicts can be resolved by interface
name. interface A
{
intx=10;
}
interfaceB
{
intx=100;
}
classHelloimplementsA,B
{
publicstaticvoidMain(Stringargs[])
{
System.out.println(x);
System.out.println(A.x);
System.out.println(B.x);
}
}

Advantagesofinterface injava:
 Withoutbotheringabouttheimplementationpart,wecanachievethesecurityof
implementation
 Injava,multipleinheritanceisnotallowed,howeveryoucanuseinterfacetomakeuse ofit as you
can implement morethan one interface.

DIFFERENCE BETWEENABSTRACTCLASSANDINTERFACE
ABSTRACTCLASS INTERFACE
1) Abstract class can haveabstractandnon- Interface can have only abstract methods. Sinc
abstract methods. Java 8, it can have default and static
methodsalso.
2)Abstractclassdoesn't supportmultiple Interfacesupportsmultipleinheritance.
inheritance.
3)Abstractclasscanhavefinal,non-final, Interfacehasonlystatic andfinal variables.
staticandnon-static variables.
4)Abstractclasscanprovidethe Interfacecan'tprovidetheimplementationof
implementationofinterface. abstract class.
5) The abstractkeywordis used to declare The interface keyword is used to declare
abstract class. interface.
6) An abstractclasscanextendanother Java An interface can extend another Java interface
classandimplementmultipleJavainterfaces. only.
7) An abstract class can be extended using Aninterfaceclasscanbeimplementedusing
keyword extends. keyword implements
8)AJavaabstractclasscanhaveclassmembers like MembersofaJavainterfacearepublicby
private, protected, etc. default.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
publicabstractvoiddraw(); void draw();
} }

FINAL KEYWORD
Finalkeywordcanbeusedalongwithvariables,methodsandclasses.
1) finalvariable
2) final method
3) final class

1.Javafinalvariable
Afinalvariableisavariablewhosevaluecannotbechangedatanytimeonceassigned,it remains as a
constant forever.
Example:
publicclassTravel
{
final int SPEED=60;
void increaseSpeed(){
SPEED=70;
}
publicstaticvoidmain(Stringargs[])
{
Travel t=new Travel();
t.increaseSpeed();
}
}
Output:
Exceptioninthread"main"java.lang.Error:Unresolvedcompilationproblem:
The final field Travel.SPEED cannot be assigned
TheabovecodewillgiveyouCompiletimeerror, aswearetryingtochangethevalueof afinal variable
‘SPEED’.
2. Javafinalmethod
When you declarea methodasfinal, then it is calledas final method. Afinal method cannot
beoverridden.
packagecom.javainterviewpoint;

classParent
{
publicfinalvoiddisp()
{
System.out.println("disp()methodofparentclass");
}
}
publicclassChildextendsParent
{
publicvoiddisp()
{
System.out.println("disp()methodofchildclass");
}
publicstaticvoidmain(Stringargs[])
{
Child c= new Child();
c.disp();
}
}
Output:Wewillgetthebelowerrorasweareoverridingthedisp()methodoftheParentclass.
Exceptioninthread"main"java.lang.VerifyError:classcom.javainterviewpoint.Childoverrides
final method disp.()
atjava.lang.ClassLoader.defineClass1(NativeMethod)atja
va.lang.ClassLoader.defineClass(UnknownSource)
at java.security.SecureClassLoader.defineClass(Unknown
Source)atjava.net.URLClassLoader.defineClass(UnknownSource)
at java.net.URLClassLoader.access$100(Unknown
Source)atjava.net.URLClassLoader$1.run(UnknownSource)
atjava.net.URLClassLoader$1.run(UnknownSource)
3. Javafinalclass
Afinalclasscannotbeextended(cannotbesubclassed),letstakealookintothebelowexample package
com.javainterviewpoint;

finalclassParent
{
}
publicclassChildextendsParent
{
publicstaticvoidmain(Stringargs[])
{
Childc=newChild();
}
}
Output:
Wewillgetthecompiletimeerrorlike“ThetypeChildcannotsubclassthefinalclassParent”
Exceptioninthread"main"java.lang.Error:Unresolvedcompilationproblem

OBJECTCLONING
Theobjectcloningisawaytocreateexactcopyofanobject.Theclone()methodofObjectclass is used to
clone an object.
Thejava.lang.Cloneableinterfacemustbeimplementedbytheclasswhoseobjectclonewe want to
create. If we don't implement Cloneable interface, clone() method generates
CloneNotSupportedException.
Theclone()methodisdefinedintheObjectclass.

Syntaxoftheclone() method:
protectedObjectclone()throwsCloneNotSupportedException

The clone() method saves the extra processing task for creating the exact copy of an object. If we
perform it by using the new keyword,it will take a lot ofprocessing time to be performed that iswhy
we use object cloning.
Advantage ofObjectcloning
 Youdon'tneedtowritelengthyandrepetitivecodes.Justuseanabstractclasswitha4-or 5-line long
clone() method.
 It is the easiest and most efficient wayfor copying objects, especially if we areapplyingit
toanalreadydeveloped or anold project.Justdefineaparentclass, implementCloneable in it,
provide the definition of the clone() method and the task will be done.
 Clone()isthefastestwaytocopyarray.
DisadvantageofObject cloning
 To use the Object.clone() method, we have to change a lot of syntaxes to our code, like
implementing a Cloneable interface, defining the clone() method and handling
CloneNotSupportedException, and finally, calling Object.clone() etc.
 Wehavetoimplementcloneableinterfacewhileitdoesn?thaveanymethodsinit.Wejust have
to use it to tell theJVM that we canperform clone() on our object.
 Object.clone() is protected, so we have to provide our own clone() and indirectly call
Object.clone() from it.
 Object.clone() doesn?t invoke any constructor so we don?t have any control over object
construction.
 Ifyouwanttowriteaclonemethodinachildclassthenallofitssuperclassesshould define the clone()
method in them or inherit it from another parent class. Otherwise, the super.clone() chain
will fail.
 Object.clone()supportsonlyshallowcopyingbutwewillneedtooverrideitifweneed deep
cloning.
Exampleofclone()method(Object cloning)
class Student implements Cloneable{
int rollno;
Stringname;
Student(int rollno,String
name){ this.rollno=rollno;
this.name=name;
}
public Object clone()throws CloneNotSupportedException{
return super.clone();
}
public static void main(String args[]){
try{
Student s1=new Student(101,"amit");
Student s2=(Student)s1.clone();
System.out.println(s1.rollno+""+s1.name);
System.out.println(s2.rollno+""+s2.name);
}
catch(CloneNotSupportedExceptionc){}
}
}
Output:
101amit
101amit

INNERCLASSES
Innerclass means oneclass which is amemberofanotherclass. Thereare basically fourtypes of
inner classes in java.
1) NestedInnerclass
2) MethodLocalinner classes
3) Anonymousinnerclasses
4) Staticnestedclasses

NestedInnerclass
NestedInnerclasscanaccessanyprivateinstancevariableofouterclass.Likeanyotherinstance
variable, we can have access modifier private, protected, public and default modifier. Like class,
interface can also benested and can have access specifiers.
Example:
classOuter{
// Simple nested inner class
class Inner {
publicvoidshow(){
System.out.println("Inanestedclassmethod");
}
}
}
classMain{
public static void main(String[] args) {
Outer.Inner in = new Outer().new Inner();
in.show();
}
}
Output:
Inanestedclassmethod

MethodLocalinner classes
Innerclasscan be declaredwithin amethodofanouterclass.In thefollowing example,Inneris an inner
class in outerMethod().
Example:
classOuter{
void outerMethod() {
System.out.println("inside outerMethod");
// Inner class is local to outerMethod()
class Inner {
void innerMethod() {
System.out.println("inside innerMethod");
}
}
Innery=newInner();
y.innerMethod();
}
}
classMethodDemo{
public static void main(String[] args) {
Outer x = new Outer();
x.outerMethod();
}
}
Output:
InsideouterMethod
InsideinnerMethod

Staticnestedclasses
Staticnestedclassesarenottechnicallyaninnerclass.Theyarelikeastaticmemberofouter
class.
Example:
classOuter{
private static void outerMethod() {
System.out.println("inside outerMethod");
}
//Astaticinnerclass
static class Inner {
public static void main(String[] args) {
System.out.println("inside inner class Method");
outerMethod();
}
}
}
Output:
inside inner class Method
inside outerMethod

Anonymousinner classes
Anonymousinnerclassesaredeclaredwithoutanynameatall.Theyarecreatedintwoways.
a) Assubclassofspecifiedtype
class Demo {
voidshow(){
System.out.println("iaminshowmethodofsuperclass");
}
}
classFlavor1Demo{
// An anonymous class with Demo as baseclass
static Demo d = new Demo() {
void show() {
super.show();
System.out.println("iaminFlavor1Democlass");
}
};
public static void main(String[] args){
d.show();
}
}
Output:
iaminshowmethodofsuperclass i
am in Flavor1Demo class
In the above code, wehave twoclassDemoand Flavor1Demo.Heredemoactassuper
classandanonymousclassactsasasubclass,bothclasseshaveamethodshow().Inanonymous
classshow()methodisoverridden.

b) Asimplementerofthespecifiedinterface
Example:
classFlavor2Demo{
//AnanonymousclassthatimplementsHellointerface static
Hello h = new Hello() {
publicvoidshow(){
System.out.println("iaminanonymousclass");
}
};
public static void main(String[] args) {
h.show();
}
}
interface Hello {
void show(); }
Output:
iamin anonymous class
Inabove code we create an object ofanonymousinnerclass butthisanonymous inner
classisanimplementeroftheinterfaceHello.Anyanonymousinnerclasscanimplementonly
oneinterfaceatone time.Itcaneitherextendaclassor implement interfaceata time.

STRINGS INJAVA
Injava,stringisbasicallyanobjectthatrepresentssequenceofcharvalues.JavaStringprovides a lot
of concepts that can beperformed ona string such ascompare, concat, equals, split, length,
replace, compareTo, intern, substring etc.
Injava,stringobjectsareimmutable.Immutablesimplymeansunmodifiableorunchangeable.
Strings="javatpoint";
TherearetwowaystocreateStringobject:
1. Bystringliteral
2. Bynewkeyword
1 )StringLiteral
JavaStringliteraliscreatedbyusingdoublequotes.ForExample: String
s="welcome";
2)Bynewkeyword
Strings=newString("Welcome");
Stringmethods:
1. charcharAt(intindex) returnscharvaluefortheparticularindex
2. intlength() returnsstringlength
3. staticStringformat(Stringformat, returnsformattedstring
Object...args)
4. staticStringformat(Localel,String returnsformattedstringwithgivenlocale
format, Object... args)
5. Stringsubstring(intbeginIndex) returns substringforgivenbeginindex
6. Stringsubstring(intbeginIndex,int returnssubstringforgivenbeginindexandend
endIndex) index
7. booleancontains(CharSequences) returnstrueorfalseaftermatchingthesequence
ofcharvalue
8. staticStringjoin(CharSequence returnsajoinedstring
delimiter,CharSequence...elements)
9. staticStringjoin(CharSequence returnsajoinedstring
delimiter, Iterable<? extends
CharSequence> elements)
10. booleanequals(Objectanother) checkstheequalityofstringwithobject
11. booleanisEmpty() checksifstringisempty
12. Stringconcat(Stringstr) concatinatesspecifiedstring
13. Stringreplace(charold,charnew) replacesalloccurrencesofspecifiedcharvalue
14. Stringreplace(CharSequenceold, replacesalloccurrencesofspecified
CharSequencenew) CharSequence
15. staticStringequalsIgnoreCase(String comparesanotherstring.Itdoesn'tcheckcase.
another)
16. String[]split(Stringregex) returnssplittedstringmatchingregex
17. String[]split(Stringregex,intlimit) returnssplittedstringmatchingregexandlimit
18. Stringintern() returnsinternedstring
19. intindexOf(intch) returnsspecifiedcharvalueindex
20. intindexOf(intch,intfromIndex) returns specifiedcharvalueindexstarting with
givenindex
21. intindexOf(Stringsubstring) returnsspecifiedsubstringindex
22. intindexOf(Stringsubstring,int returnsspecifiedsubstringindexstartingwith
fromIndex) givenindex
23. StringtoLowerCase() returnsstringinlowercase.
24. StringtoLowerCase(Localel) returnsstringinlowercaseusingspecifiedlocale.
25. StringtoUpperCase() returnsstringinuppercase.
26. StringtoUpperCase(Localel) returnsstringinuppercaseusingspecified
locale.
27. Stringtrim() removesbeginningandendingspacesofthis
string.
28. staticStringvalueOf(intvalue) convertsgiventypeintostring.Itisoverloaded.
Example:
publicclassstringmethod
{
publicstaticvoidmain(String[]args)
{
String string1 = new String("hello");
String string2 = new String("hello");
if (string1 == string2)
{
System.out.println("string1="+string1+"string2="+string2+"areequal");
}
else
{
System.out.println("string1="+string1+"string2="+string2+"areUnequal");
}
System.out.println("string1 and string2 is=
"+string1.equals(string2)); String a="information";
System.out.println("Uppercase of String a is= "+a.toUpperCase());
String b="technology";
System.out.println("Concatenationofobjectaandbis="+a.concat(b));
System.out.println("AfterconcatenationObjectais="+a.toString());
System.out.println("\"Joseph\'s\"isthegreatest\\collegeinchennai");
System.out.println("Length of Object a is= "+a.length());
System.out.println("ThethirdcharacterofObjectais="+a.charAt(2));
StringBuffer n=new StringBuffer("Technology");
StringBuffer m=new StringBuffer("Information");
System.out.println("Reverse of Object n is= "+n.reverse());
n= new StringBuffer("Technology");
System.out.println("ConcatenationofObjectmandnis="+m.append(n)); System.out.println("After
concatenation of Object m is= "+m);
}
}
Output:
string1= hello string2= hello are Unequal
string1 and string2 is= true
UppercaseofStringais=INFORMATION
Concatenationofobjectaandbis=informationtechnology After
concatenation Object a is= information
"Joseph's" is the greatest\ college in chennai
Length of Object a is= 11
ThethirdcharacterofObjectais=f
ReverseofObjectnis=ygolonhceT
ConcatenationofObjectmandnis=InformationTechnology
AfterconcatenationofObjectmis=InformationTechnology
JavaArrayListclass
JavaArrayListclassusesa dynamicarray for storingtheelements. ItinheritsAbstractListclass and
implements List interface.
TheimportantpointsaboutJavaArrayListclassare:
 JavaArrayListclasscancontainduplicateelements.
 JavaArrayListclassmaintainsinsertionorder.
 JavaArrayListclassisnon synchronized.
 JavaArrayListallowsrandomaccessbecausearrayworksattheindexbasis.
 InJavaArrayListclass,manipulationisslowbecausealotofshiftingneedstobeoccurred if any
element is removed from the array list.
ArrayListclassdeclarationSyntax:
publicclassArrayList<E>extendsAbstractList<E>implementsList<E>,RandomAccess,Clone
able, Serializable
ConstructorsofJavaArrayList
CONSTRUCTOR DESCRIPTION
ArrayList() Itisusedtobuildanemptyarraylist.
ArrayList(Collectionc) Itisusedtobuildanarraylistthatisinitializedwiththe
elementsofthecollectionc.
ArrayList(intcapacity) Itisusedtobuildanarraylistthathasthespecifiedinitial
capacity.
MethodsofJavaArrayList
METHOD DESCRIPTION
voidadd(intindex,Object Itisusedtoinsertthespecifiedelementatthespecifiedposition
element) index ina list.
booleanaddAll(Collection Itisusedtoappendalloftheelementsinthespecifiedcollection
c) to the end of this list, in the order that they are returned by the
specified collection's iterator.
voidclear() Itisusedtoremovealloftheelementsfromthislist.
intlastIndexOf(Objecto) Itisusedtoreturntheindexinthislistofthelastoccurrenceof
thespecifiedelement,or-1ifthelistdoesnotcontainthiselement.
Object[]toArray() Itisusedtoreturnanarraycontainingalloftheelementsinthis
listinthecorrectorder.
Object[]toArray(Object[] Itisusedtoreturnanarraycontainingalloftheelementsinthis
a) listinthecorrectorder.
booleanadd(Objecto) Itisusedtoappendthespecifiedelementtotheendofalist.
booleanaddAll(intindex, Itisusedtoinsertalloftheelementsinthespecifiedcollection
Collectionc) intothislist,startingatthespecifiedposition.
Objectclone() ItisusedtoreturnashallowcopyofanArrayList.
intindexOf(Objecto) Itisusedtoreturntheindexinthislistofthefirstoccurrenceof
thespecifiedelement,or-1iftheListdoesnotcontainthis element.
JavaArrayListExample:Book
Example:
import java.util.*;
class Book {
intid;
String name,author,publisher;
int quantity;
publicBook(intid,Stringname,Stringauthor,Stringpublisher,intquantity){ this.id =
id;
this.name = name;
this.author = author;
this.publisher=publisher;
this.quantity = quantity;
}
}
public class ArrayListExample {
publicstaticvoidmain(String[]args){
//CreatinglistofBooks
List<Book>list=newArrayList<Book>();
//CreatingBooks
Bookb1=newBook(101,"LetusC","YashwantKanetkar","BPB",8);
Bookb2=newBook(102,"DataCommunications&Networking","Forouzan","McGrawHill",4);
Bookb3=newBook(103,"OperatingSystem","Galvin","Wiley",6);
//Adding Books to list
list.add(b1);
list.add(b2);
list.add(b3);
//Traversing list
for(Book b:list){
System.out.println(b.id+""+b.name+""+b.author+""+b.publisher+""+b.quantity);
}
}
}
Output:
101 LetusCYashwantKanetkarBPB8
102 DataCommunications&NetworkingForouzanMcGrawHill4
103 OperatingSystemGalvinWiley6
Unit–III
ExceptionHandlingandI/O

Exceptions-exception hierarchy-throwing and catching exceptions-built-in


exceptions, creating own exceptions, Stack Trace Elements. Input /Output
Basics-Streams-Byte streams and character streams-Reading and Writing
Console-Reading and Writing Files Templates
Differencebetweenerrorandexception
Errors indicate serious problems and abnormal conditions that most
applicationsshould not try to handle. Error defines problems that are not
expected to be caught under normal circumstances by our program. For
example memory error, hardware error, JVM error etc.
Exceptions are conditions within the code. A developer can handle such
conditionsand take necessary corrective actions. Few examples

DivideByZeroexception

NullPointerException

ArithmeticException

ArrayIndexOutOfBoundsException

o An exception (or exceptional event) is a problem that arises during the


execution of a program.
o When an Exception occurs the normal flow of the program is disrupted
and the program/Application terminates abnormally, which is not
recommended, therefore, these exceptions are to be handled.
o If an exception is raised, which has not been handled by programmer
then program execution can get terminated and system prints a non user
friendly error message.
Ex: Exception in thread "main"
java.lang.ArithmeticException: / by zero at
ExceptionDemo.main(ExceptionDemo.java:5)

Where, ExceptionDemo : The class name


main : The method name
ExceptionDemo.java:Thefilename
java:5 : Line number
Anexceptioncanoccurformanydifferentreasons.Followingaresome scenarios
where an exception occurs.

Auserhasenteredaninvaliddata.

Afilethatneedstobeopenedcannotbe found.

A network connection has been lost in the middle of communications or
the JVM hasrun out of memory.
ExceptionHierarchy
All exception classes are subtypes of the java.lang.Exception class. The
exception class is a subclass of the Throwable class.
KeywordsusedinExceptionhandling
Thereare5keywords usedinjavaexceptionhandling.

Atry/catchblockisplacedaroundthecodethatmightgeneratean
1.try exception.Codewithinatry/catchblockisreferredtoasprotectedcode.
Acatchstatementinvolvesdeclaringthetypeofexceptionwearetrying
2.catch to catch.
Afinallyblockofcodealwaysexecutes,irrespectiveofoccurrenceofan
3.finally Exception.
Itisusedtoexecuteimportantcodesuchasclosingconnection,stream
4.throw etc.throwisusedtoinvokeanexceptionexplicitly.

5.throws throwsisusedtopostponethehandlingofacheckedexception.

Syntax : //Example-predefinedExcetion-for
try //ArrayindexoutofBoundsException
{ public class ExcepTest
//Protectedcode {
} publicstaticvoidmain(Stringargs[])
{inta[]=newint[2];
catch(ExceptionType1e1) try
{System.out.println("Accesselementthree:"+ a[3]);
{ }
//Catchblock catch(ArrayIndexOutOfBoundsExceptione)
} {System.out.println("Exceptionthrown:"+e);
catch(ExceptionType2e2) }
{ finally
//Catchblock {a[0]=6;
}
catch(ExceptionType3e3) System.out.println("First element value: " + a[0]);
System.out.println("The finally statement is
{ executed");
//Catchblock }
} }
finally }
{ Output
Exception thrown
//Thefinallyblockalways :java.lang.ArrayIndexOutOfBoundsException:3
executes. First element value: 6
} Thefinallystatementisexecuted
Note:herearraysizeis2butwearetryingtoaccess
3rdelement.

UncaughtExceptions
This smallprogramincludes anexpression that intentionallycauses adivide-by-
zero error:classExc0{publicstaticvoid main(Stringargs[]) {intd=0;int a=
42 / d; } } Whenthe Java run-time system detects the attempt to divide byzero, it
constructs a new exceptionobject and thenthrows this exception. This causes the
execution of Exc0 to stop, because once an exception has been thrown, it must
be caught by an exception handler and dealt with immediately

Any exception that is not caught by your program will ultimately be processed
by the default handler. The default handler displays a string describing the
exception, prints a stack trace from the point at which the exception occurred,
and terminates the program. Here is the exception generated when this example
is executed:
java.lang.ArithmeticException:/byzeroatExc0.main(Exc0.java:4)

StackTrace:
Stack Trace is a list of method calls from the point when the application was
started to the point where the exception was thrown. The most recent method
calls are at the top. A stacktrace is a very helpful debugging tool. It is a list of
the method calls that the application was in the middle of when an Exception
wasthrown.Thisisveryusefulbecauseitdoesn'tonlyshowyouwhere the error
happened,butalsohowtheprogram endedupin thatplaceof the code.

UsingtryandCatch
To guard against and handle a run-time error, simply enclose the code that you
want to monitor inside a tryblock. Immediately following the tryblock, include a
catch clause that specifies the exceptiontype that youwishto catch. A tryand its
catch statement form a unit.The the following program includes a try block and
a catch clause that processes the ArithmeticException generated by the division-
by-zero error:
classExc2{
publicstaticvoidmain(Stringargs[]){ int
d, a;
try{//monitorablockofcode. d =
0;
a = 42 /d;
System.out.println("Thiswillnotbeprinted.");
}catch(ArithmeticExceptione){// catchdivide-by-zeroerror
System.out.println("Division by zero.");
}
System.out.println("Aftercatchstatement.");
}
}
Thisprogramgeneratesthefollowingoutput:
Division by zero.
Aftercatchstatement.
The callto println()inside the tryblock is neverexecuted. Once anexception is
thrown, program control transfers out of the try block into the catch block.

MultiplecatchClauses
In some cases, more than one exception could be raised by a single piece of
code. To handle this type of situation, you can specify two or more catch
clauses, each catching a different type of exception. When an exception is
thrown, each catch statement is inspected in order, and the first one whose type
matches that of the exception is executed. After one catch statement executes,
the others are bypassed, and execution continues after the try/catch block.

Thefollowingexampletrapstwodifferentexceptiontypes:
//Demonstratemultiplecatchstatements.
classMultiCatch{
publicstaticvoidmain(Stringargs[]){ try
{
int a = args.length;
System.out.println("a="+a); int
b = 42 / a;
intc[]={1}; c[42]
= 99;
} catch(ArithmeticException e) {
System.out.println("Divideby0:"+e);
}catch(ArrayIndexOutOfBoundsExceptione){
System.out.println("Array index oob: " + e);
}
System.out.println("Aftertry/catchblocks.");
}
}

Hereistheoutputgeneratedbyrunningitbothways:
C:\>javaMultiCatch
a=0
Divideby0:java.lang.ArithmeticException:/byzero After
try/catch blocks.
C:\>javaMultiCatchTestArg
a=1
Arrayindexoob:java.lang.ArrayIndexOutOfBoundsException:42
After try/catch blocks.
NestedtryStatements
The try statement can be nested. That is, a try statement can be inside the block
ofanothertry. Eachtime a trystatement isentered, the context ofthat exception is
pushed on the stack. If an inner try statement does not have a catch handlerfor a
particular exception, the stack is unwound and the next try statement’s catch
handlers are inspected for a match. This continues until one of the catch
statements succeeds, or untilallofthe nested trystatements are exhausted. Ifno
catch statement matches, then the Java run-time system will handle the
exception.

//Anexampleofnestedtrystatements.
class NestTry {
publicstaticvoidmain(Stringargs[]){ try
{
inta = args.length;
/*Ifnocommand-lineargsarepresent, the
following statement will generate
a divide-by-zero exception. */
int b = 42 / a;
System.out.println("a="+a); try
{ // nested try block
/*Ifonecommand-lineargisused,
then a divide-by-zero exception
willbegeneratedbythefollowingcode.*/ if(a==1)
a = a/(a-a); // division by zero
/*Iftwocommand-lineargsareused,
thengenerateanout-of-boundsexception.*/
if(a==2) {
intc[]={ 1};
c[42]=99;//generateanout-of-bounds exception
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Arrayindexout-of-bounds:"+e);
}
} catch(ArithmeticException e) {
System.out.println("Divideby0:"+e);
}
}
}

C:\>javaNestTry
Divideby0:java.lang.ArithmeticException:/byzero
C:\>java NestTry One
a =1
Divideby0:java.lang.ArithmeticException:/byzero
C:\>java NestTry One Two
a =2
Array index out-of-bounds:
java.lang.ArrayIndexOutOfBoundsException:42

throw
it ispossible foryourprogramtothrowanexceptionexplicitly, usingthethrow
statement. The general form of throw is shown here:

throwThrowableInstance;
Here, ThrowableInstance must be an object of type Throwable or a subclass of
Throwable.
Primitive types, such as int or char, as well as non-Throwable classes, such as
String and
Object, cannot be used as exceptions. There are two ways you can obtain a
Throwable object: using a parameter in a catch clause, or creating one with the
new operator.
The flow of execution stops immediately after the throw statement; any
subsequent statements are not executed. The nearest enclosing try block is
inspected to see if it has a catch statement that matches the type ofexception. If
it does find a match, control is transferred to that statement. Ifnot, thenthe next
enclosing try statement is inspected, and so on. If no matching catch is found,
then the default exception handler halts the program and prints the stack trace
// Demonstrate throw.
class ThrowDemo {
staticvoiddemoproc(){
try {
thrownewNullPointerException("demo");
} catch(NullPointerException e) {
System.out.println("Caughtinsidedemoproc.");
throw e; // rethrow the exception
}
}
publicstaticvoidmain(Stringargs[]){ try
{
demoproc();
} catch(NullPointerException e) {
System.out.println("Recaught:"+e);
}
}
}
Hereistheresultingoutput:
Caughtinsidedemoproc.
Recaught:java.lang.NullPointerException:demo

Throws
If a method is capable of causing an exception that it does not handle, it must
specify this behaviour so that callers of the method can guard themselvesagainst
that exception. Youdo this byincludinga throws clause inthe method’s
declaration. A throws clause lists the types of exceptions that a method might
throw. This is necessary for all exceptions, except those of type Error or
RuntimeException, or any of their subclasses. All other exceptions that a
method can throw must be declared in the throws clause. This is the general
form of a method declaration that includes a throws clause:
typemethod-name(parameter-list)throwsexception-list
{
//bodyofmethod
}
Here, exception-list is a comma-separated list of the exceptions that amethodcan
throw.

classThrowsDemo {
staticvoidthrowOne()throwsIllegalAccessException{
System.out.println("Inside throwOne.");
thrownewIllegalAccessException("demo");
}
publicstaticvoidmain(Stringargs[]){ try
{
throwOne();
}catch(IllegalAccessExceptione){
System.out.println("Caught"+e);
}
}
}
Hereistheoutputgeneratedbyrunningthisexampleprogram: inside
throwOne
caughtjava.lang.IllegalAccessException:demo

finally
The finally keyword is designed to address this contingency. finally creates a
block of code that will be executed after a try/catch block has completed and
before the code following the try/catch block. The finally block will execute
whether or not an exception is thrown. If an exception is thrown, the finally
block willexecute evenifno catchstatement matches the exception. Anytime a
method is about to return to the caller from inside a try/catch block, via an
uncaught exception or an explicit return statement, the finally clause is also
executed just before the method returns. This can be useful for closing file
handles and freeing up anyotherresources that might have beenallocated at the
beginning of a method with the intent of disposing of them before returning.The
finally clause is optional.

//Demonstratefinally.
class FinallyDemo {
//Throughanexceptionoutofthe method.
static void procA() {
try{
System.out.println("inside procA");
thrownewRuntimeException("demo");
}finally{
System.out.println("procA'sfinally");
}
}
//Returnfromwithinatryblock. static
void procB() {
try{
System.out.println("insideprocB");
return;
} finally {
System.out.println("procB'sfinally");
}
}
//Executeatryblocknormally.
static void procC() {
try{
System.out.println("insideprocC");
} finally {
System.out.println("procC'sfinally");
}
}
publicstaticvoidmain(Stringargs[]){ try
{
procA();
} catch (Exception e) {
System.out.println("Exceptioncaught");
}
procB();
procC();
}
}
Hereistheoutputgeneratedbytheprecedingprogram:
inside procA
procA’s finally
Exceptioncaught
inside procB
procB’s finally
inside procC
procC’s finally

CategoriesofExceptions
Checked exceptions −A checked exception is an exception that occurs
at the compiletime, these are also called as compile time exceptions.
These exceptions cannot simply be ignored at the time of compilation,
the programmer should take care of (handle) these exceptions.
Unchecked exceptions − An unchecked exception is an exception that
occurs at thetime of execution. These are also called as Runtime
Exceptions. These include programming bugs, such as logic errors or
improper use of an API. Runtime exceptions are ignored at the time of
compilation.

Commonscenarioswhereexceptionsmayoccur:
Therearegivensomescenarioswhereuncheckedexceptionscanoccur. They are
as follows:
1) ScenariowhereArithmeticExceptionoccurs
Ifwedivideanynumberbyzero,thereoccursanArithmeticException. int
a=50/0;//ArithmeticException

2) ScenariowhereNullPointerExceptionoccurs
Ifwehavenullvalueinanyvariable,performinganyoperationbythe variable
occurs an NullPointerException.
String s=null;
System.out.println(s.length());//NullPointerException

3) ScenariowhereArrayIndexOutOfBoundsExceptionoccurs
If you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsException as shown below:
inta[]=new int[5];
a[10]=50;//ArrayIndexOutOfBoundsException

Java’sBuilt-inExceptions
User-definedExceptions
AllexceptionsmustbeachildofThrowable.
If we want to write a checked exception that is automatically enforced by
the Handle ,we need to extend the Exception class.

Userdefinedexceptionneedstoinherit(extends)Exceptionclassin order to
act as an exception.
throwkeywordisusedtothrowsuchexceptions.

classMyOwnExceptionextendsException
{ public
MyOwnException(String
msg) { super(msg);
}
}
classEmployeeTest
{
static void employeeAge(int age) throws
MyOwnException{
if(age < 0)
throw new MyOwnException("Age can't be less
than zero"); else
System.out.println("Inputisvalid!!");
}
publicstaticvoidmain(String[]args)
{
try{employeeAge(-2);
}
catch(MyOwnExceptione)
{
e.printStackTrace();
}
}
}

AdvantagesofExceptionHandling
Exception handling allows us to control the normal flow of the program
by using exception handling in program.
It throws an exception whenever a calling method encounters an error
providing that the calling method takes care of that error.
It also gives us the scope of organizing and differentiating between
differenterrortypes usingaseparateblock ofcodes. This isdonewiththe help
of try-catch blocks.
IOIN JAVA

Java I/O (Input and Output) is used to process the input and produce
theoutputbasedonthe input. Java usesthe conceptofstreamto make I/O
operation fast. The java.io package contains all the classes required
for input and output operations.

Stream
Astreamcanbedefinedasasequenceofdata.therearetwokindsofStreams
 InputStream:TheInputStreamis usedtoreaddatafromasource.
 OutputStream: the OutputStream is used for writing data to a
destination.
ByteStreams
Javabytestreamsare usedtoperforminputandoutputof8-bitbytes
FileInputStream , FileOutputStream.
CharacterStreams
JavaCharacterstreamsareusedtoperforminputandoutput for16-bitunicode.
FileReader , FileWriter

StandardStreams
 Standard Input: This is used to feed the data to user's program and
usually a keyboard is used as standard input stream and represented as
System.in.
 Standard Output: This is used to output the data produced by the
user's program and usually a computer screen is used to standard
output stream and represented as System.out.
 Standard Error: This is used to output the error data produced by the
user's programand usually a computer screen is used to standard error
stream and represented as System.err.

ClassificationofStreamClasses:

ByteStreamClasses:

ByteStream classes have been designed to provide functional features for


creating and manipulatingstreams and files for reading and writingbytes. Since
the streams are unidirectional, they can transmit bytes in only one direction and
therefore, Java provides two kinds ofbyte streamclasses:InputStreamclass and
OutputStream class.
InputStreamClasses
Input stream classes that are used to read 8-bit bytes include a super class
known as InputStream and number of subclasses for supporting various input-
related functions.
HierarchyofInputStreamClasses
The super class InputStream is an abstract class, so we cannot create object for
the class. InputStream class defines the methods to perform the following
functions:-
 ReadingBytes
 ClosingStreams
 MarkingpositioninStreams
 Skippingaheadinstreams
 Findingthenumberofbytesinstream.

ThefollowingaretheInputStreammethods:

TheDataInputinterfacecontainsthefollowingmethods

OutputStreamClass
The super class InputStream is an abstract class, so we cannot create object for
the class. InputStream class defines the methods to perform the following
functions:
 WritingBytes
 ClosingStreams
 FlushingStreams
HierarchyofOutputStreamClasses
OutputStreamMethods

CharacterStreamVsByteStreaminJava I/O
Stream
A stream is a method to sequentially access a file. I/O Stream means an input
source or output destination representing different types of sources e.g. disk
files.The java.io package provides classes that allow you to convert between
Unicode character streams and byte streams of non-Unicode text.
Stream:Asequenceofdata.
Input Stream: reads data from source.
OutputStream:writesdatatodestination.
Character Stream
InJava, characters are stored usingUnicode conventions (Refer this fordetails).
Character stream automatically allows us to read/write data character by
character. For example FileReader and FileWriter are character streams used to
read from source andwrite to destination.

//JavaProgramillustratingthatwecanreadafile in
//ahumanreadableformatusingFileReader
importjava.io.*; //AccessingFileReader,FileWriter,IOException
publicclassGfG
{
publicstaticvoidmain(String[]args)throwsIOException
{
FileReadersourceStream=null;
try
{
sourceStream=newFileReader("test.txt");
//Readingsourcefileandwritingcontent to
//targetfilecharacterbycharacter.
inttemp;
while((temp=sourceStream.read())!=-1)
System.out.println((char)temp);
}
finally
{
//Closingstreamasnolongerinuse if(sourceStream
!= null)
sourceStream.close();
}
}
}

ReadingandWritingFiles:
Astreamcanbedefinedasasequenceofdata. The InputStream is usedtoread data
from a source and the OutputStream is used for writing data to a destination.
TheInputStream is used to read data from a source and the OutputStream
isusedforwritingdatatoadestination.Thetwoimportantstreamsare
FileInputStream and FileOutputStream
HereisahierarchyofclassestodealwithInputandOutputstreams.
FileInputStream
Thisstreamisused forreadingdata fromthefiles.Objectscanbecreated using the
keyword new and there are several types of constructors available.
Followingconstructortakesafilenameasastringtocreateaninputstream object to
read the file –
InputStreamf= new FileInputStream("C:/java/hello");

Followingconstructortakesafileobjecttocreateaninputstreamobjectto read the


file. First we create a file object using File() method as follows −
File f = new File("C:/java/hello");
InputStreamf=newFileInputStream(f);

Once you have InputStream object in hand, then there is a list of helper
methods which can be used to read to stream or to do other operations on the
stream.
Example:
import
java.io.*;
class C{
public static void main(String args[])throws
Exception{ FileInputStream fin=new
FileInputStream("C.java"); FileOutputStream
fout=new FileOutputStream("M.java"); int i=0;
while((i=fin.read())!=-
1){fout.write((byte)i);
}
fin.close();
}
}

ByteStream
Byte streams process data byte bybyte (8 bits). For example FileInputStream is
used to read fromsource and FileOutputStreamto write to the destination.
//JavaProgramillustratingtheByteStreamtocopy
//contentsofonefiletoanother file.
importjava.io.*;
publicclassBStream
{
Publicstaticvoidmain(String[]args)throwsIOException
{
FileInputStream sourceStream = null;
FileOutputStreamtargetStream=null;
try
{
sourceStream = newFileInputStream("sorcefile.txt");
targetStream=newFileOutputStream("targetfile.txt");

//Readingsource fileandwritingcontenttotarget
//filebytebybyte
inttemp;
while((temp=sourceStream.read())!=-1)
targetStream.write((byte)temp);
}
finally
{
if(sourceStream!=null)
sourceStream.close();
if(targetStream!=null)
targetStream.close();
}
}
}
FinalKeywordInJava–Finalvariable,MethodandClass
finalkeywordcanbeusedalongwithvariables,methodsandclasses.
1) finalvariable
2) finalmethod
3) finalclass
1) finalvariable
final variables are nothing but constants. We cannot change the value of a final
variable once it is initialized. Lets have a look at the below code:
classDemo{
finalintMAX_VALUE=99;
void myMethod(){
MAX_VALUE=101;
}
Publicstaticvoidmain(Stringargs[]){
Demo obj=newDemo();
obj.myMethod();
}
}
Exceptioninthread"main"java.lang.Error:Unresolvedcompilationproblem:
ThefinalfieldDemo.MAX_VALUEcannotbeassigned at
beginnersbook.com.Demo.myMethod(Details.java:6) at
beginnersbook.com.Demo.main(Details.java:10)
Wegota compilationerrorinthe aboveprogrambecausewetriedtochange the
valueofa finalvariable“MAX_VALUE”.
2) finalmethod
A final method cannot be overridden. Which means eventhougha sub class can
callthe final method ofparent class without any issues but it cannot override it.
Example:
classXYZ{
finalvoid demo(){
System.out.println("XYZClassMethod");
}
}
classABCextendsXYZ{ void
demo(){
System.out.println("ABCClassMethod");
}
publicstaticvoidmain(Stringargs[]){
ABC obj=new ABC();obj.demo();
}
}
The above program would throw a compilation error, however we can use the
parent class final method in sub class without any issues. Lets have a look atthis
code: This program would run fine as we are not overridingthe final method.
That shows that final methods are inheritedbut theyare not eligible for
overriding.
class XYZ{
finalvoiddemo(){
System.out.println("XYZClassMethod");
}
}
classABCextendsXYZ{
publicstaticvoidmain(Stringargs[]){
ABC obj=new ABC();obj.demo();
}
}
Output:
XYZClassMethod
3)finalclass
Wecannotextendafinalclass.Considerthebelowexample: finalclass
XYZ{
}
classABCextendsXYZ{ void
demo(){
System.out.println("MyMethod");
}
Publicstaticvoidmain(Stringargs[]){
ABC obj=new ABC();obj.demo();
}
}
Output:
ThetypeABCcannotsubclassthefinalclassXYZ
UNITIV
MULTITHREADINGANDGENERICPROGRAMMING

Differencesbetweenmultithreadingandmultitasking, threadlifecycle,creating
threads, creating threads, synchronizing threads, Inter-thread communication,
daemon threads, thread groups. Generic Programming - Generic classes-generic
methods-Bounded Types-Restrictions and Limitations

Thread:
Athreadisasinglesequential(separate)flowofcontrolwithinprogram. Sometimes, it
is called an execution context or light weight process.
Multithreading
Multithreading is aconceptualprogrammingconceptwhereaprogram(process) is
divided into two or more subprograms (process), which can be implemented
atthesametimeinparallel.Amultithreadedprogramcontainstwoormoreparts that
can run concurrently. Each part of such a program is called a thread, and each
thread defines a separate path of execution.
Multitasking
Executingseveraltaskssimultaneouslyiscalledmulti-tasking. There
are 2 types of multi-tasking
1. Process-basedmultitasking
2. Thread-basedmulti-tasking
1. Process-basedmulti-tasking
Executing various jobs together where each job is a separate independent
operation is called process-based multi-tasking.
2. Thread-basedmulti-tasking
Executing several tasks simultaneously where each task is a separate
independent part of the same program is called Thread-based multitasking and
each independent partis called Thread. Itis best suitablefor the programmatic
level. The main goal of multi-tasking is to make or do a better performance
ofthe system by reducing response time
MultithreadingvsMultitasking

Multitasking is to run multiple


Multithreadingistoexecutemultiple
processes on a computer
threads in a process concurrently.
concurrently.

Execution

InMultithreading, the CPU switches In Multitasking, the CPU switches


betweenmultiplethreadsinthesame between multiple processes to
process. complete the execution.

ResourceSharing

In Multithreading, resources are


In Multitasking, resources are shared
shared among multiple threads in a
among multiple processes.
process.

Complexity

Multithreadingislight-weightand Multitasking is heavy-weight and


easy to create. harder to create.

LifeCycleofThread
Athreadcanbeinanyofthefivefollowingstates
1. NewbornState:
When a thread object is created a new thread is born and said to be in
Newborn state.
2. RunnableState:
If a thread is in this state it means that the thread is ready for execution
and waiting for the availability of the processor. If all threads in queue are of
same prioritythentheyare giventime slots for execution inround robin fashion
3. RunningState:
Itmeansthattheprocessor hasgivenitstimetothethreadforexecution.
Athreadkeepsrunninguntilthe followingconditionsoccurs
(a) Threadgiveupitscontrolonitsownanditcanhappeninthefollowing situations
i.A thread gets suspended using suspend() method which can only
be revived with resume() method
ii.A thread is made to sleep for a specified period of time using
sleep(time) method, where time in milliseconds
iii.A thread is made to wait for some event to occur using wait ()
method. Inthis casea thread canbe scheduled to runagain using notify()
method.
(b) Athread ispre-emptedbyahigherprioritythread
4. BlockedState:
If a thread is prevented from entering into runnable state and
subsequently running state, then a thread is said to be in Blocked state.
5. DeadState:
Arunnablethreadenters theDeadorterminatedstatewhenitcompletesitstask or
otherwise
TheMainThread
When we run any java program, the program begins to execute its code
starting from the main method. Therefore, the JVM creates a thread to start
executingthe code present inmainmethod. This thread is calledas mainthread.
Although the main thread is automatically created, you can control it by
obtaining a reference to it by calling currentThread() method.
Twoimportantthingstoknowaboutmainthreadare,
 Itisthethread fromwhichotherthreadswillbeproduced.
 mainthreadmustbealwaysthelastthreadtofinishexecution.
classMainThread
{
publicstaticvoidmain(String[]args)
{
Thread t1=Thread.currentThread();
t.setName("MainThread");
System.out.println("Nameofthreadis"+t1);
}
}
Output:
Nameofthread isThread[MainThread,5,main]

CreationOf Thread
ThreadCanBeImplementedInTwoWays
1) ImplementingRunnableInterface
2) ExtendingThreadClass

1. CreateThreadbyImplementingRunnable
The easiest way to create a thread is to create a class that implements the
Runnable interface. To implement Runnable, a class need only implement a
single method called run()
Example:
publicclassThreadSampleimplementsRunnable
{
publicvoidrun()
{
try
{
for(inti= 5;i>0;i--)
{
System.out.println("ChildThread"+i);
Thread.sleep(1000);
}
}
catch(InterruptedExceptione)
{
System.out.println("Childinterrupted");
}
System.out.println("ExitingChildThread");
}
}
publicclassMainThread
{
publicstaticvoidmain(String[]arg)
{
ThreadSampled=newThreadSample(); Thread
s = new Thread(d);
s.start();
try
{
for(inti= 5;i>0;i--)
{
System.out.println("MainThread"+i);
Thread.sleep(5000);
}
}
catch(InterruptedExceptione)
{
System.out.println("Maininterrupted");
}
System.out.println("ExitingMainThread");
}}
2. ExtendingThreadClass
The second way to create a thread is to create a new class that
extends Thread, and then to create an instance of that class. The
extending class must override the run( ) method, which is the entry
pointforthe newthread.Itmustalsocallstart()tobeginexecutionof
thenewthread.
Example:
publicclassThreadSampleextendsThread
{
publicvoidrun()
{
try
{
for(inti= 5;i>0;i--)
{
System.out.println("ChildThread"+i);
Thread.sleep(1000);
}
}
catch(InterruptedExceptione)
{
System.out.println("Childinterrupted");
}
System.out.println("ExitingChildThread");
}
}
publicclassMainThread
{
publicstaticvoidmain(String[]arg)
{
ThreadSampled=newThreadSample();
d.start();
try
{
for(inti= 5;i>0;i--)
{
System.out.println("MainThread"+i);
Thread.sleep(5000);
}
}
catch(InterruptedExceptione)
{
System.out.println("Maininterrupted");
}
System.out.println("ExitingMainThread");
}
}
Threadpriority:
Each thread have a priority. Priorities are represented by a
numberbetween1and10. In mostcases, threadschedularschedulesthe
threads according to their priority (known as preemptive scheduling).
But it is not guaranteed because it depends on JVM specification that
which scheduling it chooses.
3 constants defined in Thread class:
publicstaticintMIN_PRIORITY
publicstaticintNORM_PRIORITY
public static int MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY). The value of
MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.
Example:
publicclassMyThread1extendsThread{ MyThread1(String
s)
{
super(s);
start();
}
publicvoidrun()
{
for(inti=0;i<5;i++)
{
Thread cur=Thread.currentThread();
cur.setPriority(Thread.MAX_PRIORITY);
int p=cur.getPriority();
System.out.println("Thread
Name"+Thread.currentThread().getName());
System.out.println("ThreadPriority"+cur);
}
}
}
classMyThread2extendsThread{
MyThread2(String s)
{
super(s);
start();
}
publicvoidrun()
{
for(inti=0;i<5;i++)
{
Thread cur=Thread.currentThread();
cur.setPriority(Thread.MIN_PRIORITY);
System.out.println(cur.getPriority());
intp=cur.getPriority();
System.out.println("Thread
Name"+Thread.currentThread().getName());
System.out.println("ThreadPriority"+cur);
}
}
}
publicclassThreadPriority{
publicstaticvoidmain(String[]args)
{
MyThread1m1=newMyThread1("MyThread1");
MyThread2m2=newMyThread2("MyThread2");
}
}
SynchronizingThreads
o Synchronizationinjavaisthecapabilitytocontroltheaccessof multiple
threads to any shared resource.
o Java Synchronization is better option where we want to allow only
one thread to access the shared resource

GeneralSyntax:
synchronized(object)
{
//statementtobesynchronized
}
WhyuseSynchronization
Thesynchronizationismainlyusedto
o Topreventthreadinterference.
o Topreventconsistencyproblem.
TypesofSynchronization
Therearetwotypesofsynchronization
 ProcessSynchronization
 ThreadSynchronization
ThreadSynchronization
There are two types ofthread synchronization mutualexclusive and inter-thread
communication.
1. MutualExclusive
 Synchronizedmethod.
 Synchronizedblock.
 staticsynchronization.
2. Cooperation(Inter-threadcommunicationinjava)

Synchronizedmethod
 If you declare any method as synchronized, it is known as synchronized
method.
 Synchronizedmethodisusedtolockanobjectforanysharedresource.
 When a thread invokes a synchronized method, it automatically acquires
the lock for that object and releases it when the thread completes its task.
Exampleofsynchronizedmethod
package
Thread;publicclassSyn
Thread
{
publicstaticvoidmain(Stringargs[])
{
shares=newshare();
MyThreadm1=newMyThread(s,"Thread1");
MyThreadm2=newMyThread(s,"Thread2");
MyThreadm3=newMyThread(s,"Thread3");
}
}
classMyThreadextendsThread
{
shares;
MyThread(shares,Stringstr)
{
super(str);
this.s = s;
start();
}
publicvoidrun()
{
s.doword(Thread.currentThread().getName());
}
}
classshare
{
publicsynchronizedvoiddoword(Stringstr)
{
for(inti= 0;i< 5;i++)
{
System.out.println("Started:"+str);
try
{
Thread.sleep(1000);
}
catch(Exceptione)
{
}}}}
Synchronizedblock.
 Synchronizedblockcanbeusedtoperformsynchronizationonany specific
resource of the method.
 Supposeyouhave50linesofcodeinyourmethod,butyouwantto synchronize
only 5 lines, you can use synchronized block.
 If you put all the codes of themethodin the synchronized block,it
willwork same as the synchronized method.
Exampleofsynchronizedblock
classTable{
void printTable(int n){
synchronized(this){//synchronizedblock
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exceptione){System.out.println(e);}
}
}
}//endofthemethod
}
classMyThread1extendsThread{ Table
t;
MyThread1(Tablet){
this.t=t;
}
publicvoidrun(){
t.printTable(5);
}
}
classMyThread2extendsThread{
Table t;
MyThread2(Tablet){
this.t=t;
}
publicvoidrun(){
t.printTable(100);
}
}
public class TestSynchronizedBlock1{
public static void main(String args[]){
Tableobj=newTable();//onlyoneobject
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Staticsynchronization
If youmakeany staticmethodassynchronized,thelockwill beon the class
not on object.
Exampleofstaticsynchronization
Inthisexampleweareapplyingsynchronizedkeywordonthestaticmethod to
perform static synchronization.
classTable{
synchronizedstaticvoidprintTable(intn){ for(int
i=1;i<=10;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exceptione){}
}
}
}
classMyThread1extendsThread{
public void run(){
Table.printTable(1);
}
}
classMyThread2extendsThread{
public void run(){
Table.printTable(10);
}
}
classMyThread3extendsThread{
public void run(){
Table.printTable(100);
}
}
classMyThread4extendsThread{
public void run(){
Table.printTable(1000);
}
}
publicclassTestSynchronization4{
public static void main(String t[]){
MyThread1t1=newMyThread1();
MyThread2t2=newMyThread2();
MyThread3t3=newMyThread3();
MyThread4t4=newMyThread4();
t1.start();
t2.start();
t3.start();
t4.start();
}
}
Inter-threadcommunication
Inter-thread communication or Co-operation is all about allowing
synchronized threads to communicate with each other.
Inter-thread communication is a mechanism in which a thread is paused
running in its critical section and another thread is allowed to enter (or lock) in
the same critical section to be executed.It is implemented by following methods
of Object class:
 wait()
 notify()
 notifyAll()
wait()
tellscalling thread togiveupmonitor and go to sleepuntil some other
thread enters the same monitor and call notify.
notify()
wakesupathreadthatcalledwait()onsameobject.
notifyAll()
wakesupallthethreadthat calledwait()onsameobject.
wait() sleep()

wait()methodreleasesthe lock sleep() method doesn't release the


lock.

isthe methodofObjectclass isthemethodofThreadclass

isthenon-static method isthestatic method

should be notified by notify() or after the specified amount of


notifyAll() methods time, sleep is completed.

Exampleofinterthreadcommunicationinjava

class Customer{
intamount=10000;
synchronized void withdraw(int amount){
System.out.println("goingtowithdraw...");
if(this.amount<amount){
System.out.println("Lessbalance;waitingfordeposit...");
try{wait();}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdrawcompleted...");
}
synchronized void deposit(int amount){
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("depositcompleted...");
notify();
}
}
classTest{
publicstaticvoidmain(Stringargs[]){
final Customer c=new Customer();
new Thread(){
publicvoidrun(){c.withdraw(15000);}
}.start();
newThread(){
publicvoidrun(){c.deposit(10000);}
}.start();
}}
DaemonThreadinJava
Daemon thread in java is a service provider thread that provides services
to the user thread. Its life depend on the mercy of user threads i.e. when all the
user threads dies, JVM terminates this thread automatically.
Example:
publicclassTestDaemonThread1extendsThread{ public
void run(){
if(Thread.currentThread().isDaemon()){//checkingfordaemonthread
System.out.println("daemon thread work");
}
else{
System.out.println("userthreadwork");
}
}
publicstaticvoidmain(String[]args){
TestDaemonThread1t1=newTestDaemonThread1();//creatingthread
TestDaemonThread1 t2=new TestDaemonThread1();
TestDaemonThread1t3=newTestDaemonThread1();
t1.setDaemon(true);//now t1 is daemon thread
t1.start();//starting threads
t2.start();
t3.start();
}
}

ThreadGroup
Java provides a convenient way to group multiple threads in a single
object. In such way, we can suspend, resume or interrupt group of threads by a
single method call.
ConstructorsofThreadGroupclass
ThereareonlytwoconstructorsofThreadGroupclass.
1. ThreadGroup(Stringname)-createsathreadgroupwithgiven
name.
2. ThreadGroup(ThreadGroup parent, String name)-creates a thread
group with given parent group and name.
ImportantmethodsofThreadGroupclass
TherearemanymethodsinThreadGroupclass.Alistofimportant methods are
given below.

1) intactiveCount()-returnsno.ofthreadsrunningincurrentgroup.
2) intactiveGroupCount()-returnsano.ofactivegroupinthisthread
group.
3) voiddestroy()-destroysthisthreadgroupandallitssubgroups.
4) String getName()-returns the name of this group.
5)ThreadGroupgetParent()-returnstheparentofthisgroup.
6) voidinterrupt()-interruptsallthreadsofthisgroup.
7) voidlist()-printsinformationofthisgrouptostandardconsole.

Let's see a code to group multiple threads.ThreadGroup


tg1 = new ThreadGroup("Group A");
Threadt1=newThread(tg1,newMyRunnable(),"one");
Thread t2 = new Thread(tg1,new MyRunnable(),"two");
Threadt3=newThread(tg1,newMyRunnable(),"three");

Now all 3 threads belong to one group. Here, tg1 is the thread group
name, MyRunnable is the class that implements Runnable interface and "one",
"two" and "three" are the thread names.
Nowwecaninterruptallthreadsbyasinglelineofcodeonly.
Thread.currentThread().getThreadGroup().interrupt();

ThreadGroupExample
publicclassThreadGroupDemoimplementsRunnable{
public void run() {
System.out.println(Thread.currentThread().getName());
}
publicstaticvoidmain(String[]args) {
ThreadGroupDemo runnable = new ThreadGroupDemo();
ThreadGrouptg1=newThreadGroup("ParentThreadGroup"); Thread
t1 = new Thread(tg1, runnable,"one");
t1.start();
Threadt2=newThread(tg1,runnable,"two"); t2.start();
Threadt3=newThread(tg1,runnable,"three"); t3.start();
System.out.println("ThreadGroupName:"+tg1.getName());
tg1.list();
}
}
Output:

one
two
three
Thread Group Name: Parent ThreadGroup
java.lang.ThreadGroup[name=ParentThreadGroup,maxpri=10]
Thread[one,5,Parent ThreadGroup]
Thread[two,5,Parent ThreadGroup]
Thread[three,5,ParentThreadGroup]

GenericProgramming
Genericprogrammingenablestheprogrammertocreateclasses,interfaces and
methods that automatically works with all types of data(Integer, String, Float
etc). It has expanded the ability to reuse the code safely and easily.
AdvantageofJavaGenerics
Therearemainly3advantagesofgenerics.Theyareasfollows:
1) Type-safety :Wecan holdonly asingletypeofobjectsin generics.Itdoesn’t
allowtostoreotherobjects.
2) Type casting is not required: There is no need to typecast the object.
3)Compile-TimeChecking: It ischecked at compiletimeso problem will not
occur at runtime. The good programming strategy says it is far better to handle
the problem at compile time than runtime.
Genericclass
 Aclassthatcanrefertoanytypeisknownasgenericclass.
 Generic class declaration defines set of parameterized type one for
each possible invocation of the type parameters
Example:
classTwoGen<T,V>
{
Tob1;
Vob2;
TwoGen(To1,Vo2)
{
ob1=o1;
ob2=o2;
}
voidshowTypes(){
System.out.println("TypeofT is "+ob1.getClass().getName());
System.out.println("TypeofV is"+ob2.getClass().getName());
}
Tgetob1()
{
returnob1;
}

Vgetob2()
{
returnob2;
}
}
publicclassMainClass
{
publicstaticvoidmain(Stringargs[])
{
TwoGen<Integer, String> tgObj = new TwoGen<Integer,
String>(88,"Generics");
tgObj.showTypes();
int v = tgObj.getob1();
System.out.println("value:"+v);
String str = tgObj.getob2();
System.out.println("value:"+str);
}
}

GenericMethod
Like generic class, we cancreate generic method that canaccept anytype
of argument.
publicclassTestGenerics4{
publicstatic<E>voidprintArray(E[]elements){ for ( E
element : elements){
System.out.println(element);
}
System.out.println();
}
public static void main( String args[] ) {
Integer[] intArray = { 10, 20, 30, 40, 50 };
Character[] charArray = { 'J', 'A', 'V', 'A'};
System.out.println("PrintingIntegerArray");
printArray( intArray);
System.out.println("PrintingCharacterArray");
printArray(charArray);
}
}
Boundedtype
The type parameters could be replaced by any class type. This is fine for
many purposes, but sometimes it is useful to limit the types that can be passedto
a type parameter
Syntax:
<Textends superclass>
Example
classStats<TextendsNumber>{ T[]
nums;
Stats(T[] o) {
nums = o; }
doubleaverage(){
double sum = 0.0;
for(inti=0;i<nums.length;i++)
sum += nums[i].doubleValue();
return sum / nums.length;
}
}
publicclassMainClass{
publicstaticvoidmain(Stringargs[]){
Integer inums[] = { 1, 2, 3, 4, 5 };
Stats<Integer>iob=newStats<Integer>(inums);
double v = iob.average();System.out.println("iob
average is " + v);
Doublednums[]={1.1,2.2,3.3,4.4,5.5};
Stats<Double>dob=newStats<Double>(dnums);
double w = dob.average();
System.out.println("dobaverageis"+w);
}
}
RestrictionsonGenerics
TouseJavagenericseffectively,youmustconsiderthefollowing restrictions:

 CannotInstantiateGenericTypeswithPrimitiveTypes
 CannotCreateInstancesofTypeParameters
 CannotDeclareStaticFieldsWhoseTypesareTypeParameters
 CannotUseCastsorinstanceofWithParameterizedTypes
 CannotCreateArraysofParameterizedTypes
 CannotCreate,Catch,orThrowObjectsofParameterizedTypes
 Cannot Overload a Method Where the Formal Parameter Types of Each
Overload Erase to the Same Raw Type
UNIT-V
EVENTDRIVENPROGRAMMING

Graphicsprogramming-Frame-Components-workingwith2Dshapes-Usingcolor,fonts,andimages-Basics
ofeventHandling-eventhandlers-adapter classes-actionsmouseevents-AWTeventhierarchy-Introduction to
Swing-layout management-SwingComponents-Text Fields,TextAreas-Buttons-Check Boxes-Radio
Buttons-Lists-choices-Scrollbars-windows-Menus-Dialog Boxesand Interfaces, Exception handling,
Multithreaded programming, Strings, Input/output

Graphicsprogramming
 Javacontainssupportforgraphicsthatenableprogrammerstovisuallyenhanceapplications
 JavacontainsmanymoresophisticateddrawingcapabilitiesaspartoftheJava2D API
AWT
 JavaAWT(AbstractWindowToolkit)isanAPItodevelopGUIorwindow-basedapplicationsin java.
 JavaAWTcomponentsareplatform-dependenti.e.componentsaredisplayedaccordingtotheview of
operating system.
 AWT is heavyweight i.e. its components are usingtheresources of OS.The java.awt package
providesclassesforAWTapisuchasTextField,Label,TextArea,RadioButton,CheckBox,Choice, List
etc.

JavaAWTHierarchy
ThehierarchyofJavaAWTclassesaregivenbelow.
Container
TheContainerisacomponentinAWTthat cancontainanothercomponentslikebuttons,textfields,
labelsetc.TheclassesthatextendContainerclassareknownascontainersuchasFrame,DialogandPanel. Window
Thewindowisthecontainerthathasnobordersandmenubars.Youmustuseframe,dialog or
anotherwindowforcreatingawindow.
Panel
ThePanelisthecontainerthatdoesn'tcontaintitlebarandmenubars.Itcanhaveothercomponents like
button, textfield etc.
Frame
TheFrameisthecontainerthatcontaintitlebarand canhavemenu bars.Itcanhaveother components like
button, textfield etc.
TherearetwowaystocreateaFrame.Theyare,
 ByInstantiatingFrameclass
 ByextendingFrameclass
Example:
import java.awt.*;
import java.awt.event.*;
classMyLoginWindowextendsFrame
{
TextField name,pass;
Button b1,b2;
MyLoginWindow()
{
setLayout(new FlowLayout());
this.setLayout(null);
Label n=new Label("Name:",Label.CENTER);
Label p=new Label("password:",Label.CENTER);
name=new TextField(20);
pass=new TextField(20);
pass.setEchoChar('#');
b1=new Button("submit");
b2=newButton("cancel");
this.add(n);
this.add(name);
this.add(p);
this.add(pass);
this.add(b1);
this.add(b2);
n.setBounds(70,90,90,60);
p.setBounds(70,130,90,60);
name.setBounds(200,100,90,20);
pass.setBounds(200,140,90,20);
b1.setBounds(100,260,70,40);
b2.setBounds(180,260,70,40);
}
publicstaticvoidmain(Stringargs[])
{
MyLoginWindow ml=new MyLoginWindow();
ml.setVisible(true);
ml.setSize(400,400);
ml.setTitle("myloginwindow");
}}

Output:

Eventhandling:
Changingthestateofanobjectisknownasanevent.Forexample,clickonbutton,dragging mouse etc. The
java.awt.event package provides many event classesand Listener interfaces for event handling.
Eventhandlinghasthreemaincomponents,
 Events:Aneventisachangeinstateofanobject.
 EventsSource:Eventsourceisanobjectthatgeneratesanevent.
 Listeners:Alistenerisanobjectthatlistenstotheevent.Alistenergetsnotified whenan event
occur
HowEventsarehandled?
A source generatesan Event and send it to one or morelisteners registered with the source.Once
eventisreceivedbythelistener,theyprocessthe eventandthenreturn.Eventsaresupportedbyanumber of Java
packages, like java.util, java.awt and java.awt.event.
ImportantEventClassesandInterface

EventClasses Description ListenerInterface

ActionEvent generatedwhenbuttonispressed,menu-itemis selected, ActionListener


list-item is double clicked

MouseEvent generated when mouse is dragged, MouseListener


moved,clicked,pressedorreleasedandalsowhenit enters
or exit a component

KeyEvent generatedwheninputisreceivedfromkeyboard KeyListener

ItemEvent generatedwhencheck-boxorlistitemisclicked ItemListener

TextEvent generatedwhenvalueoftextareaortextfieldis changed TextListener

MouseWheelEvent generatedwhenmousewheelismoved MouseWheelListener

WindowEvent generatedwhenwindowisactivated,deactivated, WindowListener


deiconified, iconified, opened or closed

ComponentEvent generatedwhencomponentishidden,moved,resized or ComponentEventListener


set visible

ContainerEvent generatedwhencomponentisaddedorremovedfrom ContainerListener


container

AdjustmentEvent generatedwhenscrollbarismanipulated AdjustmentListener


FocusEvent generatedwhencomponentgainsorloseskeyboard focus FocusListener

Stepstohandleevents:
 Implementappropriateinterfaceintheclass.
 Registerthecomponentwiththelistener.

HowtoimplementListener
1. DeclareaneventhandlerclassandspecifythattheclasseitherimplementsanActionListener(any
listener) interface or extends a classthatimplementsan ActionListener interface. For example:

publicclassMyClassimplementsActionListener
{
//SetofCode
}
2. Registeraninstanceoftheeventhandlerclassasalistenerononeor morecomponents.For
example:
someComponent.addActionListener(instanceOfMyClass);
3. Includecodethatimplementsthemethodsinlistenerinterface.Forexample:
public void actionPerformed(ActionEvent e) {
//codethatreactstotheaction
}

MouseListener

package Listener;
import java.awt.Frame;
import java.awt.Label;
importjava.awt.TextArea;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
publicclassMouseimplementsMouseListener{
TextArea s;
publicMouse()
{
Frame d=new Frame("kkkk");
s=new TextArea("");d.add(s);
s.addMouseListener(this);
d.setSize(190, 190);
d.show();
}
publicvoidmousePressed(MouseEvente){
System.out.println("MousePressed");
inta=e.getX();
int b=e.getY();
System.out.println("X="+a+"Y="+b);
}
publicvoidmouseReleased(MouseEvente){
System.out.println("MouseReleased");
}
publicvoidmouseEntered(MouseEvente){
System.out.println("MouseEntered");
}
publicvoidmouseExited(MouseEvente){
System.out.println("MouseExited");
}
publicvoidmouseClicked(MouseEvente){
System.out.println("MouseClicked");
}
publicstaticvoidmain(Stringarg[])
{
Mousea=newMouse();
}
}

MouseMotionListener

packageListener;
importjava.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
publicclassMouseMotionEventDemoextendsJPanelimplementsMouseMotionListener
{MouseMotionEventDemo()
{
JTextArea a=new JTextArea();
a.addMouseMotionListener(this);
JFrame b=new JFrame();
b.add(a);
b.setVisible(true);
}
publicvoidmouseMoved(MouseEvente){
System.out.println("Mouse is Moving");
}
public void mouseDragged(MouseEvent e){
System.out.println("MouseDragged");
}
publicstaticvoidmain(Stringarg[])
{
MouseMotionEventDemoa=newMouseMotionEventDemo();
}
}
KEYLISTENER

packageListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
importjavax.swing.JTextField;
publicclassKeyEventDemoimplementsKeyListener
{
publicKeyEventDemo()
{
JFrames=newJFrame("hai");
JTextFieldtypingArea=newJTextField(20);
typingArea.addKeyListener(this);
s.add(typingArea);
s.setVisible(true);
}
publicvoidkeyTyped(KeyEvente){
System.out.println("KeyTyped");
}
/**Handlethekey-pressedeventfromthetextfield.*/ public
void keyPressed(KeyEvent e) {
System.out.println("KeyPressed");
}
/**Handlethekey-releasedeventfromthetextfield.*/ public
void keyReleased(KeyEvent e) {
System.out.println("Keyreleased");
}
publicstaticvoidmain(Stringg[])
{
KeyEventDemoa=newKeyEventDemo();
}
}
ITEMLISTENER

packageListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
importjava.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JTextField;
publicclassitemlistenerimplementsItemListener
{
publicitemlistener()
{
JFrames=newJFrame("hai");
JCheckBox a=new JCheckBox("Ok");
a.addItemListener(this);
s.add(a);
s.setVisible(true);
}
publicstaticvoidmain(Stringg[])
{
itemlistenerl=newitemlistener();
}
public void itemStateChanged(ItemEvent arg0) {
System.out.println("State changed");
}
}
WindowListener
packageListener;
importjava.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
publicclasswindowextendsJPanelimplementsWindowListener{ window()
{
JFrame b=new JFrame();
b.addWindowListener(this);
b.setVisible(true);
}
publicstaticvoidmain(Stringarg[])
{
windowa=newwindow();
}
public void windowActivated(WindowEvent arg0) {
System.out.println("Window activated");
}
publicvoidwindowClosed(WindowEventarg0){
//TODOAuto-generatedmethodstub
System.out.println("Windowclosed");
}
publicvoidwindowClosing(WindowEventarg0){
// TODO Auto-generated method stub
System.out.println("Window closing");
}
publicvoidwindowDeactivated(WindowEventarg0){
//TODOAuto-generatedmethodstub
System.out.println("Windowdeactivated");
}
publicvoidwindowDeiconified(WindowEventarg0){
// TODO Auto-generated method stub
System.out.println("Window deiconified");
}
publicvoidwindowIconified(WindowEventarg0){
// TODO Auto-generated method stub
System.out.println("Window Iconified");
}
publicvoidwindowOpened(WindowEventarg0){
// TODO Auto-generated method stub
System.out.println("Window opened");
}}

WINDOWFOCUSLISTENER

packageListener;
importjava.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
publicclasswindow1extendsJPanelimplementsWindowFocusListener{
window1()
{
JFrame b=new JFrame();
b.addWindowFocusListener(this);
b.setVisible(true);
}
publicstaticvoidmain(Stringarg[])
{
window1b=newwindow1();
}
publicvoidwindowGainedFocus(WindowEvente){
// TODO Auto-generated method stub
System.out.println("Window gained");
}
publicvoidwindowLostFocus(WindowEvente){
// TODO Auto-generated method stub
System.out.println("Windowlostfocus");
}}

WindowStateListener

packageListener;
importjava.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowStateListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
publicclasswindow2extendsJPanelimplementsWindowStateListener{
window2()
{
JFrame b=new JFrame();
b.addWindowStateListener(this);
b.setVisible(true);
}
publicstaticvoidmain(Stringarg[])
{
window2b=newwindow2();
}
publicvoidwindowStateChanged(WindowEvente){
//TODOAuto-generatedmethodstub
System.out.println("StateChanged");
}}
ACTIONLISTENER

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
importjavax.swing.event.*;
publicclassAextendsJFrameimplementsActionListener{
Scientific() {
JPanelbuttonpanel=newJPanel();
JButtonb1= newJButton("Hai");
buttonpanel.add(b1);
b1.addActionListener(this);
}
publicvoidactionPerformed(ActionEvente){
System.out.println(“Haibutton”);
}
publicstaticvoidmain(Stringargs[]){ A f
= new A();
f.setTitle("ActionListener");
f.setSize(500,500);
f.setVisible(true);
}}

Javaadapterclasses
Java adapter classes providethe defaultimplementation of listener interfaces. If you inherit the
adapterclass,you willnotbeforcedtoprovidetheimplementationofallthemethodsoflistenerinterfaces. So it
saves code.
Theadapterclassesarefoundinjava.awt.event,java.awt.dndandjavax.swing.eventpackages.

Adapterclass Listenerinterface

WindowAdapter WindowListener

KeyAdapter KeyListener

MouseAdapter MouseListener

MouseMotionAdapter MouseMotionListener

FocusAdapter FocusListener

ComponentAdapter ComponentListener

ContainerAdapter ContainerListener

HierarchyBoundsAdapter HierarchyBoundsListener

JavaWindowAdapterExample
import java.awt.*;
import java.awt.event.*;
publicclassAdapterExample{
Frame f;
AdapterExample(){
f=new Frame("Window Adapter");
f.addWindowListener(new WindowAdapter(){
publicvoidwindowClosing(WindowEvente){
f.dispose();
}
});
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
publicstaticvoidmain(String[]args){ new
AdapterExample();
}}

JavaMouseAdapterExample
import java.awt.*;
import java.awt.event.*;
public class MouseAdapterExample extends MouseAdapter{
Frame f;
MouseAdapterExample(){
f=new Frame("Mouse Adapter");
f.addMouseListener(this);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
publicvoidmouseClicked(MouseEvente){ Graphics
g=f.getGraphics(); g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),30,30);
}
publicstaticvoidmain(String[]args){
newMouseAdapterExample();
}}

Java MouseMotionAdapter Example


import java.awt.*;
importjava.awt.event.*;
public class MouseMotionAdapterExample extends
MouseMotionAdapter{Frame f;
MouseMotionAdapterExample(){
f=newFrame("MouseMotionAdapter");
f.addMouseMotionListener(this);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
publicvoidmouseDragged(MouseEvente){
Graphics g=f.getGraphics();
g.setColor(Color.ORANGE);
g.fillOval(e.getX(),e.getY(),20,20);
}
public static void main(String[] args) {
new MouseMotionAdapterExample();
}}

JavaKeyAdapterExample
import java.awt.*;
import java.awt.event.*;
publicclassKeyAdapterExampleextendsKeyAdapter{
Label l;
TextAreaarea;
Frame f;
KeyAdapterExample(){
f=new Frame("Key Adapter");
l=new Label();
l.setBounds(20,50,200,20);
area=new TextArea();
area.setBounds(20,80,300, 300);
area.addKeyListener(this);
f.add(l);f.add(area);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
publicvoidkeyReleased(KeyEvente){
String text=area.getText();
Stringwords[]=text.split("\\s");
l.setText("Words:"+words.length+"Characters:"+text.length());
}
publicstaticvoidmain(String[]args){ new
KeyAdapterExample();
}}

AWTEVENTHIERARCHY

Swing
 Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create window -based
applications.Itisbuiltonthe topofAWT (AbstractWindowingToolkit)APIandentirely writtenin java.
 UnlikeAWT,JavaSwingprovidesplatform-independentandlightweightcomponents.
 The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
ThehierarchyofjavaswingAPIisgivenbelow

DifferencebetweenAWTandSwing
Therearemanydifferencesbetweenjavaawtandswingthataregivenbelow.

No. JavaAWT JavaSwing

1) AWT components areplatform- Java swing components


dependent. are platform-independent.

2) AWTcomponentsareheavyweight. Swing components


are lightweight.

3) AWTdoesn'tsupportpluggablelook and Swing supports pluggable


feel. look and feel.

4) AWT provides less componentsthan Swing providesmore


Swing. powerful componentssuch as
tables, lists, scrollpanes,
colorchooser, tabbedpane etc.

5) AWTdoesn'tfollowsMVC(Model SwingfollowsMVC.
ViewController)wheremodelrepresents
data, view represents presentation and
controller acts as an interface between
model and view.
Layout management
JavaLayoutManagers
The LayoutManagers are used to arrange components in a particular manner. LayoutManager is an
interface that is implemented by all the classes of layout managers. There are following classes that
represents the layout managers:
AWTLayoutManagerClasses
FollowingisthelistofcommonlyusedcontrolswhiledesigningGUIusing AWT.

Sr.No. LayoutManager&Description

BorderLayout
1 Theborderlayoutarrangesthecomponentstofitinthefiveregions:east,west, north, south,
and center.

CardLayout
2 The CardLayout object treats each component in the container as a card. Only one
card is visible at a time.

3 FlowLayout
TheFlowLayoutisthedefaultlayout.Itlayoutthecomponentsinadirectionalflow.

4 GridLayout
TheGridLayoutmanagesthecomponentsintheformofarectangulargrid.

GridBagLayout
5 This isthe most flexible layout manager class. The object of GridBagLayout aligns
the component vertically, horizontally, or along their baseline without requiring the
components of the same size.

GroupLayout
6 TheGroupLayout hierarchically groupsthe componentsin order to position them in a
Container.

SpringLayout
7 A SpringLayout positions the children of its associated container according to a set
of constraints.

8 BoxLayout
TheBoxLayoutisusedtoarrangethecomponentseitherverticallyorhorizontally.

ScrollPaneLayout
9 ThelayoutmanagerusedbyJScrollPane.JScrollPaneLayoutisresponsiblefornine
components: a viewport, two scrollbars, a row header, a column header, and four
"corner" components.
Borderlayout:
Example:
import java.awt.*;
importjavax.swing.*;
public class Border {
JFrame f;
Border(){
f=newJFrame();
JButton b1=new JButton("NORTH");;
JButton b2=new JButton("SOUTH");;
JButton b3=new JButton("EAST");;
JButton b4=new JButton("WEST");;
JButton b5=new JButton("CENTER");;
f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);
}
publicstaticvoidmain(String[]args){
new Border();
}}

ScrollPaneLayout:
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
publicclassScrollPaneDemoextendsJFrame
{
publicScrollPaneDemo(){
super("ScrollPaneDemo");
ImageIcon img = new ImageIcon("child.png");
JScrollPanepng=newJScrollPane(newJLabel(img));
getContentPane().add(png);
setSize(300,250);
setVisible(true);
}
publicstaticvoidmain(String[]args){
new ScrollPaneDemo();
}}

Boxlayout
import java.awt.*;
import javax.swing.*;
publicclassBoxLayoutExample1extendsFrame{
Button buttons[];
publicBoxLayoutExample1(){
buttons = new Button [5];
for(inti=0;i<5;i++) {
buttons[i]=newButton("Button"+(i+1)); add
(buttons[i]);
}
setLayout(newBoxLayout(this,BoxLayout.Y_AXIS));
setSize(400,400);
setVisible(true);
}
public static void main(String args[]){
BoxLayoutExample1 b=new BoxLayoutExample1();
}
Grouplayout:
Example
publicclassGroupExample
{
publicstaticvoidmain(String[]args)
{
JFrame frame = new JFrame("GroupLayoutExample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPanel = frame.getContentPane();
GroupLayout groupLayout = new
GroupLayout(contentPanel);contentPanel.setLayout(groupLayou
t);
JLabelclickMe=newJLabel("ClickHere");
JButtonbutton=newJButton("ThisButton");
groupLayout.setHorizontalGroup(
groupLayout.createSequentialGroup()
.addComponent(clickMe)
.addGap(10,20,100)
.addComponent(button));
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(clickMe)
.addComponent(button));
frame.pack();
frame.setVisible(true);
}}}

Swingcomponents:
TextFields
TheobjectofaJTextFieldclassisatextcomponentthatallowstheeditingofa singlelinetext.It inherits
JTextComponent class.
TextAreas
TheobjectofaJTextArea classisa multilineregionthatdisplaystext.Itallowstheeditingof multiple line
text. It inherits JTextComponent class
Buttons
TheJButtonclassisusedtocreatealabeledbuttonthathasplatformindependentimplementation.
Theapplicationresultinsomeaction whenthebuttonispushed.ItinheritsAbstractButtonclass. import
javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class SwingFirstExample {
publicstaticvoidmain(String[]args){
//CreatinginstanceofJFrame
JFrameframe=newJFrame("MyFirstSwingExample");
//Settingthewidthandheightofframe
frame.setSize(350, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/*Creatingpanel.ThisissameasadivtaginHTML
* Wecancreateseveralpanelsandaddthemtospecific
* positionsinaJFrame.Insidepanelswecanaddtext
* fields,buttonsandothercomponents.
*/
JPanelpanel=newJPanel();
//addingpaneltoframe
frame.add(panel);
/*callinguserdefinedmethodforaddingcomponents
* tothepanel.
*/
placeComponents(panel);
//Settingtheframevisibilitytotrue
frame.setVisible(true); }
privatestaticvoidplaceComponents(JPanelpanel){
/* We will discuss about layouts in the later sections *ofthistutorial. Fornowwearesettingthe
layout * to null */
panel.setLayout(null);
//CreatingJLabel
JLabeluserLabel=newJLabel("User");
/*Thismethod specifiesthelocationandsize
* ofcomponent.setBounds(x,y,width,height)
* here(x,y)arecordinatesfromthetopleft
* cornerandremainingtwoargumentsarethewidth
* andheight ofthecomponent.
*/
userLabel.setBounds(10,20,80,25);
panel.add(userLabel);
/*Creatingtextfieldwhereuserissupposed to
* enterusername.
*/
JTextFielduserText=newJTextField(20);
userText.setBounds(100,20,165,25);
panel.add(userText);
// Same process for password label andtext field.
JLabelpasswordLabel=newJLabel("Password");
passwordLabel.setBounds(10,50,80,25);
panel.add(passwordLabel);
/*Thisis similartotextfieldbutithidestheuser
* entereddataanddisplaysdotsinsteadtoprotect
* thepasswordlikewenormallyseeonlogin screens.
*/
JPasswordField passwordText = new JPasswordField(20);
passwordText.setBounds(100,50,165,25);
panel.add(passwordText);
//Creatingloginbutton
JButtonloginButton=newJButton("login");
loginButton.setBounds(10, 80, 80, 25);
panel.add(loginButton);
}}
Output:

CheckBoxes
TheJCheckBoxclassisusedtocreatea checkbox.Itisusedtoturnanoptionon(true)oroff(false).
ClickingonaCheckBoxchangesitsstatefrom"on"to"off"or from"off"to"on".ItinheritsJToggleButton class.
Example:
importjavax.swing.*;
publicclassCheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
JCheckBoxcheckBox1=newJCheckBox("C++");
checkBox1.setBounds(100,100, 50,50);
JCheckBoxcheckBox2=newJCheckBox("Java",true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
publicstaticvoidmain(Stringargs[])
{
newCheckBoxExample();
}}

Radio Buttons TheJRadioButton classisusedto createa radio button. It isused to choose one option from
multipleoptions.Itiswidelyusedin examsystemsorquiz.ItshouldbeaddedinButtonGrouptoselect one
radio
buttononly.
import javax.swing.*;
import java.awt.event.*;
class RadioButtonExample extends JFrame implements
ActionListener{JRadioButton rb1,rb2;
JButton b;
RadioButtonExample(){
rb1=new JRadioButton("Male");
rb1.setBounds(100,50,100,30);
rb2=new JRadioButton("Female");
rb2.setBounds(100,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(rb1);bg.add(rb2);
b=new JButton("click");
b.setBounds(100,150,80,30);
b.addActionListener(this);
add(rb1);add(rb2);add(b);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(rb1.isSelected()){
JOptionPane.showMessageDialog(this,"You are Male.");
}
if(rb2.isSelected()){
JOptionPane.showMessageDialog(this,"YouareFemale.");
} }
publicstaticvoidmain(Stringargs[]){
new RadioButtonExample();
}}

Lists
TheobjectofJListclassrepresentsalistoftextitems.Thelistoftextitemscanbesetupsothatthe
usercanchooseeitheroneitemor multipleitems.ItinheritsJComponent class. import
javax.swing.*;
publicclassListExample
{
ListExample(){
JFramef=newJFrame();
DefaultListModel<String> l1 = new DefaultListModel<>();
l1.addElement("Item1");
l1.addElement("Item2");
l1.addElement("Item3");
l1.addElement("Item4");
JList<String>list=newJList<>(l1);
list.setBounds(100,100, 75,75);
f.add(list);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
publicstaticvoidmain(Stringargs[])
{
newListExample();
}}
Choices(JComboBox)
TheobjectofChoice classisusedtoshowpopupmenuofchoices.Choiceselectedbyuserisshown on the
top of a menu. It inherits JComponent class.
importjavax.swing.*;
public class ComboBoxExample {
JFrame f;
ComboBoxExample(){
f=newJFrame("ComboBoxExample");
String
country[]={"India","Aus","U.S.A","England","Newzealand"};JComboBox
cb=new JComboBox(country);
cb.setBounds(50, 50,90,20);
f.add(cb);
f.setLayout(null);
f.setSize(400,500);
f.setVisible(true);
}
publicstaticvoidmain(String[]args){ new
ComboBoxExample();
} }
Scrollbars
TheobjectofJScrollbarclassisusedtoaddhorizontalandverticalscrollbar.Itisanimplementation of a
scrollbar. It inherits JComponent class.
mport javax.swing.*;
class ScrollBarExample
{
ScrollBarExample(){
JFramef=newJFrame("ScrollbarExample");
JScrollBar s=new JScrollBar();
s.setBounds(100,100, 50,100);
f.add(s);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
publicstaticvoidmain(Stringargs[])
{
newScrollBarExample();
}}
Windows
TheclassJWindowisacontainerthatcanbedisplayedbutdoesnothavethetitlebar
Menus
TheJMenuBarclassisusedtodisplaymenubaronthewindowor frame.It mayhaveseveral menus.
Theobject ofJMenu classisa pull downmenu component whichisdisplayed fromthemenu bar. It
inheritstheJMenuItemclass.
TheobjectofJMenuItemclassaddsasimplelabeledmenuitem.Theitemsusedinamenu must belong to
the JMenuItem or any of its subclass.
import javax.swing.*;
class MenuExample
{
JMenu menu, submenu;
JMenuItemi1,i2,i3,i4,i5;
MenuExample(){
JFramef=newJFrame("MenuandMenuItemExample");
JMenuBar mb=new JMenuBar();
menu=new JMenu("Menu");
submenu=new JMenu("Sub Menu");
i1=new JMenuItem("Item 1");
i2=newJMenuItem("Item2");
i3=newJMenuItem("Item3");
i4=newJMenuItem("Item4");
i5=new JMenuItem("Item 5");
menu.add(i1); menu.add(i2); menu.add(i3);
submenu.add(i4); submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setJMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
publicstaticvoidmain(Stringargs[])
{
newMenuExample();
}}
Output:

DialogBoxes.
TheJDialogcontrolrepresentsa toplevelwindowwitha borderandatitleusedtotakesomeform ofinput
fromtheuser.Itinherits theDialog class.Unlike JFrame, it doesn't have maximizeand minimize buttons.
Example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
publicclassDialogExample{
private static JDialog d;
DialogExample() {
JFramef=newJFrame();
d=newJDialog(f,"DialogExample",true);
d.setLayout( new FlowLayout() );
JButton b = new JButton ("OK");
b.addActionListener ( new ActionListener()
{
publicvoidactionPerformed(ActionEvente)
{
DialogExample.d.setVisible(false);}}};
d.add(newJLabel("Clickbuttontocontinue."));
d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
publicstaticvoidmain(Stringargs[])
{
newDialogExample();}}
Output:

You might also like