Java VK
Java VK
JAVAPROGRAMMING
B.TECHIIYEAR-
IISEM(2017-18)
DEPARTMENTOFINFORMATIONTECHNOLOGY
MALLAREDDYCOLLEGEOFENGINEERING&TECHNOLOGY
(AutonomousInstitution–UGC,Govt.ofIndia)
(AffiliatedtoJNTUH,Hyderabad,ApprovedbyAICTE- AccreditedbyNBA&NAAC –‘A’ Grade-ISO9001:2015 Certified)
Maisammaguda,Dhulapally(PostVia.Hakimpet),Secunderabad –500100,TelanganaState,INDIA.
MALLAREDDYCOLLEGEOFENGINEERING&TECHNOLOGYDEPARTMENT
OFINFORMATIONTECHNOLOGY
(R15A0507)JAVAPROGRAMMING
Objectives:
This subject aims to introduce students to the Java programming language. Upon
successful completion of this subject, students should be able to create Java programs that
leverage the object-oriented features of the Java language, such as encapsulation, inheritance and
polymorphism; use data types, arrays and other data collections; implement error-handling
techniques using exception handling, create and event-driven GUI using Swing components.
UNIT-I
OOP Concepts:-Data abstraction, encapsulation, inheritance, Benefits of Inheritance,
Polymorphism, classes and objects, Procedural and object oriented programming paradigms.
Java Programming- History of Java, comments, Data types, Variables, Constants, Scope and
Lifetime of variables, Operators, Operator Hierarchy, Expressions, Type conversion and casting,
Enumerated types, Control flow- block scope, conditional statements, loops, break and continue
statements, simple java stand alone programs, arrays, console input and output, formattingoutput,
constructors,methods,parameterpassing,static fieldsandmethods,accesscontrol,thisreference,
overloading methods and constructors, recursion, garbage collection, building strings, exploring
string class.
UNIT–II
Inheritance–Inheritancehierarchiessuperandsubclasses,Memberaccessrules,super keyword, preventing
inheritance: final classes and methods, the Object class and its methods.
Polymorphism–dynamicbinding,methodoverriding,abstractclassesand methods.
Interfaces- Interfaces Vs Abstract classes, defining an interface, implement interfaces, accessing
implementations through interface references, extending interface.
Innerclasses-Usesofinnerclasses,localinnerclasses,anonymousinnerclasses,staticinner classes,
examples.
Packages- Defining, creating and accessing a package, Understanding CLASSPATH, importing
packages.
UNIT-III
Exception handling- Dealing with errors, benefits of exception handling, the classification of
exceptions- exception hierarchy, checked exceptions and unchecked exceptions, usage of try,
catch, throw, throws and finally, rethrowing exceptions, exception specification, built in
exceptions, creating own exception sub classes.
Multithreading – Differences between multiple processes and multiple threads, thread states,
creating threads, interrupting threads, thread priorities, synchronizing threads, inter-thread
communication, producer consumer pattern,Exploring java.net and java.text.
UNIT-IV
Collection Framework in Java – Introduction to java collections, Overview of java collection
framework, Generics, Commonly used collection classes- Array List, Vector, Hash table, Stack,
Enumeration, Iterator, String Tokenizer, Random, Scanner, Calendar and Properties.
Files- Streams- Byte streams, Character streams, Text input/output, Binary input/output, random
access file operations, File management using File class.
Connecting to Database – JDBC Type 1 to 4 drivers, Connecting to a database, querying a
database and processing the results, updating data with JDBC.
UNIT-V
GUI Programming with Java- The AWT class hierarchy, Introduction to Swing, Swing Vs
AWT, Hierarchy for Swing components, Containers – Jframe, JApplet, JDialog, JPanel,Overview
of some Swing components – Jbutton, JLabel, JTextField, JTextArea, simple Swing applications,
Layout management – Layout manager types – border, grid and flow
Event Handling- Events, Event sources, Event classes, Event Listeners, Relationship between
Event sources and Listeners, Delegation event model, Examples: Handling a button click,
Handling Mouse events, Adapter classes.
Applets – Inheritance hierarchy for applets, differences between applets and applications, Life
cycle of an applet, Passing parameters to applets, applet security issues.
TEXT BOOK:
1. JavaFundamentals–AComprehensiveIntroduction,HerbertSchildtandDaleSkrien, TMH.
REFERENCEBOOKS:
1. JavaforProgrammers,P.J.DeitelandH.M.Deitel,PEA(or)Java:HowtoProgram, P.J.Deitel
and H.M.Deitel, PHI
2. ObjectOrientedProgrammingthroughJava,P.RadhaKrishna,Universities Press.
3. ThinkinginJava,Bruce Eckel,PE
4. ProgramminginJava,S.MalhotraandS.Choudhary,OxfordUniversities Press.
CourseOutcomes:
An understanding of the principles and practice of object oriented analysis and design
inthe construction of robust, maintainable programs which satisfy their requirements;
Acompetencetodesign,write,compile,testandexecutestraightforwardprogramsusinga high
level language;
Anappreciationoftheprinciplesofobjectoriented programming;
Anawarenessoftheneedforaprofessionalapproachtodesignandtheimportanceof good
documentation to the finished programs.
Beabletoimplement,compile,testandrunJavaprogramscomprisingmorethanone class, to
address a particular software problem.
Demonstratethe abilitytousesimpledatastructureslikearraysinaJava program.
Beabletomakeuseofmembersofclasses foundintheJavaAPI(such astheMathclass).
INDEX
1 OOPConcepts:-Dataabstraction,encapsulationinheritance 1
I
2 Benefitsof Inheritance 2
I
3 I Polymorphism,classesandobjects 2
4 I Proceduralandobjectorientedprogrammingparadigms 3
5 I JavaProgramming-HistoryofJava 4
7 I Scopeand Lifetimeofvariables 10
8 I Operators,OperatorHierarchy,Expressions 11-12
9 I Typeconversionandcasting,Enumeratedtypes 12-13
Controlflow-blockscope,conditionalstatements,loops,break and
10 I 13-14
continue statements
11 I Simplejavastandaloneprograms,arrays 14-18
12 I Consoleinputandoutput,formattingoutput 18-19
Overloadingmethodsandconstructors,recursion,garbage
15 I 30-34
collection,
Buildingstrings, exploringstringclass.
16 I 34-36
S.No Unit Topic Pageno
Inheritance–Inheritancehierarchiessuperandsubclasses, Member
17 II 37-40
access rules
superkeyword,preventinginheritance:finalclassesandmethods, the
18 II 40-41
Object class and its methods.
19 II Polymorphism–dynamicbinding,methodoverriding, 41-42
20 II abstractclassesand methods. 43
Interfaces-InterfacesVsAbstractclasses,definingan interface,
21 II 43-44
implement interfaces
Accessing implementations through interface references,
22 II 45
extending interface.
23 II Innerclasses-Usesofinnerclasses,localinnerclasses 45-46
24 II Anonymousinnerclasses,staticinnerclasses,examples. 46
25 II Packages-Defining,creatingandaccessingapackage, 46-47
26 II UnderstandingCLASSPATH,importingpackages. 47
Exceptionhandling-Dealingwitherrors,benefitsofexception
27 III 48
handling
Theclassificationofexceptions-exceptionhierarchy,checked
28 III 48-50
exceptions and unchecked exceptions
Multithreading–Differencesbetweenmultipleprocessesand
32 III 55-56
multiple threads, thread states
Creatingthreads,interruptingthreads,threadpriorities,
33 III 56-59
synchronizing threads
34 III Inter-threadcommunication,producerconsumerpattern 59
Files-Streams-Bytestreams,Characterstreams,Text input/output,
39 IV 77-82
Binary input/output
Randomaccessfileoperations,FilemanagementusingFile class.
40 IV 83-84
ConnectingtoDatabase–JDBCType1to4drivers, Connecting
41 IV 85-88
to a a database,
Querying adatabase and processing the results, updating data
42 IV with JDBC. 89-94
OverviewofsomeSwingcomponents–Jbutton,JLabel, JTextField,
45 V 104-108
JTextArea, simple Swing applications,
Layoutmanagement–Layoutmanagertypes–border,gridand flow
46 V 109-111
EventHandling-Events,Eventsources,Eventclasses,Event
47 V 111-112
Listeners,
RelationshipbetweenEventsourcesandListeners,Delegation event
48 V 112-113
model,
Handlingabuttonclick,HandlingMouseevents,Adapterclasses.
49 V 114-116
Differencesbetweenappletsandapplications,Lifecycleofan applet,
51 V 120
52 V Passingparameterstoapplets,appletsecurityissues. 121
OOPConcepts
Smalltalkisconsidered asthefirsttrulyobject-orientedprogramminglanguage.
OOPs(ObjectOrientedProgrammingSystem)
Objectmeans a real word entity such as pen, chair, table etc. Object-Oriented Programmingis a
methodology or paradigm to design a program using classes and objects. It simplifies the software
development and maintenance by providing some concepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Object
Class
Collectionofobjectsiscalledclass.Itisalogical entity.
Inheritance
When one object acquires all the properties and behaviours of parent object i.e. known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
JAVAPROGRAMMING Page1
Polymorphism
Anotherexamplecanbetospeaksomethinge.g.catspeaksmeaw,dogbarkswoofetc.
Abstraction
Hidinginternaldetailsandshowingfunctionalityisknownasabstraction.Forexample:phone
call,wedon't knowthe internalprocessing.
Injava,weuseabstractclassandinterfacetoachieve abstraction.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as encapsulation.
For example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all
the data members are private here.
BenefitsofInheritance
One of the key benefits of inheritance is to minimize the amount of duplicate code in an
application by sharing common code amongst several subclasses. Where equivalent code
exists in two related classes, the hierarchy can usually be refactored to move the common
codeuptoamutualsuperclass.Thisalsotendstoresultinabetterorganizationofcodeand smaller,
simpler compilation units.
Inheritancecanalsomakeapplicationcodemoreflexibletochangebecauseclassesthat inherit
from a common superclass can be used interchangeably. If the return type of a method
is superclass
Reusability-facilitytousepublicmethodsofbaseclasswithoutrewritingthesame.
Extensibility-extendingthebaseclasslogicasperbusinesslogicofthederived class.
JAVAPROGRAMMING Page2
Datahiding-baseclasscandecidetokeepsome dataprivatesothatitcannotbe
alteredbythe derivedclass
Proceduralandobjectorientedprogrammingparadigms
JAVAPROGRAMMING Page3
JavaProgramming-HistoryofJava
ThehistoryofjavastartsfromGreenTeam.Javateammembers(alsoknownasGreenTeam
),initiatedarevolutionarytasktodevelopalanguagefordigitaldevicessuchasset-
topboxes,televisionsetc.
Forthegreenteammembers,itwasanadvanceconceptatthattime.But,itwassuitedforinter
netprogramming.Later,JavatechnologyasincorporatedbyNetscape.
Currently,Javaisusedininternetprogramming,mobiledevices,games,e-
businesssolutionsetc.Therearegiventhemajorpointsthatdescribesthehistoryofjava.
1) JamesGosling,MikeSheridan,andPatrickNaughtoninitiatedtheJavalanguagepr
ojectinJune1991.ThesmallteamofsunengineerscalledGreenTeam.
2) Originallydesignedforsmall,embeddedsystemsinelectronicapplianceslikeset-
topboxes.
3) Firstly,itwascalled"Greentalk"byJamesGoslingandfileextensionwas.gt.
4) Afterthat,itwascalledOakandwasdevelopedasapartoftheGreenproject.
JavaVersionHistory
Therearemanyjavaversionsthathasbeenreleased.CurrentstablereleaseofJavaisJavaSE
8.
1. JDKAlphaandBeta(1995)
2. JDK1.0(23rdJan,1996)
3. JDK1.1(19thFeb,1997)
4. J2SE1.2(8thDec,1998)
5. J2SE1.3(8thMay,2000)
6. J2SE1.4(6thFeb,2002)
7. J2SE5.0(30thSep,2004)
8. JavaSE6(11thDec,2006)
9. JavaSE7(28thJuly,2011)
10.JavaSE8(18thMarch,2014)
JAVAPROGRAMMING Page4
FeaturesofJava
Thereis givenmanyfeaturesofjava. Theyarealsoknownasjava buzzwords.TheJavaFeatures given
below are simple and easy to understand.
1. Simple
2. Object-Oriented
3. Portable
4. Platformindependent
5. Secured
6. Robust
7. Architectureneutral
8. Dynamic
9. Interpreted
10. HighPerformance
11. Multithreaded
12. Distributed
JavaComments
The java comments are statements that are not executed by the compiler and interpreter. The
commentscanbeusedtoprovideinformationorexplanationaboutthevariable,method, classor any
statement. It can also be used to hide program code for specific time.
TypesofJavaComments
1. SingleLineComment
2. MultiLine Comment
3. DocumentationComment
JavaSingleLineComment
Syntax:
1. //Thisis singlelinecomment
JAVAPROGRAMMING Page5
Example:
publicclassCommentExample1{
publicstaticvoidmain(String[]args){ int
i=10;//Here, i is a variable
System.out.println(i);
}
}
Output:
10
JavaMultiLineComment
Syntax:
/*
This
is
multiline
comment
*/
Example:
publicclassCommentExample2{
publicstaticvoidmain(String[]args){
/* Let's declare
andprintvariableinjava.
*/
int i=10;
System.out.println(i);
}}
Output:
10
JavaDocumentationComment
JAVAPROGRAMMING Page6
ThedocumentationcommentisusedtocreatedocumentationAPI.TocreatedocumentationAPI, youneed to use
javadoc tool.
Syntax:
/**
This
is
documentation
comment
*/
Example:
/**TheCalculatorclassprovidesmethodstogetadditionandsubtractionofgiven2numbers.*/
publicclassCalculator{
/**Theadd()methodreturnsadditionofgivennumbers.*/
publicstaticintadd(inta,intb){returna+b;}
/**Thesub()methodreturnssubtractionofgivennumbers.*/
publicstaticintsub(inta,intb){returna-b;}
}
Compileitbyjavactool:
javacCalculator.java
CreateDocumentationAPIbyjavadoc tool:
javadocCalculator.java
Now, there will be HTML files created for your Calculator class in the current directory. Open the HTML
files and see the explanation of Calculator class provided through documentation comment.
DataTypes
Datatypesrepresentthedifferentvaluestobestoredinthevariable.Injava,therearetwotypesofdatatypes:
JAVAPROGRAMMING Page7
o Primitivedatatypes
o Non-primitivedatatypes
byte 0 1byte
short 0 2byte
int 0 4byte
long 0L 8byte
JavaVariableExample:AddTwo Numbers
classSimple{
publicstaticvoidmain(String[]args){
int a=10;
int b=10;
intc=a+b;
System.out.println(c);
}}
Output:20
JAVAPROGRAMMING Page8
VariablesandDataTypesinJava
Variable is a name of memory location. There are three types of variables in java: local, instance
and static.
TypesofVariable
Therearethreetypesof variablesin java:
o local variable
o instancevariable
o static variable
1) Local Variable
Avariablewhichisdeclaredinsidethemethodiscalledlocal variable.
2) InstanceVariable
3) Staticvariable
Avariablethatisdeclaredasstaticiscalledstaticvariable.Itcannotbelocal. We will
Exampletounderstandthetypesofvariablesinjava
classA{
int data=50;//instance variable
staticintm=100;//staticvariable
void method(){
intn=90;//localvariable
}
}//endofclass
ConstantsinJava
Aconstantisavariablewhichcannothaveitsvaluechangedafterdeclaration.Itusesthe 'final'keyword.
Syntax
modifierfinaldataTypevariableName=value; //global constant
modifierstaticfinaldataTypevariableName=value; //constantwithinac
JAVAPROGRAMMING Page9
ScopeandLifeTimeofVariables
The scope of a variable defines the section of the code in which the variable is visible. As a
general rule, variables that are defined within a block are not accessible outside that block.
The lifetime of a variable refers to how long the variable exists before it is destroyed.
Destroying variables refersto deallocating the memory that was allotted to the variableswhen
declaring it. We have written a few classes till now. You might have observed that not all
variables are the same. The ones declared in the body of a method were different from those
that were declared in the class itself. There are three types of variables: instance variables,
formal parameters or local variables and local variables.
Instancevariables
Instance variables are those that are defined within a class itself and not in any method or
constructor of the class. They are known as instance variables because every instance of the
class(object)containsacopyofthesevariables. Thescopeofinstancevariablesisdetermined by the
access specifier thatis applied to thesevariables. Wehave already seenabout it earlier. The
lifetime of these variables is the same as the lifetime of the object to which it belongs. Object
once created do not exist for ever. They are destroyed by the garbage collector of Java when
there are no more reference to that object. We shall see about Java's automatic garbage
collector later on.
Argumentvariables
These are the variables that are defined in the header oaf constructor or a method. The scope
of these variables is the method or constructor in which they are defined. The lifetime is
limited to the time for which the method keeps executing. Once the method finishesexecution,
these variables are destroyed.
Localvariables
A local variable is the one that is declared within a method or a constructor (not in theheader).
The scope and lifetime are limited to the method itself.
One important distinction between these three types of variables is that access specifiers can
be applied to instance variables only and not to argument or local variables.
In addition to the local variables defined in a method, we also have variables that are defined
in bocks life an if block and an else block. The scope and is the same as that of the blockitself.
JAVAPROGRAMMING Page10
Operatorsinjava
o UnaryOperator,
o ArithmeticOperator,
o shift Operator,
o RelationalOperator,
o BitwiseOperator,
o LogicalOperator,
o TernaryOperator and
o AssignmentOperator.
OperatorsHierarchy
JAVAPROGRAMMING Page11
Expressions
Expressionsareessential buildingblocksofanyJavaprogram,usuallycreatedtoproduceanew value,
although sometimes an expression simply assigns a value to a variable. Expressions are built
using values, variables, operators and method calls.
TypesofExpressions
Whileanexpressionfrequentlyproducesaresult,itdoesn'talways.Therearethreetypesof
expressions in Java:
JavaTypecastingandType conversion
WideningorAutomaticTypeConversion
Widening conversion takes place when two data types are automatically converted. This happens
when:
Thetwodatatypesarecompatible.
Whenweassignvalueofasmallerdatatypetoabiggerdata type.
For Example, in java the numeric data types are compatible with each other but no automatic
conversion is supported from numeric type to char or boolean. Also, char and boolean are not
compatible with each other.
NarrowingorExplicitConversion
Ifwewanttoassignavalueoflargerdatatypetoasmallerdatatypeweperformexplicittype casting or
narrowing.
Thisisusefulforincompatibledatatypeswhere automaticconversioncannotbe done.
Here,target-typespecifiesthedesiredtypetoconvertthespecifiedvalueto.
JAVAPROGRAMMING Page12
JavaEnum
Enuminjavaisadatatypethatcontainsfixedsetof constants.
Itcanbeusedfordaysoftheweek(SUNDAY,MONDAY,TUESDAY,WEDNESDAY,
THURSDAY,FRIDAYandSATURDAY),directions(NORTH,SOUTH,EASTandWEST)
etc.Thejavaenumconstantsarestaticandfinalimplicitly.ItisavailablefromJDK1.5. Java
Simpleexampleofjavaenum
class EnumExample1{
publicenumSeason{WINTER,SPRING,SUMMER,FALL}
publicstaticvoidmain(String[]args){
for (Season s : Season.values())
System.out.println(s);
}}
Output:
ControlFlowStatements
WINTE
R
ThecontrolflowstatementsinJavaallowyoutorunorskipblocksofcodewhenspecial
SPRING
conditions are met.
SUMM
The“if”Statement
The“if” statement in Java works exactlylike in most programminglanguages. With the help of
“if” youcanchoosetoexecuteaspecificblockofcodewhenapredefinedconditionismet.The structure
of the “if” statement in Java looks like this:
if(condition){
//executethiscode
}
JAVAPROGRAMMING Page13
TheconditionisBoolean.Booleanmeansitmaybetrueorfalse.Forexampleyoumayput a mathematical
equation as condition.Look at this full example:
CreatingaStand-AloneJavaApplication
1. Writeamainmethodthatrunsyourprogram.Youcanwritethismethodanywhere. Inthis
example, I'll write my main method in a class called Main that has no other methods. For
example:
2. publicclass Main
3. {
4. publicstaticvoidmain(String[]args)
5. {
6. Game.play();
7. }}
8. Makesureyour codeiscompiled, andthatyouhavetestedit thoroughly.
9. If you're using Windows, you will need to set your path to include Java, if you haven't
done so already. This is a delicate operation. Open Explorer, and look inside C:\
ProgramFiles\Java, and you should see some version of the JDK. Open this folder, and
thenopenthebinfolder.SelectthecompletepathfromthetopoftheExplorerwindow,and press
Ctrl-C to copy it.
Next,findthe"MyComputer"icon(on yourStartmenuordesktop),right-clickit,andselect
properties. Click on the Advanced tab, and then click on the Environment variables button.
Look at the variables listed for all users, and click on the Path variable. Do not delete the
contents of this variable! Instead, edit the contents by moving the cursor to the right end,
entering a semicolon (;), and pressing Ctrl-V to paste the path you copied earlier. Then go
ahead and save your changes. (If you have any Cmd windows open, you will need to close
them.)
JAVAPROGRAMMING Page14
12. Nowwewanttochangetothedirectory/folderthatcontains yourcompiledcode. Lookat
thelistingofsub-directorieswithinthisdirectory,andidentifywhichonecontainsyourcode. Type
cd followed by the name of that directory, to change to that directory. For example, to
change to a directory called Desktop, you would type:
cdDesktop
Tochangetotheparentdirectory,type:
cd..
javac-target1.5 *.java
Arrays
Java provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,numbers[99]
to represent individual variables.
This tutorial introduces how to declare array variables, create arrays, and process arrays using
indexed variables.
DeclaringArrayVariables:
To use an array in a program, you must declare a variable to reference the array, and you must
specify the type of array the variable can reference. Here is the syntax for declaring an array
variable:
Note:ThestyledataType[]arrayRefVarispreferred.Thestyle
dataType[]arrayRefVar;//preferredway. dataType arrayRefVar[]comes
from the C/C++ language and was adopted in Java to accommodate C/C++ programmers.
or
dataTypearrayRefVar[];//worksbutnotpreferredway.
Example:
JAVAPROGRAMMING Page15
Thefollowingcodesnippets are examples ofthis syntax:
double[]myList; //preferredway.
or
doublemyList[];
//worksbutnotpreferredway.
CreatingArrays:
Youcancreateanarraybyusingthenewoperatorwiththefollowingsyntax:
The array elements are accessed through the index. Array indices are 0-based; that is, they start
dataType[]arrayRefVar={value0,value1,...,valuek};
from 0 to arrayRefVar.length-1.
Example:
Followingstatementdeclaresanarrayvariable,myList,createsanarrayof10elementsof double type
and assigns its reference to myList:
Following picture represents array myList. Here, myList holds ten double values and the indices
double[]myList=newdouble[10];
are from 0 to 9.
JAVAPROGRAMMING Page16
ProcessingArrays:
When processing array elements, we often use either for loop or for each loop because all of the
elements in an array are of the same type and the size of the array is known.
Example:
Hereisa completeexampleofshowinghowtocreate,initializeandprocessarrays:
publicclass TestArray
{
public static void main(String[] args) {
double[]myList={1.9,2.9,3.4,3.5};
// Print all the array elements
for(inti=0;i<myList.length;i++){
System.out.println(myList[i]+"");
}
//Summingallelements
double total = 0;
for(inti=0;i<myList.length;i++){ total
+= myList[i];
}
System.out.println("Totalis"+total);
//Findingthelargestelement
double max = myList[0];
for (int i = 1; i <myList.length; i++) {
if(myList[i]>max)max=myList[i];
}
System.out.println("Maxis"+max);
}
}
JAVAPROGRAMMING Page17
Thiswould producethe followingresult:
1.9
2.9
3.4
3.5
Totalis 11.7
Maxis 3.5
publicclassTestArray{
public static void main(String[] args) { double[]myList={1.9,2.9,3.4,3.5};
//Printallthearrayelements
for(doubleelement:myList){ System.out.println(element);
}}}
JavaConsoleClass
The Java Console class is be used to get input from console. It provides methods to read texts and
passwords.
IfyoureadpasswordusingConsoleclass,itwillnotbedisplayedtothe user.
Let'sseeasimpleexampletoreadtextfromconsole.
1. Stringtext=System.console().readLine();
2. System.out.println("Textis:"+text);
JavaConsoleExample
importjava.io.Console;
classReadStringTest{
public static void main(String args[])
{ Console c=System.console();
System.out.println("Enter your name: ");
String n=c.readLine();
System.out.println("Welcome "+n); } }
JAVAPROGRAMMING Page18
Output
Enteryourname:NakulJain
Welcome Nakul Jain
Constructors
Constructorinjava isaspecialtypeofmethodthatisusedtoinitializetheobject.
1. Constructornamemustbesameasitsclassname
2. Constructormusthavenoexplicitreturn type
Typesofjava constructors
1. Defaultconstructor(no-argconstructor)
2. Parameterizedconstructor
JavaDefaultConstructor
Aconstructorthathavenoparameterisknownasdefaultconstructor.
Syntaxofdefaultconstructor:
1. <class_name>(){}
Exampleofdefaultconstructor
JAVAPROGRAMMING Page19
Exampleofparameterizedconstructor
Inthisexample,wehavecreatedtheconstructorofStudentclassthathavetwoparameters.We can have
any number of parameters in the constructor.
classStudent4{
int id;
Stringname;
Student4(inti,Stringn){ id
= i;
name=n;
}
voiddisplay(){System.out.println(id+""+name);}
Output:
111 Karan
ConstructorOverloadinginJava
222 Aryan
Constructor overloading is a technique in Java in which a class can have any number of
constructorsthatdifferinparameterlists.Thecompilerdifferentiatestheseconstructorsby taking
into account the number of parameters in the list and their type.
ExampleofConstructor Overloading
classStudent5{
int
id;Stringna
me; int age;
Student5(inti,Stringn){ id
= i;
name=n;
}
Student5(inti,Stringn,inta)
{ id = i;
name=n;
age=a;
}
voiddisplay(){System.out.println(id+""+name+""+age);}
JAVAPROGRAMMING Page20
s2.display();
}}
Output:
JavaCopyConstructor
111Karan0
222Aryan25
There is no copy constructor in java. But, we can copy the values of one object to another like
copy constructor in C++.
o Byconstructor
o Byassigningthevaluesof oneobjectinto another
o Byclone()methodofObjectclass
Inthisexample,wearegoingtocopythevaluesofoneobjectintoanotherusingjava constructor.
classStudent6{
int id;
Stringname;
Student6(inti,Stringn){ id
= i;
name=n;
}
Student6(Student6s)
{ id = s.id;
name =s.name;
}
voiddisplay(){System.out.println(id+""+name);}
Output:
111 Karan
111 Karan
JAVAPROGRAMMING Page21
Java-Methods
A Java method is a collection of statements that are grouped together to perform an operation.
When you call the System.out.println()method, for example, the system actually executes
several statements in order to display a message on the console.
Now you will learn how to create your own methods with or without return values, invoke a
method with or without parameters, and apply method abstraction in the program design.
CreatingMethod
Consideringthe followingexampleto explain thesyntax of amethod −
Syntax
Here,
publicstaticintmethodName(int a,intb) {
// body
publicstatic−modifier
}
int−return type
methodName−nameofthemethod
a,b−formalparameters
Methoddefinitionconsistsofamethodheaderandamethodbody.Thesameisshowninthe
followingsyntax−
Syntax
Thesyntaxshownaboveincludes−
modifierreturnTypenameOfMethod(ParameterList){
// method body Itdefinesthe accesstypeofthemethodanditisoptionaltouse.
modifier−
}
returnType−Methodmayreturna value.
JAVAPROGRAMMING Page22
Parameter List− The list of parameters, it is the type, order, and number of parametersof
a method. These are optional, method may contain zero parameters.
methodbody −Themethodbodydefineswhatthemethoddoeswiththestatements.
CallbyValueandCallbyReferenceinJava
Thereisonlycallbyvalueinjava,notcallbyreference. If wecallamethodpassinga value, it is known
as call by value. The changes being done in the called method, is not affected in the calling
method.
Exampleofcallbyvaluein java
In caseofcallbyvalueoriginalvalueisnotchanged. Let'stakeasimpleexample:
classOperation{
int data=50;
voidchange(intdata){
data=data+100;//changeswillbeinthelocalvariableonly
}
public static void main(String args[])
{ Operation op=new Operation();
System.out.println("beforechange"+op.data);
op.change(500);
System.out.println("afterchange"+op.data);
}
}
Output:beforechange50
InJava,parametersarealwayspassedbyvalue.Forexample,followingprogramprints
afterchange50 i = 10,
j = 20.
//Test.java
classTest{
//swap()doesn'tswapiandj
publicstaticvoidswap(Integeri,Integerj){ Integer
temp = new Integer(i);
i = j;
j = temp;
}
publicstaticvoidmain(String[]args)
{ Integer i = new Integer(10);
Integerj=newInteger(20);
swap(i, j);
System.out.println("i =" +i+ ",j= "+j);
JAVAPROGRAMMING Page23
}
}
StaticFieldsandMethods
Thestatic keyword in java is used for memory management mainly. We can apply java static
keywordwithvariables,methods,blocksandnestedclass.Thestatickeywordbelongstotheclass than
instance of the class.
Thestaticcanbe:
1. variable(alsoknownasclass variable)
2. method(alsoknownasclass method)
3. block
4. nestedclass
Javastaticvariable
If youdeclareanyvariableasstatic,itisknownstaticvariable.
o The static variable can be used to refer the common property of all objects (that is not unique for
each object) e.g. company name of employees,college name of students etc.
o Thestaticvariablegetsmemoryonlyonceinclassareaatthetimeofclassloading.
Advantageofstaticvariable
Itmakesyourprogrammemoryefficient(i.eitsavesmemory).
Understandingproblemwithoutstaticvariable
1. class Student{
2. introllno;
3. Stringname;
4. Stringcollege="ITS";
5.}
Exampleofstaticvariable
//Programofstaticvariable
class Student8{
introllno;
JAVAPROGRAMMING Page24
Stringname;
staticStringcollege="ITS";
Student8(int r,String n)
{ rollno = r;
name=n;
}
voiddisplay(){System.out.println(rollno+""+name+""+college);}
public static void main(String args[])
{ Student8s1=newStudent8(111,"Karan");
Student8s2=new Student8(222,"Aryan");
s1.display();
s2.display();
}}
Output:111KaranITS
222AryanITS
Javastaticmethod
Ifyouapplystatickeywordwithanymethod,itisknownasstatic method.
o Astaticmethodbelongstotheclassratherthanobjectofaclass.
o Astaticmethod canbeinvokedwithoutthe needforcreatingan instanceof aclass.
o staticmethodcanaccessstaticdatamemberandcanchangethevalue ofit.
Exampleofstaticmethod
//Programof changingthecommonpropertyof allobjects(static field).
classStudent9{
int rollno;
Stringname;
staticStringcollege="ITS";
staticvoidchange()
{ college = "BBDIT";
}
Student9(intr,Stringn)
{ rollno = r;
name=n;
JAVAPROGRAMMING Page25
}
voiddisplay(){System.out.println(rollno+""+name+""+college);}
publicstaticvoidmain(Stringargs[]){
Student9.change();
Student9s1=new Student9(111,"Karan");
Student9s2=newStudent9(222,"Aryan");
Student9s3=newStudent9(333,"Sonoo");
s1.display();
s2.display();
s3.display();
}}
Output:111KaranBBDIT
Javastatic block
222 Aryan BBDIT
o 333SonooBBDIT
Isusedtoinitializethestaticdata member.
o Itisexecuted beforemainmethod atthetimeofclassloading.
Exampleofstaticblock class
A2{
static{System.out.println("staticblockisinvoked");}
public static void main(String args[])
{ System.out.println("Hello main");
}}
Output:staticblockisinvoked
Access Control
Hello main
AccessModifiersinjava
Thereare4typesofjava accessmodifiers:
JAVAPROGRAMMING Page26
1. private
2. default
3. protected
4. public
privateaccessmodifier
Theprivate accessmodifierisaccessibleonlywithinclass.
Simpleexampleofprivateaccess 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
}}
2) defaultaccessmodifier
If you don't use any modifier, it is treated as defaultbydefault. The default modifier is
accessible only within package.
Exampleofdefaultaccessmodifier
In this example, we have created two packages pack and mypack. We are accessing the Aclass
from outside 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.*;
JAVAPROGRAMMING Page27
classB{
public static void main(String args[]){
Aobj=newA();//CompileTimeError
obj.msg();//Compile Time Error}}
In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.
3) protectedaccessmodifier
Theprotected access modifieris accessible within package and outside the package but through
inheritance only.
Theprotectedaccessmodifiercanbeappliedonthedatamember,methodandconstructor. Itcan't be
applied on the class.
Exampleofprotectedaccessmodifier
In this example, we have created the two packages pack and mypack. The A class of packpackage
is public, so can be accessed from outside the package. But msg method of this package is
declared as protected, so it can be accessed from outside the class only through inheritance.
//savebyA.java
package pack;
publicclassA{
protectedvoidmsg(){System.out.println("Hello");}}
//savebyB.java
package mypack;
import pack.*;
classBextendsA{
publicstaticvoidmain(Stringargs[]){ B
obj = new B();
obj.msg();
}}
Output:Hello
4) publicaccessmodifier
Thepublic access modifieris accessible everywhere. It has the widest scope among all other
modifiers.
JAVAPROGRAMMING Page28
Exampleofpublicaccessmodifier
//savebyA.java
package pack;
publicclassA{
publicvoidmsg(){System.out.println("Hello");}}
//save by B.java
packagemypack;
import pack.*;
class B{
publicstaticvoidmain(Stringargs[]){ A
obj = new A();
obj.msg();
}}
Output:Hello
Understandingalljavaaccessmodifiers
Let'sunderstandthe accessmodifiersbyasimpletable.
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
thiskeywordinjava
Usageofjavathiskeyword
Hereisgiventhe6usage ofjavathiskeyword.
1. thiscanbeusedtorefercurrentclassinstancevariable.
2. thiscanbeusedtoinvokecurrentclassmethod(implicitly)
3. this()canbeusedtoinvokecurrentclass constructor.
JAVAPROGRAMMING Page29
4. thiscanbepassedasanargumentinthemethodcall.
5. thiscanbepassed asargumentintheconstructor call.
6. thiscanbeusedtoreturn thecurrentclassinstancefromthe method.
classStudent{
int rollno;
String name;
float fee;
Student(introllno,Stringname,floatfee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
voiddisplay(){System.out.println(rollno+""+name+""+fee);}
}
classTestThis2{
public static void main(String args[])
{ Student s1=new
Student(111,"ankit",5000f);
Students2=newStudent(112,"sumit",6000f);
s1.display();
s2.display();
}}
Output:
111 ankit5000
Differencebetweenconstructorandmethodinjava
112 sumit 6000
JAVAPROGRAMMING Page30
sameasclassname.
ConstructorOverloadinginJava
Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists.The compiler differentiates these constructors by
taking into account the number of parameters in the list and their type.
ExampleofConstructorOverloading
classStudent5{
int
id;Stringna
me; int age;
Student5(inti,Stringn){ id
= i;
name=n;
}
Student5(inti,Stringn,inta)
{ id = i;
name=n;
age=a;
}
voiddisplay(){System.out.println(id+""+name+""+age);}
Output:
JAVAPROGRAMMING Page31
111Karan0
222Aryan25
MethodOverloadingin java
Ifaclasshasmultiplemethodshavingsamenamebutdifferentinparameters,itisknownas Method
Overloading.
MethodOverloading:changingno.ofarguments
In this example, we are creating static methods so that we don't need to create instance for calling
methods.
classAdder{
staticintadd(inta,intb){returna+b;}
staticintadd(inta,intb,intc){returna+b+c;}
}
classTestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
Output:
MethodOverloading:changingdatatypeofarguments
22
33
Inthisexample,wehavecreatedtwomethodsthatdiffersindatatype.Thefirstaddmethod receives two integer
arguments and second add method receives two double arguments.
JAVAPROGRAMMING Page32
RecursioninJava
Recursioninjavaisaprocessinwhichamethodcallsitselfcontinuously.Amethodinjavathat calls
itself is called recursive method.
JavaRecursionExample1:Factorial Number
publicclassRecursionExample3{
staticintfactorial(intn){
if (n==1)
return1;
else
return(n*factorial(n-1));
}}
public static void main(String[] args)
{ System.out.println("Factorialof5is:"+factorial(5));
}}
Output:
JavaGarbageCollection
Factorialof5is:120
Injava,garbagemeansunreferencedobjects.
Garbage Collection is process of reclaiming the runtime unused memory automatically. In other
words, it is a way to destroy the unused objects.
Todoso,wewereusingfree()functioninClanguageanddelete()inC++.But,injavaitis performed
automatically. So, java provides better memory management.
AdvantageofGarbageCollection
o Itmakesjavamemoryefficientbecausegarbagecollectorremovestheunreferenced objects
from heap memory.
o It isautomatically doneby the garbage collector(a part of JVM) so we don't need to make
extra efforts.
gc() method
JAVAPROGRAMMING Page33
Thegc()methodisusedtoinvokethegarbagecollectortoperformcleanupprocessing.The gc() is
found in System and Runtime classes.
publicstaticvoidgc(){}
SimpleExampleofgarbagecollectioninjava
public class TestGarbage1{
publicvoidfinalize(){System.out.println("objectisgarbagecollected");}
public static void main(String args[])
{ TestGarbage1s1=newTestGarbage1();
TestGarbage1s2=newTestGarbage1();
s1=null;
s2=null;
System.gc();
}}
objectisgarbagecollected
objectisgarbage collected
JavaString
string is basically an object that represents sequence of char values. An array of characters works
same as java string. For example:
1. char[]ch={'j','a','v','a','t','p','o','i','n','t'};
2. Strings=newString(ch);
ssame as:
1. Strings="javatpoint";
2. Java Stringclass provides a lot of methods to perform operations on string such as
compare(),concat(),equals(),split(),length(), replace(),compareTo(),intern(),substring() etc.
3. The java.lang.String class
implements Serializable, Comparable and CharSequence interfaces.
CharSequenceInterface
JAVAPROGRAMMING Page34
The CharSequence interface is used to represent sequence of characters. It is implemented by
String, StringBuffer and StringBuilder classes. It means, we can create string in java by using
these 3 classes.
The java String is immutable i.e. it cannot be changed. Whenever we change any
string,anewinstanceiscreated.Formutablestring, youcanuseStringBufferandStringBuilder classes.
TherearetwowaystocreateStringobject:
1. Bystring literal
2. Bynew keyword
StringLiteral
JavaStringliteraliscreatedbyusingdoublequotes.For Example:
1. Strings="welcome";
Each time you create a string literal, the JVM checks the string constant pool first. If the string
already exists in the pool, a reference to the pooled instance is returned. If string doesn't exist in
the pool, a new string instance is created and placed in the pool. For example:
1. Strings1="Welcome";
2. Strings2="Welcome";//will notcreatenewinstance
Bynew keyword
1. Strings=newString("Welcome");//createstwoobjectsandonereferencevariable
In such case, JVM will create a new string object in normal (non pool) heap memory and the
literal "Welcome" will be placed in the string constant pool. The variable s will refer to the object
in heap (non pool).
JavaStringExample
publicclassStringExample{
publicstaticvoidmain(Stringargs[]){
Strings1="java";//creatingstringbyjavastring literal
charch[]={'s','t','r','i','n','g','s'};
Strings2=new String(ch);//convertingchararrayto string
Strings3=newString("example");//creatingjavastringbynewkeyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
java
JAVAPROGRAMMING Page35
strings
examp
ImmutableStringinJava
Injava,stringobjectsareimmutable.Immutablesimplymeansunmodifiableorunchangeable. Once
string object is created its data or state can't be changed but a new string object is created. Let's try
classTestimmutablestring{
publicstaticvoidmain(Stringargs[])
{ String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//willprintSachinbecausestringsareimmutableobjects
}}
Output:Sachin
classTestimmutablestring1{
publicstaticvoidmain(Stringargs[])
{ String s="Sachin";
s=s.concat("Tendulkar");
System.out.println(s);
}}Output:Sachin Tendulkar
JAVAPROGRAMMING Page36
InheritanceinJava
Inheritanceinjavaisamechanisminwhichoneobjectacquiresallthepropertiesandbehaviors of parent
object. Inheritance represents the IS-A relationship, also known as parent-
childrelationship.
Whyuseinheritancein java
o ForMethodOverriding(soruntimepolymorphismcanbeachieved).
o ForCodeReusability.
SyntaxofJavaInheritance
1. classSubclass-nameextendsSuperclass-name
2. {
3. //methodsand fields
4.}
classEmployee{
float salary=40000;
}
classProgrammerextendsEmployee{
int bonus=10000;
publicstaticvoidmain(Stringargs[])
{ Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("BonusofProgrammeris:"+p.bonus);
}}
Programmersalaryis:40000.0
JAVAPROGRAMMING Page37
Bonusofprogrammeris:10000
Typesofinheritanceinjava
SingleInheritanceExample
File:TestInheritance.java
classAnimal{
voideat(){System.out.println("eating...");}
}
classDogextendsAnimal{
voidbark(){System.out.println("barking...");}
}
classTestInheritance{
publicstaticvoidmain(Stringargs[])
{ Dog d=new Dog();
d.bark();
d.eat();
}}
Output:
barking
...
MultilevelInheritanceExample
File:TestInheritance2.java
classAnimal{
voideat(){System.out.println("eating...");}
}
classDogextendsAnimal{
voidbark(){System.out.println("barking...");}
}
classBabyDogextendsDog{
voidweep(){System.out.println("weeping...");}
}
classTestInheritance2{
JAVAPROGRAMMING Page38
publicstaticvoidmain(Stringargs[])
{ BabyDog d=new
BabyDog();d.weep();
d.bark();
d.eat();
}}
Output:
weeping...
barking... HierarchicalInheritanceExample
eating...
File:TestInheritance3.java
classAnimal{
voideat(){System.out.println("eating...");}
}
classDogextendsAnimal{
voidbark(){System.out.println("barking...");}
}
classCatextendsAnimal{
voidmeow(){System.out.println("meowing...");}
}
classTestInheritance3{
publicstaticvoidmain(Stringargs[])
{ Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing...
eating...
JAVAPROGRAMMING Page39
MemberaccessandInheritance
superkeywordinjava
Wheneveryoucreatetheinstanceofsubclass,aninstanceofparentclassiscreatedimplicitly which is
referred by super reference variable.
UsageofjavasuperKeyword
1. supercanbeusedtoreferimmediateparentclassinstance variable.
2. supercanbeusedtoinvokeimmediateparentclass method.
3. super()canbeusedtoinvokeimmediateparentclassconstructor.
superisusedtoreferimmediateparentclassinstancevariable.
classAnimal{
Stringcolor="white";
}
classDogextendsAnimal{ S
tring color="black";
void
printColor(){System.out.println(color);//printscolor
ofDogclass
System.out.println(super.color);//printscolorofAnimalclass
}
}
classTestSuper1{
publicstaticvoidmain(Stringargs[])
{ Dog d=new Dog();
JAVAPROGRAMMING Page40
JAVAPROGRAMMING Page41
d.printColor();
}}
Output:
FinalKeywordinJava
bla
ckw
Thefinal keywordinjava is usedto restrict theuser.Thejavafinal keyword canbe used inmany context. Final
can be:
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it is called blank
final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final
variable can be static also which will be initialized in the static block only.
ObjectclassinJava
TheObject classis the parent class of all the classes in java by default. In other words, it is the
topmost class of java.
The Object class is beneficial if you want to refer any object whose type you don't know. Notice
that parent class reference variable can refer the child class object, know as upcasting.
Let's take an example, there is getObject() method that returns an object but it can be of any type
like Employee,Student etc, we can use Object class reference to refer that object. For example:
1. Objectobj=getObject();//wedon'tknowwhatobjectwillbereturnedfromthis method
The Object class provides some common behaviors to all the objects such as object can be
compared, object can be cloned, object can be notified etc.
MethodOverridingin Java
Ifsubclass(childclass)hasthesamemethodasdeclaredintheparentclass,itisknown as method
overriding in java.
JAVAPROGRAMMING Page42
UsageofJavaMethodOverriding
o Method overriding is used to provide specific implementation of a method that is already
provided by its super class.
o Methodoverridingisusedforruntimepolymorphism
RulesforJavaMethodOverriding
1. methodmusthavesamenameas intheparentclass
2. methodmusthavesameparameterasintheparentclass.
3. mustbeIS-Arelationship(inheritance).
Exampleofmethodoverriding Class
Vehicle{
voidrun(){System.out.println("Vehicleisrunning");}
}
classBike2extendsVehicle{
voidrun(){System.out.println("Bikeisrunningsafely");}
publicstaticvoidmain(Stringargs[]){ Bike2
obj = new Bike2();
obj.run();
}
Output:Bikeisrunningsafely
1.classBank{
intgetRateOfInterest(){return0;}
}
classSBIextendsBank{
intgetRateOfInterest(){return8;}
}
classICICIextendsBank{
intgetRateOfInterest(){return7;}
}
classAXISextendsBank{
intgetRateOfInterest(){return9;}
}
classTest2{
publicstaticvoidmain(Stringargs[]){ SBI
s=new SBI();
ICICIi=new ICICI();
AXISa=newAXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICIRate of Interest: "+i.getRateOfInterest());
System.out.println("AXISRateofInterest:"+a.getRateOfInterest());
}}
Output:
SBIRateofInterest:8
JAVAPROGRAMMING Page43
ICICIRateofInterest:7
AXISRateofInterest:9
AbstractclassinJava
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). It needs to be extended and its method
implemented. It cannot be instantiated.
Exampleabstractclass
1.abstractclassA{}
abstractmethod
1.abstractvoidprintStatus();//nobodyandabstract
Exampleofabstractclassthathasabstractmethod
abstractclassBike{
abstractvoidrun();
}
classHonda4extendsBike{
voidrun(){System.out.println("runningsafely..");}
publicstaticvoidmain(Stringargs[])
{ Bike obj = new Honda4();
obj.run();
}
1.}
runningsafely..
InterfaceinJava
Aninterfacein javaisa blueprintofaclass. Ithasstaticconstantsandabstractmethods.
JavaInterfacealsorepresentsIS-Arelationship. It
Therearemainlythreereasonstouseinterface.Theyaregiven below.
o Itisusedtoachieveabstraction.
o Byinterface,wecansupport thefunctionalityof multiple inheritance.
o Itcanbeusedtoachieve loosecoupling.
JAVAPROGRAMMING Page44
Internaladditionbycompiler
Understandingrelationshipbetweenclassesandinterfaces
//Interfacedeclaration:byfirstuser
interfaceDrawable{
voiddraw();
}
//Implementation: bysecond user
classRectangleimplementsDrawable{
publicvoiddraw(){System.out.println("drawingrectangle");}
}
classCircleimplementsDrawable{
publicvoiddraw(){System.out.println("drawingcircle");}
}
//Usinginterface:bythirduser
classTestInterface1{
publicstaticvoidmain(Stringargs[]){
Drawabled=newCircle();//Inrealscenario,objectisprovidedbymethode.g.getDrawable() d.draw();
}}
Output:drawingcircle
MultipleinheritanceinJavabyinterface
interfacePrintable{
JAVAPROGRAMMING Page45
voidprint();
}
interfaceShowable{
voidshow();
}
classA7implementsPrintable,Showable{
public void print(){System.out.println("Hello");}
publicvoidshow(){System.out.println("Welcome");}
public static void main(String args[]){
A7obj=newA7();
obj.print();
obj.show();
}}
Output:Hell
o
Abstractclass Interface
JavaInnerClasses
Javainnerclass ornestedclassisaclasswhichisdeclaredinsidetheclassor interface.
We use inner classes to logically group classes and interfaces in one place so that it can be more
readable and maintainable.
SyntaxofInnerclass
1. classJava_Outer_class{
2. //code
3. classJava_Inner_class{
4. //code
5. }}
JAVAPROGRAMMING Page46
Advantageofjavainnerclasses
Therearebasicallythree advantagesofinnerclassesinjava.Theyareasfollows:
3) CodeOptimization:Itrequireslesscodetowrite.
DifferencebetweennestedclassandinnerclassinJava
Innerclassisapartofnestedclass.Non-staticnestedclassesareknown as innerclasses.
TypesofNestedclasses
o Non-staticnestedclass(innerclass)
1. Memberinner class
2. Anonymousinner class
3. Localinner class
o Staticnested class
JavaPackage
A java package is a group of similar types of classes, interfaces and sub-packages.
are manybuilt-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
1) Javapackageisusedtocategorizetheclassesandinterfacessothattheycanbeeasilymaintained.
2) Javapackageprovidesaccessprotection.
3) Javapackageremoves namingcollision.
packagemypack;
publicclassSimple{
public static void main(String args[])
{ System.out.println("Welcometopackage");
}}
JAVAPROGRAMMING Page47
Howtocompilejava package
If youarenotusinganyIDE,youneedtofollowthesyntaxgivenbelow: javac -d
directory javafilename
Howtorunjavapackageprogram
ToCompile:javac-d.Simple.java
ToRun:javamypack.Simple
Usingfullyqualifiedname
//savebyA.java
package pack;
publicclassA{
publicvoidmsg(){System.out.println("Hello");}}
//save by B.java
packagemypack;
class B{
publicstaticvoidmain(Stringargs[]){
pack.Aobj=newpack.A();//usingfullyqualifiedname obj.msg();
}
}
Output:Hello
JAVAPROGRAMMING Page48
UNIT-3
ExceptionHandling
Theexceptionhandlinginjava isoneofthepowerfulmechanismtohandletheruntime errors so that
normal flow of the application can be maintained.
Whatisexception
AdvantageofExceptionHandling
The core advantage of exception handling is to maintain the normal flow of the application.
Exception normally disrupts the normal flow of the application that is why we use exception
handling.
TypesofException
There are mainly two types of exceptions: checked and unchecked where error is considered
asunchecked exception. The sun microsystem says there are three types of exceptions:
1. CheckedException
2. UncheckedException
3. Error
Differencebetweencheckedandunchecked exceptions
1) Checked
Exception:TheclassesthatextendThrowableclassexceptRuntimeExceptionandErrorareknownascheck
edexceptionse.g.IOException,SQLExceptionetc.Checkedexceptionsarecheckedatcompile-time.
2) Unchecked Exception:
TheclassesthatextendRuntimeExceptionareknownasuncheckedexceptionse.g.ArithmeticException,Nul
lPointerException,ArrayIndexOutOfBoundsExceptionetc.Uncheckedexceptionsarenotcheckedatcompil
e-timerathertheyarecheckedatruntime.
3) Error:Errorisirrecoverablee.g.OutOfMemoryError,VirtualMachineError,AssertionErroretc.
JAVAPROGRAMMING Page49
HierarchyofJavaExceptionclasses
CheckedandUnCheckedExceptions
JAVAPROGRAMMING Page50
Javatryblock
Javatryblockmustbefollowedbyeithercatchorfinallyblock.
Syntaxofjavatry-catch
1. try{
2. //codethatmaythrow exception
3. }catch(Exception_class_Nameref){}
1. try{
2. //codethatmaythrow exception
3. }finally{}
Javacatchblock
Problemwithoutexceptionhandling
publicclassTesttrycatch1{
public static void main(String args[]){int
data=50/0;//may throw exception
System.out.println("restofthecode...");
}}
Output:
Exceptioninthreadmainjava.lang.ArithmeticException:/byzero
Asdisplayedintheaboveexample,restofthecodeisnotexecuted(insuchcase,restofthe code...
statement is not printed).
Therecanbe100linesofcodeafterexception.Soallthecodeafterexceptionwillnotbe executed.
Solutionbyexception handling
publicclassTesttrycatch2{
JAVAPROGRAMMING Page51
publicstaticvoidmain(Stringargs[]){
try{
int data=50/0;
}catch(ArithmeticExceptione){System.out.println(e);}
System.out.println("rest of the code...");
}}
1. Output:
Exceptioninthreadmainjava.lang.ArithmeticException:/byzero rest
Now,asdisplayedintheaboveexample,restofthecodeisexecutedi.e.restofthecode...
of the code... statement is
printed.
JavaMulticatch block
Let'sseeasimpleexampleofjavamulti-catch block.
1. publicclassTestMultipleCatchBlock{
2. publicstaticvoidmain(Stringargs[]){
3. try{
4. inta[]=newint[5];
5. a[5]=30/0;
6. }
7. catch(ArithmeticExceptione){System.out.println("task1iscompleted");}
8. catch(ArrayIndexOutOfBoundsExceptione){System.out.println("task2completed");
9. }
10. catch(Exceptione){System.out.println("commontaskcompleted");
11. }
12. System.out.println("restofthecode...");
13. }}
Output:task1complete
Javanestedtryexample
d rest of the
classExcep6{
publicstaticvoidmain(Stringargs[]){
try{ try
{
System.out.println("goingtodivide");
intb=39/0;
}catch(ArithmeticExceptione){System.out.println(e);}
try{
JAVAPROGRAMMING Page52
inta[]=newint[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsExceptione){System.out.println(e);}
System.out.println("other statement);
}catch(Exceptione){System.out.println("handeled");}
System.out.println("normal flow..");
}
1.}
Java finally block
Java finally block isa block that isusedto execute important codesuch as closing
connection,stream etc.
Javafinallyblockisalwaysexecutedwhetherexceptionishandledornot. Java
UsageofJavafinally
Case1
Let'sseethejavafinallyexamplewhereexceptiondoesn'toccur. class
TestFinallyBlock{
publicstaticvoidmain(Stringargs[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finallyblockisalwaysexecuted");}
System.out.println("rest of the code...");
}
}
Output:5
Javathrow keyword
finallyblockisalwaysexecuted
rest of the code...
TheJavathrowkeywordisusedtoexplicitlythrowanexception.
Wecanthroweithercheckedorunchekedexceptioninjavabythrowkeyword.Thethrow keyword
is mainly used to throw custom exception. We will see custom exceptions later.
1. throwexception;
JAVAPROGRAMMING Page53
Javathrowkeywordexample
1. publicclassTestThrow1{
staticvoidvalidate(intage){
if(age<18)
thrownewArithmeticException("notvalid");
else
System.out.println("welcometovote");
}
publicstaticvoidmain(Stringargs[]){
validate(13);
System.out.println("restofthecode...");
}}
Output:
Exceptioninthreadmainjava.lang.ArithmeticException:notvalid
Javathrowskeyword
Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers fault that he is not
performing check up before the code being used.
Syntaxofjavathrows
1. return_typemethod_name()throwsexception_class_name{
2. //methodcode
3. }
4.
Javathrowsexample
Let'sseetheexampleofjavathrowsclausewhichdescribesthatcheckedexceptionscanbe propagated by
throws keyword.
importjava.io.IOException;
classTestthrows1{
void m()throwsIOException{
thrownewIOException("deviceerror");//checkedexception
JAVAPROGRAMMING Page54
}
voidn()throwsIOException{ m(
);
}
voidp(){
try{
n();
}catch(Exceptione){System.out.println("exceptionhandled");}
}
publicstaticvoidmain(Stringargs[])
{ Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normalflow...");}} Output:
exceptionhandle
d normal flow...
JavaCustomException
IfyouarecreatingyourownExceptionthatisknownascustomexceptionoruser-definedexception. Java
custom exceptions are used to customize the exception according to user need.
classInvalidAgeExceptionextendsException{ InvalidAgeException(Strin
g s){
super(s);
}}
classTestCustomException1{
staticvoidvalidate(intage)throwsInvalidAgeException{
if(age<18)
thrownewInvalidAgeException("notvalid");
else
System.out.println("welcometovote");
}
publicstaticvoidmain(Stringargs[]){
try{ validate
(13);
}catch(Exceptionm){System.out.println("Exceptionoccured:"+m);}
System.out.println("restofthecode...");
}}
Output:Exceptionoccured:InvalidAgeException:notvalidrestofthecode...
JAVAPROGRAMMING Page55
Multithreading
Multithreadinginjavaisaprocessofexecutingmultiplethreadssimultaneously.
But we use multithreading than multiprocessing because threads share a common memory area.
They don't allocate separate memory area so saves memory, and context-switching between the
threads takes less time than process.
JavaMultithreadingismostlyusedingames,animation etc.
AdvantagesofJavaMultithreading
1) Itdoesn'tblocktheuserbecausethreadsareindependentandyoucanperformmultiple operations at
same time.
2) Youcanperformmanyoperationstogethersoitsavestime.
3) Threadsareindependentsoitdoesn'taffectotherthreadsifexceptionoccurinasingle thread.
LifecycleofaThread(Thread States)
A thread can be in one of the five states. According to sun, there is only 4 states in thread life
cycle in java new, runnable, non-runnable and terminated. There is no running state.
JAVAPROGRAMMING Page56
Howtocreate thread
Therearetwowaystocreatea thread:
1. ByextendingThreadclass
2. ByimplementingRunnableinterface.
Threadclass:
Threadclassprovideconstructorsandmethodstocreateandperformoperationsona
thread.Thread class extends Object class and implements Runnable interface.
CommonlyusedConstructorsofThreadclass:
o Thread()oThread(Str
ingname)
oThread(Runnable r)
o Thread(Runnabler,Stringname)
JAVAPROGRAMMING Page57
CommonlyusedmethodsofThreadclass:
1. publicvoidrun():isusedtoperformactionfora thread.
2. publicvoidstart():startstheexecutionofthethread.JVMcallstherun()methodonthe thread.
3. public void sleep(long miliseconds):Causes the currently executing thread to sleep (temporarily
cease execution) for the specified number of milliseconds.
4. publicvoidjoin():waitsforathreadtodie.
5. publicvoidjoin(longmiliseconds):waitsforathreadtodieforthespecified miliseconds.
6. publicintgetPriority(): returnsthepriorityofthe thread.
7. publicintsetPriority(intpriority): changesthe priorityofthethread.
8. publicStringgetName():returnsthenameofthethread.
9. publicvoidsetName(Stringname):changesthe nameofthethread.
10. publicThreadcurrentThread():returnsthereferenceofcurrentlyexecutingthread.
11. publicintgetId():returnstheidofthethread.
12. publicThread.StategetState():returnsthestateofthethread.
13. publicbooleanisAlive():testsifthethreadisalive.
14. public void yield():causes the currently executing thread object to temporarily pause and
allowother threads to execute.
15. publicvoidsuspend():isusedtosuspendthethread(depricated).
16. publicvoidresume():isusedtoresumethesuspendedthread(depricated).
17. publicvoidstop():isusedtostopthethread(depricated).
18. publicbooleanisDaemon():testsifthethreadisadaemonthread.
19. publicvoidsetDaemon(booleanb):marksthethreadasdaemonoruserthread.
20. publicvoidinterrupt():interruptsthethread.
21. publicbooleanisInterrupted():testsifthethreadhasbeeninterrupted.
22. publicstaticbooleaninterrupted():testsifthecurrentthreadhasbeeninterrupted.
Runnableinterface:
TheRunnableinterfaceshouldbeimplementedbyanyclasswhoseinstancesareintendedtobe executed by a
thread. Runnable interface have only one method named run().
1. publicvoidrun():isusedtoperformactionfora thread.
Startinga thread:
start()methodofThreadclassisusedtostartanewlycreatedthread.Itperformsfollowing tasks:
o Anewthreadstarts(withnewcallstack).
o ThethreadmovesfromNewstatetotheRunnable state.
o Whenthethread getsa chancetoexecute,itstarget run()methodwillrun.
JAVAPROGRAMMING Page58
JavaThreadExamplebyextendingThreadclass
classMultiextendsThread{
public void run()
{ System.out.println("threadisrunning...");
}
publicstaticvoidmain(Stringargs[])
{ Multi t1=new Multi();
t1.start();
}}
Output:threadisrunning...
JavaThreadExamplebyimplementingRunnableinterface class
3constantsdefinedinThreadclass:
JAVAPROGRAMMING Page59
TestMultiPriority1m1=newTestMultiPriority1();
TestMultiPriority1m2=newTestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}}
Output:runningthreadnameis:Thread-0
running thread priority is:10Javasynchronizedmethod
runningthreadnameis:Thread-1
If youdeclareanymethodassynchronized,itisknownassynchronizedmethod.
running thread priority is:1 Synchronized
Whenathreadinvokesasynchronizedmethod,itautomaticallyacquiresthelockforthatobject and
releases it when the thread completes its task.
Exampleofinterthreadcommunicationinjava
Let'sseethesimpleexampleofinterthreadcommunication.
classCustomer{
int amount=10000;
synchronizedvoidwithdraw(intamount)
{ System.out.println("goingtowithdraw...")
; if(this.amount<amount){
System.out.println("Lessbalance;waitingfordeposit...");
try{wait();}catch(Exceptione){}
}
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(){
JAVAPROGRAMMING Page60
publicvoidrun(){c.deposit(10000);}
}
start();
}}
Output:goingtowithdraw... ThreadGroupinJava
Lessbalance;waitingfordeposit...
Java provides a convenient way to group multiple threads in a single object. In such way, we can
going to deposit...
suspend, resume or interrupt group of threads by a single method call.
depositcompleted...
withdrawcompleted
Note:Nowsuspend(),resume()andstop()methodsaredeprecated.
Javathreadgroupisimplementedbyjava.lang.ThreadGroupclass. Constructors
of ThreadGroup class
Thereareonlytwoconstructors ofThreadGroupclass.
ThreadGroup(String name)
ThreadGroup(ThreadGroupparent,Stringname)
1. ThreadGrouptg1=newThreadGroup("GroupA");
2. Threadt1=newThread(tg1,newMyRunnable(),"one");
3. Threadt2=newThread(tg1,newMyRunnable(),"two");
4. Threadt3=newThread(tg1,newMyRunnable(),"three");
Nowwecaninterruptallthreadsbyasinglelineofcode only.
1. Thread.currentThread().getThreadGroup().interrupt();
Exploringjava.netandjava.text
JAVAPROGRAMMING Page61
java.net
The termnetwork programmingrefers to writing programs that execute across multiple devices
(computers), in which the devices are all connected to each other using a network.
The java.net package of the J2SE APIs contains a collection of classes and interfaces thatprovide
the low-level communication details, allowing you to write programs that focus on solving the
problem at hand.
Thejava.netpackageprovidessupportforthetwo commonnetworkprotocols−
TCP− TCP stands for Transmission Control Protocol, which allows for reliable
communication between two applications. TCP is typically used over the Internet
Protocol, which is referred to as TCP/IP.
UDP− UDP stands for User Datagram Protocol, a connection-less protocol that allowsfor
packets of data to be transmitted between applications.
Thischaptergivesa goodunderstandingonthefollowingtwosubjects−
SocketProgramming−ThisisthemostwidelyusedconceptinNetworkingandithas
been explained in verydetail.
URLProcessing−This wouldbecoveredseparately.
java.text
The java.textpackage is necessary for every java developer to master because it has a lot of
classes that is helpful in formatting such as dates, numbers, and messages.
java.textClasses
Thefollowingaretheclassesavailableforjava.textpackage [table]
Class|Description
SimpleDateFormat|isaconcreteclassthathelpsinformattingandparsingofdates. [/table]
JAVAPROGRAMMING Page62
UNIT-4
CollectionFrameworkinJava
Collections in javais a framework that provides an architecture to store and manipulate thegroup
of objects.
All the operations that you perform on a data such as searching, sorting, insertion, manipulation,
deletion etc. can be performed by Java Collections.
Java Collection simply means a single unit of objects. Java Collection framework provides many
interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList,
PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).
Whatisframeworkinjava
o providesreadymade architecture.
o representssetofclassesandinterface.
o is optional.
WhatisCollectionframework
Collection framework represents a unified architecture for storing and manipulating group of
objects. It has:
1. Interfacesanditsimplementationsi.e. classes
2. Algorithm
JAVAPROGRAMMING Page63
HierarchyofCollectionFramework
JavaArrayListclass
JavaArrayListclassusesadynamicarrayforstoringtheelements.ItinheritsAbstractListclass and
implements List interface.
TheimportantpointsaboutJavaArrayListclassare:
JAVAPROGRAMMING Page64
ArrayListclassdeclaration
Let'sseethedeclarationforjava.util.ArrayListclass.
ConstructorsofJavaArrayList
Constructor Description
JavaArrayListExample
import java.util.*;
classTestCollection1{
publicstaticvoidmain(Stringargs[]){
ArrayList<String>list=newArrayList<String>();//Creatingarraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());}}}
Ra
vi
Vij
ay
JAVAPROGRAMMING Page65
vector
ArrayListandVectorbothimplementsListinterfaceandmaintainsinsertion order.
ButtherearemanydifferencesbetweenArrayListandVectorclassesthat aregivenbelow.
ArrayList Vector
1)ArrayListisnotsynchronized. Vectorissynchronized.
3)ArrayListisnotalegacyclass, it is Vectorisalegacyclass.
introduced in JDK 1.2.
5)ArrayListusesIteratorinterface to VectorusesEnumerationinterfacetotraversethe
traverse the elements. elements. But it can use Iterator also.
ExampleofJava Vector
Let'sseeasimpleexampleofjavaVector classthatusesEnumerationinterface.
1. importjava.util.*;
2. classTestVector1{
3. publicstaticvoidmain(Stringargs[]){
4. Vector<String>v=newVector<String>();//creatingvector
5. v.add("umesh");//methodofCollection
6. v.addElement("irfan");//methodofVector
7. v.addElement("kumar");
8. //traversingelementsusingEnumeration
JAVAPROGRAMMING Page66
9. Enumeratione=v.elements();
10. while(e.hasMoreElements()){
11. System.out.println(e.nextElement());
12. }}}
Output:
umesh
irfan
JavaHashtableclass
kum
TheimportantpointsaboutJavaHashtableclass are:
o A Hashtable is an array of list. Each list is known as a bucket. The position of bucket is
identified by calling the hashcode() method. A Hashtable contains values based on thekey.
o Itcontains onlyuniqueelements.
o It mayhavenothaveanynull keyorvalue.
o Itis synchronized.
Hashtableclassdeclaration
Let'sseethedeclarationforjava.util.Hashtableclass.
1. publicclassHashtable<K,V>extendsDictionary<K,V>implementsMap<K,V>,Cloneable,Ser
ializable
HashtableclassParameters
Let'sseetheParametersforjava.util.Hashtable class.
o K: Itisthetypeofkeysmaintainedbythismap.
o V: Itisthetypeofmappedvalues.
JAVAPROGRAMMING Page67
ConstructorsofJavaHashtableclass
Constructor Description
Hashtable(int size, float It is used to create a hash table that has an initial size specified by
fillRatio) size and a fill ratio specified by fillRatio.
JavaHashtableExample
importjava.util.*;
classTestCollection16{
public static void main(String args[])
{Hashtable<Integer,String>hm=newHashtable<Integer,String>();
hm.put(100,"Amit");
hm.put(102,"Ravi");
hm.put(101,"Vijay");
hm.put(103,"Rahul");
for(Map.Entry m:hm.entrySet())
{ System.out.println(m.getKey()+""+m.getValue());
}}}
Output:
Stack
103 Rahul
102 Ravi
StackisasubclassofVectorthatimplementsastandardlast-in, first-outstack.
101 Vijay
100 Amit
Stack only defines the default constructor, which creates an empty stack. Stack includes all
themethods defined by Vector, and adds several of its own.
JAVAPROGRAMMING Page68
Stack()
Example
Thefollowingprogram illustratesseveral of themethods supported bythiscollection −
importjava.util.*;
publicclassStackDemo{
staticvoidshowpush(Stackst,inta){
st.push(newInteger(a));
System.out.println("push("+a+")");
System.out.println("stack:"+st);}
staticvoidshowpop(Stackst){
System.out.print("pop->");
Integera=(Integer)st.pop();
System.out.println(a);
System.out.println("stack:"+st);}
publicstaticvoidmain(Stringargs[]){
Stackst=newStack();
System.out.println("stack:"+st);
showpush(st,42);
showpush(st,66);
showpush(st,99);
showpop(st);
showpop(st);
showpop(st);
try{
showpop(st);
}catch(EmptyStackExceptione){
System.out.println("emptystack");
JAVAPROGRAMMING Page69
}}}
Thiswillproducethefollowingresult−
Output
Enumeration
stack: [ ]
TheEnumerationInterface
push(42)
stack: [42]
TheEnumerationinterfacedefinesthemethodsbywhich youcanenumerate(obtainoneata time)
push(66)
the elements in a collection of objects.
stack:
ThemethodsdeclaredbyEnumerationaresummarizedin thefollowingtable −
[42,66]
Sr.No. Method&Description
push(99)
stack:[42, 66, 99]
1
pop->99 booleanhasMoreElements()
stack:[42, 66]
When implemented, it must return true while there are still more elements to extract,
pop->66
andfalse when all the elements have been enumerated.
stack:[42]
2
pop->42
ObjectnextElement()
stack: [ ]
Thisreturnsthenextobjectintheenumeration asagenericObjectreference.
Example
JAVAPROGRAMMING Page70
Followingis anexampleshowingusageofEnumeration.
import java.util.Vector;
Thiswillproducethefollowingresult−
importjava.util.Enumeration
Output
;
Sunday
Iterator
Monday
publicclassEnumerationTester{
Tuesday
publicstaticvoidmain(Stringargs[]){
Wednesday
Enumeration days;
Thursday
Friday
VectordayNames=newVector();
Saturday
dayNames.add("Sunday");
dayNames.add("Monday");
dayNames.add("Tuesday");
dayNames.add("Wednesday");
dayNames.add("Thursday");
dayNames.add("Friday");
dayNames.add("Saturday");
days = dayNames.elements();
while(days.hasMoreElements()){
System.out.println(days.nextElement());
JAVAPROGRAMMING Page71
It is a universal iterator as we can apply it to any Collection object. By using Iterator, we can
performbothreadandremoveoperations.ItisimprovedversionofEnumerationwithadditional
functionality of remove-ability of a element.
Iterator must be used whenever we want to enumerate elements in all Collection framework
implemented interfaces like Set, List, Queue, Deque and also in all implemented classes of Map
interface. Iterator is the only cursor available for entire collection framework.
Iteratorobjectcanbecreatedbycallingiterator()methodpresentinCollectioninterface.
publicvoidremove();
remove()methodcanthrowtwoexceptions
UnsupportedOperationException:Iftheremove operationisnotsupportedbythis iterator
IllegalStateException: Ifthenextmethodhasnotyetbeencalled,ortheremovemethod has
already been called after the last call to the next method
LimitationsofIterator:
Onlyforwarddirectioniteratingispossible.
Replacementandadditionofnewelementisnot supportedbyIterator.
StringTokenizerinJava
Itdoesn'tprovidethefacilitytodifferentiatenumbers,quotedstrings,identifiersetc.
ConstructorsofStringTokenizerclass
Thereare3constructorsdefinedintheStringTokenizerclass.
JAVAPROGRAMMING Page72
Constructor Description
StringTokenizer(Stringstr) createsStringTokenizerwithspecifiedstring.
MethodsofStringTokenizerclass
Publicmethod Description
StringnextToken(Stringdelim) returnsthenexttokenbasedonthedelimeter.
SimpleexampleofStringTokenizerclass
Let's see the simple example of StringTokenizer class that tokenizes a string "my name is
khan"on the basis of whitespace.
importjava.util.StringTokenizer;
publicclassSimple{
publicstaticvoidmain(Stringargs[]){
JAVAPROGRAMMING Page73
StringTokenizerst=newStringTokenizer("mynameiskhan","");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}}}
ExampleofnextToken(Stringdelim)methodofStringTokenizerclass
Output:my
name
importjava.util.*;
publicclassTest{
is
kh
publicstaticvoidmain(String[]args){
StringTokenizerst=newStringTokenizer("my,name,is,khan");
// printingnext token
System.out.println("Nexttokenis:"+st.nextToken(","));
} }
Output:Nexttokenis:my
java.util.Random
For using this class to generate random numbers, we have to first create an instance of this
class and then invoke methods such as nextInt(), nextDouble(), nextLong() etc using that
instance.
We can generate random numbers of types integers, float, double, long, booleans using this
class.
We can pass arguments to the methods for placing an upper bound on the range of the
numbers to be generated. For example, nextInt(6) will generate numbers in the range 0 to 5
both inclusive.
//AJavaprogramtodemonstraterandomnumbergeneration
//usingjava.util.Random; import
java.util.Random;
publicclass generateRandom{
//Generaterandomintegersinrange0to999 int
rand_int1 = rand.nextInt(1000);
intrand_int2=rand.nextInt(1000);
JAVAPROGRAMMING Page74
// Print random integers
System.out.println("RandomIntegers:"+rand_int1);
System.out.println("RandomIntegers:"+rand_int2);
//GenerateRandomdoubles
doublerand_dub1=rand.nextDouble();
doublerand_dub2= rand.nextDouble();
//Printrandomdoubles
System.out.println("RandomDoubles:"+rand_dub1);
System.out.println("RandomDoubles:"+rand_dub2);
}}
Output:
JavaScannerclass
RandomIntegers:547
RandomIntegers:126
Therearevariousways toread inputfromthekeyboard,thejava.util.Scannerclassisoneofthem.
RandomDoubles: 0.8369779739988428
TheJava Scannerclass breaks the input into tokens using a delimiter that is whitespace bydefault.
ItRandomDoubles: 0.5497554388209912
provides many methods to read and parse various primitive values.
Java Scanner class is widely used to parse text for string and primitive types using regular
expression.
CommonlyusedmethodsofScanner class
ThereisalistofcommonlyusedScannerclass methods:
Method Description
publicStringnextLine() it moves the scanner position to the next line and returns the value
as a string.
publicbytenextByte() itscansthenexttokenasabyte.
JAVAPROGRAMMING Page75
publicshort nextShort() itscansthenexttokenasashortvalue.
JavaScannerExampletogetinputfromconsole
Let'sseethesimpleexampleoftheJavaScannerclasswhichreadstheint,stringanddouble value as an
input:
importjava.util.Scanner;
classScannerTest{
public static void main(String args[])
{ Scanner sc=new Scanner(System.in);
System.out.println("Enteryourrollno");
int rollno=sc.nextInt();
System.out.println("Enter your name");
String name=sc.next();
System.out.println("Enter your fee");
double fee=sc.nextDouble();
System.out.println("Rollno:"+rollno+"name:"+name+"fee:"+fee);
sc.close();
}}Output:
Enteryourrollno
111
Enteryourname
Ratan
Enter
4500
00
JAVAPROGRAMMING Page76
JavaCalendarClass
Java Calendar class is an abstract class that provides methods for converting date between a
specific instant in time and a set of calendar fields such as MONTH, YEAR, HOUR, etc. It
inherits Object class and implements the Comparable interface.
JavaCalendarclassdeclaration
Let'sseethedeclarationofjava.util.Calendar class.
1. publicabstractclassCalendarextendsObject
2. implementsSerializable,Cloneable,Comparable<Calendar>
JavaCalendarClassExample
importjava.util.Calendar;
publicclassCalendarExample1{
public static void main(String[] args)
{ Calendarcalendar=Calendar.getInstance();
System.out.println("Thecurrentdateis:"+calendar.getTime()); calendar.add(Calendar.DATE, -
15);
System.out.println("15daysago:"+calendar.getTime());
calendar.add(Calendar.MONTH, 4);
System.out.println("4monthslater:"+calendar.getTime());
calendar.add(Calendar.YEAR, 2);
System.out.println("2yearslater:"+calendar.getTime());
}}
Output:
Thecurrentdateis:ThuJan1918:47:02IST2017 15
days ago: Wed Jan 04 18:47:02 IST 2017
4monthslater:ThuMay0418:47:02 IST2017
2 yearslater:SatMay0418:47:02IST2019
JAVAPROGRAMMING Page77
Java-FilesandI/O
Thejava.io package contains nearlyeveryclass you might ever need to perform input and output
(I/O) in Java. All these streams represent an input source and an output destination. The streamin
the java.io package supports many data such as primitives, object, localized characters, etc.
Stream
Astreamcanbedefinedasasequenceof data.TherearetwokindsofStreams−
InPutStream−TheInputStreamisusedtoread datafromasource.
OutPutStream−TheOutputStreamisusedforwritingdatato a destination.
Java provides strong but flexible support for I/O related to files and networks but this tutorial
covers very basic functionality related to streams and I/O. We will see the most commonly used
examples one by one −
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many
classesrelatedtobytestreamsbutthemostfrequentlyusedclasses are,
FileInputStreamandFileOutputStream. Following is an example which makes use of these two
classes to copy an input file into an output file −
Example
importjava.io.*;
publicclassCopyFile{
publicstaticvoidmain(Stringargs[])throwsIOException{ FileInputStream in = null;
FileOutputStreamout=null; try {
in=newFileInputStream("input.txt");
out=newFileOutputStream("output.txt"); int c;
while((c =in.read())!= -1){
JAVAPROGRAMMING Page78
out.write(c);
}finally{
if(in!=null){
in.close();
if(out!=null){
out.close();
}}}}
Nowlet'shaveafileinput.txtwiththefollowingcontent−
As a next step, compile the above program and execute it, which will result in creatingoutput.txt
Thisistestforcopyfile.
file with the same content as we have in input.txt. So let's put the above code in CopyFile.java
file and do the following −
$javacCopyFile.java
$java CopyFile
CharacterStreams
JavaBytestreamsareusedtoperforminputandoutputof8-bitbytes,whereas JavaCharacterstreams
are used to perform input and output for 16-bit unicode. Though there
aremanyclassesrelatedtocharacterstreamsbutthemostfrequentlyusedclasses are, FileReader and
FileWriter. Though internally FileReader uses FileInputStream and FileWriter uses
FileOutputStream but here the major difference is that FileReader reads two bytes at a time and
FileWriter writes two bytes at a time.
Wecanre-writetheaboveexample,whichmakestheuseofthesetwoclassestocopyaninput
file(havingunicodecharacters) intoanoutputfile−
Example
importjava.io.*;
publicclassCopyFile{
publicstaticvoidmain(Stringargs[])throwsIOException{
JAVAPROGRAMMING Page79
FileReader in =
null;
FileWriterout=null;
try {
in = new FileReader("input.txt");
out=newFileWriter("output.txt");
int c;
while((c=in.read())!=-1){
out.write(c);}
}finally{
if(in!=null){
in.close();}
if(out!=null){
out.close();
Nowlet'shaveafileinput.txtwiththefollowingcontent−
As a next step, compile the above program and execute it, which will result in creatingoutput.txt
This is test forcopyfile.
file with the same content as we have in input.txt. So let's put the above code in CopyFile.java
file and do the following −
$javacCopyFile.java
$java CopyFile
StandardStreams
All the programming languages provide support for standard I/O where the user's program can
takeinputfromakeyboardandthenproduceanoutputonthecomputerscreen.Javaprovidesthe
following three standard streams −
StandardInput−Thisisusedtofeedthedatatouser'sprogramandusuallyakeyboard
isusedasstandardinput streamandrepresented asSystem.in.
JAVAPROGRAMMING Page80
Standard Output− This is used to output the data produced by the user's program and
usuallyacomputerscreenisusedforstandardoutputstreamandrepresented as System.out.
Standard Error− This is used to output the error data produced by the user's program
andusuallyacomputerscreenisusedforstandarderrorstreamandrepresented as System.err.
Followingisasimpleprogram,whichcreatesInputStreamReadertoreadstandardinputstream until
the user types a "
Example
importjava.io.*;
publicclassReadConsole{
Thisprogramcontinues toread andoutput thesamecharacter untilwepress'q'−
publicstaticvoidmain(Stringargs[])throwsIOException{ InputStreamReader
$javacReadConsole.java
cinReadConsole
$java = null;
try{
System.out.println("Entercharacters,'q'toquit.");
char c;
do{
c=(char)cin.read();
System.out.print(c);
}while(c!='q');
}finally{
if(cin!=null){
cin.close();
}} }}
JAVAPROGRAMMING Page81
Entercharacters,'q'toquit.
1
1
e
ReadingandWritingFiles
As described earlier, a stream can be defined as a sequence of data. The InputStreamis used to
read data from a source and the OutputStream is used for writing data to a destination.
Hereisahierarchyof classestodealwithInputandOutputstreams.
ThetwoimportantstreamsareFileInputStreamandFileOutputStream
FileInputStream
Thisstreamisusedforreadingdatafromthefiles.Objectscanbecreatedusingthe keyword new and there are
several types of constructors available.
Followingconstructortakesafilenameasastringtocreateaninputstreamobjecttoreadthe
file −
InputStreamf=newFileInputStream("C:/java/hello");
JAVAPROGRAMMING Page82
Following constructortakesafileobjecttocreateaninputstreamobjectto readthefile.Firstwe
createafileobjectusingFile()method asfollows−
DataInputStream
FileOutputStream
FileOutputStream is used to create a file and write data into it. The stream would create a file, if
it doesn't already exist, before opening it for output.
Followingconstructortakesafilenameasastringtocreateaninputstreamobjecttowritethe
file −
Followingconstructortakesafileobjecttocreateanoutputstreamobjecttowritethefile.First,
OutputStreamf=new FileOutputStream("C:/java/hello")
wecreate afileobjectusingFile()methodasfollows−
Once you haveOutputStreamobject in hand, then there is a list of helper methods, which can be
File f = new File("C:/java/hello");
used to write to stream or to do other operations on the stream.
OutputStreamf=newFileOutputStream(f);
ByteArrayOutputStream
DataOutputStream
Example
FollowingistheexampletodemonstrateInputStreamandOutputStream−
importjava.io.*;
publicclassfileStreamTest {
publicstaticvoidmain(Stringargs[]){
try {
JAVAPROGRAMMING Page83
bytebWrite[]={11,21,3,40,5};
OutputStreamos=newFileOutputStream("test.txt"); for(int x = 0; x <bWrite.length ; x++) {
os.write(bWrite[x]);//writesthebytes} os.close();
InputStreamis=newFileInputStream("test.txt"); int size = is.available();
for(int i = 0; i <size; i++) { System.out.print((char)is.read()+"");}
is.close();
} catch (IOException e) { System.out.print("Exception");
} }}
Java.io.RandomAccessFileClass
TheJava.io.RandomAccessFileclassfilebehaveslikealargearray ofbytesstoredinthefile system.Instances
of this class support both reading and writing to a random access file.
Classdeclaration
FollowingisthedeclarationforJava.io.RandomAccessFileclass−
Classconstructors
publicclassRandomAccessFile
S.N.
extends Object Constructor&Description
implementsDataOutput,DataInput,Closeable
1
RandomAccessFile(Filefile,Stringmode)
JAVAPROGRAMMING Page84
2
RandomAccessFile(Filefile,Stringmode)
This creates a random access file stream to readfrom, and optionally towrite to, a file withthe
specified name.
Methodsinherited
Thisclassinheritsmethodsfromthefollowingclasses−
Java.io.Object
Java.io.FileClassinJava
The File class is Java’s representation of a file or directory path name. Becausefile and directory
nameshavedifferent formats on different platforms, asimplestringis notadequateto namethem. The
File class contains several methods for working with the path name, deleting and renaming files,
creating new directories, listing the contents of a directory, and determining severalcommon
attributes of files and directories.
Itisan abstractrepresentationoffileanddirectorypathnames.
Apathname,whetherabstractorinstringform canbeeitherabsoluteorrelative.Theparent of an
abstract pathname may be obtained by invoking the getParent() method of this class.
First of all, we should create the File class object bypassing the filename or directoryname
to it. A file system may implement restrictions to certain operations on the actual file-
system object, such as reading, writing, and executing. These restrictions are collectively
known as access permissions.
Instances of the File class are immutable; that is, once created, the abstract pathname
represented by a File object will never change.
HowtocreateaFile Object?
A File object is created by passing in a String that represents the name of a file, or a String or
another File object. For example,
Filea=new File("/usr/local/bin/geeks");
//Displayingfileproperty
class fileProperty
{
publicstaticvoidmain(String[]args){
JAVAPROGRAMMING Page85
//acceptfilenameordirectorynamethroughcommandlineargs String
fname =args[0];
//passthefilenameordirectorynametoFileobject File f
= new File(fname);
Output:
ConncetingtoDB
Filename:file.txtPath:
file.txt
WhatisJDBCDriver?
Absolutepath:C:\Users\akki\IdeaProjects\codewriting\src\
JDBCdriversimplementthedefinedinterfacesintheJDBCAPI,forinteractingwithyour
file.txtParent:null database server.
Exists:true
For example,usingJDBCdrivers enable youtoopendatabase connections andtointeract withit by
Iswriteable:trueI
sending SQL or database commands then receiving results with Java.
sreadabletrue
Isadirectory:falseFile
Sizeinbytes20
JAVAPROGRAMMING Page86
TheJava.sqlpackagethat ships with JDK, contains various classes with theirbehaviours defined
and their actual implementaions are done in third-party drivers. Third party vendors implements
the java.sql.Driver interface in their database driver.
JDBCDriversTypes
JDBC driver implementations vary because of the wide variety of operating systems and
hardware platforms in which Java operates. Sun has divided the implementation types into four
categories, Types 1, 2, 3, and 4, which is explained below −
Type1:JDBC-ODBCBridgeDriver
In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client
machine. Using ODBC, requires configuring on your system a Data Source Name (DSN) that
represents the target database.
TheJDBC-ODBCBridgethatcomeswith
JDK 1.2 is a good example of this kind of driver.
Type2:JDBC-NativeAPI
In a Type 2 driver, JDBC APIcalls are converted into native C/C++ API calls, which are unique
to the database. These drivers are typically provided by the database vendors and used in the
same manner as the JDBC-ODBC Bridge. The vendor-specific driver must be installed on each
client machine.
JAVAPROGRAMMING Page87
If we change the Database, we have to change the native API, as it is specific to a database and
they are mostly obsolete now, but you may realize some speed increase with a Type 2 driver,
because it eliminates ODBC's overhead.
Type3:JDBC-NetpureJava
In a Type 3 driver, a three-tier approach is used to access databases. The JDBC clients use
standard network sockets to communicate with a middleware application server. The socket
information is then translated by the middleware application server into the call format required
by the DBMS, and forwarded to the database server.
This kind of driver is extremely flexible, since it requires no code installed on the client and a
single driver can actually provide access to multiple databases.
JAVAPROGRAMMING Page88
You can think of the application server as a JDBC "proxy," meaning that it makes calls for the
clientapplication.Asaresult,youneedsomeknowledgeoftheapplicationserver'sconfiguration in
order to effectively use this driver type.
Your application server might use a Type 1, 2, or 4 driver to communicate with the database,
understanding the nuances will prove helpful.
Type4:100%PureJava
In a Type 4 driver, a pure Java-based driver communicates directly with the vendor's database
through socket connection. This is the highest performance driver available for the database and
is usually provided by the vendor itself.
This kind of driver is extremely flexible, you don't need to install special software on the clientor
server. Further, these drivers can be downloaded dynamically.
MySQL'sConnector/JdriverisaType4driver.Becauseoftheproprietarynatureoftheir network
protocols, database vendors usually supply type 4 drivers.
WhichDrivershouldbeUsed?
If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred
drivertype is 4.
Ifyour Java application is accessing multiple types of databases at the same time, type 3 is
thepreferred driver.
JAVAPROGRAMMING Page89
Thetype1driverisnotconsideredadeployment-leveldriver,andistypicallyusedfor development and testing
purposes only.
Exampletoconnecttothemysqldatabaseinjava
For connecting java applicationwith the mysql database,you need to follow 5 steps to
performdatabase connectivity.
In this example we are using MySql as the database. So we need to know following informations
for the mysql database:
1. Driverclass:Thedriverclassforthemysqldatabaseis com.mysql.jdbc.Driver.
2. ConnectionURL:TheconnectionURLforthemysqldatabase
isjdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the database,
localhost is the server name on which mysql is running, we may also use IP address, 3306
is the port number and sonoo is the database name. We may use any database, in suchcase,
you need to replace the sonoo with your database name.
3. Username:Thedefaultusernameforthemysqldatabaseisroot.
4. Password:Password is given by the user at the time of installing the mysql database. In
this example, we are going to use root as the password.
1. createdatabasesonoo;
2. usesonoo;
3. create table emp(id int(10),name varchar(40),age int(3));
ExampletoConnectJavaApplicationwithmysqldatabase
importjava.sql.*;
classMysqlCon{
public static void main(String args[]){
try{ Class.forName("com.mysql.jdbc.Driv
er");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sonoo","root","root");
//heresonoo isdatabasename,rootisusernameand password
JAVAPROGRAMMING Page90
Statementstmt=con.createStatement();
ResultSetrs=stmt.executeQuery("select*fromemp");
while(rs.next())
System.out.println(rs.getInt(1)+""+rs.getString(2)+""+rs.getString(3));
con.close();
}catch(Exceptione){System.out.println(e);}
}}
Theabove examplewillfetchalltherecordsofemptable.
Toconnectjavaapplicationwiththemysqldatabasemysqlconnector.jarfileisrequiredtobe loaded.
Twowaystoloadthejarfile:
1. pastethemysqlconnector.jarfileinjre/lib/extfolder
2. setclasspath
1) pastethemysqlconnector.jarfileinJRE/lib/extfolder:
Downloadthemysqlconnector.jarfile.Gotojre/lib/extfolderandpastethejarfilehere.
2) setclasspath:
Therearetwowaystosettheclasspath:
1.temporary2.permanent
Howtosetthetemporary classpath
opencommandpromptandwrite:
1.C:>setclasspath=c:\folder\mysql-connector-java-5.0.8-bin.jar;.;
Howtosetthepermanentclasspath
Go to environment variable then click on new tab. In variable name write classpathand in
variable value paste the path to the mysqlconnector.jar file by appending mysqlconnector.jar;.; as
C:\folder\mysql-connector-java-5.0.8-bin.jar;
JDBC-ResultSets
The SQL statements that read data from a database query, return the data in a result set. The
SELECT statement is the standard way to select rows from a database and view them in a result
set. The java.sql.ResultSet interface represents the result set of a database query.
JAVAPROGRAMMING Page91
AResultSetobjectmaintainsacursorthatpointstothecurrentrowintheresultset.Theterm "result set"
refers to the row and column data contained in a ResultSet object.
ThemethodsoftheResultSetinterfacecanbebrokendownintothreecategories −
Navigationalmethods:Usedtomovethecursor around.
Get methods:Used to view the data in the columns of the current row being pointed by
the cursor.
Update methods:Used to update the data in the columns of the current row. The updates
can then be updated in the underlying database as well.
The cursor is movable based on the properties of the ResultSet. These properties are designated
when the corresponding Statement that generates the ResultSet is created.
JDBCprovidesthefollowingconnectionmethodstocreatestatementswithdesiredResultSet−
createStatement(intRSType,intRSConcurrency);
prepareStatement(StringSQL,intRSType,intRSConcurrency);
prepareCall(Stringsql,intRSType,intRSConcurrency);
TypeofResultSet
ThepossibleRSTypearegivenbelow.IfyoudonotspecifyanyResultSettype,youwill automatically get one
that is TYPE_FORWARD_ONLY.
Type Description
JAVAPROGRAMMING Page92
ResultSet.TYPE_SCROLL_SENSITIVE. The cursor can scroll forward and backward, and
the result set is sensitive to changes made by
otherstothedatabasethatoccuraftertheresultset was
created.
ConcurrencyofResultSet
The possible RSConcurrency are given below. If you do not specify any Concurrency type, you
will automatically get one that is CONCUR_READ_ONLY.
Concurrency Description
ResultSet.CONCUR_UPDATABLE Createsanupdateableresultset.
ViewingaResultSet
The ResultSet interface contains dozens of methods for getting the data of the current row.
Thereisagetmethodforeachofthepossibledatatypes,andeachgetmethodhastwoversions
Forexample,ifthecolumnyouareinterestedinviewingcontainsanint,youneedtouseoneof
thegetInt()methodsofResultSet−
S.N. Methods&Description
1 publicintgetInt(StringcolumnName)throwsSQLException
ReturnstheintinthecurrentrowinthecolumnnamedcolumnName.
2 publicintgetInt(intcolumnIndex)throwsSQLException
Returns the int in the current row in the specified column index. The column index starts
at 1, meaning the first column of a row is 1, the second column of a row is 2, and so on.
JAVAPROGRAMMING Page93
Similarly, there are get methods in the ResultSet interface for each of the eight Java primitive
types, as well as common types such as java.lang.String, java.lang.Object, and java.net.URL.
There are also methods for getting SQL data types java.sql.Date, java.sql.Time,
java.sql.TimeStamp, java.sql.Clob, and java.sql.Blob. Check the documentation for more
information about using these SQL data types.
UpdatingaResultSet
The ResultSet interface contains a collection of update methods for updating the data of a result
set.
Aswiththegetmethods,therearetwoupdatemethodsforeachdatatype−
JAVAPROGRAMMING Page94
Forexample,toupdateaStringcolumnofthecurrentrowofaresultset,youwoulduseoneof
thefollowingupdateString()methods−
S.N. Methods&Description
1 publicvoidupdateString(intcolumnIndex,Strings)throwsSQLException
There are update methods for the eight primitive data types, as well as String, Object, URL, and
the SQL data types in the java.sql package.
Updating a row in the result set changes the columns of the current row in the ResultSet object,
but not in the underlying database. To update your changes to the row in the database, you need
to invoke one of the following methods.
S.N. Methods&Description
1 publicvoidupdateRow()
2 publicvoiddeleteRow()
Deletesthecurrent rowfromthe database
3 publicvoidrefreshRow()
Refreshesthe datain the resultsettoreflectanyrecentchangesinthe database.
4 publicvoidcancelRowUpdates()
Cancelsanyupdates madeon thecurrent row.
5 publicvoidinsertRow()
Insertsarowintothedatabase.Thismethodcanonlybeinvokedwhenthecursoris pointing to the
insert row.
JAVAPROGRAMMING Page95
UNIT-5
GUIProgrammingwithjava
TheAWTClasshierarchy
JavaAWTcomponentsareplatform-dependenti.e.componentsaredisplayedaccordingtothe view of
operatingsystem. AWT is heavyweight i.e. its components are usingthe resources of OS.
Thejava.awtpackageprovidesclassesforAWTapisuchasTextField,Label,TextArea, RadioButton,
CheckBox, Choice, List etc.
JavaAWT Hierarchy
ThehierarchyofJavaAWTclassesare givenbelow.
JAVAPROGRAMMING Page96
Container
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such as
Frame, Dialog and Panel.
Window
The window is the container that have no borders and menu bars. You must use frame, dialog or
another window for creating a window.
Panel
Frame
UsefulMethodsofComponent class
Method Description
publicvoidsetSize(intwidth,intheight) setsthesize(widthandheight)ofthecomponent.
publicvoidsetLayout(LayoutManager m) definesthelayoutmanagerforthecomponent.
JavaAWT Example
Tocreatesimpleawtexample,youneedaframe. TherearetwowaystocreateaframeinAWT.
o ByextendingFrameclass(inheritance)
o Bycreatingtheobject of Frame class(association)
JAVAPROGRAMMING Page97
AWTExampleby Inheritance
Let's see a simple example of AWT where we are inheriting Frame class. Here, we are
showingButton component on the Frame.
importjava.awt.*;
classFirstextendsFrame{ Fi
rst(){
Button b=new Button("click me");
b.setBounds(30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//framesize300widthand300height
setLayout(null);//no layout manager
setVisible(true);//nowframewillbevisible,bydefaultnot visible
}
publicstaticvoidmain(Stringargs[])
{ First f=new First();
}}
ThesetBounds(intxaxis,int yaxis,intwidth,intheight)methodisused intheaboveexamplethat sets the
position of the awt button.
JavaSwing
Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create window-
based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely
written in java.
UnlikeAWT,JavaSwingprovidesplatform-independentandlightweightcomponents.
The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
JAVAPROGRAMMING Page98
DifferencebetweenAWTand Swing.
CommonlyusedMethodsofComponentclass
Method Description
publicvoidsetSize(intwidth,intheight) setssizeofthecomponent.
JAVAPROGRAMMING Page99
HierarchyofJavaSwingclasses
ThehierarchyofjavaswingAPIis givenbelow.
JavaSwingExamples
Therearetwowaystocreateaframe:
SimpleJavaSwingExample
Let's see a simple swing example where we are creating one button and adding it on the
JFrameobject inside the main() method.
File:FirstSwingExample.java
JAVAPROGRAMMING Page100
importjavax.swing.*;
publicclassFirstSwingExample{
publicstaticvoidmain(String[]args){
JFramef=newJFrame();//creatinginstanceofJFrame
JButtonb=newJButton("click");//creatinginstanceofJButton
b.setBounds(130,100,100, 40);//x axis, y axis, width, height
f.add(b);//adding button in JFrame
f.setSize(400,500);//400widthand500height
f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}}
Containers
JavaJFrame
The javax.swing.JFrame class is a type of container which inherits the java.awt.Frame class.
JFrame works like the main window where components like labels, buttons, textfields are addedto
create a GUI.
Unlike Frame, JFrame has the option to hide or close the window with the help of
setDefaultCloseOperation(int) method.
JFrameExample
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Jpanel;
publicclassJFrameExample{
publicstaticvoidmain(Strings[]){
JFrameframe=newJFrame("JFrameExample");
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
JLabellabel=newJLabel("JFrameByExample");
JButton button = new JButton();
button.setText("Button");
panel.add(label);
JAVAPROGRAMMING Page101
panel.add(button);frame.add(panel)
; frame.setSize(200, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}}
JApplet
AswepreferSwingtoAWT.NowwecanuseJAppletthatcanhaveallthecontrolsofswing. The JApplet
class extends the Applet class.
ExampleofEventHandlinginJApplet:
import java.applet.*;
import javax.swing.*;
importjava.awt.event.*;
publicclassEventJAppletextendsJAppletimplementsActionListener{ JButton
b;
JTextFieldtf;
public void init()
{ tf=newJTextField();
tf.setBounds(30,40,150,20);
b=new JButton("Click");
b.setBounds(80,150,70,40);
add(b);add(tf);
b.addActionListener(this);
setLayout(null);
}
publicvoidactionPerformed(ActionEvente){
tf.setText("Welcome");
}}
In the above example, we have created all the controls in init() method because it is
invokedonly once.
myapplet.html
1. <html>
2. <body>
3. <appletcode="EventJApplet.class"width="300"height="300">
JAVAPROGRAMMING Page102
</applet>
</body>
</html>
JDialog
UnlikeJFrame,itdoesn'thavemaximizeandminimize buttons.
JDialogclassdeclaration
Let'sseethedeclarationforjavax.swing.JDialogclass.
1. publicclassJDialogextendsDialogimplementsWindowConstants,Accessible,RootPaneConta iner
CommonlyusedConstructors:
Constructor Description
JAVAPROGRAMMING Page103
JavaJDialogExample
importjavax.swing.*;
importjava.awt.*;
import java.awt.event.*;
publicclassDialogExample{ p
rivate static JDialog d;
DialogExample() {
JFramef=newJFrame();
d=newJDialog(f,"DialogExample",true);
d.setLayout( new FlowLayout() );
JButton b = new JButton ("OK");
b.addActionListener(newActionListener()
{
publicvoidactionPerformed(ActionEvente)
{
DialogExample.d.setVisible(false);
}
}); Output:
d.add(newJLabel("Clickbuttontocontinue."));
d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
publicstaticvoidmain(Stringargs[])
{
newDialogExample();
}}
JPanel
The JPanel is a simplest container class. It provides space in which an application can attach any
other component. It inherits the JComponents class.
Itdoesn'thavetitlebar.
JAVAPROGRAMMING Page104
JPanelclassdeclaration
1.publicclassJPanelextendsJComponentimplementsAccessible
JavaJPanelExample
importjava.awt.*;
importjavax.swing.*;
publicclassPanelExample{ PanelE
xample()
{
JFramef=newJFrame("PanelExample");
JPanel panel=new JPanel();
panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
JButtonb1=newJButton("Button1");
b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);
JButtonb2=newJButton("Button2");
b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);
panel.add(b1); panel.add(b2);
f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
publicstaticvoidmain(Stringargs[])
{
newPanelExample();
}}
OverviewofsomeSwingComponents Java
JButton
JAVAPROGRAMMING Page105
JButtonclassdeclaration
Let'sseethedeclarationforjavax.swing.JButtonclass.
1.publicclassJButtonextendsAbstractButtonimplementsAccessible
JavaJButtonExample
importjavax.swing.*;
publicclassButtonExample{
public static void main(String[] args)
{ JFramef=newJFrame("ButtonExample");
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);}}
JavaJLabel
The object of JLabel class is a component for placing text in a container. It is used to display a
single line of read only text. The text can be changed by an application but a user cannot edit it
directly. It inherits JComponent class.
JLabelclassdeclaration
Let'sseethedeclarationforjavax.swing.JLabel class.
1.publicclassJLabelextendsJComponentimplementsSwingConstants,Accessible
CommonlyusedConstructors:
Constructor Description
JAVAPROGRAMMING Page106
CommonlyusedMethods:
Methods Description
voidsetText(Stringtext) Itdefinesthesinglelineoftextthiscomponentwill
display.
JavaJLabelExample
importjavax.swing.*;
classLabelExample
{
publicstaticvoidmain(Stringargs[])
{
JFramef=newJFrame("LabelExample");
JLabel l1,l2;
l1=new JLabel("First Label.");
l1.setBounds(50,50, 100,30);
l2=newJLabel("SecondLabel.");
l2.setBounds(50,100, 100,30);
f.add(l1); f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
JAVAPROGRAMMING Page107
JTextField
The object of a JTextField class is a text component that allows the editing of a single line text. It
inherits JTextComponent class.
JTextFieldclassdeclaration
Let'sseethedeclarationforjavax.swing.JTextFieldclass.
1.publicclassJTextFieldextendsJTextComponentimplementsSwingConstants
JavaJTextFieldExample
importjavax.swing.*;
classTextFieldExample
{
publicstaticvoidmain(Stringargs[])
{
JFramef=newJFrame("TextFieldExample");
JTextField t1,t2;
t1=newJTextField("WelcometoJavatpoint.");
t1.setBounds(50,100, 200,30);
t2=newJTextField("AWTTutorial");
t2.setBounds(50,150, 200,30);
f.add(t1); f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
} }
JavaJTextArea
JTextAreaclassdeclaration
Let'sseethedeclarationforjavax.swing.JTextAreaclass.
1. publicclassJTextAreaextendsJTextComponent
JavaJTextAreaExample
JAVAPROGRAMMING Page108
importjavax.swing.*;
publicclassTextAreaExample
{
TextAreaExample(){
JFramef=newJFrame();
JTextAreaarea=newJTextArea("Welcometojavatpoint");
area.setBounds(10,30, 200,200);
f.add(area);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
publicstaticvoidmain(Stringargs[])
{
newTextAreaExample();
}}
SimpleJavaApplications
import
javax.swing.JFrame;importjavax.s
wing.SwingUtilities;
publicclassExampleextendsJFrame{ pub
lic Example() {
setTitle("Simple example");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
publicstaticvoidmain(String[]args)
{ Example ex = new Example();
ex.setVisible(true);
}}
JAVAPROGRAMMING Page109
JAVAPROGRAMMING Page110
LayoutManagement
JavaLayoutManagers
BorderLayout
TheBorderLayoutprovidesfiveconstantsforeach region:
1. publicstaticfinalintNORTH
2. publicstaticfinalint SOUTH
3. publicstaticfinalint EAST
4. publicstaticfinalint WEST
5. publicstaticfinalintCENTER
ConstructorsofBorderLayoutclass:
o BorderLayout():creates aborderlayoutbutwithnogapsbetweenthecomponents.
o JBorderLayout(inthgap,intvgap):createsaborderlayoutwiththegivenhorizontaland vertical
gaps between the components.
ExampleofBorderLayoutclass:
importjava.awt.*; Output:
importjavax.swing.*;
publicclassBorder
{
JFramef;
Border()
{
f=newJFrame();
JButton b1=new JButton("NORTH");;
JButton b2=new JButton("SOUTH");;
JButton b3=new JButton("EAST");;
JButton b4=new JButton("WEST");;
JButtonb5=newJButton("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)
{
newBorder();
}}
JAVAPROGRAMMING Page111
JavaGridLayout
TheGridLayoutisusedtoarrangethecomponentsinrectangulargrid.Onecomponentis displayed in each
rectangle.
ConstructorsofGridLayoutclass
1. GridLayout(): createsagridlayoutwith onecolumnpercomponentinarow.
2. GridLayout(introws,intcolumns): createsagridlayoutwiththegivenrowsandcolumns but
no gaps between the components.
3. GridLayout(introws,intcolumns,inthgap,intvgap): createsagridlayoutwiththe given
rows and columns alongwith given horizontal and vertical gaps.
ExampleofGridLayoutclass
1. importjava.awt.*;
2. import javax.swing.*;
publicclassMyGridLayout{
JFrame f;
MyGridLayout(){
f=newJFrame();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
JButton b6=new JButton("6");
JButton b7=new JButton("7");
JButton b8=new JButton("8");
JButton b9=new JButton("9");
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.add(b6);f.add(b7);f.add(b8);f.add(b9);
f.setLayout(new GridLayout(3,3));
//settinggridlayoutof3rowsand3columns
f.setSize(300,300);
f.setVisible(true);
}
publicstaticvoidmain(String[]args){
newMyGridLayout();}}
JavaFlowLayout
TheFlowLayout is usedto arrangethecomponents in aline, oneafteranother(inaflow). It is the default
layout of applet or panel.
FieldsofFlowLayoutclass
1. publicstaticfinalint LEFT
2. publicstaticfinalint RIGHT
3. publicstaticfinalintCENTER
4. publicstaticfinalintLEADING
5. publicstaticfinalintTRAILING
JAVAPROGRAMMING Page112
ConstructorsofFlowLayoutclass
1. FlowLayout():createsaflowlayoutwithcenteredalignmentandadefault5unit horizontal and
vertical gap.
2. FlowLayout(intalign):createsaflowlayoutwiththegivenalignmentandadefault5 unit
horizontal and vertical gap.
3. FlowLayout(intalign,inthgap,intvgap): createsaflowlayoutwiththegiven alignment and
the given horizontal and vertical gap.
ExampleofFlowLayoutclass
importjava.awt.*;
import
javax.swing.*;publicclassMy
FlowLayout{ JFrame f;
MyFlowLayout(){
f=newJFrame();
JButtonb1=newJButton("1");
JButtonb2=newJButton("2");
JButtonb3=newJButton("3");
JButtonb4=newJButton("4");
JButtonb5=newJButton("5");
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.setLayout(newFlowLayout(FlowLayout.RIGHT));
//settingflowlayoutofrightalignment
f.setSize(300,300);
f.setVisible(true);
}
publicstaticvoidmain(String[]args){
newMyFlowLayout();
}}
EventHandling
EventandListener(JavaEvent Handling)
Changing the state of an object is known as an event. For example, click on button, dragging
mouseetc.Thejava.awt.eventpackageprovidesmanyeventclasses and Listenerinterfaces for
event handling.
TypesofEvent
Foreground Events- Those events which require the direct interaction of user.They are
generated as consequences of a person interacting with the graphical components in
Graphical User Interface. For example, clicking on a button, moving the mouse, entering
a character through keyboard,selecting an item from list, scrolling the page etc.
BackgroundEvents -Thoseeventsthatrequiretheinteractionofenduserareknownas
JAVAPROGRAMMING Page113
backgroundevents.Operatingsysteminterrupts,hardwareorsoftwarefailure,timer expires, an
operation completion are the example of background events.
EventHandling
Event Handling is the mechanism that controls the event and decides what should happen if an
event occurs. This mechanism have the code which is known as event handler that is executed
when an event occurs. Java Uses the Delegation Event Model to handle the events. This model
defines the standard mechanism to generate and handle the events.Let's have a brief introduction
to this model.
TheDelegationEventModelhasthefollowingkeyparticipantsnamely:
Source- The source is an object on which event occurs. Source is responsible for
providing information of the occurred event to it's handler. Java provide as with classes
for source object.
EventclassesandListenerinterfaces:
EventClasses ListenerInterfaces
ActionEvent ActionListener
MouseEvent MouseListenerandMouseMotionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
JAVAPROGRAMMING Page114
StepstoperformEvent Handling
1. ImplementtheListenerinterfaceandoverridesits methods
2. Registerthecomponentwiththe Listener
For registering the component with the Listener, many classes provide the registration
methods.For example:
o Button
o publicvoidaddActionListener(ActionListenera){}
o MenuItem
o publicvoidaddActionListener(ActionListenera){}
o TextField
o publicvoidaddActionListener(ActionListenera){}
o publicvoidaddTextListener(TextListenera){}
o TextArea
o publicvoidaddTextListener(TextListener a){}
o Checkbox
o publicvoidaddItemListener(ItemListenera){}
o Choice
o publicvoidaddItemListener(ItemListenera){}
o List
o publicvoidaddActionListener(ActionListenera){}
o publicvoidaddItemListener(ItemListenera){}
EventHandlingCodes:
Wecan put the event handlingcodeinto oneof thefollowingplaces:
1. Sameclass
2. Otherclass
3. Annonymousclass
Exampleofeventhandlingwithinclass:
importjava.awt.*;
importjava.awt.event.*;
classAEventextendsFrameimplementsActionListener{ Te
xtField tf;
JAVAPROGRAMMING Page115
AEvent(){
tf=new TextField();
tf.setBounds(60,50,170,20);Button
b=newButton("clickme");
b.setBounds(100,120,80,30);
b.addActionListener(this);
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
publicvoidactionPerformed(ActionEvente){
tf.setText("Welcome");
}
publicstaticvoidmain(Stringargs[]){
newAEvent();
}}
publicvoidsetBounds(intxaxis,intyaxis,intwidth,intheight); havebeenusedinthe above
example that sets the position of the component it may be button, textfield etc.
JavaeventhandlingbyimplementingActionListener
importjava.awt.*;
importjava.awt.event.*;
classAEventextendsFrameimplementsActionListener{ Te
xtField tf;
AEvent(){
//createcomponents
tf=newTextField();
tf.setBounds(60,50,170,20);Button
b=newButton("clickme");
b.setBounds(100,120,80,30);
//register listener
b.addActionListener(this);//passingcurrentinstance
//addcomponentsandsetsize,layoutandvisibility
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
publicvoidactionPerformed(ActionEvente){
tf.setText("Welcome");
}
publicstaticvoidmain(Stringargs[]){
newAEvent();
}}
JAVAPROGRAMMING Page116
JavaMouseListenerInterface
The Java MouseListener is notified whenever you change the state of mouse. It is notified against
MouseEvent. The MouseListener interface is found in java.awt.event package. It has fivemethods.
MethodsofMouseListenerinterface
Thesignatureof5methodsfoundinMouseListenerinterface aregivenbelow:
1. publicabstractvoidmouseClicked(MouseEvente);
2. publicabstractvoidmouseEntered(MouseEvent e);
3. publicabstractvoidmouseExited(MouseEvente);
4. publicabstractvoidmousePressed(MouseEvente);
5. publicabstractvoidmouseReleased(MouseEvente);
JavaMouseListenerExample
import java.awt.*;
importjava.awt.event.*;
publicclassMouseListenerExampleextendsFrameimplementsMouseListener{ Lab
el l;
MouseListenerExample()
{ addMouseListener(this);
l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
publicvoidmouseClicked(MouseEvente)
{ l.setText("Mouse Clicked");
}
publicvoidmouseEntered(MouseEvente)
{ l.setText("Mouse Entered");
}
publicvoidmouseExited(MouseEvente)
{ l.setText("Mouse Exited");
}
publicvoidmousePressed(MouseEvente)
{ l.setText("Mouse Pressed");
}
publicvoidmouseReleased(MouseEvente)
{ l.setText("Mouse Released");
}
publicstaticvoidmain(String[]args){ new
MouseListenerExample();
}}
JAVAPROGRAMMING Page117
JavaKeyListenerInterface
TheJavaKeyListenerisnotifiedwheneveryouchangethestateofkey.Itisnotifiedagainst KeyEvent. The
KeyListener interface is found in java.awt.event package. It has three methods.
MethodsofKeyListenerinterface
Thesignatureof3methodsfoundinKeyListenerinterfacearegivenbelow:
1. publicabstractvoidkeyPressed(KeyEvent e);
2. publicabstractvoidkeyReleased(KeyEvent e);
3. publicabstractvoidkeyTyped(KeyEvente);
JavaKeyListenerExample
import java.awt.*;
importjava.awt.event.*;
publicclassKeyListenerExampleextendsFrameimplementsKeyListener{ Label
l;
TextArea area;
KeyListenerExample(){
l=new Label();
l.setBounds(20,50,100,20);
area=new TextArea();
area.setBounds(20,80,300,300);
area.addKeyListener(this);
add(l);add(area);
setSize(400,400);
setLayout(null);setVisible(true);
}
publicvoidkeyPressed(KeyEvente)
{ l.setText("Key Pressed");
}
publicvoidkeyReleased(KeyEvente)
{ l.setText("Key Released");
}
publicvoidkeyTyped(KeyEvente)
{ l.setText("Key Typed");
}
publicstaticvoidmain(String[]args){ new
KeyListenerExample();}}
JavaAdapterClasses
Java adapter classesprovide the default implementation of listener interfaces. If you inherit the
adapter class, you will not be forced to provide the implementation of all the methods of listener
interfaces. So it saves code.
JAVAPROGRAMMING Page118
java.awt.eventAdapterclasses
Adapterclass Listenerinterface
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
JavaWindowAdapterExample
1. importjava.awt.*;
importjava.awt.event.*;
publicclassAdapterExample{
Frame f;AdapterExample(){
f=new Frame("Window Adapter");
f.addWindowListener(newWindowAdapter(){
publicvoidwindowClosing(WindowEvente){
f.dispose(); } });
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
publicstaticvoidmain(String[]args){
newAdapterExample();
}}
JAVAPROGRAMMING Page119
Applets
AdvantageofApplet
Therearemanyadvantages ofapplet. Theyareasfollows:
o Itworksatclientsidesolessresponsetime.
o Secured
o Itcanbeexecutedbybrowsersrunningundermanyplateforms,includingLinux, Windows, Mac
Os etc.
Drawbackof Applet
o Pluginisrequiredat clientbrowsertoexecute applet.
LifecycleofJavaApplet HierarchyofApplet
1. Appletisinitialized.
2. Appletisstarted.
3. Appletispainted.
4. Appletisstopped.
5. Appletisdestroyed.
LifecyclemethodsforApplet:
The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1
lifecycle methods for an applet.
java.applet.Appletclass
Forcreatinganyappletjava.applet.Appletclassmustbeinherited.Itprovides4lifecyclemethods of
applet.
1. publicvoidinit():isusedtoinitializedtheApplet. Itisinvokedonlyonce.
2. public void start():is invoked after the init() method or browser is maximized. It is used
to start the Applet.
3. publicvoidstop():isusedtostoptheApplet.ItisinvokedwhenAppletisstopor browser is
minimized.
4. publicvoiddestroy():isusedtodestroytheApplet. Itisinvokedonlyonce.
JAVAPROGRAMMING Page120
java.awt.Componentclass
SimpleexampleofAppletbyhtmlfile:
To execute the applet by html file, create an applet and compile it. After that create an html file
and place the applet code in html file. Now click the html file.
1.//First.java
importjava.applet.Applet;
importjava.awt.Graphics;
publicclassFirstextends Applet{
public void paint(Graphics g){
g.drawString("welcome",150,150);
}
}
SimpleexampleofAppletbyappletviewertool:
To execute the applet by appletviewer tool, create an applet that contains applet tag in comment
and compile it. After that run it by: appletviewer First.java. Now Html file is not required but it is
for testing purpose only.
1.//First.java
importjava.applet.Applet;
importjava.awt.Graphics;
publicclassFirstextendsApplet{
public void paint(Graphics g)
{ g.drawString("welcometoapplet",150,150)
;
}
}
/*
<appletcode="First.class"width="300"height="300">
</applet>
*/
JAVAPROGRAMMING Page121
JAVAPROGRAMMING Page122
Toexecutetheappletbyappletviewertool,write incommandprompt:
c:\>javacFirst.java
DifferencebetweenAppletandApplicationprogramming
c:\>appletviewerFirst.java
JAVAPROGRAMMING Page123
Parameterin Applet
We cangetany informationfromthe HTML file asa parameter.For thispurpose,Appletclass provides a
method named getParameter(). Syntax:
1. publicStringgetParameter(StringparameterName)
ExampleofusingparameterinApplet:
1. importjava.applet.Applet;
2. importjava.awt.Graphics;
3. publicclassUseParamextendsApplet
4. {
5. publicvoidpaint(Graphicsg)
6. {
7. Stringstr=getParameter("msg");
8. g.drawString(str,50,50);
9. }}
myapplet.html
1. <html>
2. <body>
3. <appletcode="UseParam.class"width="300"height="300">
4. <paramname="msg"value="Welcometo applet">
5. </applet>
6. </body>
7. </html>
JAVAPROGRAMMING Page124