0% found this document useful (0 votes)
2 views108 pages

Introduction to Java Programming Basics

Java is a high-level, object-oriented programming language known for its platform independence, security, and robustness. It supports various applications including desktop, web, mobile, and enterprise applications, and follows the principle of 'Write Once, Run Anywhere'. Key features include multithreading, dynamic memory management, and a strong emphasis on error checking, making it suitable for a wide range of programming tasks.

Uploaded by

trail3299
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views108 pages

Introduction to Java Programming Basics

Java is a high-level, object-oriented programming language known for its platform independence, security, and robustness. It supports various applications including desktop, web, mobile, and enterprise applications, and follows the principle of 'Write Once, Run Anywhere'. Key features include multithreading, dynamic memory management, and a strong emphasis on error checking, making it suitable for a wide range of programming tasks.

Uploaded by

trail3299
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT–I

I. INTRODUCTIONTOJAVA

WhatisJava

JavaisahighLevel programming language and it is also called as


[Link] secured and robust high level object-
orientedprogramminglanguage.

Platform:Anysoftwareorhardwareenvironmentinwhichaprogramrunsisknown
as a platform. Java has its own runtime environment (JRE)
andAPIsojavaisalsocalledasplatform.

Java fallows the concept of Write Once, Run

[Link]

1. DesktopApplications
2. WebApplications
3. Mobile
4. EnterpriseApplications
5. SmartCard
6. EmbeddedSystem
7. Games
8. Roboticsetc

HistoryofJava

JamesGosling,PatrickNaughtonandMikeSheridaninitiatedtheJavalanguag
[Link],embedded
systems in electronic appliances like set-top boxes. Initially it
wascalled"Greentalk"lateritwascalledOak.

Java is an open source software produced by Sunmicro system under


thetermsoftheGNUGeneralPublicLicense(GPL).
FeaturesofJava:

 Object Oriented – Java implements basic concepts of Object


orientedprogrammingSystem(OOPS)ieObject,Class,Inheritance,Poly
morphism, Abstraction, Encapsulation. In Java, everything is
[Link]
l.
 PlatformIndependent−Unlikemanyotherprogramminglanguagesincludi
ngCandC++,whenJavaiscompiled,itisnotcompiledintoplatform specific
machine, rather into platform independent byte
[Link] and interpreted by
theVirtualMachine(JVM)onwhicheverplatformitisbeingrunon.
 Simple–JavafallowsthebasicSyntaxofC,C++.Ifyouunderstandthebas
icconceptofOOPSthenitiseasytomasterinjava.
 Secure − With Java's secure feature it enables to develop virus-
free,tamper-free systems. Authentication techniques are based on
public-keyencryption.
 Architecture-neutral−Javacompiler generates an architecture-
neutralobjectfileformat,which makes the compiled code
executableonmanyprocessors,withthepresenceofJavaruntimesystem.
 Portable − Being architecture-neutral and having no
implementationdependent aspects of the specification makes Java
portable. Compilerin Java is written in ANSI C with a clean
portability boundary, whichisaPOSIXsubset.
 Robust − Java makes an effort to eliminate error prone situations
byemphasizingmainlyoncompiletimeerrorcheckingandruntimecheck
ing.
 Multithreaded−WithJava'smultithreadedfeature In java we
canwriteprogramsthatcanperformmany tasks simultaneously.
Thisdesignfeatureallowsthedevelopers to construct
interactiveapplicationsthatcanrunsmoothly.
 Interpreted−Javabytecodeistranslatedonthefly to nativemachine
instructions and is not stored anywhere. The
developmentprocessismorerapidandanalyticalsincethelinkingisanin
crementalandlight-weightprocess.
 HighPerformance−WiththeuseofJust-In-
Timecompilers,Javaenableshighperformance.
 Distributed − Java is designed for the distributed environment of
theinternet.
 Dynamic−Javaisconsideredtobemoredynamicthan C or
C++[Link]
programscancarryextensiveamountofrun-time information
thatcanbeusedtoverifyandresolveaccessestoobjectsonrun-time.

ObjectOrientedProgrammingSystem(OOPS)

Objectmeansarealwordentitysuchaspen,chair,tableetc. Object-Oriented
Programming is a methodology or paradigm to design a
[Link]
maintenancebyprovidingsomeconcepts:

 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation

If any language fallows the OOPS concepts that language we call it as


objectorientedlanguage

ProceduretowritesimplejavaProgram

TowriteajavaprogramFirstwehaveinstall theJDK.

Tocreateasimplejavaprogram,youneed to create a class that


[Link]'sunderstandtherequirementfirst.

 installtheJDKandinstallit.
 setpathofthejdk
 createthejavaprogram
 compile andrunthejavaprogram

SettingUpthePathforWindows

AssumingyouhaveinstalledJavainc:\Program Files\java\jdkdirectory−

 Right-clickon'MyComputer'andselect'Properties'.
 Clickthe 'Environmentvariables' buttonunderthe 'Advanced'tab.
 Now, alter the 'Path' variable so that it also contains the path to
[Link],ifthepathiscurrentlysetto'C:\WINDOWS\
SYSTEM32',thenchangeyourpathtoread'C:\WINDOWS\SYSTEM32;c:
\ProgramFiles\java\jdk\bin'.
SettingUpthePathforLinux,UNIX,Solaris,FreeBSD

EnvironmentvariablePATHshouldbesettopointtowherethe Javabinaries
have been installed. Refer to your shell documentation, if you
[Link], then
youwouldaddthefollowinglinetotheendofyour'.bashrc:exportPATH=
/path/to/java:$PATH'

PopularJavaEditors

 Notepad−OnWindowsmachine,youcanuseanysimpletexteditorlikeNote
pad(Recommendedforthistutorial),TextPad.
 Netbeans − A JavaIDE that is open-source and free which can
bedownloaded from Eclipse − A Java IDE developed by the eclipse
open-sourcecommunityandcanbedownloadedfrom

JVM(JavaVirtualMachine)

JVM(JavaVirtual Machine)[Link]
isaspecificationthatprovidesruntime environment in which java bytecode
can be
[Link]([Link]
splatformdependent).

WhatisJVM

Itis:

1. Aspecificationwhereworking of Java Virtual Machine is


[Link] to choose the
[Link]
s.
2. AnimplementationItsimplementationisknownasJRE(JavaRuntimeE
nvironment).
3. RuntimeInstanceWheneveryouwritejavacommandonthecommandpr
ompttorunthejavaclass,aninstanceofJVMiscreated.

Whatitdoes

TheJVMperformsfollowingoperation:

 Loadscode
 Verifiescode
 Executescode
 ProvidesruntimeenvironmentJ

VMprovidesdefinitionsforthe:

 Memoryarea
 Classfileformat
 Registerset
 Garbage-collectedheap
 Fatalerrorreportingetc.

JAVAVIRTUALMACHINE

Java’sMagic:TheBytecodeoutputofaJava compiler is not


[Link],[Link]
ructions designed to be executed by the Java run-time system, which
iscalledtheJavaVirtualMachine(JVM).

Java complier translates thejava source code into byte code or


intermediatecode,[Link] convert
intoexecutablecodecorrespondingtoOperatingsystem

Becauseoftheabovefeaturejavaisportable

II. CLASS,OBJECTANDMETHODS

Java program is a collection of objects that communicate via invoking


eachother'[Link],object,methods,andinsta
ncevariables.
Class−Aclasscanbedefinedasatemplate/blueprintthatdescribesthebehavior/statethat
theobjectofitstypesupports.

[Link]
finitionisshownhere:

classclassname

typeinstance-variable1;typeinstance-variable2;

// ... type instance-

variableN;typemethodname1(para

meter-list)

{//bodyofmethod}

typemethodname2(parameter-list)

{//bodyofmethod}

//...typemethodnameN(parameter-list)

{//bodyofmethod}}

The data, or variables, defined within a class are called instance


[Link],themethodsand
variables defined within a class are called members of the class. In
mostclasses, the instance variables are acted upon and accessed by the
methodsdefinedforthatclass

SimpleClass

ClassSample

intlen,

floathtvoidget()

{ //body
} }

HereaclassSamplecontainstwovariable len andht

ObjectinJava

Objectisthephysicalaswellaslogicalentitywhereasclassisthelogicalentityonl
y.

Anobjecthasthreecharacteristics:

 state:representsdata(value)ofanobject.
 behavior: represents the behavior (functionality) of an object such
asdeposit,withdrawetc.
 identity: Object identity is typically implemented via a unique ID.
ThevalueoftheIDisnotvisibletotheexternal user. But, it is
usedinternallybytheJVMtoidentifyeachobjectuniquely.

Objectisaninstanceof a class. Class is a template or blueprint


[Link](result)ofaclass.

ObjectDefinitions:

 Objectisarealworldentity. Objectisaruntimeentity.
 Objectisanentitywhichhasstateandbehavior.
 Objectisaninstanceofaclass.

Samples=newSample() heresisanobjectfortheclassSample

newoperatorisusedtocreateanobject

Methods−[Link].
It is in methods where the logics are written, data is
manipulatedandalltheactionsareexecuted.

Let'screatetheSimplejavaprogram:

1. classSample{
2. publicstaticvoidmain(Stringargs[]){
3. [Link]("Howareyou ");4. }
5.}

[Link]
Tocompile: [Link]

Toexecute: javaSample

JavaIdentifiers

[Link],variables,andme
thodsarecalledidentifiers.

InJava,[Link]
ws−

 Allidentifiersshouldbeginwithaletter(AtoZoratoz),currencycharacter($)o
ranunderscore(_).
 Afterthefirstcharacter,identifierscanhaveanycombinationofcharacte
rs.
 Akeywordcannotbeusedasanidentifier.
 Mostimportantly, identifiersarecasesensitive.
 Examplesoflegalidentifiers:age,$salary,_value, 1_value.
 Examplesofillegalidentifiers:123abc,-salary.

JavaModifiers:Therearetwocategoriesofmodifiers−

 Access Modifiers−default,public,protected,private
 Non-accessModifiers− final,abstract, strictfp

IIIDATATYPES

TherearetwodatatypesavailableinJava−

 PrimitiveDataTypes
 NonPrimitiveTypes
PrimitiveDataTypes

[Link]
efinedbythelanguageandnamedby a keyword. Let us now
lookintotheeightprimitivedatatypesindetail.

byte

 Bytedatatypeisan8-bitsignedtwo'scomplementinteger
 Minimumvalueis-128(-2^7)
 Maximumvalueis127(inclusive)(2^7-1)
 Defaultvalueis0
 Bytedatatypeisusedtosavespaceinlargearrays,mainlyinplaceofintege
rs,sinceabyteisfourtimessmallerthananinteger.
 Example:bytea=100,byteb=-50

short

 Shortdatatypeisa16-bitsignedtwo'scomplementinteger
 Minimumvalueis-32,768(-2^15)
 Maximumvalueis32,767(inclusive)(2^15-1)
 Shortdatatypecanalsobeusedtosavememoryasbytedatatype.Ashortis2t
imessmallerthananinteger
 Defaultvalueis0.
 Example:shorts=10000,shortr=-20000
int

 Intdatatypeisa32-bitsignedtwo'scomplementinteger.
 Minimumvalue is- 2,147,483,648 (-2^31)
 Maximumvalueis2,147,483,647(inclusive)(2^31-1)
 Integerisgenerallyusedasthedefaultdatatypeforintegralvaluesunlessthe
reisaconcernaboutmemory.
 Thedefaultvalueis0
 Example:inta=100000,intb=-200000

long

 Longdatatypeisa64-bitsignedtwo'scomplementinteger
 Minimumvalueis-9,223,372,036,854,775,808(-2^63)
 Maximumvalueis9,223,372,036,854,775,807(inclusive)(2^63-1)
 Thistypeisusedwhenawiderrangethanintisneeded
 Defaultvalueis0L
 Example:longa=100000L,longb=-200000L

float

 Floatdatatypeisasingle-precision32-bitIEEE754floatingpoint
 Floatismainlyusedtosavememoryinlargearraysoffloatingpointnumbers
 Defaultvalueis0.0f
 Floatdatatypeisneverusedforprecisevaluessuchascurrency
 Example:floatf1=234.5f

double

 doubledatatypeisadouble-precision64-bitIEEE754floatingpoint
 Thisdatatypeisgenerallyusedasthedefaultdatatypefordecimalvalues,ge
nerallythedefaultchoice
 Doubledatatypeshouldneverbeusedforprecisevaluessuchascurrency
 Defaultvalueis0.0d
 Example:doubled1=123.4

boolean

 booleandatatyperepresentsonebitofinformation
 Thereareonlytwopossiblevalues:trueandfalse
 Thisdatatypeisusedforsimpleflagsthattracktrue/falseconditions
 Defaultvalueisfalse
 Example:booleanone=true

char

 chardatatypeisasingle16-bitUnicodecharacter
 Minimumvalueis'\u0000'(or0)
 Maximumvalueis'\uffff'(or65,535inclusive)
 Chardatatypeisusedtostoreanycharacter
 Example:charletterA='A'

JavaLiterals

[Link] can
beassignedtoanyprimitivetypevariable.

bytea=68; chara='A'

byte,int,long,andshortcanbeexpressedindecimal(base10),hexadecimal(base1
6)oroctal(base8)numbersystemsaswell.

Prefix 0 is used to indicate octal, and prefix 0x indicates hexadecimal


[Link]−

intdecimal=100; intoctal=0144; inthexa= 0x64;

String literals in Java are specified like they are in most other languages
[Link]
esofstringliteralsare−

Example
"HelloWorld" "two\nlines" "\"Thisisinquotes\""

[Link]
e− chara='\u0001'; Stringa="\u0001";

JavalanguagesupportsfewspecialescapesequencesforStringandchar

Notation Characterrepresented

\n Newline(0x0a)

\r Carriagereturn(0x0d)

\f Formfeed(0x0c)

\b Backspace(0x08)

\s Space(0x20)

\t Tab

\" Doublequote
\' Singlequote

\\ Backslash

\ddd Octalcharacter(ddd)

\uxxxx HexadecimalUNICODEcharacter(xxxx)

JavaVariableExample:AddTwoNumbers

1. classSample{
2. publicstaticvoidmain(String[]args){
3. inti=50;
4. intj=60;
5. intk=a+b;
6. [Link](k);7.
}}

JavaVariableExample:Widening

1. classSample{
2. publicstaticvoidmain(String[]args){
3. intj=10;
4. floatk=a;
5. [Link](i);
6. [Link](j);7.}}

UnicodeSystem
Unicodeisauniversalinternationalstandardcharacterencodingthatiscapableo
frepresentingmostoftheworld'swrittenlanguages.

Before Unicode,there weremany language standards:

 ASCII(AmericanStandardCodeforInformationInterchange)fortheUnited
States.
 ISO8859-1 forWesternEuropean Language.
 KOI-8forRussian.
 GB18030andBIG-5forchinese,andsoon.
JavaTokens

Java Tokens are the smallest individual building block or smallest unit of
aJava program, it is used by the Java compiler for constructing
[Link]
ns,comments,andwhitespaces.
JavaSupportsFiveTypesofTokens:

 ReservedKeywords Identifiers Literals


 Operators Separators

JavaKeywordscannotbeusedasavariablename.

Abstrac Assert boolean break


t
Byte Case catch char
Class Const continu default
e
Do Double else enum
extends Final finally float
For Goto if implements
Import Instanceof int interface
Long Native new package
private Protected public return
Short Static strictfp super
Switch synchronized this throw
throws Transient try void
volatile While true false
Null

Variable

[Link],itisa
name ofmemory location. It is a combination of "vary + able" that
meansitsvaluecanbechanged.

Therearethreetypesofvariablesinjava:

 localvariable
 instancevariable
 static variable
1) LocalVariable

A variablewhichisdeclaredinsidethemethod iscalled localvariable.

2) InstanceVariable

Avariablewhichisdeclaredinsidetheclassbutoutsidethemethod,iscalle
[Link].

3) Staticvariable

[Link].

Wewillhavedetailedlearningofthesevariablesinnextchapters.

IVOPERATORS&IF,Switch,loopStatementsOperatorsinj

ava

[Link]:+,
-,*,/etc.

Therearemanytypesofoperatorsinjavawhicharegivenbelow:

 UnaryOperator,
 ArithmeticOperator,
 shiftOperator,
 RelationalOperator,
 BitwiseOperator,
 LogicalOperator,
 TernaryOperatorand
 AssignmentOperator.
JavaIf-elseStatement

[Link]:tr
[Link].

 ifstatement if-elsestatement
 if-else-ifladder nestedifstatement

JavaIFStatement

[Link].
Thefollowingisthesyntax

1. if(condition){
2. //codetobeexecuted3.}

1. public class Example {


2. publicstaticvoidmain(String[]args){
3. intk=35;
4. if(k>18){ [Link]("Hello");5. }
}}

IF-elseStatement

Theif-
[Link]
eotherwiseelseblockisexecuted.

Syntax:

1. if(condition){
2. //codeifconditionistrue
3. }else{
4. //codeifconditionis false5.}

public class Sample {


publicstaticvoidmain(String[]args){intn=
23;
if(number%2==0){[Link]
ntln("even");
}else{
[Link]("odd");
} }
}
IF-else-ifladderStatement

The if-else-if ladder statement executes one condition from


multiplestatements.

Syntax:

1. if(condition1){
2. //codetobeexecutedifcondition1istrue
3. }elseif(condition2){
4. //codetobeexecutedifcondition2istrue5.}
6. elseif(condition3){
7. //codetobeexecutedifcondition3istrue8.}
9....
10. else{
11. //codetobeexecutedifalltheconditionsarefalse
12. }

1. public class Simple {


2. publicstaticvoidmain(String[]args){
3. intmarks=70;
4.
5. if(marks<40){
6. [Link]("FAIL"); 7. }
8. elseif(marks>=40&&marks<50){
9. [Link]("Dgrade");
10. }
11. elseif(marks>=50&&marks<60){
12. [Link]("Cgrade");
13. }
14. elseif(marks>=60&&marks<70){
15. [Link]("Bgrade");
16. }
17. elseif(marks>=70&&marks<80){
18. [Link]("Agrade");
19. }elseif(marks>=80&&marks<100){
20. [Link]("A+grade");
21. }else{
22. [Link]("Invalid!");
23. }
24. }
25. }
SwitchStatement

The switch statement in java executes one statement from


[Link]-else-ifladderstatement.

Syntax:

1. switch(expression){
2. casevalue1:
3. //codetobeexecuted;
4. break;//optional
5. casevalue2:
6. //codetobeexecuted;
7. break;//optional8.
......
9.
10. default:
11. codetobeexecutedifallcasesarenotmatched;
12. }

Example:

1. public class Sample {


2. publicstaticvoidmain(String[]args){
3. intk=20;
4. switch(k){
5. case10: [Link]("10");break;
6. case20: [Link]("20");break;
7. case30: [Link]("30");break;
8. default:[Link]("Notin 10, 20 or 30");9. } }
10. }

JavaForLoop

[Link]
fiterationisfixed,itisrecommendedtouseforloop.

Therearethreetypesofforloopinjava.

 SimpleForLoop
 For-eachorEnhancedForLoop
 LabeledForLoop
JavaSimpleForLoop

ThesimpleforloopissameasC/C++.Wecaninitializevariable,checkcondition
andincrement/decrementvalue.

Syntax:

1. for(initialization;condition;incr/decr){
2. //codetobeexecuted3.}

Example:

1. public class Sample {


2. publicstaticvoidmain(String[] args) {3.
for(inti=1;i<=20;i++){
4. [Link](i);5.
}
6. }
7. }

JavaWhileLoop

[Link]
rofiterationisnotfixed,itisrecommendedtousewhileloop.

Syntax:

1. while(condition){
2. //codetobeexecuted3.}

1. public class Sample {


2. publicstaticvoidmain(String[]args){
3. intj=1;
4. while(j<=10){
5.
[Link](j);6.
j++;
7. }
8.}}

Javado-whileLoop

TheJavado-
[Link]
onisnotfixedandyoumusthavetoexecutetheloopatleastonce,itisrecommended
[Link]-
whileloopisexecutedatleastoncebecauseconditionischeckedafterloopbody.
Syntax:do{ /codetobeexecuted

}while(condition);

public class Example {

publicstaticvoidmain(String[]args){intj

=1;

do{

[Link](j);j++;

}while(j<=10);

}}

JavaBreakStatement

[Link]
flow of the program at specified condition. In case of inner loop,
itbreaksonlyinnerloop.

Example:

1. public class Simple {


2. publicstaticvoidmain(String[] args) {3.
for(inti=1;i<=10;i++){
4. if(i==5){
5. break;
6. }
7. [Link](i);8.
}
9.}
10. }

JavaContinueStatement

[Link]
thecurrentflowoftheprogramandskipstheremainingcodeatspecifiedconditi
[Link],itcontinuesonlyinnerloop.

Example:

1. public class Sample {


2. publicstaticvoidmain(String[]args){3.
for(intk=1;k<=10;k++){
4. if(k==5){
5.
continue;6. }
7.
[Link](k);8.}
9.}
10. }

VARRAYS&COMMENTSinJAVA

Arrayinjava

Arrayisgroupofelementsofsimilartypesoccupyingcontiguousmemorylocati
ons

AdvantageofJavaArray

 CodeOptimization Random access

DisadvantageofJavaArrayisithasfixedsizeitcannotgrowTherea

retwotypesofarrayinjava.

 SingleDimensional Array
 MultidimensionalArray

SingleDimensionalArrayinjavaSyntax
toDeclareanArrayinjava

1. datatype[]arrayname(or)
2. datatype[]arrayname;(or)
3. datatypearrayname[];

Arrayinitializationinjava

[Link]=newdatatype[size];

Example

Let'sseethesimpleexampleofjavaarray,wherewearegoingtodeclare,instantiate,
initializeandtraverseanarray.
1. classTestarray{
2. publicstaticvoidmain(Stringargs[]){
3. int a[]=new int[5];//declaration and instantiation4.
a[0]=10; a[1]=20; a[2]=70; a[3]=40;a[4]=50;
5. for(inti=0;i<[Link];i++)//lengthisthepropertyofarray
6. [Link](a[i]);7.
}}

Declaration,InstantiationandInitializationofJavaArray

We candeclare, instantiateandinitializethejavaarray togetherby:

[Link][]={33,3,4,5};//declaration,instantiationandinitializationLet'ss

eethesimpleexampletoprintthisarray.

1. classTestarray1{
2. publicstaticvoidmain(Stringargs[]){3.
[Link][]={33,3,4,5};//declaration,instantiationandinitialization5.
6. //printingarray
7. for(inti=0;i<[Link];i++)//lengthisthepropertyofarray
8. [Link](a[i]);
9.
10. }}

Multidimensionalarrayinjava

Insuchcase,dataisstoredinrowandcolumnbasedindex(alsoknownasmatrixf
orm).

SyntaxtoDeclareMultidimensionalArrayinjava

1. dataType[][]arrayRefVar;(or) dataType[][]arrayRefVar;(or)
2. dataTypearrayRefVar[][];(or) dataType []arrayRefVar[];

ExampletoinstantiateMultidimensionalArrayinjava

[Link][][]arr=newint[3][3];//3rowand3column

ExampletoinitializeMultidimensionalArrayinjava

[Link][0][0]=1;
[Link][0][1]=2;
[Link][0][2]=3;
[Link][1][0]=4;
[Link][1][1]=5;
[Link][1][2]=6;
[Link][2][0]=7;
[Link][2][1]=8;
[Link][2][2]=9;

ExampleofMultidimensionaljavaarray

Let's see the simple example to declare, instantiate, initialize and print
the2Dimensionalarray.

1. classEx{
2. publicstaticvoidmain(Stringargs[]){3.
4.//[Link]
arr[][]={{1,2,3},{2,4,5},{4,4,5}};
6.
7.//printing2Darray8.f
or(int i=0;i<3;i++){9.
for(intj=0;j<3;j++){
10. [Link](arr[i][j]+"");
11. }
12. [Link]();
13. }
14. } }

JavaComments

Thejavacommentsare statements that are not executed by the


[Link]
anationaboutthe variable, method, class or any statement. It can
alsobeusedtohideprogramcodeforspecifictime.

TypesofJavaComments

Thereare3typesofcommentsinjava.

1. SingleLineComment
2. MultiLineComment
3. DocumentationComment

1) JavaSingleLineComment

Thesinglelinecommentisusedtocommentonlyoneline.

Syntax:

1. //Thisissinglelinecomment
Example:

1. publicclassSample{
2. publicstaticvoidmain(String[]args){
3. intj=10;//Here,iisavariable
4. [Link](j);5.}
6.}

2) JavaMultiLineComment

Themultilinecommentisusedtocommentmultiplelinesofcode.

Syntax:

1./*
2. This
3. is
4. multiline
5. comment
6.*/

Example:

1. public class CommentExample2 {


2. publicstaticvoidmain(String[]args){
3. /*Let's declare and
4. printvariableinjava.*/
5. intj=10;
6. [Link](j);7.}
8.}

3) JavaDocumentationComment

Thedocumentationcomment is used tocreate documentation API. To


createdocumentationAPI,youneedtousejavadoctool.

Syntax:

1./**
2. This
3. is
4. documentation
5. comment
6.*/

VICONSTRUCTORS

Constructorisspecialmemberfunction,ithasthesame name as
[Link]
atedfortheobject.

Itisaspecialtypeofmethodwhichisusedtoinitializetheobject

Rulesforcreatingjavaconstructor

Therearebasicallytworulesdefinedfortheconstructor.

1. Constructornamemustbesameasitsclassname
2. Constructormusthavenoexplicitreturntype

Typesofjavaconstructors

Therearetwotypesofconstructorsinjava:

1. Defaultconstructor(no-argconstructor)
2. Parameterizedconstructor

Aconstructoriscalled"DefaultConstructor"whenitdoesn'thaveanyparameter.

classSample{Sa
mple()
{
[Link]("Sampleiscreated");
}
publicstaticvoidmain(Stringargs[])
{
Sampleb=newSample();
} }

A constructor which has a specific number of parameters is


calledparameterizedconstructor.
1. classStudent4{
2. intid;
3. Stringname;
4. Student4(inti,Stringn){
5. id=i;
6. name=n;
7. }
8. voiddisplay(){[Link](id+""+name);}9.
10. publicstaticvoidmain(Stringargs[]){
11. Student4s1=newStudent4(111,"Karan");
12. Student4s2=newStudent4(222,"Aryan");
13. [Link]();
14. [Link]();
15. }
16. }

Differencebetweenconstructorandmethodinjava

Therearemanydifferencesbetweenconstructors and methods. They


aregivenbelow.

JavaConstructor JavaMethod
Constructorisusedtoinitializethestateofano Methodisusedtoexposebehavio
bject. urofanobject.
Method must have
Constructormustnothavereturntype.
returntype.
Constructorisinvokedimplicitly. Methodisinvokedexplicitly.
Thejavacompilerprovidesadefaultconstruct
Methodisnotprovidedbyco
orifyoudon'thaveanyconstructor.
mpilerinanycase.
Constructornamemustbesameastheclassn Methodnamemayormaynotbe
ame. sameasclassname.

Javastatickeyword

The static keyword in java is used for memory management mainly. We


canapply java static keyword with variables, methods, blocks and nested
[Link].

Thestaticcanbe:

1. variable(alsoknownasclassvariable)
2. method(alsoknownasclassmethod)
3. block
4. nestedclass

1) Javastaticvariable

Ifyoudeclareanyvariableasstatic,itisknownstaticvariable.

 Thestaticvariablecanbeusedtoreferthecommonpropertyof
allobjects(thatisnotuniqueforeachobject)[Link]
es,collegenameofstudentsetc.
 The static variable gets memory only once in class area at the time
ofclassloading.

Advantageofstaticvariable:Itmakesyourprogrammemoryefficient
([Link]).
classStud{in
trollno;Strin
gname;
staticStringcollege="ITS";Stud(i
ntr,Stringn){
rollno=r;name
=n;
}
voiddisplay(){[Link](rollno+""+name+""+college);}

publicstaticvoidmain(Stringargs[]){St
uds1=newStud(11,"Krishna");Studs2
=newStud(22,"Rama");[Link]();
[Link]();
} }

2) Javastaticmethod

Ifyouapplystatickeywordwithanymethod,itisknownasstaticmethod.

 Astaticmethodbelongstotheclassratherthanobjectofaclass.
 Astaticmethodcanbeinvokedwithouttheneedforcreatinganinstanceo
faclass.
 staticmethodcanaccessstaticdatamemberandcanchangethevalueof
it.

Exampleofstaticmethod
1.//Programofchangingthecommonpropertyofallobjects(staticfield).

2.
3. classStud{
4. introllno;
5. Stringname;
6. staticStringcollege="BEC";7.
8. staticvoidchange(){
9. college="JBIEIT";
10. }
11. Stud(intr,Stringn){
12. rollno=r;
13. name=n;
14. }
15.
16. voiddisplay(){[Link](rollno+""+name+""+college
);}
17. publicstaticvoidmain(Stringargs[]){
18. [Link]();
19. Studs1=newStud(11,"Kiran");
20. Studs2=newStud(22,"Arjun");
21. Studs3=newStud(33,"srinu");
22. [Link]();
23. [Link]();
24. [Link]();
25. }
26. }

thiskeywordinjava

[Link],thisisareferencevariablet
hatreferstothecurrentobject.

Usageofjavathiskeyword

Hereisgiventhe6usageofjavathiskeyword.

1. thiscanbeusedtorefercurrentclassinstancevariable.
2. thiscanbeusedto invokecurrentclassmethod(implicitly)
3. this()canbeusedtoinvokecurrentclassconstructor.
4. thiscanbepassedasanargumentinthemethodcall.
5. thiscanbepassedasargumentintheconstructorcall.
6. thiscanbeusedtoreturnthecurrentclassinstancefromthemethod.

1) this:torefercurrentclassinstancevariable
[Link]
mbiguitybetweentheinstancevariablesandparameters,thiskeywordresolve
stheproblemofambiguity.

classStudent
{introllno;Stri
ngname;float
fee;
Student(introllno,Stringname,floatfee){[Link]
o=rollno;
[Link]=nam
e;[Link]=fee;
}
voiddisplay(){[Link](rollno+""+name+""+fee);}
}
classTestThis2{
public static void main(String
args[]){Students1=newStudent(111,"ankit",50
00f);Students2=newStudent(112,"sumit",600
0f);[Link]();
[Link](); }}
2) this:toinvokecurrentclassmethod

[Link] you
don't use the this keyword, compiler automatically adds this
keywordwhileinvokingthemethod

1. classB{
2. void m(){[Link]("hello m");}
3. voidn(){
4. [Link]("hellon");
5. //m();//sameasthis.m()
6. this.m();
7. }
8. }
9. classTestThis4{
10. publicstaticvoidmain(Stringargs[]){
11. Bb=newB();
12. b.n();
13. }}

3) this():toinvokecurrentclassconstructor

Thethis()constructorcallcanbeusedtoinvokethecurrentclassconstructor. It
is used to reuse the constructor. In other words, it is used
forconstructorchaining.
Callingdefaultconstructorfromparameterizedconstructor:

1. classB{
2. B(){[Link]("hello ");}
3. B(intx){
4. this();
5. [Link](x);6.}
7.}
8. classSample{
9. publicstaticvoidmain(Stringargs[]){
10. Ba=newB(10);
11. }}

1. classStudent{
2. introllno;
3. Stringname,course;
4. floatfee;
5. Student(introllno,Stringname,Stringcourse){
6. [Link]=rollno;
7. [Link]=name;
8. [Link]=course;
9.}
10. Student(introllno,Stringname,Stringcourse,floatfee){
11. this(rollno,name,course);//reusing constructor
12. [Link]=fee;
13. }
14. voiddisplay(){[Link](rollno+""+name+""+course+""
+fee);}
15. }
16. classSamplTest{
17. publicstaticvoidmain(Stringargs[]){
18. Students1=newStudent(111,"ankit","java");
19. Students2=newStudent(112,"sumit","java",6000f);
20. [Link]();
21. [Link]();
22. }}

4) this:topassasanargumentinthemethod

[Link]
[Link]'sseetheexample:

1. classS2{
2. voidm(S2obj){
3. [Link]("method is invoked");4.
}
5. voidp(){
6. m(this);
7. }
8. publicstaticvoidmain(Stringargs[]){9.
S2s1=newS2();
10. s1.p();
11. }
12. }

5) this:topassasargumentintheconstructorcall

[Link]
[Link]'sseetheexample:

1. classB{
2. A4obj;
3. B(A4obj){
4. [Link]=obj;
5. }
6. voiddisplay(){
7. [Link]([Link]);//usingdatamember of A4 class8.
}
9.}
10.
11. classA4{
12. intdata=10;
13. A4(){
14. Bb=newB(this);
15. [Link]();
16. }
17. publicstaticvoidmain(Stringargs[]){
18. A4a=newA4();
19. }
20. }

6) thiskeywordcanbeusedtoreturncurrentclassinstance

We can return this keyword as an statement from the method. In such


case,returntypeofthemethodmustbetheclasstype(non-
primitive).Let'sseetheexample:

Syntaxofthisthatcanbereturnedasastatement

1. return_typemethod_name(){
2. returnthis;3.
}
Exampleofthiskeywordthatyoureturnasastatementfromthem
ethod

1. classA{
2. AgetA(){
3. returnthis;4.
}
5. void msg(){[Link]("Hello java");}6.}
7. classTest1{
8. publicstaticvoidmain(Stringargs[]){
9. newA().getA().msg();
10. }
11. }
UNIT-II

[Link]

Inheritance can be defined as the procedure or mechanism of acquiring


allthepropertiesandbehaviorofoneclasstoanother,[Link]
s and behavior of child class from the parent class. This conceptwas built
in order to achieve the advantage of creating a new class that getsbuilt
upon an already existing class(es). It is mainly used for code
reusabilitywithin a Java program. The class that gets inherited taking the
properties ofanother class is the subclass or derived class or child class.
Again, the
classwhosepropertiesgetinheritedisthesuperclassorbaseclassor
parentclass. The keyword extends is used to inherit the properties of the
baseclass to derived class. The structure of using this keyword looks
somethinglikethis:

classbase
{
.....
.....
}
class deriveextendsbase
{
.....
.....
}
classPerson{voi
dteach(){
[Link]("Teaching subjects");
}}

classPersonextendsTeacher{void
listen(){
[Link]("Listeningtoteacher");
}}

class CheckForInheritance {
publicstaticvoidmain(Stringargs[]){Person
s1=newStudents();
[Link]();
[Link]();
}
}

Inthistypeofinheritance,aderivedclassgetscreatedfromanotherderivedclas
sandcanhaveanynumberoflevels.

classTeacher{voi
dteach(){
[Link]("Teaching subject");
}
}
classStudentextendsTeacher{voidl
isten(){
[Link]("Listening");
}
}
class homeTution extends Student
{void explains()
{[Link]("Doeshomework");
}
}
class CheckForInheritance {
publicstaticvoidmain(Stringargu[]){homeT
utionh=newhimeTution();[Link]();
[Link]();
[Link]();
}
}

Inthistypeofinheritance,therearemorethan1derivedclasseswhichgetcreate
dfromonesinglebaseclass.

classTeacher{voi
dteach(){
[Link]("Teaching subject");
}
}
classStudentextendsTeacher{voidli
sten(){[Link]("Listenin
g");
}
}
classPrincipalextendsTeacher
{void
evaluate(){[Link]("Ev
aluating");
}
}
class CheckForInheritance {
publicstaticvoidmain(Stringargu[]){Princi
palp=newPrincipal();[Link]();
[Link]();
//[Link]();willproduceanerror
}
}

Letusimaginea situationwherethere arethree classes: A, B and C. The


[Link] case, class A and class B have a
methodwithsamenameandtypeandasaprogrammer,youhavetocallthat
method from child class's (C) object, there-there will be ambiguity as
whichmethodwillbecalledeitherofAorofBclass.

SoJavareducesthishecticsituationby the use of interfaces


whichimplementsthisconcept and reduce this problem; as compile-time
errorsaretolerablethanruntimefaultsintheprogram.

VIIIPolymorphism

Thewordpolymorphismmeanshavingmultipleforms. The
termPolymorphismgetsderivedfromtheGreek word where poly +
morphoswherepolymeansmanyandmorphosmeansforms.

Polymorphism is another special feature of object-oriented


programming(OOPs). The approach which lies beneath this concept is
"single interfacewith multiple implementations." This offers a single
interface for controllingaccesstoageneralclassofactions.

Polymorphismcanbeachievedintwoofthefollowingways:

 MethodOverloading(CompiletimePolymorphism)
 MethodOverriding(RuntimePolymorphism)

 Static Polymorphism is in other words termed as compile-time


bindingorearlybinding.
 Static binding occurs at compile time. Method overloading is a case
ofstatic binding and in this case binding of method call to its
definitionhappensatthetimeofcompilation.

 TocallanoverloadedmethodinJava,itismustusethetypeand/orthenum
berofargumentstodeterminewhichversionoftheoverloadedmethodto
actuallycall.
 The overloaded methods may have varied return types and the
returntypesingle-
handedlyisinsufficienttomakeouttwoversionsofamethod.
 AsandwhenJavacompilerencountersacallto an
overloadedmethod,itsimplyexecutestheversionofthemethodwhosep
arametersmatchtheargumentsusedinthecall.
 Itpermitstheusertoobtaincompiletimepolymorphismwithnamemethodn
ame.
 Anoverloadedmethodisabletothrowdifferentkindsofexceptions.
 Amethodwhichisoverloadedcancontaindifferentaccessmodifiers.

Overloadingmethod'sargumentlistsmightdifferin:

 Numberofparameterspassed
 Datatypeofactualparameters
 Sequenceofdatatypeofactualparameters
classMltply{
void mul(int a,int
b){[Link]("Sumoftwo="+(a*b));
}

voidmul(inta,intb,intc){[Link]("Sumof
three="+(a*b*c));
}
}
classPolymorphism{
publicstaticvoidmain(Stringargs[]){Mltply
m=newMltply();
[Link](6,10);
[Link](10,6,5);
}}

Rulestomethodoverriding

 Argumentlist:Theargumentlistat the time of overriding


methodneedtobesameasthatofthemethodof the parent class. The
datatypesoftheargumentsalongwiththeirsequencemusthavetobepreser
vedasitisintheoverridingmethod.
 AccessModifier:TheAccess Modifier present in the
overridingmethod(methodofsubclass) cannot be more restrictive
than that ofanoverriddenmethodoftheparentclass.
 Theprivate,staticandfinalmethodscan'tbeoverridden as they
arelocaltotheclass.
 Anymethodwhichisoverridingisabletothrowanyuncheckedexception
s, in spite of whether the overridden method usually
methodofparentclassmightthrowanexceptionornot.

//methodoverridingclas
sparent{
publicvoidwork(){
[Link]("Parentisunderretirementfromwork.");
}
}
classchildextendsparent{pu
blicvoidwork(){
[Link]("Childhasajob");[Link].
println("Heisdoingitwell");
}
publicstaticvoidmain(Stringargu[]){childc1
=newchild();
[Link]();
}}
Advantageofmethodoverriding

Onemajoradvantageofmethodoverridingisthataclasscangiveitsownspecificex
ecutiontoaninheritedmethodwithouthavingthemodificationintheparentclass(b
aseclass).

superkeywordinjava

Thesuperkeywordinjavaisareferencevariablewhichisusedtoreferimmediatepa
rentclassobject.

Whenever you create the instance of subclass, an instance of parent class


iscreatedimplicitlywhichisreferredbysuperreferencevariable.

UsageofjavasuperKeyword

1. supercanbeusedtoreferimmediateparentclassinstancevariable.
2. supercanbeusedtoinvokeimmediateparentclassmethod.
3. super()canbeusedto invoke immediate parentclassconstructor.

1) superisusedtoreferimmediateparentclassinstancevariable.

Wecanusesuperkeywordtoaccess the data member or field of


[Link].

1. classAnimal{
2. Stringcolor="white";3.}
4. classDogextendsAnimal{
5. Stringcolor="black";
6. voidprintColor(){
7. [Link](color);//printscolorofDogclass
8. [Link]([Link]);//printscolorof Animal
class9.}
10. }
11. classTestSuper1{
12. publicstaticvoidmain(Stringargs[]){
13. Dogd=newDog();
14. [Link]();
15. }}

2) supercanbeusedtoinvokeparentclassmethod
Thesuperkeywordcanalso be used to invoke parent class method.
Itshouldbeusedifsubclass contains the same method as parent class.
Inotherwords,itisusedifmethodisoverridden.

1. classAnimal{
2. void
eat(){[Link]("eating...");}3.}
4. classDogextendsAnimal{
5. voideat(){[Link]("eatingbread...");}
6. voidbark(){[Link]("barking...");}
7. voidwork(){
8. [Link]();
9. bark();
10. }
11. }
12. classTestSuper2{
13. publicstaticvoidmain(Stringargs[]){
14. Dogd=newDog();
15. [Link]();
16. }}

3) superisusedtoinvokeparentclassconstructor.

The super keyword can also be used to invoke the parent class
[Link]'sseeasimpleexample:

1. classAnimal{
2. Animal(){[Link]("animal is created");}3.}
4. classDogextendsAnimal{
5. Dog(){
6. super();
7. [Link]("dog is
created");8.}
9.}
10. classTestSuper3{
11. publicstaticvoidmain(Stringargs[]){
12. Dogd=newDog();
13. }}

1. classPerson{
2. intid;
3. Stringname;
4. Person(intid,Stringname){
5. [Link]=id;
6. [Link]=nam
e;
7. }
8. }
9. classEmpextendsPerson{
10. floatsalary;
11. Emp(intid,Stringname,floatsalary){
12. super(id,name);//reusing parent constructor
13. [Link]=salary;
14. }
15. voiddisplay(){[Link](id+""+name+""+salary);}
16. }
17. classTestSuper5{
18. publicstaticvoidmain(String[]args){
19. Empe1=newEmp(1,"ankit",45000f);
20. [Link]();
21. }}

MethodOverloadinginJava

Ifaclasshasmultiplemethodshavingsamenamebutdifferentinparameters,iti
sknownasMethodOverloading.

Advantageofmethodoverloading

Methodoverloadingincreasesthereadabilityoftheprogram.

Differentwaystooverloadthemethod

Therearetwowaystooverloadthemethodinjava

1. Bychangingnumberofarguments
2. Bychangingthedatatype

1) MethodOverloading:[Link]

In this example, we have created two methods, first add() method


performsaddition of two numbers and second add method performs addition
of threenumbers.

In this example, we are creating static methods so that we don't need


tocreateinstanceforcallingmethods.

1. classAdder{
2. staticintadd(inta,intb){returna+b;}
3. staticintadd(inta,intb,intc){returna+b+c;}4.}
5. classTestOverloading1{
6. publicstaticvoidmain(String[]args){
7. [Link]([Link](11,11));
8. [Link]([Link](11,11,11));
9.}}

2) MethodOverloading:changingdatatypeofarguments

In this example, we have created two methods that differs in data type.
Thefirst add method receives two integer arguments and second add
methodreceivestwodoublearguments.

1. classAdder{
2. staticintadd(inta,intb){returna+b;}
3. staticdoubleadd(doublea,doubleb){returna+b;}4.}
5. classTestOverloading2{
6. publicstaticvoidmain(String[]args){
7. [Link]([Link](11,11));
8. [Link]([Link](12.3,12.6));
9.}}

MethodOverridinginJava

Ifsubclass(child class) has the same method as declared in the


parentclass,itisknownasmethodoverridinginjava.

Inotherwords,Ifsubclassprovides the specific implementation of


themethodthathasbeenprovidedbyoneofitsparentclass,it is known
asmethodoverriding.

UsageofJavaMethodOverriding

 Methodoverridingisusedtoprovidespecificimplementationofamethodth
atisalreadyprovidedbyitssuperclass.
 MethodoverridingisusedforruntimepolymorphismRul

esforJavaMethodOverriding

1. methodmusthavesamenameasintheparentclass
2. methodmusthavesameparameterasintheparentclass.
3. mustbeIS-Arelationship(inheritance).
1. classVehicle{
2. void run(){[Link]("Vehicle is running");}3.}
4. classBike2extendsVehicle{
5. voidrun(){[Link]("Bikeisrunningsafely");}6.
7. publicstaticvoidmain(Stringargs[]){
8. Bike2obj=newBike2();
9. [Link]();
10. }

IXABSTRACTION

AbstractioninJava

Abstractionisaprocessofhidingtheimplementation details and


showingonlyfunctionalitytotheuser.

Anotherway,itshowsonlyimportantthingstotheuserandhidestheinternal
details for example sending sms, you just type the text and send
[Link]'tknowtheinternalprocessingaboutthe
messagedelivery.

Abstraction letsyoufocusonwhattheobject doesinsteadofhowitdoesit.

WaystoachieveAbstraction

Therearetwowaystoachieveabstractioninjava

1. Abstractclass(0to100%)
2. Interface(100%)

AbstractclassinJava

[Link]
[Link].

Exampleabstractclass

1. abstractclassA{}

abstractmethod
Amethodthatisdeclaredasabstractanddoesnothaveimplementationis
knownasabstractmethod.

Exampleabstractmethod

[Link]();//nobodyandabstract

Exampleofabstractclassthathasabstractmethod

Inthisexample,Biketheabstractclassthatcontainsonlyoneabstractmethodr
[Link].

1. abstractclassBike{
2. abstractvoidrun();3.}
4. classHonda4extendsBike{
5. voidrun(){[Link]("runningsafely..");}
6. publicstaticvoidmain(Stringargs[]){
7. Bikeobj=newHonda4();
8. [Link]();
9.}
10. }

1. abstractclassShape{
2. abstractvoiddraw();3.}
4. //Inrealscenario,implementationis provided by others i.e.
unknownbyenduser
5. classRectangleextendsShape{
6. void draw(){[Link]("drawing
rectangle");}7.}
8. classCircle1extendsShape{
9. void draw(){[Link]("drawing circle");}
10. }
11. //Inrealscenario,methodiscalledbyprogrammeroruser
12. classTestAbstraction1{
13. publicstaticvoidmain(Stringargs[]){
14. Shapes=newCircle1();//Inrealscenario,objectisprovidedthroughm
[Link]()method
15. [Link]();
16. }
17. }
InterfaceinJava

An interface in java is a blueprint of a class. It has static constants


andabstractmethods.

The interface in java is a mechanism to achieve abstraction. There can


beonly abstract methods in the java interface not method body. It is used
toachieveabstractionandmultipleinheritanceinJava.

Java Interface also represents IS-A

[Link]

[Link]?

[Link].

 Itisusedtoachieveabstraction.
 Byinterface,wecansupportthefunctionalityofmultipleinheritance.
 Itcanbeusedtoachieveloosecoupling

JavaInterfaceExample

Inthisexample,Printableinterfacehasonlyonemethod,itsimplementationisp
rovidedintheAclass.

1. interfaceprintable{
2. voidprint();
3.}
4. classA6implementsprintable{
5. public voidprint(){[Link]("Hello");}6.
7. publicstaticvoidmain(Stringargs[]){
8. A6obj=newA6();
9. [Link]();
10. }
11. }

Differencesbetweenabstractclassandinterfacethataregivenbelow.

Abstractclass Interface
1)Abstractclasscanhaveabstract Interface can have only abstract
andnon-abstractmethods. methods.SinceJava8,itcan have default
andstaticmethodsalso.
2)Abstractclassdoesn'tsupportmu
Interfacesupportsmultipleinheritance.
ltipleinheritance.
3)Abstract class canhave final, Interface has only static and final
non-final,staticandnon- variables.
staticvariables.
4)Abstractclasscanprovidetheimp Interface can't provide
lementationofinterface. theimplementationofabstractclass.
5)Theabstractkeywordisusedtod Theinterfacekeywordisusedtodeclareinterfa
eclareabstractclass. ce.
6)Example: Example:
public abstract class public interface
Shape{public abstract Drawable{void draw();
void draw(); }
}

1. interfaceA{
2. voida();voidb();
3. voidc(); voidd();
4.}
5. abstractclassBimplementsA{
6. publicvoid c(){[Link]("I am c");}7.}
8. classMextendsB{
9. publicvoida(){[Link]("Iama");}
10. public voidb(){[Link]("Iamb");}
11. publicvoidd(){[Link]("Iamd");}
12. }
13. classTest5{
14. publicstaticvoidmain(Stringargs[]){
15. Aa=newM();
16. a.a();
17. a.b();
18. a.c();
19. a.d();
20. }}

XPACKAGE

Ajavapackageisagroupofsimilartypesofclasses,interfacesandsub-
packages.

Packageinjavacanbecategorizedintwoform,built-inpackageanduser-
definedpackage.

Therearemanybuilt-
inpackagessuchasjava,lang,awt,javax,swing,net,io,util,sqletc.

Here,wewillhavethedetailedlearningofcreatingandusinguser-definedpackages.
AdvantageofJavaPackage

1) Javapackageisusedtocategorizetheclassesandinterfacessothattheycan
beeasilymaintained.

2) Javapackageprovidesaccessprotection.

3) Javapackageremovesnamingcollision.

Simpleexampleofjavapackage

Thepackagekeywordis used tocreate a package injava.

1. //[Link]
2. packagemypack;
3. publicclassSimple{
4. publicstaticvoidmain(Stringargs[]){
5. [Link]("Welcome to package");6.
}
7.}

Howtocompilejavapackage

If youare not usingany IDE,you need tofollow thesyntaxgivenbelow:

[Link]-

ddirectoryjavafilenameForexample

[Link]-d. [Link]

The -d switch specifies the destination where to put the generated class
[Link]/home(incaseofLinux),d:/abc(incaseo
fwindows)[Link],youcan
use.(dot).

Howtoaccesspackagefromanotherpackage?

Thereare threewaysto access thepackagefromoutsidethepackage.

1. importpackage.*;
2. [Link];
3. fullyqualifiedname.

1) Usingpackagename.*

Ifyouusepackage.*thenalltheclassesandinterfacesofthispackagewillbeacc
essiblebutnotsubpackages.
Theimportkeywordisusedtomaketheclassesandinterfaceofanotherpackag
eaccessibletothecurrentpackage.

Exampleofpackagethatimportthepackagename.*

1. //[Link]
2. packagepack;
3. publicclassA{
4. public void msg(){[Link]("Hello");}5.}

1. //[Link]
2. packagemypack;
3. importpack.*;
4.
5. classB{
6. publicstaticvoidmain(Stringargs[]){
7. Aobj=newA();
8. [Link]();
9. }
10. }

2) [Link]

[Link]
eaccessible.

[Link]

1. //[Link]
2.
3. packagepack;
4. publicclassA{
5. public void msg(){[Link]("Hello");}6.}

1. //[Link]
2. packagemypack;
3. importpack.A;
4.
5. classB{
6. publicstaticvoidmain(Stringargs[]){
7. Aobj=newA();
8. [Link]();
9. }
10. }
3) Usingfullyqualifiedname

Ifyouusefullyqualifiednamethenonlydeclaredclassofthispackagewillbeaccessi
[Link] use
fullyqualifiednameeverytimewhenyouareaccessingtheclassorinterface.

It is generally used when two packages have same class name e.g.
[Link].

Exampleofpackagebyimportfullyqualifiedname

1. //[Link]
2. packagepack;
3. publicclassA{
4. public void msg(){[Link]("Hello");}5.}
6.

1. //[Link]
2. packagemypack;
3. classB{
4. publicstaticvoidmain(Stringargs[]){
5. [Link]=newpack.A();//usingfullyqualifiedname
6. [Link]();
7. }
8.}

AccessModifiersinjava

There are two types of modifiers in java: access modifiers and non-
accessmodifiers.

The access modifiers in java specifies accessibility (scope) of a data


member,method,constructororclass.

Thereare4typesofjavaaccessmodifiers:

1. private
2. default
3. protected
4. public
Understandingalljavaaccessmodifiers

Access within withinpa outside package outside


Modifier class ckage bysubclassonly package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

[Link]

AstringisasequenceofcharacterinJava,widelyusedasanobject.

In java, string is basically an object that represents sequence of char


[Link]:

[Link][]ch={'j','a','v','a','t','p','o','i','n','t'};
[Link]=newString(ch);is

sameas:

[Link]="javatpoint";

JavaStringclassprovidesalotofmethodstoperformoperationsonstringsuch as
compare(), concat(), equals(), split(), length(), replace(),
compareTo(),intern(),substring()etc.

WhatisStringinjava

Generally, string is a sequence of characters. But in java, string is an


[Link]
edtocreatestringobject.

HowtocreateStringobject?
TherearetwowaystocreateStringobject:

1. Bystringliteral
2. Bynewkeyword
1) StringLiteral

[Link]:

[Link]="welcome";

Eachtimeyoucreateastringliteral,theJVMchecksthestringconstantpool first.
If the string already exists in the pool, a reference to the pooledinstance is
returned. If string doesn't exist in the pool, a new string
[Link]:

1. Strings1="Welcome";
2. Strings2="Welcome";//willnotcreatenewinstance

2) Bynewkeyword

[Link]=newString("Welcome");//createstwoobjectsandonereferencevari
able

1. publicclassStringExample{
2. publicstaticvoidmain(Stringargs[]){
3. Strings1="java";//[Link]
arch[]={'s','t','r','i','n','g','s'};
5. Strings2=newString(ch);//convertingchararraytostring
6. Strings3=newString("example");//creatingjavastringbynewkeyword
7. [Link](s1);
8. [Link](s2);
9. [Link](s3);10.
}}

JavaStringclassmethods

[Link]
sonsequenceofcharvalues.

No. Method Description

returnscharvalueforthepartic
1 charcharAt(intindex)
ularindex

2 intlength() returnsstringlength

staticStringformat(Stringformat,Object...a
3 returnsformattedstring
rgs)
staticStringformat(Localel,Stringformat,O returns formatted
4
bject...args) stringwithgivenlocale

returnssubstringforgivenbe
5 Stringsubstring(intbeginIndex)
ginindex

String substring(int beginIndex, returnssubstringforgivenbe


6
intendIndex) ginindexandendindex

returnstrueorfalseaftermatc
7 booleancontains(CharSequences) hingthesequenceofcharvalu
e

staticStringjoin(CharSequencedelimiter,C
8 returnsajoinedstring
harSequence...elements)

static String join(CharSequence


9 delimiter,Iterable<? extends returnsajoinedstring
CharSequence>elements)

checksthe equalityof
10 booleanequals(Objectanother)
stringwithobject

11 booleanisEmpty() checksifstringisempty

12 Stringconcat(Stringstr) concatinatesspecifiedstring

replacesalloccurrencesofsp
13 Stringreplace(charold,charnew)
ecifiedcharvalue

String replace(CharSequence replacesalloccurrencesofsp


14
old,CharSequencenew) ecifiedCharSequence

static String [Link]


15
equalsIgnoreCase(Stringanother) oesn'tcheckcase.

returns splitted
16 String[]split(Stringregex)
stringmatchingregex

returns splitted
17 String[]split(Stringregex,intlimit)
stringmatchingregexandlimi
t
18 Stringintern() returnsinterned string
returnsspecifiedcharvaluein
19 intindexOf(intch)
dex

returnsspecifiedcharvalueind
20 intindexOf(intch,intfromIndex) exstartingwithgivenindex

returns specified
21 intindexOf(Stringsubstring)
substringindex

returnsspecifiedsubstringind
int indexOf(String substring,
22 exstartingwithgivenindex
intfromIndex)

23 StringtoLowerCase() returnsstringinlowercase.

returnsstringinlowercaseusi
24 String toLowerCase(Locale l)
ngspecifiedlocale.

25 StringtoUpperCase() returnsstringinuppercase.

returnsstringinuppercaseus
26 String toUpperCase(Locale l)
ingspecifiedlocale.

removes beginning
27 Stringtrim()
andendingspacesofthisstri
ng.
converts given type
28 staticStringvalueOf(intvalue)
[Link].

public class Sample {

publicstaticvoid
main(Stringargs[]){char[]nameArray={'A',
'l','e','x'};
Stringname=newString(nameArray);Sy
[Link](name);
}}

concat()[Link]

classSample{

publicstaticvoid
main(Stringargs[]){Stringstr1="Hello",
str2="World!";[Link](str1.
concat(str2));
}
}

+operatorismorecommonlyusedtoattachstrings."Hello,"

+"world"+"!"

JavatoUpperCase()andtoLowerCase()methodisusedtochange stringcase.

public class Sample {

publicstaticvoid
main(Stringargs[]){Stringstr1="Hello";S
[Link]([Link]());
[Link]([Link]());
}
}

Javatrim()methodisusedtoeliminateswhitespacesbeforeandafterastring.

public class Sample {

publicstaticvoidmain(Stringargs[]){Strin
gstr=
"Hello";[Link]([Link]());
}
}

Javalength()[Link]

Sample{

publicstaticvoidmain(Stringargs[]){Strin
gstr="Cloud";[Link]([Link]
ngth());
}
}

JavaStringcompare

Wecancomparestringinjavaonthebasisofcontentandreference.

Itisusedinauthentication(byequals()method),sorting(bycompareTo()meth
od),referencematching(by==operator)etc.

Therearethreewaystocomparestringinjava:
1. Byequals()method
2. By==operator
3. BycompareTo()method

1) Stringcomparebyequals()method

TheStringequals()[Link]
[Link]:

 publicbooleanequals(Objectanother)comparesthisstringtothespecifie
dobject.
 publicbooleanequalsIgnoreCase(Stringanother)comparesthisStringto
anotherstring,ignoringcase.

1. classTeststringcomparison1{
2. publicstaticvoidmain(Stringargs[]){
3. Strings1="Sachin";
4. Strings2="Sachin";
5. Strings3=newString("Sachin");
6. Strings4="Saurav";
7. [Link]([Link](s2));//true
8. [Link]([Link](s3));//true
9. [Link]([Link](s4));//false
10. }
11. }

2) Stringcompareby==operator

The==operatorcomparesreferencesnotvalues.

1. classTeststringcomparison3{
2. publicstaticvoidmain(Stringargs[]){
3. Strings1="Sachin";
4. Strings2="Sachin";
5. Strings3=newString("Sachin");
6. [Link](s1==s2);//true(becausebothrefertosameinstance)
7.
[Link](s1==s3);//false(becauses3referstoinstancecreated
innonpool)
8. }
9.}
3) StringcomparebycompareTo()method

TheStringcompareTo()methodcomparesvalueslexicographicallyandreturn
s an integer value that describes if first string is less than, equal to
orgreaterthansecondstring.

[Link]:

 s1==s2:0
 s1>s2 :positivevalue
 s1<s2 :negativevalue

1. classTeststringcomparison4{
2. publicstaticvoidmain(Stringargs[]){
3. Strings1="Sachin";
4. Strings2="Sachin";
5. Strings3="Ratan";
6. [Link]([Link](s2));//0
7. [Link]([Link](s3));//1(becauses1>s3)
8. [Link]([Link](s1));//-1(because s3 < s1 )9. }
10. }

StringConcatenationinJava

In java, string concatenation forms a new string that is the combination


[Link]:

1. By+(stringconcatenation)operator
2. Byconcat()method

1) StringConcatenationby+(stringconcatenation)operator

Javastringconcatenationoperator(+)[Link]:

1. classTestStringConcatenation1{
2. publicstaticvoidmain(Stringargs[]){
3. Strings="Sachin"+"Tendulkar";
4. [Link](s);//Sachin Tendulkar5. }
6.}

2) StringConcatenationbyconcat()method

TheStringconcat()methodconcatenatesthespecifiedstringtotheendofcurre
[Link]:
[Link](Stringanother)

Let'sseetheexampleofStringconcat()method.

1. classTestStringConcatenation3{
2. publicstaticvoidmain(Stringargs[]){
3. Strings1="Sachin";
4. Strings2="Tendulkar";
5. Strings3=[Link](s2);
6. [Link](s3);//Sachin Tendulkar7.
}}

SubstringinJava

A part of string is called substring. In other words, substring is a subset


ofanother string. In case of substring startIndex is inclusive and endIndex
[Link]:Indexstartsfrom0.

Youcangetsubstringfromthegivenstringobjectbyoneofthetwomethods:

1. publicStringsubstring(intstartIndex):Thismethodreturns
newStringobjectcontaining the substring of the given string
fromspecifiedstartIndex(inclusive).
2. publicStringsubstring(intstartIndex,intendIndex):Thismethodreturnsne
wStringobjectcontainingthesubstringofthegivenstringfromspecifiedstar
tIndextoendIndex.

Incaseofstring:

 startIndex:inclusive endIndex:exclusive

Let'sunderstandthestartIndexandendIndexbythecodegivenbelow.

1. Strings="hello";
2. [Link]([Link](0,2));//he

In the above substring, 0 points to h but 2 points to e (because end index


isexclusive).

Exampleofjavasubstring

1. publicclassTestSubstring{
2. publicstaticvoidmain(Stringargs[]){
3. Strings="SachinTendulkar";
4. [Link]([Link](6));//Tendulkar
5. [Link]([Link](0,6));//Sachin
6. }
7. }

StringTokenizerinJava

[Link]
[Link].

Itdoesn'tprovidethefacilitytodifferentiatenumbers,quoted
strings,[Link]
mTokenizerclassinI/Ochapter.

ConstructorsofStringTokenizerclass

There are 3 constructors defined in the StringTokenizer

classThereare3constructorsdefinedintheStringTokenizerclass.

Constructor Description

StringTokenizer(Stringstr) createsStringTokenizerwithspecifiedstring.

StringTokenizer(String createsStringTokenizerwithspecified
str,Stringdelim) stringanddelimeter.

createsStringTokenizerwithspecifiedstring,deli
StringTokenizer(Stringstr,St [Link] istrue,
ringdelim,booleanreturnVal delimiter characters are considered to
ue) [Link],delimitercharactersserve
toseparatetokens.

MethodsofStringTokenizerclass

The6usefulmethodsofStringTokenizerclassareasfollows:

Publicmethod Description

booleanhasMoreTokens() checksifthereismoretokensavailable.
returns the next token from
StringnextToken()
theStringTokenizerobject.

String
returnsthenexttokenbasedonthedelimeter.
nextToken(Stringdelim)

booleanhasMoreElements() sameashasMoreTokens()method.

sameasnextToken()butitsreturntype isObject.
ObjectnextElement()

intcountTokens() returnsthetotalnumberoftokens.

1. import [Link];
2. publicclassSimple{
3. publicstaticvoidmain(Stringargs[]){
4. StringTokenizerst=newStringTokenizer("mynameiskhan","");
5. while([Link]()){
6. [Link]([Link]()); 7. }
8. }
9.}

Example of nextToken(String delim) method


ofStringTokenizerclass

1. [Link].*;
2.
3. publicclassTest{
4. publicstaticvoidmain(String[]args){
5. StringTokenizerst=newStringTokenizer("my,name,is,khan");6.
7. //printingnexttoken
8. [Link]("Nexttokenis:"+[Link](","));9. }
10. }

XIIJAVAI/OTUTORIAL

JavaI/O(InputandOutput)isusedtoprocesstheinputandproducetheoutput.

JavausestheconceptofstreamtomakeI/[Link]
containsalltheclassesrequiredforinputandoutputoperations.

WecanperformfilehandlinginjavabyJavaI/OAPI.
Stream

[Link]'scall
edastreambecauseitislikeastreamofwaterthatcontinuestoflow.

Injava,[Link]
dwithconsole.

1) [Link]:standardoutputstream

2) [Link]:standardinputstream

3) [Link]:standarderrorstream

ByteBased CharacterBased
Input Output Input Output
Reader Writer
Basic InputStream OutputStream InputStreamReader Output
S

Arrays ByteArrayInputStream ByteArrayOutputStream CharArrayReader CharArr


FileInputStream FileOutputStream
Files RandomAccessFile RandomAccessFile FileReader FileWrite
Pipes PipedInputStream PipedOutputStream PipedReader PipedWr
Buffering BufferedInputStream BufferedOutputStream BufferedReader Buffered
Filtering FilterInputStream FilterOutputStream FilterReader FilterWri
PushbackInputStream PushbackReader
Parsing StreamTokenizer LineNumberReader
Strings StringReader StringW
Data DataInputStream DataOutputStream
Data–For
matted PrintStream PrintWri
Objects ObjectInputStream ObjectOutputStream
U ili i S I S
Byte Streams Java byte streams are used to perform input and output of
8-bit bytes. Though there are many classes related to byte streams but
themostfrequentlyusedclassesare,FileInputStreamandFileOutputStream.F
ollowing is an example which makes use of these two classes to copy
aninputfileintoanoutputfile:

import

[Link].*;publicclassC

opyFile{

publicstaticvoidmain(Stringargs[])throwsIOException

{
FileInputStream

in=null;FileOutputStreamout

=null;try{

in=newFileInputStream("[Link]");out=

newFileOutputStream("[Link]");

intc;

while((c=[Link]())!=-

1){[Link](c);

}finally{

if(in!=null){

[Link]();

if(out!=null){[Link]

ose();

} }

CharacterStreamsJavaBytestreamsareusedtoperforminputandoutputof8-
bitbytes,whereasJavaCharacterstreamsareusedtoperforminputand output
for 16-bit unicode. Though there are many classes related tocharacter
streams but the most frequently used classes are, FileReader
[Link]
erusesFileOutputStreambutherethemajordifferenceisthatFileReader reads
two bytes at a time and FileWriter writes two bytes at atime.

import

[Link].*;publicclassC

opyFile{

publicstaticvoidmain(Stringargs[])throwsIOException
{

FileReaderin=null;File

Writerout=null;try{

in=newFileReader("[Link]");out=

newFileWriter("[Link]");intc;

while((c=[Link]())!=-

1){[Link](c);

}finally{

if(in!=null){

[Link]();

if(out!=null){

[Link](); } } } }

[Link].*;

public class ReadConsole {

publicstaticvoidmain(Stringargs[])throwsIOException

InputStreamReadercin=null;try{

cin=newInputStreamReader([Link]);[Link]("Ente

rcharacters,'q'toquit.");
charc;do

c=(char)[Link]();

[Link](c);

}while(c!='q');

}finally{

if(cin!=null)

{[Link]();

JavaBufferedInputStreamClass

[Link]
rnallyusesbuffermechanismtomaketheperformancefast.

1. [Link].*;
2. publicclassBufferedInputStreamExample{
3. publicstaticvoidmain(Stringargs[]){
4. try{
5. FileInputStream fin=new FileInputStream("D:\\[Link]");
6. BufferedInputStreambin=newBufferedInputStream(fin);
7. inti;
8. while((i=[Link]())!=-1){
9. [Link]((char)i);
10. }
11. [Link]();
12. [Link]();
13. }catch(Exceptione){[Link](e);}
14. }
15. }
UNITIII

XIIIEXCEPTIONHANDLINGINJAVA

Theexception handling injavaisoneofthepowerfulmechanismtohandlethe


runtime errors so that normal flow of the application can be
[Link]
nismtohandleruntimeerrors
HierarchyofJavaExceptionclasses

TypesofException

Therearemainlytwotypesofexceptions: checked and unchecked


[Link]
earethreetypesofexceptions:

1. CheckedException
2. UncheckedException
3. Error

Differencebetweencheckedanduncheckedexceptions
1) CheckedException
The classes that extend Throwable class except RuntimeException and
[Link],SQLExceptionetc.
Checkedexceptionsarecheckedatcompile-time.

2) UncheckedException

TheclassesthatextendRuntimeExceptionareknownasuncheckedexception
[Link],NullPointerException,ArrayIndexOutOfBoundsEx
ception etc. Unchecked exceptions are notcheckedatcompile-
timerathertheyarecheckedatruntime.

3) Error

[Link],VirtualMachineError,Assertion
Erroretc.

Java Exception Handling Keywords

Thereare5keywordsusedinjavaexceptionhandling.

1. Try catch finally throwthrows

Javatry-

catchJavatryblo

ck

[Link]
eusedwithinthemethod.

[Link]

avatry-catch

1. try{
2. //codethatmaythrowexception
3. }catch(Exception_class_Name ref){}

1. publicclassTesttrycatch2{
2. publicstaticvoidmain(Stringargs[]){
3. try{
4. intdata=50/0;
5. }catch(ArithmeticExceptione){[Link](e);}
6. [Link]("restofthecode...");7.}
8.}
JavaMulticatchblock

IfyouhavetoperformdifferenttasksattheoccurrenceofdifferentExceptions,usej
avamulticatchblock.

Let'sseeasimpleexampleofjavamulti-catchblock.

1. publicclassTestMultipleCatchBlock{
2. publicstaticvoidmain(Stringargs[]){
3. try{
4. inta[]=newint[5];5.
a[5]=30/0;
6. }
7.
catch(ArithmeticExceptione){[Link]("task1iscompleted");}
8. catch(ArrayIndexOutOfBoundsException
e){[Link]("task2completed");}
9. catch(Exceptione){[Link]("commontask
completed");}10.
11. [Link]("restofthecode...");
12. }
13. }

Javafinallyblock

Javafinallyblockisablockthatisusedtoexecuteimportantcodesuchasclosin
gconnection,streametc.

[Link]

yblockfollowstryorcatchblock.

Whyusejavafinally

 Finallyblockinjavacanbeusedtoput"cleanup"codesuchasclosi
ngafile,closingconnectionetc.

Case1

Let'sseethejavafinallyexamplewhereexceptiondoesn'toccur.

1. classTestFinallyBlock{
2. publicstaticvoidmain(Stringargs[]){
3. try{
4. intdata=25/5;
5. [Link](data);6. }
7. catch(NullPointerExceptione){[Link](e);}
8. finally{[Link]("finallyblockisalwaysexecuted");}
9. [Link]("restofthecode...");
10. }
11. }

Case3

Let'sseethejavafinallyexamplewhereexceptionoccursandhandled.

1. publicclassTestFinallyBlock2{
2. publicstaticvoidmain(Stringargs[]){
3. try{
4. intdata=25/0;
5. [Link](data);6. }
7. catch(ArithmeticExceptione){[Link](e);}
8. finally{[Link]("finallyblockisalwaysexecuted");}
9. [Link]("restofthecode...");
10. }
11. }

Javathrowkeyword

TheJavathrowkeyword isusedto explicitlythrow anexception.

Wecanthroweithercheckedorunchekedexceptioninjavaby
[Link]
willseecustomexceptionslater.

Thesyntaxofjavathrowkeywordisgivenbelow.

[Link] exception;

1. publicclassTestThrow1{
2. staticvoidvalidate(intage){
3. if(age<18)
4. thrownewArithmeticException("notvalid");
5. else
6. [Link]("welcome to vote");7. }
8. publicstaticvoidmain(Stringargs[]){
9. validate(13);
10. [Link]("restofthecode...");
11. }
12. }

Javathrowskeyword

[Link]
heprogrammerthattheremayoccuranexceptionsoitisbetterfortheprogrammert
oprovidetheexceptionhandlingcodesothatnormalflowcanbemaintained.

[Link]
cursanyuncheckedexceptionsuchasNullPointerException,itisprogrammer
sfaultthatheisnotperformingcheckupbeforethecodebeingused.

Syntaxofjavathrows

1. return_typemethod_name()throwsexception_class_name{
2. //methodcode3.
}

import
[Link].*;class
M{
voidmethod()throwsIOException{throw
newIOException("deviceerror");
} }
publicclassTestthrows2{
publicstaticvoidmain(Stringargs[]){try{
Mm=newM();
[Link]();
}catch(Exceptione){[Link]("exceptionhandled");}
[Link]("normalflow...");
} }

JavaCustomException

If you are creating your own Exception that is known as custom exception
oruser-
[Link]
naccordingtouserneed.

Let'sseeasimpleexampleofjavacustomexception.

1. classInvalidAgeExceptionextendsException{
2. InvalidAgeException(String s){
3. super(s);4.
}
5.}

[Link]
TestCustomException1{2.
3. staticvoidvalidate(intage)throwsInvalidAgeException{
4. if(age<18)
5. thrownewInvalidAgeException("notvalid");
6. else
7. [Link]("welcome to vote");8. }
9.
10. publicstaticvoidmain(Stringargs[]){
11. try{
12. validate(13);
13. }catch(Exceptionm){[Link]("Exceptionoccured:"
+m);}
14.
15. [Link]("restofthecode..."); }}

XIVMULTITHREADINGINJAVA

Multithreadinginjavaisaprocessofexecutingmultiplethreadssimultaneousl
[Link]-process, a
[Link],bothareused
toachievemultitasking.

AdvantagesofJavaMultithreading

1) Itdoesn'tblocktheuserbecausethreadsareindependentandyoucanperfor
mmultipleoperationsatsametime.

2) Youcanperformmanyoperationstogethersoitsavestime.

3) Threadsareindependentsoitdoesn'taffectotherthreadsifexceptionoccurina
singlethread.

WhatisThreadinjava

A thread is a lightweight sub process, a smallest unit of processing. It is


aseparatepathofexecution.
Threadsareindependent,ifthereoccursexceptioninonethread,itdoesn'taffect
[Link].

LifecycleofaThread(ThreadStates)

1. New
2. Runnable
3. Running
4. Non-Runnable(Blocked)
5. Terminated

[Link],thereisonly4statesinth
readlifecycleinjavanew,runnable,non-
[Link].

Butforbetterunderstandingthethreads,weareexplainingitinthe5states.

ThelifecycleofthethreadinjavaiscontrolledbyJVM.

Thejavathreadstatesareasfollows:

1. New
2. Runnable
3. Running
4. Non-Runnable(Blocked)
5. Terminated
1) New

ThethreadisinnewstateifyoucreateaninstanceofThreadclassbutbeforeth
einvocationofstart()method.
2) Runnable

Thethreadisinrunnablestateafterinvocationofstart()method,butthethreadsche
dulerhasnotselectedittobetherunningthread.

3) Running

Thethreadisinrunningstateifthethreadschedulerhasselectedit.

4) Non-Runnable (Blocked)

Thisisthestatewhenthethreadisstillalive,butiscurrentlynoteligibletorun.

5) Terminated

Athreadisinterminatedordeadstatewhenitsrun()methodexits.
Howtocreatethread

Therearetwowaystocreateathread:

1. ByextendingThreadclass
2. ByimplementingRunnableinterface.

Threadclass:
Threadclassprovideconstructorsandmethodstocreateandperformoperatio
[Link]
rface.

CommonlyusedConstructorsofThreadclass:
 Thread()
 Thread(Stringname)
 Thread(Runnable r)
 Thread(Runnabler,Stringname)

CommonlyusedmethodsofThreadclass:publicvoi
drun():isusedtoperformactionforathread.

publicvoidstart():[Link]()meth
odonthethread.

public void sleep(long miliseconds): Causes the currently


executingthreadtosleep(temporarilyceaseexecution)forthespecifiednu
mberofmilliseconds.

publicvoidjoin():waitsforathreadtodie.

publicvoidjoin(longmiliseconds):waits for a thread to die for


thespecifiedmiliseconds.

publicintgetPriority():returnsthepriorityofthethread.

publicintsetPriority(intpriority):changesthepriorityofthethread.

publicStringgetName():returnsthenameofthethread.

publicvoidsetName(Stringname):changesthenameofthethread.

publicThreadcurrentThread():returnsthecurrentthread.

publicintgetId():returnstheidofthethread.
[Link]():returnsthestateofthethread.

publicbooleanisAlive():testsifthethreadisalive.

publicvoidyield():causesthecurrentlyexecutingthreadobjecttotemporari
lypauseandallowotherthreadstoexecute.

publicvoidsuspend():isusedtosuspendthethread(depricated).

publicvoidresume():isusedtoresumethesuspendedthread(depricated).

publicvoidstop():isusedtostopthethread(depricated).

publicbooleanisDaemon():testsifthethreadisadaemonthread.

publicvoidsetDaemon(booleanb):marks the thread as daemon


oruserthread.

publicvoidinterrupt():interruptsthethread.

publicbooleanisInterrupted():testsifthethreadhasbeeninterrupted.

publicstaticbooleaninterrupted():testsifthecurrentthreadhasbeeninterr
upted.
Runnableinterface:
TheRunnableinterfaceshouldbe implemented by any class
[Link]
onlyonemethodnamedrun().

1. publicvoidrun():isusedtoperformactionforathread.

Startingathread:
start()[Link]
owingtasks:

 Anewthreadstarts(withnewcallstack).
 The thread moves fromNew state totheRunnable state.
 Whenthethread getsachancetoexecute,itstarget
run()methodwillrun.

1) JavaThreadExamplebyextendingThreadclass

1. classMultiextendsThread{
2. publicvoidrun(){
3. [Link]("threadisrunning...");
4.}
5. publicstaticvoidmain(Stringargs[]){
6. Multit1=newMulti();
7. [Link]();
8. }
9.}

2) JavaThreadExamplebyimplementingRunnableinterf
ace

1. classSampleimplementsRunnable{
2. publicvoidrun(){
3. [Link]("Threadisrunning...");4.}
5.
6. publicstaticvoidmain(Stringargs[]){
7. Samples=newSample();
8. Threadt1=newThread(s);
9. [Link]();
10. }
11. }

Sleepmethodinjava

Thesleep()methodofThreadclassisusedtosleepathreadforthespecifiedamoun
toftime.

Syntaxofsleep()methodinjava

TheThreadclassprovidestwomethodsforsleepingathread:

 publicstaticvoidsleep(longmiliseconds)throwsInterruptedException
 publicstaticvoidsleep(longmiliseconds,intnanos)throwsInt
erruptedException

Exampleofsleepmethodinjava

1. classExextendsThread{
2. publicvoid run(){3.
for(intj=1;j<5;j++){
4.
try{[Link](500);}catch(InterruptedExceptione){[Link]
n(e);}
5. [Link](j);
6. }
7. }
8. publicstaticvoidmain(Stringargs[]){
9. Ex t1=newEx();
10. Ext2=newEx();
11.
12. [Link]();
13. [Link]();
14. }
15. }

Thejoin()method

Thejoin()[Link],itcausesthecurrentlyrunn
ingthreadstostopexecutinguntilthethreaditjoinswithcompletesitstask.

Syntax:
publicvoidjoin()throwsInterruptedException

publicvoidjoin(longmilliseconds)throwsInterruptedException

Exampleofjoin()method

1. classSampleextendsThread{
2. publicvoidrun(){
3. for(inti=1;i<=5;i++){
4. try{
5. [Link](500);
6. }catch(Exceptione){[Link](e);}
7. [Link](i);8.
} }
9. publicstaticvoidmain(Stringargs[]){
10. Samplet1=newSample();
11. Samplet2=newSample();
12. Samplet3=newSample();
13. [Link]();
14. try{
15. [Link]();
16. }catch(Exceptione){[Link](e);}
17. [Link]();
18. [Link]();
19. } }

getName(),setName(String)andgetId() method:
publicStringgetName()

publicvoidsetName(Stringname)

publiclonggetId()

1. classSample1extends Thread{
2. publicvoidrun(){
3. [Link]("running..."); 4. }
5. publicstaticvoidmain(Stringargs[]){
6. Sample1t1=new Sample1 ();
7. Sample1t2=newSample1();
8. [Link]("Nameoft1:"+[Link]());
9. [Link]("Nameoft2:"+[Link]());
10. [Link]("idoft1:"+[Link]());
11. [Link]();
12. [Link]();
13. [Link]("SonooJaiswal");
14. [Link]("After changing name of t1:"+[Link]());15.

}}

PriorityofaThread(ThreadPriority):
Eachthreadhaveapriority.Prioritiesarerepresentedbyanumberbetween1and
[Link],threadschedularschedulesthethreadsaccordingto their
priority (known as preemptive scheduling). But it is not
guaranteedbecauseitdependsonJVMspecificationthatwhichschedulingitc
hooses.

3constantsdefinedinThreadclass:
1. publicstaticintMIN_PRIORITY
2. publicstaticintNORM_PRIORITY
3. publicstaticintMAX_PRIORITY

Defaultpriorityofathreadis5(NORM_PRIORITY).ThevalueofMIN_PRIORITYis1a
ndthevalueofMAX_PRIORITYis10.
ExampleofpriorityofaThread:

1. classTestMultiPriority1extendsThread{
2. publicvoidrun(){
3. [Link]("running thread name
is:"+[Link]().getName());
4.
[Link]("runningthreadpriorityis:"+[Link]().g
etPriority());
5.
6. }
7. publicstaticvoidmain(Stringargs[]){
8. TestMultiPriority1 m1=newTestMultiPriority1();
9. TestMultiPriority1 m2=newTestMultiPriority1();
10. [Link](Thread.MIN_PRIORITY);
11. [Link](Thread.MAX_PRIORITY);
12. [Link]();
13. [Link]();
14.
15. }
16. }

ThreadGroupinJava

[Link]
way,wecan suspend,resumeorinterruptgroup of threads by
asinglemethodcall.

ConstructorsofThreadGroupclass

ThereareonlytwoconstructorsofThreadGroupclass.

No. Constructor Description


createsathreadgroupwithgivenn
1) ThreadGroup(Stringname)
ame.
ThreadGroup(ThreadGroupparent,St createsathreadgroupwithgivenp
2)
ringname) arentgroupandname.
ThreadGroupExample

File:[Link]

1. publicclassThreadGroupDemoimplementsRunnable{
2. publicvoidrun()3.
{
4. [Link]([Link]().getName());
5. }
6. publicstaticvoidmain(String[]args)7.
{
8. ThreadGroupDemorunnable=newThreadGroupDemo();
9. ThreadGrouptg1=newThreadGroup("ParentThreadGroup");10.
11. Threadt1=newThread(tg1,runnable,"one");
12. [Link]();
13. Threadt2=newThread(tg1,runnable,"two");
14. [Link]();
15. Threadt3=newThread(tg1,runnable,"three");
16. [Link]();
17.
18. [Link]("ThreadGroupName:"+[Link]()
);
19. [Link]();
20.
21. }
22. }

1. classTestMultitasking1extendsThread{
2. publicvoidrun(){
3. [Link]("task one");4. }
5. publicstaticvoidmain(Stringargs[]){
6. TestMultitasking1t1=newTestMultitasking1();
7. TestMultitasking1t2=newTestMultitasking1();
8. TestMultitasking1t3=newTestMultitasking1();
9.
10. [Link]();
11. [Link]();
12. [Link]();
13. }
14. }

SynchronizationinJava

Synchronization in java is the capability to control the access of


multiplethreadstoanysharedresource.
JavaSynchronizationisbetteroptionwherewewanttoallowonlyonethre
adtoaccessthesharedresource.

WhyuseSynchronization

Thesynchronizationismainlyusedto

1. Topreventthreadinterference.
2. Topreventconsistencyproblem.

TypesofSynchronization

Therearetwotypesofsynchronization

1. ProcessSynchronization
2. ThreadSynchronization

ThreadSynchronization

Therearetwotypesofthreadsynchronizationmutualexclusiveandinter-
threadcommunication.

1. MutualExclusive
1. Synchronizedmethod.
2. Synchronizedblock.
3. staticsynchronization.
2. Cooperation(Inter-threadcommunicationinjava)

MutualExclusive

MutualExclusivehelpskeepthreadsfrominterferingwithoneanotherwhilesharin
[Link]:

1. bysynchronizedmethod
2. bysynchronizedblock
3. bystaticsynchronization

ConceptofLockinJava

[Link]
[Link],athreadthatneedsconsi
stentaccesstoanobject'sfieldshastoacquiretheobject'slockbeforeaccessin
gthem,andthenreleasethelockwhenit'sdonewiththem.

[Link].
1. //exampleofjavasynchronizedmethod
2. classTable{
3. synchronizedvoidprintTable(intn){//synchronizedmethod4.
for(inti=1;i<=5;i++){
5. [Link](n*i);
6. try{
7. [Link](400);
8. }catch(Exception e){[Link](e);}9. }
10.
11. }
12. }
13.
14. classMyThread1extendsThread{
15. Tablet;
16. MyThread1(Tablet){
17. this.t=t;
18. }
19. publicvoidrun(){
20. [Link](5);
21. }
22.
23. }
24. classMyThread2extendsThread{
25. Tablet;
26. MyThread2(Tablet){
27. this.t=t;
28. }
29. publicvoidrun(){
30. [Link](100);
31. }
32. }
33.
34. publicclassTestSynchronization2{
35. publicstaticvoidmain(Stringargs[]){
36. Tableobj=newTable();//onlyoneobject
37. MyThread1t1=newMyThread1(obj);
38. MyThread2t2=newMyThread2(obj);
39. [Link]();
40. [Link]();
41. }
42. }

Inter-threadcommunicationinJava

Inter-threadcommunicationorCo-
operationisallaboutallowingsynchronizedthreadstocommunicatewitheach
other.
Cooperation(Inter-
threadcommunication)isamechanisminwhichathreadispausedrunninginit
scriticalsectionandanotherthreadisallowedtoenter(orlock)inthesamecriti
[Link]
ass:

 wait()
 notify()
 notifyAll()

1) wait()method

Causescurrentthreadtoreleasethelockandwaituntil either
anotherthreadinvokesthenotify()methodorthenotifyAll()methodforthisobjec
t,oraspecifiedamountoftimehaselapsed.

Thecurrentthreadmustownthisobject'smonitor,soitmustbecalledfromthesync
hronizedmethodonlyotherwiseitwillthrowexception.

Method Description

publicfinalvoidwait()throwsIn
waits untilobject is notified.
terruptedException

publicfinalvoidwait(longtimeout)throwsIn waitsforthespecifieda
terruptedException mountoftime.

2) notify()method

Wakesupasinglethreadthatiswaitingonthisobject'[Link]
ewaitingonthisobject,[Link]
choiceisarbitrary and occurs at thediscretion of
[Link]:

publicfinalvoidnotify()

3) notifyAll()method

Wakesupallthreadsthatarewaitingonthisobject'[Link]:publi

cfinalvoidnotifyAll()

UNITIV
JavaApplet

Applet isa special typeof program thatisembedded inthe webpage


[Link].

AdvantageofApplet

[Link]:

 Itworksatclientsidesolessresponsetime.
 Secured
 It can be executed by browsers running under many
plateforms,includingLinux,Windows,MacOsetc.

DrawbackofApplet

 Pluginisrequiredatclientbrowsertoexecuteapplet.

DoYouKnow

 Whoisresponsibletomanagethelifecycleofanapplet?
 Howtoperformanimationinapplet?
 Howtopaintlikepaintbrushinapplet?
 Howtodisplaydigitalclockinapplet?
 Howtodisplayanalogclockinapplet?
 Howtocommunicatetwoapplets?

HierarchyofApplet
DisplayingGraphicsinApplet

[Link].

CommonlyusedmethodsofGraphicsclass:

1. publicabstractvoiddrawString(Stringstr,intx,inty):isusedtodrawthesp
ecifiedstring.
2. publicvoiddrawRect(intx,inty,intwidth,intheight):draws
arectanglewiththespecifiedwidthandheight.
3. publicabstractvoidfillRect(intx,inty,intwidth,intheight):isused
tofillrectangle withthedefaultcolor andspecified widthandheight.
4. public abstractvoiddrawOval(intx,inty,intwidth,intheight):
isusedtodrawovalwiththespecifiedwidthandheight.
5. publicabstractvoidfillOval(intx,inty,intwidth,intheight):isusedtofilloval
withthedefaultcolorandspecifiedwidthandheight.
6. publicabstractvoiddrawLine(intx1,inty1,intx2,inty2):isusedtodraw
linebetweenthepoints(x1,y1)and(x2,y2).
7. publicabstractbooleandrawImage(Imageimg,intx,inty,Imag
eObserverobserver):isuseddrawthespecifiedimage.
8. publicabstractvoiddrawArc(intx,inty,intwidth,intheight,intstartAngl
e,intarcAngle):isuseddrawacircularorellipticalarc.
9. publicabstractvoidfillArc(intx,inty,intwidth,intheight,intstartAngl
e,intarcAngle):isusedtofillacircularorellipticalarc.
10. publicabstractvoidsetColor(Colorc):isusedtosetthegraphi
cscurrentcolortothespecifiedcolor.
11. publicabstractvoidsetFont(Fontfont):isusedtosetthegrap
hicscurrentfonttothespecifiedfont.

ExampleofGraphicsinapplet:

1. [Link];
2. [Link].*;
3.
[Link]{5.
6. publicvoidpaint(Graphicsg){
7. [Link]([Link]);
8. [Link]("Welcome",50,50);
[Link](20,30,20,300);
10. [Link](70,100,30,30);
11. [Link](170,100,30,30);
12. [Link](70,200,30,30);
13.
14.
[Link]([Link]);15.
[Link](170,200,30,30);
16. [Link](90,150,30,30,30,270);
17. [Link](270,150,30,30,0,180);
18.
19. }
20. }

EventHandlinginApplet
AsweperformeventhandlinginAWTorSwing,[Link]'s
seethesimpleexampleofeventhandlinginappletthatprintsamessagebyclickont
hebutton.

ExampleofEventHandlinginapplet:

1. [Link].*;
2. [Link].*;
3. [Link].*;
4. publicclassEventAppletextendsAppletimplementsActionListener{
5. Buttonb;
6. TextFieldtf;
7.
8. publicvoidinit(){
9. tf=newTextField();
10. [Link](30,40,150,20);
11.
12. b=newButton("Click");
13. [Link](80,150,60,50);
14.
15. add(b);add(tf);
16. [Link](this);
17.
18. setLayout(null);
19. }
20.
21. public void actionPerformed(ActionEvent e){
22. [Link]("Welcome");
23. }
24. }

Intheaboveexample,wehavecreatedallthecontrolsininit()methodbecauseitisin
vokedonlyonce.

[Link]

1. <html>
2. <body>
3. <appletcode="[Link]"width="300"height="300">
4. </applet>
5. </body>
6. </html>

JavaAWTTutorial

JavaAWT(AbstractWindowToolkit)isanAPItodevelopGUIorwindow-
basedapplicationsinjava.

JavaAWT components are platform-dependent i.e. components


[Link]
componentsareusingtheresourcesofOS.

[Link],Label,Te
xtArea,RadioButton,CheckBox,Choice,Listetc.
JavaAWTHierarchy

Thehierarchy of Java AWTclasses are given below.

JavaAWTButton

Thebuttonclassisusedtocreatealabeledbuttonthathasplatformindepen
[Link]
spushed.

AWTButtonClassdeclaration

[Link]
JavaAWTButtonExample

1. [Link].*;
2. public class ButtonExample {
3. publicstaticvoidmain(String[]args){
4. Framef=newFrame("ButtonExample");
5. Buttonb=newButton("ClickHere");6.
[Link](50,100,80,30);
7. [Link](b);
8. [Link](400,400);
9. [Link](null);
10. [Link](true);
11. }
12. }

Output:

JavaActionListenerInterface

TheJavaActionListenerisnotifiedwhenever you click on the button


[Link]
[Link]:actionPerformed().

actionPerformed()method

TheactionPerformed()methodisinvokedautomaticallywheneveryouclickonth
eregisteredcomponent.

[Link](ActionEvente);
JavaActionListenerExample:OnButtonclick

1. [Link].*;
2. [Link].*;
3. public class ActionListenerExample {
4. publicstaticvoidmain(String[]args){
5. Framef=newFrame("ActionListenerExample");
6. finalTextFieldtf=newTextField();7.
[Link](50,50,150,20);
8. Buttonb=newButton("ClickHere");9.
[Link](50,100,60,30);
10.
11. [Link](newActionListener(){
12. public void actionPerformed(ActionEvent e){
13. [Link]("WelcometoJavatpoint.");
14. }
15. });
16. [Link](b);[Link](tf);
17. [Link](400,400);
18. [Link](null);
19. [Link](true);
20. }
21. }

Output:

UNITV

JavaLayoutManagers
TheLayoutManagersareusedtoarrangecomponentsinaparticularmanner.
LayoutManagerisaninterfacethatisimplementedbyalltheclassesof
[Link] are followingclassesthatrepresents
thelayoutmanagers:

1. [Link]
2. [Link]
3. [Link]
4. [Link]
5. [Link]
6. [Link]
7. [Link]
8. [Link]
9. [Link].

JavaBorderLayout

The BorderLayoutisused toarrange thecomponentsinfiveregions:


north,south,east,[Link](area)maycontainonecomponent
[Link]
tantsforeachregion:

1. publicstaticfinalintNORTH
2. publicstaticfinalintSOUTH
3. publicstaticfinalintEAST
4. publicstaticfinalintWEST
5. publicstaticfinalintCENTERConstructorsof

BorderLayoutclass:

 BorderLayout():createsaborderlayoutbutwithnogapsbetweenthecomp
onents.
 JBorderLayout(inthgap,intvgap):createsaborderlayoutwiththegive
nhorizontalandverticalgapsbetweenthecomponents.
JavaGridBagLayout

TheJavaGridBagLayoutclassisusedtoaligncomponentsvertically,horizonta
llyoralongtheirbaseline.

[Link]
nsadynamic,[Link]
[Link]
[Link]
component's display area on thegrid. The GridBagLayout
manageseachcomponent'sminimumandpreferredsizesinordertodetermi
necomponent'ssize.

Fields
ModifierandType Field Description

Itisusedtohold
theoverrides
double[] columnWeights tothecolumn
weights.
Itisusedtoh
oldtheoverri
des
int[] columnWidths
tothecolum
nminimum
width.

Itisusedto
maintainst
heassociat
protectedHashtable<Component,GridBag ionbetwee
Constraints comptable nacompon
> entanditsgr
idbagconst
raints.

Itisusedtoh
oldagridba
gconstraint
defaultConstraint sinstancec
protectedGridBagConstraints
s ontainingth
edefaultval
ues.

Itisusedtoh
oldthelayou
tinformatio
protectedGridBagLayoutInfo layoutInfo
nforthegrid
bag.

Nolongerin
usejustforb
protectedstaticint MAXGRIDSIZE ackwardco
mpatibility

Itissmallest
protectedstaticint MINSIZE gridthatcan
belaidoutbyt
hegrid
baglayout.

Itispreferre
dgridsizeth
atcanbelaid
protectedstaticint PREFERREDSIZE outbythegri
d
baglayout.

Itisusedtohol
dtheoverride
s
int[] rowHeights
totherowmini
mumheights.

Itisusedtohol
dtheoverride
double[] rowWeights s totherow
weights.

UsefulMethods
ModifierandType Method Description

Itaddsspecified
componenttoth
addLayoutComponent(Componentco elayout,usingth
void
mp,Objectconstraints) especifiedconst
raintsobject.

Ithasnoeffect,si
ncethislayoutm
addLayoutComponent(Stringname,Co anagerdoesnot
void
mponentcomp) useaper-
componentstri
ng.

adjustForGravity(GridBagConstraints Itadjuststhex,y,
protectedvoid width,andheigh
constraints,Rectangler)
t fieldsto
thecorrectval
uesdependin
g onthe
constraintge
ometryandpa
ds.

Thismethodisfo
AdjustForGravity(GridBagConstraintsc rbackwardsco
protectedvoid
onstraints,Rectangler) mpatibilityonly

Laysoutthe
protectedvoid arrangeGrid(Containerparent)
grid.

Thismethodiso
bsoleteandsup
protectedvoid ArrangeGrid(Containerparent) pliedforbackwa
rdscompatibilit
y

Itisforgettingth
econstraintsfor
GridBagConstraint getConstraints(Componentcomp)
thespecifiedco
s
mponent.

Itreturnsthealig
getLayoutAlignmentX(Containerparen
float nment
t)
alongthexaxis.

Itreturnsthealig
getLayoutAlignmentY(Containerparen
float nment
t)
alongtheyaxis.

Itdeterminescol
umnwidthsandr
int[][] getLayoutDimensions() owheightsforth
elayoutgrid.

protectedGridBagLa getLayoutInfo(Containerparent,intsize Thismethodis


youtInfo flag) obsoleteands
uppliedfor
backwardsco
mpatibility.

Thismethodis
obsoleteands
protectedGridBagL GetLayoutInfo(Containerparent,int
uppliedforbac
ayoutInfo sizeflag)
kwardscompa
tibility.

Itdeterminestheo
riginofthelayouta
rea,
Point getLayoutOrigin() inthegraphicsco
ordinatespaceoft
hetargetcontaine
r.

Itdeterminesthe
weightsofthelay
double[][] getLayoutWeights() outgrid'scolumn
sandrows.

Itfiguresout
theminimumsize
protectedDimensio getMinSize(Containerparent,GridBa ofthe
n gLayoutInfoinfo) masterbasedont
heinformationfro
mgetLayoutInfo.

Thismethodis
obsoleteandsu
protectedDimensio GetMinSize(Containerparent, ppliedforback
n GridBagLayoutInfoinfo) wardscompati
bility
only

Example

1. [Link];
2. [Link];
3. import
[Link];4.
5. [Link].*;
6. publicclassGridBagLayoutExampleextendsJFrame{
7. publicstaticvoidmain(String[]args){
8. GridBagLayoutExamplea=newGridBagLayoutExample();
9. }
10. public GridBagLayoutExample() {
11. GridBagLayoutgrid=newGridBagLayout();
12. GridBagConstraints gbc = new GridBagConstraints();
13. setLayout(grid);
14. setTitle("GridBagLayoutExample");
15. GridBagLayoutlayout=newGridBagLayout();
16. [Link](layout);
17. [Link]=[Link];
18. [Link]=0;
19. [Link]=0;
20. [Link](newButton("ButtonOne"),gbc);
21. [Link]=1;
22. [Link]=0;
23. [Link](newButton("Buttontwo"),gbc);
24. [Link]=[Link];
25. [Link]=20;
26. [Link]=0;
27. [Link]=1;
28. [Link](newButton("ButtonThree"),gbc);
29. [Link]=1;
30. [Link]=1;
31. [Link](newButton("ButtonFour"),gbc);
32. [Link]=0;
33. [Link]=2;
34. [Link]=[Link];
35. [Link]=2;
36. [Link](newButton("ButtonFive"),gbc);
37. setSize(300,300);
38. setPreferredSize(getSize());
39. setVisible(true);
40. setDefaultCloseOperation(EXIT_ON_CLOSE);
41.
42. }
43.
44. }

Output:
JavaSwingTutorial

JavaSwingtutorialisapartofJavaFoundationClasses(JFC)thatisusedtocrea
[Link]
(AbstractWindowingToolkit)APIandentirelywritteninjava.

UnlikeAWT,JavaSwingprovidesplatform-
independentandlightweightcomponents.

[Link]
ton,JTextField,JTextArea,JRadioButton,JCheckbox,JMenu,JColorCh
ooseretc.

DifferencebetweenAWTandSwing

Therearemanydifferencesbetweenjavaawtandswingthataregivenbelow.

No. JavaAWT JavaSwing

1) AWTcomponentsareplatform- Javaswingcomponentsare
dependent. platform-independent.

Swingcomponentsare
2) AWTcomponentsareheavyweight.
lightweight.

AWTdoesn'tsupportpluggablelookan Swingsupportspluggablel
3)
dfeel. ookandfeel.

Swingprovidesmorepowerfu
AWTprovideslesscomponentsthanSwin l components
4)
g. suchastables,lists,scrollpan
es,colorchooser,tabbedpane
etc.
AWTdoesn'tfollowsMVC(ModelViewCon
troller)wheremodelrepresentsdata,viewr
5) epresentspresentationandcontrolleracts
asaninterfacebetween
modelandview.

JavaJButton

TheJButtonclassisusedtocreatealabeledbuttonthathasplatformindepe
[Link]
[Link].

JButtonclassdeclaration

Let'[Link].

[Link]

CommonlyusedConstructors:
Constructor Description

JButton() Itcreatesabuttonwithnotextandicon.

JButton(Strings) Itcreatesabuttonwiththespecifiedtext.

JButton(Iconi) Itcreatesabuttonwiththespecifiediconobject.

CommonlyusedMethodsofAbstractButtonclass:
Methods Description

Itisusedtosetspecifiedtextonbut
voidsetText(Strings)
ton

Itisusedtoreturnthetextofthebutto
StringgetText()
n.

Itisusedtoenableordisablethebu
voidsetEnabled(booleanb)
tton.

ItisusedtosetthespecifiedIconontheb
voidsetIcon(Iconb)
utton.

ItisusedtogettheIconofthebut
IcongetIcon()
ton.

Itisusedtosetthemnemoniconthebut
voidsetMnemonic(inta)
ton.

voidaddActionListener(ActionListener Itisusedtoaddtheactionlistenertothiso
a) bject.

JavaJRadioButton

[Link]
ption from multiple options. It iswidelyused in exam systems or quiz.

ItshouldbeaddedinButtonGrouptoselectoneradiobuttononly.

JRadioButtonclassdeclaration

Let'[Link].

[Link]
le

CommonlyusedConstructors:
Constructor Description

Createsanunselectedradiobuttonwithnotex
JRadioButton()
t.
Createsanunselectedradiobuttonwiths
JRadioButton(Strings)
pecifiedtext.

JRadioButton(Strings,boolean Createsaradiobuttonwiththespecifiedtex
selected) tandselectedstatus.

CommonlyusedMethods:
Methods Description

Itisusedtosetspecifiedtextonbut
voidsetText(Strings)
ton.

Itisusedtoreturnthetextofthebutto
StringgetText()
n.

Itisusedtoenableordisablethebu
voidsetEnabled(booleanb)
tton.

ItisusedtosetthespecifiedIconontheb
voidsetIcon(Iconb)
utton.

ItisusedtogettheIconofthebut
IcongetIcon()
ton.

Itisusedtosetthemnemoniconthebut
voidsetMnemonic(inta)
ton.

voidaddActionListener(ActionListener Itisusedtoaddtheactionlistenertothiso
a) bject.

JavaJRadioButtonExample

1. [Link].*;
2. public class RadioButtonExample {
3. JFramef;
4. RadioButtonExample(){
5. f=newJFrame();
6. JRadioButtonr1=newJRadioButton("A)Male");
7. JRadioButton r2=new JRadioButton("B)
Female");[Link](75,50,100,30);
[Link](75,100,100,30);
10. ButtonGroupbg=newButtonGroup();
11. [Link](r1);[Link](r2);
12. [Link](r1);[Link](r2);
13. [Link](300,300);
14. [Link](null);
15. [Link](true);
16. }
17. publicstaticvoidmain(String[]args){
18. newRadioButtonExample();
19. }
20. }

JavaGridBagLayout

TheJavaGridBagLayoutclassisusedtoaligncomponentsvertically,horizonta
llyoralongtheirbaseline.

[Link]
nsadynamic,[Link]
[Link]
[Link]
component's display area on the grid. The GridBagLayout
manageseachcomponent'sminimumandpreferredsizesinordertodetermi
necomponent'ssize.

Fields
ModifierandType Field Description

double[] columnWeights Itisusedtohold


the
overrides
tothe
columnwei
ghts.
Itisusedtoh
oldtheoverri
des
int[] columnWidths
tothecolum
nminimum
width.

Itisusedto
maintainst
heassociat
protectedHashtable<Component,GridBag ionbetwee
Constraints comptable nacompon
> entanditsgr
idbagconst
raints.

Itisusedtoh
oldagridba
gconstraint
defaultConstraint sinstancec
protectedGridBagConstraints
s ontainingth
edefaultval
ues.

Itisusedtoh
oldthelayou
tinformatio
protectedGridBagLayoutInfo layoutInfo
nforthegrid
bag.

Nolongerin
usejustforb
protectedstaticint MAXGRIDSIZE ackwardco
mpatibilit
y
Itissmallest
gridthatcan
protectedstaticint MINSIZE belaidoutbyt
hegridbagla
yout.

Itispreferre
dgridsizeth
atcanbelaid
protectedstaticint PREFERREDSIZE outbythegri
d
baglayout.

Itisusedtoho
ldtheoverrid
es
int[] rowHeights
totherowmin
imumheight
s.

Itisusedtoho
ldtheoverrid
double[] rowWeights es totherow
weights.

UsefulMethods
ModifierandType Method Description

Itaddsspecified
componenttoth
addLayoutComponent(Componentco elayout,usingth
void
mp,Objectconstraints) especifiedconst
raintsobject.

Ithasnoeffect,si
ncethislayoutm
addLayoutComponent(Stringname,C anagerdoesnot
void
omponentcomp) useaper-
component
string.
Itadjuststhex,y,
width,andheigh
t
fieldstothecorr
adjustForGravity(GridBagConstraints
protectedvoid ectvaluesdepe
constraints,Rectangler)
ndingonthecon
straintgeometr
y andpads.

Thismethodisfo
AdjustForGravity(GridBagConstraintsc rbackwardsco
protectedvoid
onstraints,Rectangler) mpatibilityonly

Laysoutthe
protectedvoid arrangeGrid(Containerparent)
grid.

Thismethodiso
bsoleteandsup
protectedvoid ArrangeGrid(Containerparent) pliedforbackwa
rdscompatibilit
y

Itisforgettingth
econstraintsfor
GridBagConstraint getConstraints(Componentcomp)
thespecifiedco
s
mponent.

Itreturnsthealig
getLayoutAlignmentX(Containerparen
float nment
t)
alongthexaxis.

Itreturnsthealig
getLayoutAlignmentY(Containerparen
float nment
t)
alongtheyaxis.

Itdeterminescol
umnwidthsandr
int[][] getLayoutDimensions() owheightsforth
elayout
grid.
Thismethodis
obsoleteands
protectedGridBagL getLayoutInfo(Containerparent,intsi
uppliedforbac
ayoutInfo zeflag)
kwardscompa
tibility.

Thismethodis
obsoleteands
protectedGridBagL GetLayoutInfo(Containerparent,int
uppliedforbac
ayoutInfo sizeflag)
kwardscompa
tibility.

Itdeterminestheo
riginofthelayouta
rea,
Point getLayoutOrigin() inthegraphicsco
ordinatespaceoft
hetargetcontaine
r.

Itdeterminesthe
weightsofthelay
double[][] getLayoutWeights() outgrid'scolumn
sandrows.

Itfiguresout
theminimumsize
protectedDimensio getMinSize(Containerparent,GridBa ofthe
n gLayoutInfoinfo) masterbasedont
heinformationfro
mgetLayoutInfo.

Thismethodis
obsoleteandsu
protectedDimensio GetMinSize(Containerparent, ppliedforback
n GridBagLayoutInfoinfo) wardscompati
bility
only

Example

1. [Link];
2. [Link];
3. import
[Link];4.
5. [Link].*;
6. publicclassGridBagLayoutExampleextendsJFrame{
7. publicstaticvoidmain(String[]args){
8. GridBagLayoutExample a = new GridBagLayoutExample();9. }
10. public GridBagLayoutExample() {
11. GridBagLayoutgrid=newGridBagLayout();
12. GridBagConstraints gbc = new GridBagConstraints();
13. setLayout(grid);
14. setTitle("GridBagLayoutExample");
15. GridBagLayoutlayout=newGridBagLayout();
16. [Link](layout);
17. [Link]=[Link];
18. [Link]=0;
19. [Link]=0;
20. [Link](newButton("ButtonOne"),gbc);
21. [Link]=1;
22. [Link]=0;
23. [Link](newButton("Buttontwo"),gbc);
24. [Link]=[Link];
25. [Link]=20;
26. [Link]=0;
27. [Link]=1;
28. [Link](newButton("ButtonThree"),gbc);
29. [Link]=1;
30. [Link]=1;
31. [Link](newButton("ButtonFour"),gbc);
32. [Link]=0;
33. [Link]=2;
34. [Link]=[Link];
35. [Link]=2;
36. [Link](newButton("ButtonFive"),gbc);
37. setSize(300,300);
38. setPreferredSize(getSize());
39. setVisible(true);
40. setDefaultCloseOperation(EXIT_ON_CLOSE
);
41.
42. }
43.
44. }

Output:
JavaJTree

[Link]
[Link]'rootnode'atthetopmostwhichisaparentfo
[Link].

JTreeclassdeclaration

Let'[Link].

[Link],Accessi
ble

CommonlyusedConstructors:
Constructor Description

JTree() CreatesaJTreewithasamplemodel.

JTree(Object[ CreatesaJTreewitheveryelementofthespecifiedarrayasth
]value) echildofanewrootnode.

JTree(TreeNoder Createsa JTree withthespecified TreeNodeas


oot) itsroot,whichdisplaystherootnode.
JavaJTreeExample

1. [Link].*;
2. import [Link];
3. public class TreeExample {
4. JFramef;
5. TreeExample(){
6. f=newJFrame();
7. DefaultMutableTreeNodestyle=newDefaultMutableTreeNode("Style"
);
8. DefaultMutableTreeNodecolor=newDefaultMutableTreeNode("color"
);
9. DefaultMutableTreeNodefont=newDefaultMutableTreeNode("font");

10. [Link](color);
11. [Link](font);
12. DefaultMutableTreeNodered=newDefaultMutableTreeNode("r
ed");
13. DefaultMutableTreeNodeblue=newDefaultMutableTreeNode("
blue");
14. DefaultMutableTreeNodeblack=newDefaultMutableTreeNode
("black");
15. DefaultMutableTreeNodegreen=newDefaultMutableTreeNode
("green");
16. [Link](red);[Link](blue);[Link](black);[Link](gre
en);
17. JTreejt=newJTree(style);
18. [Link](jt);
19. [Link](200,200);
20. [Link](true);
21. }
22. publicstaticvoidmain(String[]args){
23. newTreeExample();24.
}}

Output:

You might also like