JP Cse Course Plan and Notes
JP Cse Course Plan and Notes
Course Objectives:
• To introduce the object-oriented programming concepts.
• To understand object-oriented programming concepts, and apply them in solving problems.
• To introduce the principles of inheritance and polymorphism; and demonstrate how they relate to the design of abstract classes
• To introduce the implementation of packages and interfaces
• To introduce the concepts of exception handling and multithreading.
• To introduce the design of Graphical User Interface using applets and swing controls.
Course Outcomes:
• Able to solve real world problems using OOP techniques.
• Able to understand the use of abstract classes.
• Able to solve problems using java collection framework and I/o classes.
• Able to develop multithreaded applications with synchronization.
• Able to develop applets for web applications.
• Able to design GUI based applications
UNIT - I
Object-Oriented Thinking- A way of viewing world – Agents and Communities, messages and methods,
Responsibilities, Classes and Instances, Class Hierarchies- Inheritance, Method binding, Overriding and
Exceptions, Summary of Object-Oriented concepts. Java buzzwords, An Overview of Java, Data types,
Variables and Arrays, operators, expressions, control statements, Introducing classes, Methods and Classes,
String handling.
Inheritance– Inheritance concept, Inheritance basics, Member access, Constructors, Creating Multilevel
hierarchy, super uses, using final with inheritance, Polymorphism-ad hoc polymorphism, pure polymorphism,
method overriding, abstract classes, Object class, forms of inheritance- specialization, specification,
construction, extension, limitation, combination, benefits of inheritance, costs of inheritance.
UNIT - II
Packages- Defining a Package, CLASSPATH, Access protection, importing packages.
Interfaces- defining an interface, implementing interfaces, Nested interfaces, applying interfaces, variables in
interfaces and extending interfaces.
Stream based I/O (java.io) – The Stream classes-Byte streams and Character streams, Reading console Input
and Writing Console Output, File class, Reading and writing Files, Random access file operations, The Console
class, Serialization, Enumerations, auto boxing, generics.
UNIT - III
Exception handling - Fundamentals of exception handling, Exception types, Termination or resumptive
models, Uncaught exceptions, using try and catch, multiple catch clauses, nested try statements, throw, throws
and finally, built- in exceptions, creating own exception sub classes.
Multithreading- Differences between thread-based multitasking and process-based multitasking, Java thread
model, creating threads, thread priorities, synchronizing threads, inter thread communication.
UNIT - IV
The Collections Framework (java.util)- Collections overview, Collection Interfaces, The Collection classes-
Array List, Linked List, Hash Set, Tree Set, Priority Queue, Array Deque. Accessing a Collection via an Iterator,
Using an Iterator, The For-Each alternative, Map Interfaces and Classes, Comparators, Collection algorithms,
Arrays, The Legacy Classes and Interfaces- Dictionary, Hashtable,Properties, Stack, Vector
More Utility classes, String Tokenizer, Bit Set, Date, Calendar, Random, Formatter, Scanner
UNIT - V
GUI Programming with Swing – Introduction, limitations of AWT, MVC architecture, components,
containers. Understanding Layout Managers, Flow Layout, Border Layout, Grid Layout, Card Layout, Grid Bag
Layout.
Event Handling- The Delegation event model- Events, Event sources, Event Listeners, Event classes, Handling
mouse and keyboard events, Adapter classes, Inner classes, Anonymous Inner classes.
A Simple Swing Application, Applets – Applets and HTML, Security Issues, Applets and Applications,
passing parameters to applets. Creating a Swing Applet, Painting in Swing, A Paint example, Exploring Swing
Controls- JLabel and Image Icon, JText Field, The Swing Buttons- JButton, JToggle Button, JCheck Box,
JRadio Button, JTabbed Pane, JScroll Pane, JList, JCombo Box, Swing Menus, Dialogs.
TEXT BOOKS:
1. Java The complete reference, 9th edition, Herbert Schildt, McGraw Hill Education (India) Pvt.Ltd.
2. Understanding Object-Oriented Programming with Java, updated edition, T. Budd, Pearson Education.
REFERENCE BOOKS:
1. An Introduction to programming and OO design using Java, J. Nino and F.A. Hosch,John Wiley & sons
2. Introduction to Java programming, Y. Daniel Liang, Pearson Education.
3. Object Oriented Programming through Java, P. Radha Krishna, University Press.
4. Programming in Java, S. Malhotra, S. Chudhary, 2nd edition, Oxford Univ. Press.
5. Java Programming and Object-oriented Application Development, R. A. Johnson, Cengage Learning.
KOMMURI PRTAP REDDY INSTITUTE OF TECHNOLOGY
Ghanpur (v),Ghatkesar(m),Medchal dist pin:-504304
Department Computer Science And Engineering
JAVA Programming - LESSON PLAN
Course Code: CS405PC Course Title: JAVA Programming
Class: II – B.Tech – II - Sem Academic Year: 2021 -2022
Instructor: A.simhadri Babu Designation: Asst. Professor
UNIT I Syllabus
Object-Oriented Thinking- A way of viewing world – Agents and Communities, messages and methods,
Responsibilities, Classes and Instances, Class Hierarchies- Inheritance, Method binding, Overriding and Exceptions,
Summary of Object-Oriented concepts. Java buzzwords, An Overview of Java, Data types, Variables and Arrays,
operators, expressions, control statements, Introducing classes, Methods and Classes, String handling.
Text COs
Sessio Chapter No. & Web
Date Topic Proposed to be Covered /Referenc Achieve
n No. Page No. Resources
e Book d
https://www.
A Way of Viewing World — tutorialspoin
T1 Ch1 &
1 21.03.2022 Agents, Responsibility, Messages, t.com/java/ja
P 3 -9
Methods, History of Java, va_overview
.html
http://www.
w3professors
.com/java-
T1 CH-1 & tutorials/java
2 22.03.2022 Java Buzzwords,
P 10 - 13 -
introduction/j
ava-
buzzwords/
https://howt
odoinjava.co
3 24.03.2022 JRE, JVM, JDK T2 Ch-1 & P14 CO1
m/java/basics
/jdk-jre-jvm/
http://web.e
ngr.oregonst
Object Oriented Thinking and
ate.edu/~bud
Java Basics: Need for OOP
4 24.03.2022 T2 Ch-1 & P 17-34 d/Books/oop
Paradigm, Summary of OOP
intro3e/info/
Concepts- Over view of JAVA
slides/chap0
1/java.pdf
http://www.
T1 Ch-3 & pskills.in/jav
5 26.03.2022 Data Types, Variables,
p35 -45 a/data-types-
java.jsp
https://www.
Scope and Life Time of Variables, T1 Ch-3 &
6 28.03.2022 tutorialspoin
type conversion and casting p45- 47
t.com/java/ja
va_overview
.html
https://www.
tutorialspoin
T1 Ch-3 &
7 03.04.2022 Arrays t.com/java/ja
p51- 58
va_overview
.html
https://sites.
google.com/
T1 Ch-4& site/parishud
8 04.04.2022 Operators, Expressions
p61- 79 h/corejavat/4
-java-
operators
https://sites.
google.com/
Control Statements, Simple Java T1 Ch-5& site/parishud
9 5.04.2022
Program, p81- 106 h/corejavat/4
-java-
operators
https://www.
javatpoint.co
Concepts of Classes, Objects, T1 Ch-6 &
10 6.04.2022 m/object-
Constructors p109- 032
and-class-in-
java
https://www.
javatpoint.co
Methods, Access Control, This T1 Ch-7&
11 7.04.2022 m/object-
Keyword, Garbage Collection, P039- 159
and-class-in-
java
https://www.
Overloading Methods and T1 Ch-7& javatpoint.co
03 8.04.2022
Constructors, Method Binding, p035- 155 m/object-
class
https://www.
Inheritance, Overriding and T1 Ch-8 & javatpoint.co
13 10.04.2022
Exceptions, super, final p161 - 185 m/object-
class
https://www.
Parameter Passing, Recursion,
T1 Ch-7 & javatpoint.co
14 13.04.2022 Nested and Inner Classes,
p035 - 145 m/object-
Exploring String Class.
class
Polymorphism-ad hoc
polymorphism, pure T1 Ch-8 &
15 13.04.2022
polymorphism, method overriding, p161 - 185
abstract classes, Object class
UNIT II Syllabus
Packages- Defining a Package, CLASSPATH, Access protection, importing packages.
Interfaces- defining an interface, implementing interfaces, Nested interfaces, applying interfaces, variables in
interfaces and extending interfaces.
Stream based I/O (java.io) – The Stream classes-Byte streams and Character streams, Reading console Input and
Writing Console Output, File class, Reading and writing Files, Random access file operations, The Console class,
Serialization, Enumerations, auto boxing, generics.
https://www.
T1 Ch-9 &
16 16.04.2022 Packages Introduction javatpoint.co
p 187- 188
m/package
https://www.
T1 Ch-8 &
17 17.04.2022 Package CLASSPATH javatpoint.co
p 188- 189
m/package
https://www.
Access Protection in packages, T1 Ch-8 &
18 19.04.2022 javatpoint.co
importing and creating packages p 190- 194
m/package
https://www.
Interface introduction – Defining
T1 Ch-9 & javatpoint.co
19 22.04.2022 an interface, implementing
p 196- 204 m/interface-
interfaces
in-java
https://www.
Nested interfaces, applying T1 Ch-9 & javatpoint.co
20 24.04.2022
interfaces p 205- 203 m/interface-
in-java
https://www.
variables in interfaces and
T1 Ch-8 & javatpoint.co
21 25.04.2022 extending interfaces.
p 205- 203 m/interface-
Multiple Inheritance with interface CO2
in-java
Stream based I/O (java.io) – The
https://www.
Stream classes-Byte streams and
T1 Ch-13 & inf.unibz.it/~r
22 26.04.2022 Character streams, Reading
p 304- 308 usso/AP/LECT
console Input and Writing Console 4.pdf
Output
https://docs.
oracle.com/ja
File class, Reading and writing
T1 Ch 13 & vase/7/docs/
23 27.04.2022 Files, Random access file
P309-336 api/java/io/R
operations
andomAccess
File.html
https://www.
T1 Ch 13 & inf.unibz.it/~r
24 28.04.2022 The Console class, Serialization
P308 usso/AP/LECT
4.pdf
https://www.
javatpoint.co
Enumerations, auto boxing, T1 Ch 03 &
25 30.04.2022 m/autoboxin
annotations, generics. P263-292
g-and-
unboxing
Unite -3 Syllabus
Exception handling - Fundamentals of exception handling, Exception types, Termination or resumptive models,
Uncaught exceptions, using try and catch, multiple catch clauses, nested try statements, throw, throws and finally,
built- in exceptions, creating own exception sub classes.
Multithreading- Differences between thread-based multitasking and process-based multitasking, Java thread model,
creating threads, thread priorities, synchronizing threads, inter thread communication.
https://www.
javatpoint.co
Exception Handling: T1 Ch 10&
26 04.05.2022 m/exception
Introduction p 213 - 232
-handling-
in-java
https://www.
Ch 10& javatpoint.co
Concepts of Exception Handling, T1
27 05.05.2022 m/exception
Benefits of Exception Handling, p 213 - 232
-handling-
in-java
Ch 10& https://www.
Termination or Resumptive T1 javatpoint.co
28 5.05.2022
Models, Exception Hierarchy, p 213 - 232 m/try-catch-
block
Usage of Try, Catch, Throw, Ch 10& https://www.
Throws and Finally, Built in T1 javatpoint.co
29 05.05.2022
Exceptions, Creating Own p 213 - 232 m/try-catch-
Exception Sub Classes. block
https://www.
javatpoint.co
m/multithrea
ding
CO3
Differences between Multi- T1 Ch 11 & http://www.
30 14.05.2022
Threading and Multitasking, p233 - 259 pskills.in/jav
a/user-
custom-
define.jsp -
in-java
https://www.
Thread Life Cycle, Creating T1 Ch 11 & javatpoint.co
31 5.06.2022
Threads, p233 - 259 m/life-cycle-
of-a-thread
https://www.
Thread Priorities, Synchronizing T1 Ch 11 & javatpoint.co
32 6.06.2022
Threads, p233 - 259 m/life-cycle-
of-a-thread
https://www.
javatpoint.co
T1 Ch 11 & m/inter-
33 7.06.2022 Inter-thread Communication,
p233 - 259 thread-
communicati
on-example
https://www.
javatpoint.co
T1 Ch 11 & m/inter-
34 08.06.2022 Thread Groups
p233 - 259 thread-
communicati
on-example
https://www.
javatpoint.co
T1 Ch 11 &
35 12.06.2022 Daemon Threads. Enumerations, m/autoboxin
p233 - 259
g-and-
unboxing
Unit -4 Syllabus
The Collections Framework (java.util)- Collections overview, Collection Interfaces, The Collection classes- Array
List, Linked List, Hash Set, Tree Set, Priority Queue, Array Deque. Accessing a Collection via an Iterator, Using an
Iterator, The For-Each alternative, Map Interfaces and Classes, Comparators, Collection algorithms, Arrays, The
Legacy Classes and Interfaces- Dictionary, Hashtable ,Properties, Stack, Vector More Utility classes, String
Tokenizer, Bit Set, Date, Calendar, Random, Formatter, Scanner
https://docs.
oracle.com/ja
The Collections Framework vase/8/docs/t
T1 Ch 11 &
36 13.06.2022 (java.util)- Collections overview, echnotes/gui
P 497 - 577
Collection Interfaces des/collectio
ns/overview.
html
Ch 11 & https://docs.
P 497 - 577 oracle.com/ja
vase/8/docs/t
T1
37 14.06.2022 The Collection classes- echnotes/gui
des/collectio
ns/overview.
html
Ch 11 & https://docs.
P 497 - 577 oracle.com/ja
T1 vase/8/docs/ CO4
38 16.06.2022 Array List, Linked List
api/java/util/
ArrayList.htm
l
Ch 11 & https://docs.
P 497 - 577 oracle.com/ja
T1
39 17.06.2022 Hash Set, Tree Set vase/8/docs/
api/java/util/
HashSet.html
Ch 11 & https://docs.
P 497 - 577 oracle.com/ja
18.06.2022 Priority Queue, Array Deque. T1
40 vase/8/docs/
api/java/util/
Queue.html
Ch 11 & https://docs.
P 497 - 577 oracle.com/ja
Accessing a Collection via an T1
41 20.06.2022 vase/8/docs/
Iterator, Using an Iterator
api/java/util/
concurrent/C
oncurrentHas
hMap.html
Ch 11 & https://docs.
P 497 - 577 oracle.com/ja
vase/8/docs/
The For-Each alternative, Map T1
api/java/util/
Interfaces and Classes
concurrent/C
oncurrentHas
hMap.html
Ch 11 & https://docs.
P 497 - 577 oracle.com/ja
vase/8/docs/
21.06.2022 Comparators T1
42 api/java/util/
concurrent/C
oncurrentHas
hMap.html
Ch 11 & https://www.
P 497 - 577 tutorialspoint
T1 .com/java/jav
43 22.06.2022 Collection algorithms
a_collection_
algorithms.ht
m
Ch 11 & https://www.
P 497 - 577 tutorialspoint
Arrays, The Legacy Classes and T1
44 23.06.2022 .com/java/jav
Interfaces- Dictionary
a_collections.
htm
Ch 11 & https://begin
P 497 - 577 nersbook.co
T1 m/2044/07/h
45 24.06.2022 Hashtable ,Properties
ashtable-in-
java-with-
example/
Ch 11 & https://docs.
P 497 - 577 oracle.com/ja
T1
46 25.06.2022 Stack, Vector More Utility classes vase/7/docs/
api/java/util/
Stack.html
Ch 11 & https://www.
P 497 - 577 geeksforgeek
s.org/stringto
T1 kenizer-class-
47 26.06.2022 String Tokenizer,
java-
example-set-
1-
constructors/
Ch 11 & https://www.
P 497 - 577 codota.com/c
T1 ode/java/met
48 27.06.2022 Bit Set, Date, Calendar
hods/java.util
.Calendar/set
Time
T1 Ch 11 & https://docs.
49 29.06.2022 Random, Formatter, Scanner
P 497 - 577 oracle.com/ja
vase/8/docs/
api/?java/util
/Scanner.htm
l
50 30.06.2022 Revision on Collections - Test
Unity -5 Syllabus
GUI Programming with Swing – Introduction, limitations of AWT, MVC architecture, components, containers.
Understanding Layout Managers, Flow Layout, Border Layout, Grid Layout, Card Layout, Grid Bag Layout.
Event Handling- The Delegation event model- Events, Event sources, Event Listeners, Event classes, Handling
mouse and keyboard events, Adapter classes, Inner classes, Anonymous Inner classes.
A Simple Swing Application, Applets – Applets and HTML, Security Issues, Applets and Applications, passing
parameters to applets. Creating a Swing Applet, Painting in Swing, A Paint example, Exploring Swing Controls-
JLabel and Image Icon, JText Field,
The Swing Buttons- JButton, JToggle Button, JCheck Box, JRadio Button, JTabbed Pane, JScroll Pane, JList,
JCombo Box, Swing Menus, Dialogs.
https://docs.
oracle.com/ja
vase/8/docs/
GUI Programming with Swing – T1 Ch 25 & api/java/awt/
51 1.07.2022
Introduction, limitations of AWT P 797 - 803 package-
summary.htm
l
https://www.
tutorialspoint
MVC architecture, components, T1 Ch 25 & .com/design_
52 2.03.2022
containers. P 797 - 803 pattern/mvc_
pattern.htm
Ch 26 & https://docs.
P 855 - 865 oracle.com/ja
vase/8/docs/ CO5
Understanding Layout Managers, T1
53 2.07.2022 api/java/awt/
Flow Layout, Border Layout,
LayoutManag
er.html
Ch 26 & https://docs.
P 855 - 865 oracle.com/ja
Grid Layout, Card Layout, Grid vase/8/docs/
54 3.07.2022 Bag Layout. api/java/awt/
LayoutManag
er.html
https://docs.
oracle.com/ja
Event Handling: Events Ch 24 &
55 4.07.2022 vase/8/docs/
Introduction Event Sources P 769 - 795
api/java/awt/
event/Action
Listener.html
https://www.
javatpoint.co
T1 Ch 24 &
56 5.07.2022 Event Classes, Event Listeners, m/event-
P 769 - 795
handling-in-
java
https://www.
javatpoint.co
T1 Ch 24 &
57 6.07.2022 Delegation Event Model, m/event-
P 769 - 795
handling-in-
java
https://www.
javatpoint.co
Handling Mouse and Keyboard T1 Ch 24 &
58 7.07.2022 m/event-
Events, Adapter Classes. P 769 - 795
handling-in-
java
https://docs.
oracle.com/ja
A Simple Swing Application,
T1 CH 31 & vase/8/docs/
59 8.07.2022 Applets – Applets and HTML,
P 1051 - 1037 api/java/appl
Security Issues,
et/package-
frame.html
https://www.
javatpoint.co
Differences between Applets and T1 Ch 23 &
60 10.07.2022 m/java-
Applications, Creating Applets, P747-767
applet
Ch 23 & https://www.
Passing Parameters to Applets, P747-767 javatpoint.co
11.07.2022 Creating a Swing Applet, Painting T1
61 m/java-
in Swing applet
https://docs.
oracle.com/ja
Exploring Swing Controls - JLabel Ch 23 & vase/8/docs/
T1
62 12.07.2022 and Image Icon, JText Field P747-767 api/javax/swi CO6
ng/package-
frame.html
https://docs.
oracle.com/ja
The Swing Buttons- JButton, vase/8/docs/
T1 Ch 23 &
63 13.07.2022 JToggle Button, JCheck Box, api/javax/swi
P747-767
JRadio Button, ng/package-
frame.html
TEXT BOOK:
1. Java The complete reference, 9th edition, Herbert Schildt, McGraw Hill Education (India)
Pvt.Ltd.
2. Understanding Object-Oriented Programming with Java, updated edition, T. Budd, Pearson
Education.
REFERENCE BOOKS:
1. An Introduction to programming and OO design using Java, J. Nino and F.A. Hosch,
John Wiley & sons
2. Introduction to Java programming, Y. Daniel Liang, Pearson Education.
3. Object Oriented Programming through Java, P. Radha Krishna, University Press.
4. Programming in Java, S. Malhotra, S. Chudhary, 2nd edition, Oxford Univ. Press.
5. Java Programming and Object-oriented Application Development, R. A. Johnson, Cengage
Learning.
Course Objective
This course is aimed for the student to understanding of OOP concepts and basics
of Java programming (Console and GUI based), the skills to apply OOP and ava
programming in problem solving and should have the ability to extend his
knowledge of java programming further on his/her own.
Course Outcomes
CO1 3 2 2 1 2 2 2 2 2 2 3 3 CO1 3 3
CO2 2 3 3 1 2 2 2 1 2 3 2 CO2 3 2
CO3 2 2 3 2 2 2 2 2 2 2 CO3 2 3
CO4 2 2 3 2 2 2 2 2 1 2 2 2 CO4 2 2
CO5 1 2 3 2 2 1 2 2 3 2 2 CO5 2 3
CO6 1 2 3 2 2 2 2 3 2 3 3 3 CO6 2 3
B.TECH II YEAR - II
SEM(2021-2022)
UNIT-I
UNIT - II
Stream based I/O (java.io) – The Stream classes-Byte streams and Character streams, Reading
console Input and Writing Console Output, File class, Reading and writing Files, Random access file
operations, The Console class, Serialization, Enumerations, auto boxing, generics.
UNIT - III
UNIT - IV
The Collections Framework (java.util)- Collections overview, Collection Interfaces, The Collection
classes- Array List, Linked List, Hash Set, Tree Set, Priority Queue, Array Deque. Accessing a
Collection via an Iterator, Using an Iterator, The For-Each alternative, Map Interfaces and Classes,
Comparators, Collection algorithms, Arrays, The Legacy Classes and Interfaces- Dictionary,
Hashtable ,Properties, Stack, Vector,More Utility classes, String Tokenizer, Bit Set, Date,
Calendar, Random, Formatter, Scanner
UNIT - V
GUI Programming with Swing – Introduction, limitations of AWT, MVC architecture, components,
containers. Understanding Layout Managers, Flow Layout, Border Layout, Grid Layout, Card Layout,
Grid Bag Layout.
Event Handling- The Delegation event model- Events, Event sources, Event Listeners, Event
classes, Handling mouse and keyboard events, Adapter classes, Inner classes, Anonymous Inner
classes.
A Simple Swing Application, Applets – Applets and HTML, Security Issues, Applets and
Applications, passing parameters to applets. Creating a Swing Applet, Painting in Swing, A Paint
example, Exploring Swing Controls- JLabel and Image Icon, JText Field, The Swing Buttons
JButton, JToggle Button, JCheck Box, JRadio Button, JTabbed Pane, JScroll Pane, JList, JCombo
Box, Swing Menus, Dialogs.
TEXT BOOKS:
1. Java The complete reference, 9th edition, Herbert Schildt, McGraw Hill Education (India) Pvt.
Ltd.
2. Understanding Object-Oriented Programming with Java, updated edition, T. Budd, Pearson
Education.
REFERENCEBOOKS:
1. JavaforProgrammers,P.J.DeitelandH.M.Deitel,PEA(or)Java:HowtoProgram,P.J.Deiteland
H.M.Deitel, PHI
2. ObjectOrientedProgrammingthroughJava,P.RadhaKrishna,UniversitiesPress.
3. ThinkinginJava, Bruce Eckel, PE
4. ProgramminginJava,S.MalhotraandS.Choudhary,OxfordUniversitiesPress.
CourseOutcomes:
1 OOPConcepts:-Dataabstraction,encapsulationinheritance 1
I
2 BenefitsofInheritance 2
I
3 I Polymorphism,classesandobjects 2
4 I Procedural andobjectorientedprogrammingparadigms 3
5 I JavaProgramming-Historyof Java 4
7 I ScopeandLifetimeofvariables 10
8 I Operators,OperatorHierarchy,Expressions 11-12
9 I Typeconversionandcasting,Enumeratedtypes 12-13
Controlflow-
10 I 13-14
blockscope,conditionalstatements,loops,breakandcontinuestate
ments
11 I Simplejavastandalone programs,arrays 14-18
13 I Constructors,methods,parameterpassing 19-20
14 I Staticfieldsandmethods,accesscontrol,thisreference, 21-30
Overloadingmethodsandconstructors,recursion,
15 I 30-34
garbagecollection,
Buildingstrings, exploringstringclass.
16 I 34-36
S.No Unit Topic Pageno
19 I Polymorphism–dynamicbinding,methodoverriding, 41-42
Interfaces-InterfacesVs
21 II 43-44
Abstractclasses,defininganinterface,implement
interfaces
Accessing implementations through interface
22 II 45
references,extendinginterface.
24 II Anonymousinnerclasses,staticinnerclasses,examples. 46
25 II Packages-Defining,creatingandaccessingapackage, 46-47
26 II UnderstandingCLASSPATH, importingpackages. 47
30 III Rethrowingexceptions,exceptionspecification, 54
31 III Builtinexceptions,creatingownexceptionsubclasses. 54
Multithreading–
32 III 55-56
Differencesbetweenmultipleprocessesandmultiplethreads,
thread states
Creatingthreads,interruptingthreads,threadpriorities,sy
33 III 56-59
nchronizingthreads
34 III Inter-threadcommunication,producerconsumerpattern 59
CollectionFrameworkin Java–
36 IV 62
Introductiontojavacollections,Overviewofjavacollectionframe
work,Generics
Commonlyusedcollection classes-ArrayList,Vector,
37 IV 63-71
Hashtable,Stack, Enumeration,Iterator
ConnectingtoDatabase –
41 IV 85-88
JDBCType1to4drivers,Connectingto aadatabase,
Queryingadatabaseandprocessingtheresults,updatingdatawith
42 IV JDBC. 89-94
OverviewofsomeSwingcomponents–
45 V 104-108
Jbutton,JLabel,JTextField,JTextArea,
simpleSwingapplications,
Layoutmanagement– Layoutmanagertypes –
46 V 109-111
border,gridandflow
EventHandling-
47 V 111-112
Events,Eventsources,Eventclasses,EventListeners,
RelationshipbetweenEventsourcesandListeners,Delegationeve
48 V 112-113
ntmodel,
Handlingabuttonclick,HandlingMouseevents,Adapterclasses.
49 V 114-116
Differencesbetweenappletsandapplications,
51 V 120
Lifecycleofanapplet,
OOPConcepts
Simula isconsideredasthefirstobject-
orientedprogramminglanguage.Theprogrammingparadigmwhereeverythingisrepresentedasanobjec
tisknownastrulyobject-orientedprogramminglanguage.
OOPs(ObjectOrientedProgrammingSystem)
Objectmeansarealwordentitysuchaspen,chair,tableetc.Object-OrientedProgramming isa
methodology or paradigm to design a program using classes and objects. It simplifies
thesoftwaredevelopment and maintenancebyprovidingsomeconcepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Object
Any entity that has state and behavior is known as an object. For example: chair, pen,
table,keyboard,bikeetc. It can bephysicalandlogical.
Class
Collectionof objectsiscalledclass.Itisalogicalentity.
Inheritance
When one object acquires all the properties and behaviours of parent object i.e. known
asinheritance.It providescodereusability.It isusedtoachieveruntimepolymorphism.
JAVAPROGRAMMING Page1
JAVAPROGRAMMING Page2
Polymorphism
Whenonetaskisperformedbydifferentwaysi.e.knownaspolymorphism.Forexample:toconvincethecusto
mer differently, todraw somethinge.g. shapeorrectangleetc.
polymorphism.Another example can be to speak something e.g. cat speaks meaw, dog
Hidinginternaldetailsandshowingfunctionalityisknownasabstraction.Forexample:phone
call,wedon'tknowtheinternalprocessing.
Encapsulation
Binding(orwrapping)codeanddatatogetherintoasingleunitisknownasencapsulation.Forexampl
e: capsule, it is wrapped with differentmedicines.
Ajavaclassistheexampleofencapsulation.Javabeanisthefullyencapsulatedclassbecauseallthedata
membersareprivate here.
Benefitsof Inheritance
One of the key benefits of inheritance is to minimize the amount of duplicate code in
anapplication by sharing common code amongst several subclasses. Where equivalent
codeexists in two related classes, the hierarchy can usually be refactored to move the
commoncode up to a mutual superclass. This also tends to result in a better organization of
code andsmaller,simpler compilation units.
Inheritancecanalsomakeapplication code moreflexibleto
changebecauseclassesthatinherit from a common superclass can be used
interchangeably. If the return type of amethodis superclass
Reusability-facilitytouse publicmethods of baseclass without rewritingthe same.
JAVAPROGRAMMING Page3
Extensibility -extending thebaseclass logic asperbusiness logicofthederivedclass.
JAVAPROGRAMMING Page4
Datahiding-baseclass candecide tokeep some data privateso thatit cannotbe
alteredbythe derivedclass
Proceduralandobjectorientedprogrammingparadigms
JAVAPROGRAMMING Page5
JavaProgramming-HistoryofJava
ThehistoryofjavastartsfromGreenTeam.Javateammembers(alsoknownas Green
Team), initiated a revolutionary task to develop a language for digitaldevicessuchas
set-topboxes,televisionsetc.
For the green team members, it was an advance concept at that time. But, it
wassuitedforinternetprogramming.Later,JavatechnologyasincorporatedbyNetscape.
2) Originally designed for small, embedded systems in electronic appliances like set-
topboxes.
3) Firstly,itwascalled"Greentalk"byJamesGoslingandfileextensionwas.gt.
4) After that, it was called Oak and was developed as a part of the
Greenproject.
JavaVersionHistory
Therearemanyjava
versionsthathasbeenreleased.CurrentstablereleaseofJavaisJavaSE8.
JAVAPROGRAMMING Page6
FeaturesofJava
There is given many features of java. They are also known as java buzzwords. The Java
Featuresgivenbelow aresimple and easyto 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.
Thecomments can be used to provide information or explanation about the variable, method,
class oranystatement.It canalsobeusedto hide programcodeforspecifictime.
TypesofJavaComments
1. SingleLineComment
2. MultiLineComment
3. DocumentationComment
JavaSingleLineComment
Syntax:
JAVAPROGRAMMING Page7
1. //Thisissingle linecomment
JAVAPROGRAMMING Page8
Example:
publicclassCommentExample1{
public static void main(String[] args)
{int i=10;//Here, i is a
variableSystem.out.println(i);
}
}
Output:
10
JavaMultiLineComment
Syntax:
/*T
hisis
multi
linecom
ment
*/
Example:
publicclassCommentExample2{
publicstaticvoidmain(String[] args){
/*Let'sdeclareandprintva
riableinjava.*/
int
i=10;System.out.prin
tln(i);
}}
Output:
10
JAVAPROGRAMMING Page9
JAVAPROGRAMMING Page10
JavaDocumentationComment
The documentation comment is used to create documentation API. To create documentation API, you
needto usejavadoctool.
Syntax:
/**
This
is
documentation
comment
*/
Example:
Compileitbyjavactool:
javacCalculator.java
CreateDocumentation APIbyjavadoctool:
javadocCalculator.java
Now,therewillbeHTMLfilescreatedforyourCalculatorclassinthecurrentdirectory.OpentheHTMLfilesandseet
heexplanation ofCalculatorclass provided throughdocumentationcomment.
JAVAPROGRAMMING Page11
DataTypes
o Primitivedatatypes
o Non-primitivedatatypes
byte 0 1byte
short 0 2byte
int 0 4byte
long 0L 8byte
JavaVariableExample:AddTwoNumbers
classSimple{
publicstaticvoid main(String[] args){
int
a=10;int
b=10;intc
=a+b;
System.out.println(c);
}}
Output:20
JAVAPROGRAMMING Page12
VariablesandDataTypes inJava
Variableisanameofmemorylocation.Therearethreetypesofvariablesinjava:local,instanceandstatic.
TypesofVariable
Therearethreetypes of variablesinjava:
o localvariable
o instancevariable
o staticvariable
1) LocalVariable
Avariablewhichisdeclaredinsidethemethodiscalledlocalvariable.
2) InstanceVariable
3) Staticvariable
Exampletounderstandthetypesofvariablesinjava
classA{
int data=50;//instance
variablestatic int m=100;//static
variablevoid method(){
intn=90;//localvariable
}
}//endofclass
ConstantsinJava
A constant is a variable which cannot have its value changed after declaration. It uses the
'final'keyword.
Syntax
modifierfinaldataType variableName=value;//globalconstant
modifierstaticfinal dataTypevariableName=value;//constantwithin ac
JAVAPROGRAMMING Page13
ScopeandLifeTimeofVariables
The scope of a variable defines the section of the code in which the variable is visible. As
ageneral rule, variables that are defined withina block are not accessible outside that
block.Thelifetimeofavariablereferstohowlongthevariableexistsbeforeitisdestroyed.Destroying
variables refers to deallocating the memory that was allotted to the variables whendeclaring it.
We have written a few classes till now. You might have observed that not allvariables are the
same. The ones declared in the body of a method were different from thosethat were declared
in the class itself. There are three types of variables: instance variables,formalparametersor
localvariablesandlocalvariables.
Instancevariables
Instance variables are those that are defined within a class itself and not in any method
orconstructor of the class. They are known as instance variables because every instance of
theclass (object) contains a copy of these variables. The scope of instance variables is
determinedby the access specifier that is applied to these variables. We have already seen
about 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 Javawhen there are no more reference to that object. We shall see about Java's
automatic garbagecollectorlateron.
Argumentvariables
Thesearethevariablesthataredefinedintheheaderoafconstructororamethod.Thescopeof these
variables is the method or constructor in which they are defined. The lifetime
islimitedtothetimeforwhichthemethodkeepsexecuting.Oncethemethodfinishesexecution,thesev
ariablesaredestroyed.
Localvariables
One important distinction between these three types of variables is that access specifiers
canbeappliedtoinstancevariablesonlyandnottoargumentor localvariables.
In addition to the local variables defined in a method, we also have variables that are
definedinbockslifeanifblockandanelseblock.Thescopeandisthesameasthatoftheblockitself.
JAVAPROGRAMMING Page14
Operatorsinjava
o UnaryOperator,
o ArithmeticOperator,
o shiftOperator,
o RelationalOperator,
o BitwiseOperator,
o LogicalOperator,
o TernaryOperatorand
o AssignmentOperator.
OperatorsHierarchy
JAVAPROGRAMMING Page15
JAVAPROGRAMMING Page16
Expressions
Expressions are essential building blocks of any Java program, usually created to produce a
newvalue, although sometimes an expression simply assigns a value to a variable. Expressions
arebuiltusingvalues, variables, operatorsand method calls.
TypesofExpressions
While an expression frequently produces a result, it doesn't always. There are three types
ofexpressions inJava:
JavaTypecastingandTypeconversion
WideningorAutomatic TypeConversion
Wideningconversiontakesplacewhentwodatatypesareautomaticallyconverted.Thishappenswhen:
Thetwodatatypesarecompatible.
Whenweassignvalueofasmallerdatatypetoabiggerdata type.
For Example, in java the numeric data types are compatible with each other but no
automaticconversion is supported from numeric type to char or boolean. Also, char and boolean
are notcompatible with each other.
NarrowingorExplicitConversion
Ifwewanttoassignavalueoflargerdatatypetoasmallerdatatypeweperformexplicittypecastingornarrowing.
Thisisuseful forincompatible datatypeswhere automaticconversion cannotbedone.
Here,target-typespecifiesthedesiredtypetoconvertthespecifiedvalue to.
JAVAPROGRAMMING Page17
JavaEnum
Itcanbeusedfordaysoftheweek(SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDA
YandSATURDAY),directions(NORTH,SOUTH,EASTandWEST)
etc. The java enum constants are static and final implicitly. It is available from JDK
Simpleexampleofjava enum
classEnumExample1{
publicenumSeason{WINTER,SPRING, SUMMER,FALL}
ControlFlow Statements
The control flow statements in Java allow you to run or skip blocks of code when
specialconditionsaremet.
The“if”Statement
The “if” statement in Java works exactly like in most programming languages. With the help
of“if” you can choose to execute a specific block of code when a predefined condition is met.
Thestructureof the“if”statement in Javalooks likethis:
if (condition){
//executethiscode
}
JAVAPROGRAMMING Page18
JAVAPROGRAMMING Page19
The condition is Boolean. Boolean means it may be true or false. For example you may put
amathematicalequation ascondition.Look atthis full example:
CreatingaStand-AloneJavaApplication
1. Write a main method that runs your program. You can write this method anywhere. In
thisexample, I'll write my main method in a class called Main that has no other methods.
Forexample:
2. public class
Main3. {
4. public static void main(String[]
args)5. {
6. Game.play();
7. }}
8. Makesureyourcodeiscompiled,andthatyou havetesteditthoroughly.
9. If you're using Windows, you will need to set your path to include Java, if you
haven'tdone so already. This is a delicate operation. Open Explorer, and look
insideC:\ProgramFiles\Java, and you should see some version of the JDK. Open this folder,
andthen open the bin folder. Select the complete path from the top of the Explorer window,
andpressCtrl-C to copyit.
Next, find the "My Computer" icon (on your Start menu or desktop), right-click it, and
selectproperties. 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
thecontents 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
goahead and save your changes. (If you have any Cmd windows open, you will need to
closethem.)
10. If you're using Windows, go to the Start menu and type "cmd" to run a program
thatbrings up a command prompt window. If you're using a Mac or Linux machine, run
theTerminalprogram to bringup acommand prompt.
11. In Windows, type dir at the command prompt to list the contents of the current
directory.OnaMacorLinuxmachine, type ls to do this.
JAVAPROGRAMMING Page20
12. Now we want to change to the directory/folder that contains your compiled code. Look
atthe listing of sub-directories within this directory, and identify which one contains your
code.Type cd followed by the name of that directory, to change to that directory. For
example, tochangeto a directorycalledDesktop,you would type:
cdDesktop
Tochangetotheparentdirectory,type:
cd..
Every time you change to a new directory, list the contents of that directory to see where to
gonext.Continuelistingandchangingdirectoriesuntilyoureachthedirectorythatcontains
your.classfiles.
13. IfyoucompiledyourprogramusingJava1.6,but
plantorunitonaMac,you'llneedtorecompileyourcodefrom thecommand line, bytyping:
javac-target1.5*.java
Arrays
Java provides a data structure, the array,which stores afixed-size sequential collection
ofelements of the same type. An array is used to store a collection of data, but it is often
moreusefulto think ofan arrayasacollection ofvariables ofthesame type.
Instead of declaring individual variables, such as number0, number1, ..., and number99,
youdeclareonearrayvariablesuchasnumbersandusenumbers[0],numbers[1],and...,numbers[99] to
represent individual variables.
This tutorial introduces how to declare array variables, create arrays, and process arrays
usingindexedvariables.
DeclaringArrayVariables:
To use an array in a program, you must declare a variable to reference the array, and you
mustspecify the type of array the variable can reference. Here is the syntax for declaring an
arrayvariable:
JAVAPROGRAMMING Page22
Thefollowingcodesnippets are examples ofthis syntax:
double[]myList; //preferredway.
or
doublemyList[]; //worksbutnotpreferred way.
CreatingArrays:
Youcan createan arraybyusingthe new operator with the followingsyntax:
arrayRefVar=newdataType[arraySize];
Theabovestatement does two things:
ItcreatesanarrayusingnewdataType[arraySize];
Declaringanarrayvariable,creatinganarray,andassigningthereferenceofthearraytothevariablecan
becombined in one statement, as shown below:
dataType[]arrayRefVar=newdataType[arraySize];
Alternativelyyoucancreatearraysasfollows:
dataType[]arrayRefVar={value0,value1,...,valuek};
Thearrayelementsareaccessedthroughtheindex.Arrayindicesare0-based;thatis,theystartfrom0 to
arrayRefVar.length-1.
Example:
Followingstatementdeclaresanarrayvariable,myList,createsanarrayof10elementsofdoubletypeand
assigns its referenceto myList:
double[]myList=newdouble[10];
FollowingpicturerepresentsarraymyList.Here,myListholdstendoublevaluesandtheindicesarefrom 0
to 9.
JAVAPROGRAMMING Page23
JAVAPROGRAMMING Page24
ProcessingArrays:
Whenprocessingarrayelements,weoftenuseeitherforlooporforeachloopbecausealloftheelementsin an
arrayare ofthe same typeand thesizeof thearrayis known.
Example:
Hereisacompleteexample ofshowinghowto create,initializeand processarrays:
publicclass TestArray
{
public static void main(String[] args)
{double[]myList={1.9,2.9,3.4,3.5};
//Printallthearrayelementsfor(in
t i=0;i<myList.length; i++){
System.out.println(myList[i]+"");
}
// Summing all
elementsdoubletotal =0;
for (int i = 0; i <myList.length; i++)
{total+=myList[i];
}
System.out.println("Totalis"+total);
// Finding the largest
elementdoublemax=myList[
0];
for (int i = 1; i <myList.length; i++)
{if(myList[i]>max)max =myList[i];
}
System.out.println("Maxis"+max);
}
JAVAPROGRAMMING Page25
JAVAPROGRAMMING Page26
Thiswouldproducethefollowingresult:
1.9
2.9
3.4
3.5
Totalis 11.7
Maxis 3.5
publicclass TestArray{
public static void main(String[] args)
{double[]myList ={1.9,2.9,3.4,3.5};
//Print all the arrayelements
for(doubleelement:myList){S
ystem.out.println(element);
}}}
JavaConsoleClass
TheJavaConsoleclassisbeusedtogetinputfromconsole.Itprovidesmethodstoreadtextsandpasswords.
Ifyou readpasswordusingConsoleclass,itwillnotbedisplayedtotheuser.
Thejava.io.Consoleclassisattachedwithsystemconsoleinternally.TheConsoleclassisintroducedsince
1.5.
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("E
nter your name: ");String
n=c.readLine();System.out.println("Welco
me"+n); } }
JAVAPROGRAMMING Page27
Output
Constructors
Java constructor is invoked at the time of object creation. It constructs the values i.e. provides
dataforthe object that is whyit is known as constructor.
Typesofjavaconstructors
Therearetwotypes ofconstructors:
1. Defaultconstructor(no-argconstructor)
2. Parameterizedconstructor
JavaDefaultConstructor
Aconstructorthat havenoparameterisknownasdefaultconstructor.
Syntaxofdefaultconstructor:
1. <class_name>(){}
Exampleofdefaultconstructor
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked
atthetimeof object creation.
classBike1{
Bike1(){System.out.println("Bikeiscreated");}
public static void main(String
JAVAPROGRAMMING Page28
args[]){Bike1b=newBike1();
}}
Output:Bikeis created
JAVAPROGRAMMING Page29
Exampleofparameterizedconstructor
In this example, we have created the constructor of Student class that have two parameters.
Wecan haveanynumberofparameters in the constructor.
classStudent4{
intid;
Stringname;
Student4(int i,String
n){id =i;
name=n;
}
voiddisplay(){System.out.println(id+""+name);}
Output:
111Karan
222Aryan
ConstructorOverloading inJava
Constructor overloading is a technique in Java in which a class can have any number
ofconstructors that differ in parameter lists.The compiler differentiates these constructors
bytakinginto account thenumberof parameters in the list and their type.
ExampleofConstructorOverloading
classStudent5{
intid;String
name;intage
;
Student5(int i,String
n){id =i;
name=n;
}
Student5(int i,String n,int
a){id =i;
name =
n;age=a;
}
voiddisplay(){System.out.println(id+""+name+""+age);}
Output:
111Karan0
222Aryan25
JavaCopyConstructor
Thereisnocopyconstructorinjava.But,wecancopythevaluesofoneobjecttoanotherlikecopyconstruc
tor in C++.
oByconstructor
oByassigningthe values
of oneobject into another
oByclone()method ofObject class
Inthisexample,wearegoingtocopythevaluesofoneobjectintoanotherusingjavaconstructor.
classStudent6{
intid;
Stringname;
Student6(int i,String
n){id =i;
name=n;
}
Student6(Student6
s){id =s.id;
name=s.name;
}
voiddisplay(){System.out.println(id+""+name);}
Output:
111Karan
111Karan
JAVAPROGRAMMING Page31
Java-Methods
A Java method is a collection of statements that are grouped together to perform an
operation.WhenyoucalltheSystem.out.println()
method,forexample,thesystemactuallyexecutesseveralstatements in order to
displayamessageonthe console.
Now you will learn how to create your own methods with or without return values, invoke
amethodwith or without parameters, and applymethod abstraction in theprogram design.
CreatingMethod
Consideringthe followingexampleto explainthesyntaxof amethod−
Syntax
Here,
publicstatic−modifier
int−returntype
methodName −nameofthemethod
a,b−formalparameters
inta, intb−listofparameters
Methoddefinitionconsistsofamethodheaderandamethodbody.Thesameisshowninthe
followingsyntax−
Syntax
modifierreturnTypenameOfMethod(Parameter List){
// methodbody
}
Thesyntaxshownabove includes−
returnType−Methodmayreturnavalue.
JAVAPROGRAMMING Page32
nameOfMethod − Thisisthe methodname. Themethodsignature consistsof the method
nameand theparameter list.
JAVAPROGRAMMING Page33
Parameter List − The list of parameters, it is the type, order, and number
ofparametersofamethod. Theseareoptional, method maycontainzero parameters.
Exampleofcallbyvaluein java
Incaseof callbyvalueoriginal valueis notchanged.Let'stake asimpleexample:
classOperation{
intdata=50;
voidchange(intdata){
data=data+100;//changes willbein thelocalvariableonly
}
public static void main(String
args[]){Operationop=newOperation();System.
out.println("before change
"+op.data);op.change(500);
System.out.println("afterchange"+op.data);
}
}
Output:beforechange50
afterchange50
StaticFieldsandMethods
The static keyword in java is used for memory management mainly. We can apply java
statickeyword with variables, methods, blocks and nested class. The static keyword belongs to the
classthan instanceof the class.
Thestatic canbe:
1. variable(alsoknownasclassvariable)
2. method(alsoknownas classmethod)
3. block
4. nestedclass
Javastaticvariable
Ifyoudeclareanyvariableasstatic,itisknownstaticvariable.
o Thestaticvariablecanbeusedtoreferthecommonpropertyofallobjects(thatisnotuniqueforeachobject)
e.g. companyname ofemployees,collegenameofstudents etc.
Itmakesyourprogrammemoryefficient (i.eitsavesmemory).
Understandingproblemwithoutstaticvariable
1. class Student{
2. introllno;
3. Stringname;
4. String
college="ITS";5.}
Exampleofstaticvariable
//Programof staticvariable
class Student8{
JAVAPROGRAMMING Page35
introllno;
JAVAPROGRAMMING Page36
Stringname;
static String college
="ITS";Student8(int r,String
n){rollno= r;
name=n;
}
voiddisplay(){System.out.println(rollno+""+name+""+college);}
public static void main(String
args[]){Student8 s1 = new
Student8(111,"Karan");Student8s2=newStude
nt8(222,"Aryan");
s1.display();
s2.display();
}}
Output:111KaranITS
222AryanITS
Javastaticmethod
Exampleofstaticmethod
//Programof changingthecommon propertyof allobjects(staticfield).
class
Student9{in
t
rollno;String
name;
staticStringcollege= "ITS";
static void
change(){college="B
JAVAPROGRAMMING Page37
BDIT";
}
Student9(int r, String
n){rollno=r;
name=n;
JAVAPROGRAMMING Page38
}
void display(){System.out.println(rollno+""+name+""+college);}
public static void main(String
args[]){Student9.change();
Student9 s1 = new Student9
(111,"Karan");Student9 s2 = new Student9
(222,"Aryan");Student9 s3 = new Student9
(333,"Sonoo");s1.display();
s2.display();
s3.display();
}}
Output:111 Karan
BBDIT222AryanBB
DIT
Javastaticblock
o Isusedtoinitializethestaticdatamember.
o Itis executedbefore mainmethod at thetime ofclassloading.
Example of static
blockclassA2{
static{System.out.println("static block is
invoked");}public static void main(String
args[]){System.out.println("Hello main");
}}
Output: static block is
invokedHellomain
AccessControl
AccessModifiersinjava
Therearetwotypesofmodifiersinjava:accessmodifiersandnon-accessmodifiers.
Theaccessmodifiersinjavaspecifiesaccessibility(scope)of adatamember,method,constructororclass.
privateaccess modifier
Theprivate access modifieris accessibleonlywithinclass.
Simpleexampleofprivateaccess modifier
In this example, we have created two classes A and Simple. A class contains private
datamember and private method. We are accessing these private members from outside the
class,sothereis compile timeerror.
classA{
privateintdata=40;
privatevoid msg(){System.out.println("Hellojava");}}
publicclassSimple{
public static void main(String
args[]){Aobj=newA();
System.out.println(obj.data);//Compile Time
Errorobj.msg();//CompileTimeError
}}
2) defaultaccessmodifier
Ifyoudon'tuseany modifier,itistreatedas default
bydefault.Thedefaultmodifierisaccessibleonlywithin package.
Exampleofdefaultaccessmodifier
In this example, we have created two packagespack and mypack. We are accessing the Aclass
from outside its package, since A class is not public, so it cannot be accessed from
outsidethepackage.
//save by
A.javapackage
pack;classA{
voidmsg(){System.out.println("Hello");}
}
//save by
B.javapackage
JAVAPROGRAMMING Page41
mypack;importp
ack.*;
JAVAPROGRAMMING Page42
classB{
public static void main(String
args[]){A obj = new A();//Compile
Time
Errorobj.msg();//CompileTimeError}}
In theabove example, the scope of class A and its method msg() is default so it cannot
beaccessedfrom outsidethepackage.
3) protectedaccess modifier
The protected access modifier is accessible within package and outside the package but
throughinheritanceonly.
The protected access modifier can be applied on the data member, method and constructor. It
can'tbeapplied on the class.
Exampleofprotectedaccessmodifier
Inthisexample,wehavecreatedthetwopackagespackandmypack.TheAclassofpackpackageispublic,s
ocanbeaccessedfromoutsidethepackage.Butmsgmethodofthispackageisdeclaredasprotected,soit
canbeaccessedfrom outsidethe classonlythroughinheritance.
//save by
A.javapackage
pack;publicclas
sA{
protectedvoid msg(){System.out.println("Hello");}}
//save by
B.javapackage
mypack;import
pack.*;classBexten
dsA{
public static void main(String
args[]){Bobj =newB();
obj.msg();
}}
Output:Hello
JAVAPROGRAMMING Page43
4) publicaccessmodifier
Thepublicaccessmodifier isaccessibleeverywhere.Ithasthewidestscopeamongallothermodifiers.
Exampleofpublicaccess modifier
//save by
A.javapackage
pack;publicclas
sA{
publicvoidmsg(){System.out.println("Hello");}}
//save by
B.javapackage
mypack;import
pack.*;classB{
public static void main(String
args[]){Aobj =newA();
obj.msg();
}}
Output:Hello
Understandingalljavaaccess modifiers
Let'sunderstandtheaccessmodifiers byasimpletable.
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
JAVAPROGRAMMING Page44
thiskeywordinjava
Usageof javathiskeyword
class
Student{int
rollno;String
name;floatfee
;
Student(introllno,Stringname,floatfee){
this.rollno=rollno;
this.name=name;t
his.fee=fee;
}
voiddisplay(){System.out.println(rollno+""+name+""+fee);}
}
classTestThis2{
public static void main(String
args[]){Student s1=new
Student(111,"ankit",5000f);Student s2=new
Student(112,"sumit",6000f);s1.display();
s2.display();
}}
Output:
111 ankit5000
112 sumit 6000
JAVAPROGRAMMING Page45
Differencebetweenconstructorandmethodin java
JavaConstructor JavaMethod
Constructorisinvokedimplicitly. Methodisinvokedexplicitly.
JAVAPROGRAMMING Page46
Constructornamemustbesameas the classname. Methodnamemayormaynotbe
sameasclassname.
ConstructorOverloadinginJava
Constructor overloading is a technique in Java in which a class can have any number
ofconstructors that differ in parameter lists.The compiler differentiates these constructors
bytakinginto account thenumberof parameters in the list and their type.
ExampleofConstructorOverloading
classStudent5{
intid;String
name;intage
;
Student5(int i,String
n){id =i;
name=n;
}
Student5(int i,String n,int
a){id =i;
name =
n;age=a;
}
voiddisplay(){System.out.println(id+""+name+""+age);}
Output:
JAVAPROGRAMMING Page47
111Karan0
222Aryan25
MethodOverloadinginjava
Ifaclasshasmultiplemethodshavingsamenamebutdifferentinparameters,itisknownasMethod
Overloading.
Ifwehavetoperformonlyoneoperation,havingsamenameofthemethodsincreasesthereadabilityof
theprogram.
MethodOverloading:changingno.ofarguments
Inthisexample,wehavecreatedtwomethods,firstadd()methodperformsadditionoftwonumbersandsec
ond addmethod performs addition of threenumbers.
Inthisexample,wearecreatingstaticmethodssothatwedon'tneedtocreateinstanceforcallingmethods.
classAdder{
staticintadd(inta,int b){returna+b;}
staticintadd(inta,intb,intc){returna+b+c;}
}
classTestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));Syst
em.out.println(Adder.add(11,11,11));
}}
Output:
22
33
JAVAPROGRAMMING Page48
MethodOverloading:changingdatatypeofarguments
Inthisexample,wehavecreatedtwomethodsthatdiffersindatatype.Thefirstaddmethodreceivestwo
integer arguments andsecond add methodreceives twodoublearguments.
RecursioninJava
Recursion in java is a process in which a method calls itself continuously. A method in java
thatcallsitself is called recursive method.
publicclassRecursionExample3 {
staticintfactorial(intn){
if (n ==
1)return
1;else
return(n*factorial(n-1));
}}
public static void main(String[] args)
{System.out.println("Factorialof5is:"+factorial(5));
}}
Output:
Factorialof5 is:120
JavaGarbageCollection
Injava, garbagemeansunreferencedobjects.
GarbageCollectionisprocessofreclaimingtheruntimeunusedmemoryautomatically.Inotherwords, it is a
wayto destroythe unusedobjects.
Todoso,wewereusingfree()functioninClanguageanddelete()inC++.But,injavaitisperformed
automatically.So, javaprovidesbettermemorymanagement.
JAVAPROGRAMMING Page49
Advantageof Garbage Collection
o Itmakesjavamemoryefficient becausegarbagecollectorremovestheunreferencedobjectsfrom
heap memory.
o Itisautomaticallydonebythegarbagecollector(apartofJVM)sowedon'tneedtomakeextraeffort
s.
gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing.
Thegc()is found in System and Runtime classes.
stringisbasicallyanobjectthatrepresentssequenceofcharvalues.Anarrayofcharactersworkssameas
javastring.Forexample:
1.char[]ch={'j','a','v','a','t','p','o','i','n','t'};
2.String s=new
String(ch);ssameas:
1. Strings="javatpoint";
2. Java String class provides a lot of methods to perform operations onstring such
ascompare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(),
substring()etc.
JAVAPROGRAMMING Page50
3. The java.lang.String
classimplements Serializable,Comparableand CharSequenceinterfaces.
CharSequenceInterface
StringLiteral
1.Strings="welcome";
Each time you create a string literal, the JVM checks the string constant pool first. If the
stringalready exists in the pool, a reference to the pooled instance is returned. If string doesn't
exist inthepool, anew stringinstanceis createdand placed in thepool. Forexample:
1. Strings1="Welcome";
2. Strings2="Welcome";//will not createnewinstance
JAVAPROGRAMMING Page51
Bynewkeyword
1.Strings=new String("Welcome");//createstwoobjectsandonereferencevariable
In such case, JVM will create a new string object in normal (non pool) heap memory and
theliteral "Welcome" will be placed in the string constant pool. The variable s will refer to the
objectinheap (non pool).
JavaStringExample
publicclassStringExample{
publicstaticvoid main(Stringargs[]){
Strings1="java";//creatingstringbyjavastringliteral
charch[]={'s','t','r','i','n','g','s'};
Strings2=newString(ch);//convertingchararraytostring
String s3=new String("example");//creating java string by new
keywordSystem.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
Java
stringse
xample
ImmutableStringin Java
unchangeable.Once string object is created its data or state can't be changed but a new string
classTestimmutablestring{
public static void main(String
args[]){Strings="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the
endSystem.out.println(s);//willprintSachinbecause stringsareimmutableobjects
}}
Output:Sachin
classTestimmutablestring1{
public static void main(String
args[]){String s="Sachin";
s=s.concat("
Tendulkar");System.out.pr
intln(s);
}}Output:Sachin Tendulkar
JAVAPROGRAMMING Page52
InheritanceinJava
Inheritance in java is a mechanism in which one object acquires all the properties and
behaviorsofparent object.Inheritancerepresents theIS-A relationship, alsoknownasparent-
childrelationship.
Whyuseinheritanceinjava
o ForMethod Overriding(so runtimepolymorphismcan beachieved).
o ForCodeReusability.
SyntaxofJavaInheritance
1.class Subclass-name extends Superclass-
name2.{
3. //methods and
fields4.}
Theextendskeywordindicatesthatyouaremakinganewclassthatderivesfromanexistingclass.Themea
ningof "extends"is to increasethefunctionality.
classEmployee{
floatsalary=40000;
}
classProgrammerextendsEmployee{
intbonus=10000;
public static void main(String
args[]){Programmerp=new
Programmer();
System.out.println("Programmer salary
is:"+p.salary);System.out.println("BonusofProgrammeris
JAVAPROGRAMMING Page53
:"+p.bonus);
}}
Programmersalaryis:40000.0
JAVAPROGRAMMING Page54
Bonusofprogrammer is:10000
Types ofinheritanceinjava
SingleInheritanceExample
File:TestInheritance.java
classAnimal{
voideat(){System.out.println("eating...");}
}
classDogextendsAnimal{
voidbark(){System.out.println("barking...");}
}
classTestInheritance{
public static void main(String
args[]){Dogd=newDog();
d.bark();
d.eat();
}}
Output:
barking...
eating...
MultilevelInheritanceExample
File:TestInheritance2.java
classAnimal{
voideat(){System.out.println("eating...");}
}
classDogextendsAnimal{
voidbark(){System.out.println("barking...");}
}
classBabyDogextendsDog{
voidweep(){System.out.println("weeping...");}
}
classTestInheritance2{
JAVAPROGRAMMING Page55
public static void main(String
args[]){BabyDogd=newBabyDog();d.
weep();
d.bark();
d.eat();
}}
Output:
weeping...
barking...
eating...
HierarchicalInheritanceExample
File:TestInheritance3.java
classAnimal{
voideat(){System.out.println("eating...");}
}
classDogextends Animal{
voidbark(){System.out.println("barking...");}
}
classCatextends Animal{
voidmeow(){System.out.println("meowing...");}
}
classTestInheritance3{
public static void main(String
args[]){Catc=newCat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing...
eating...
JAVAPROGRAMMING Page56
Memberaccess andInheritance
superkeywordinjava
Thesuperkeywordinjavaisareferencevariablewhichisusedtoreferimmediateparentclassobject.
Wheneveryoucreatetheinstanceofsubclass,aninstanceofparentclassiscreatedimplicitlywhichis
referredbysuper referencevariable.
Usageof javasuperKeyword
3. super()canbeusedtoinvokeimmediateparent classconstructor.
superisusedtoreferimmediateparentclassinstancevariable.
classAnimal{
Stringcolor="white";
}
class Dog extends
Animal{Stringcolor="black
";
voidprintColor(){System.out.println(color);//prints
colorofDogclass
System.out.println(super.color);//printscolorofAnimalclass
}
}
classTestSuper1{
public static void main(String
args[]){Dogd=newDog();
JAVAPROGRAMMING Page57
JAVAPROGRAMMING Page58
d.printColor();
}}
Output:
black
white
FinalKeywordinJava
The final keyword in java is used to restrict the user. The java final keyword can be used in many
context.Finalcanbe:
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
blankfinal variable or uninitialized final variable. It can be initialized in the constructor only. The blank
finalvariablecan bestatic alsowhich willbeinitialized inthe static blockonly.
ObjectclassinJava
The Object class is the parent class of all the classes in java by default. In other words, it is
thetopmostclass ofjava.
The Object class is beneficial if you want to refer any object whose type you don't know.
Noticethatparent classreferencevariablecanrefer thechild classobject, knowas upcasting.
Let's take an example, there is getObject() method that returns an object but it can be of any
typelikeEmployee,Studentetc, wecan useObject classreferenceto referthat object.Forexample:
1. Objectobj=getObject();//wedon'tknowwhatobjectwillbereturnedfromthismethod
The Object class provides some common behaviors to all the objects such as object can
becompared,object can becloned, object can benotifiedetc.
MethodOverridinginJava
If subclass (child class) has the same method as declared in the parent class, it is
knownasmethod overriding injava.
JAVAPROGRAMMING Page59
Usageof JavaMethodOverriding
o Methodoverridingisusedtoprovidespecificimplementationofamethodthatisalreadyprovided
byits superclass.
o Methodoverridingisused forruntimepolymorphism
RulesforJavaMethodOverriding
1. methodmust havesame nameas in theparentclass
2. methodmust havesame parameteras in theparent class.
3. mustbeIS-Arelationship(inheritance).
Example of method
overridingClassVehicle{
voidrun(){System.out.println("Vehicleisrunning");}
}
classBike2extendsVehicle{
voidrun(){System.out.println("Bikeisrunningsafely");}
public static void main(String
args[]){Bike2obj =newBike2();
obj.run();
}
Output:Bike is runningsafely
1.classBank{
intgetRateOfInterest(){return0;}
}
classSBIextendsBank{
intgetRateOfInterest(){return8;}
}
class ICICIextendsBank{
intgetRateOfInterest(){return7;}
}
classAXISextendsBank{
intgetRateOfInterest(){return9;}
}
classTest2{
public static void main(String
args[]){SBIs=newSBI();
ICICI i=new
ICICI();AXISa=newA
XIS();
System.out.println("SBI Rate of Interest:
"+s.getRateOfInterest());System.out.println("ICICI Rate of Interest:
"+i.getRateOfInterest());System.out.println("AXISRateofInterest:"+
a.getRateOfInterest());
}}
JAVAPROGRAMMING Page60
Output:
SBIRateofInterest:8
JAVAPROGRAMMING Page61
ICICIRateofInterest:7A
XISRateofInterest:9
AbstractclassinJava
A class that is declared with abstract keyword is known as abstract class in java. It can
haveabstract and non-abstract methods (method with body). It needs to be extended and its
methodimplemented. Itcannot beinstantiated.
Exampleabstractclass
1.abstractclass A{}
abstractmethod
1.abstractvoidprintStatus();//nobodyandabstract
Exampleofabstractclassthathasabstractmethod
abstractclassBike{
abstractvoid run();
}
classHonda4extendsBike{
voidrun(){System.out.println("runningsafely..");}
public static void main(String
args[]){Bikeobj =newHonda4();
obj.run();
}
1.}
runningsafely..
Unit-2
JAVAPROGRAMMING Page62
Interface inJava
The interface in java is a mechanism to achieve abstraction. There can be only abstract
methodsin the java interface not method body. It is used to achieve abstraction and multiple
inheritance inJava.
relationship.Itcannotbeinstantiated
justlikeabstract class.
JAVAPROGRAMMING Page63
Internaladditionbycompiler
Understandingrelationshipbetweenclassesandinterfaces
//Interfacedeclaration: byfirstuser
interfaceDrawable{
voiddraw();
}
//Implementation: bysecond user
classRectangleimplementsDrawable{
publicvoiddraw(){System.out.println("drawingrectangle");}
}
classCircleimplementsDrawable{
publicvoiddraw(){System.out.println("drawingcircle");}
}
//Usinginterface: bythirduser
classTestInterface1{
publicstaticvoid main(Stringargs[]){
Drawable d=new Circle();//In real scenario, object is provided by method e.g.
getDrawable()d.draw();
}}
Output:drawingcircle
MultipleinheritanceinJavabyinterface
interfacePrintable{
JAVAPROGRAMMING Page64
JAVAPROGRAMMING Page65
voidprint();
}
interfaceShowable{
void show();
}
classA7implementsPrintable,Showable{
public void
print(){System.out.println("Hello");}public void
show(){System.out.println("Welcome");}publicstatic
voidmain(Stringargs[]){
A7 obj = new
A7();obj.print();
obj.show();
}}
Output:Hello
Welcome
Abstractclass Interface
JavaInnerClasses
Weuseinnerclassestologicallygroupclassesandinterfacesinoneplacesothatitcanbemorereadableand
maintainable.
SyntaxofInnerclass
1. classJava_Outer_class{
2. //code
3. classJava_Inner_class{
JAVAPROGRAMMING Page66
4. //code
5. }}
JAVAPROGRAMMING Page67
Advantageof javainnerclasses
1) Nestedclassesrepresentaspecialtypeofrelationshipthatisitcanaccessallthemembers(data
members and methods)of outerclassincludingprivate.
2) Nestedclassesareused
todevelopmorereadableandmaintainablecodebecauseitlogicallygroupclasses and interfaces in
oneplaceonly.
3) CodeOptimization:Itrequireslesscodetowrite.
TypesofNestedclasses
Therearetwotypesofnestedclassesnon-staticandstaticnestedclasses.Thenon-
staticnestedclassesarealso knownas innerclasses.
o Non-staticnestedclass(innerclass)
1. Memberinner class
2. Anonymousinnerclass
3. Localinner class
o Staticnestedclass
JavaPackage
java can be categorized in two form, built-in package and user-defined package.There are
many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql
etc.AdvantageofJavaPackage
1) Javapackageisusedtocategorizetheclassesandinterfacessothattheycanbeeasilymaintained.
2) Javapackageprovides accessprotection.
3) Javapackageremovesnamingcollision.
packagemypack;
publicclassSimple{
public static void main(String
args[]){System.out.println("Welcometopackage"
);
}}
JAVAPROGRAMMING Page68
Howto compile javapackage
If you are not using any IDE, you need to follow the syntax given
below:javac-d directoryjavafilename
How torunjavapackageprogram
ToCompile:javac-d. Simple.java
ToRun:javamypack.Simple
Usingfully qualifiedname
//save by
A.javapackage
pack;publicclas
sA{
publicvoidmsg(){System.out.println("Hello");}}
//save by
B.javapackage
mypack;classB{
publicstaticvoid main(Stringargs[]){
pack.A obj = new pack.A();//using fully qualified
nameobj.msg();
}
}
Output:Hello
JAVAPROGRAMMING Page69
UNIT-3
ExceptionHandling
The exceptionhandlinginjava isoneofthepowerful mechanismtohandletheruntimeerrorsso that
normal flow ofthe application canbemaintained.
Whatis exception
In java, exception is an event that disrupts the normal flow of the program. It is an object which
isthrownat runtime.
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
exceptionhandling.
TypesofException
Therearemainlytwotypesofexceptions:checkedanduncheckedwhereerrorisconsideredasuncheckede
xception. Thesunmicrosystem says therearethreetypes of exceptions:
1. CheckedException
2. UncheckedException
3. Error
Differencebetweencheckedanduncheckedexceptions
1) Checked Exception: The classes that extend Throwable class except RuntimeException and
Errorare known as checked exceptions e.g.IOException, SQLException etc. Checkedexceptions are
checkedatcompile-time.
2) UncheckedException:
TheclassesthatextendRuntimeExceptionareknownasuncheckedexceptionse.g.ArithmeticException,Nul
lPointerException,ArrayIndexOutOfBoundsExceptionetc.Unchecked exceptions are notchecked
atcompile-timeratherthey are checkedatruntime.
3) Error:Errorisirrecoverablee.g.OutOfMemoryError,VirtualMachineError,AssertionErroretc.
JAVAPROGRAMMING Page70
JAVAPROGRAMMING Page71
HierarchyofJavaExceptionclasses
CheckedandUnCheckedExceptions
JAVAPROGRAMMING Page72
Javatryblock
Java try block is used to enclose the code that might throw an exception. It must be used
withinthe method.
Syntaxofjavatry-catch
1. try{
2. //codethat maythrowexception
3. }catch(Exception_class_Name
ref){}Syntax of try-finallyblock
1. try{
2. //codethat maythrowexception
3. }finally{}
Javacatchblock
Java catch block is used to handle the Exception. It must be used after the try block
Problemwithoutexceptionhandling
publicclassTesttrycatch1{
publicstaticvoidmain(Stringargs[]){int
data=50/0;//may throw
exceptionSystem.out.println("restofthec
ode...");
}}
Output:
Exceptioninthreadmainjava.lang.ArithmeticException:/byzero
As displayed in the above example, rest of the code is not executed (in such case, rest of
thecode...statement is not printed).
There can be 100 lines of code after exception. So all the code after exception will not
beexecuted.
JAVAPROGRAMMING Page73
Solutionbyexceptionhandling
publicclassTesttrycatch2{
JAVAPROGRAMMING Page74
publicstaticvoid main(Stringargs[]){
try{
intdata=50/0;
}catch(ArithmeticException
e){System.out.println(e);}System.out.println("rest
ofthecode...");
}}
1.Output:
Exceptioninthreadmainjava.lang.ArithmeticException:/byzerorest
of the code...
Now, as displayed in the above example, rest of the code is executed i.e. rest of the
code...statement isprinted.
JavaMulticatchblock
IfyouhavetoperformdifferenttasksattheoccurrenceofdifferentExceptions,usejavamulticatchblo
ck.
Let'sseeasimpleexampleofjavamulti-catchblock.
1. publicclassTestMultipleCatchBlock{
2. publicstaticvoidmain(Stringargs[]){
3. try{
4. int a[]=new
int[5];5. a[5]=30/0;
6. }
7. catch(ArithmeticExceptione){System.out.println("task1iscompleted");}
8. catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2
completed");9.}
10. catch(Exceptione){System.out.println("commontaskcompleted");
11. }
12. System.out.println("rest of the
code...");13.}}
Output:task1
completedrestof
Javanestedtryexample
classExcep6{
publicstaticvoid main(Stringargs[]){
try{t
ry{
System.out.println("goingtodivide");
intb =39/0;
}catch(ArithmeticExceptione){System.out.println(e);}
JAVAPROGRAMMING Page75
try{
JAVAPROGRAMMING Page76
int a[]=new
int[5];a[5]=4;
}catch(ArrayIndexOutOfBoundsException
e){System.out.println(e);}System.out.println("otherstatement);
}catch(Exception
e){System.out.println("handeled");}System.out.println
("normalflow..");
}
1.}
Java finallyblock
Javafinallyblockisablockthatisusedtoexecuteimportantcodesuchasclosingconnection,streametc.
UsageofJavafinally
Case1
occur.classTestFinallyBlock{
publicstaticvoid main(Stringargs[]){
try{
int
data=25/5;System.out.pr
intln(data);
}
catch(NullPointerException
e){System.out.println(e);}finally{System.out.println("finally
block is always
executed");}System.out.println("restofthecode...");
}
}
Output:5
finallyblockisalwaysexecutedre
stof the code...
Javathrowkeyword
We can throw either checked or uncheked exception in java by throw keyword. The
throwkeywordismainlyusedtothrow customexception.Wewillseecustom exceptionslater.
JAVAPROGRAMMING Page77
Thesyntaxofjavathrow keywordisgivenbelow.
1.throwexception;
JAVAPROGRAMMING Page78
Javathrowkeywordexample
1.publicclassTestThrow1{
staticvoid validate(intage){
if(age<18)
thrownewArithmeticException("notvalid");
else
System.out.println("welcometovote");
}
public static void main(String
args[]){validate(13);
System.out.println("restofthecode...");
}}
Output:
Exceptioninthreadmainjava.lang.ArithmeticException:notvalid
Javathrowskeyword
ExceptionHandlingismainlyusedtohandlethecheckedexceptions.Ifthereoccursanyuncheckedexcepti
onsuchasNullPointerException,itisprogrammersfaultthatheisnotperformingcheck up beforethe
codebeingused.
Syntaxofjavathrows
1. return_typemethod_name()throwsexception_class_name{
2. //method
code3.}
4.
Javathrowsexample
Let's see the example of java throws clause which describes that checked exceptions can
bepropagated bythrows keyword.
importjava.io.IOException;
classTestthrows1{
JAVAPROGRAMMING Page79
voidm()throwsIOException{
thrownew IOException("deviceerror");//checkedexception
JAVAPROGRAMMING Page80
}
void n()throws
IOException{m();
}
void p(){
try{
n();
}catch(Exceptione){System.out.println("exceptionhandled");}
}
public static void main(String
args[]){Testthrows1 obj=new
Testthrows1();obj.p();
System.out.println("normal
flow...");}}Output:
exception
handlednormalflo
JavaCustomException
IfyouarecreatingyourownExceptionthatisknownascustomexceptionoruser-
definedexception.Javacustomexceptions areusedto customizethe exceptionaccordingto userneed.
By the help of custom exception, you can have your own exception and
else
System.out.println("welcometovote");
}
publicstaticvoid main(Stringargs[]){
try{validate
(13);
}catch(Exceptionm){System.out.println("Exceptionoccured: "+m);}
System.out.println("restofthecode...");
}}
Output:Exceptionoccured: InvalidAgeException:notvalidrestofthecode...
JAVAPROGRAMMING Page81
JAVAPROGRAMMING Page82
Multithreading
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
thethreadstakes less timethan process.
AdvantagesofJavaMultithreading
LifecycleofaThread(ThreadStates)
A thread can be in one of the five states. According to sun, there is only 4 states in thread
lifecyclein java new, runnable, non-runnableandterminated. Thereis norunningstate.
JAVAPROGRAMMING Page83
JAVAPROGRAMMING Page84
Howto createthread
Thereare twowaystocreateathread:
1. ByextendingThreadclass
2. ByimplementingRunnable interface.
Threadclass:
Thread class provide constructors and methods to create and perform operations on
athread.Threadclass extendsObject class andimplements Runnableinterface.
CommonlyusedConstructorsofThreadclass:
oThread()
oThread(Stringname)
oThread(Runnabler)
oThread(Runnabler,String name)
JAVAPROGRAMMING Page85
JAVAPROGRAMMING Page86
CommonlyusedmethodsofThreadclass:
1. publicvoidrun(): isusedtoperformactionforathread.
2. publicvoidstart():startstheexecutionofthe thread.JVMcallstherun()methodonthe thread.
3. publicvoidsleep(longmiliseconds):Causesthecurrentlyexecutingthreadtosleep(temporarilycease
execution) forthe specifiednumber ofmilliseconds.
4. publicvoidjoin(): waitsforathreadtodie.
5. publicvoidjoin(long miliseconds): waitsforathreadto dieforthespecifiedmiliseconds.
6. publicintgetPriority():returns thepriorityof thethread.
7. publicintsetPriority(intpriority):changesthe priorityofthethread.
8. publicStringgetName():returnsthenameofthe thread.
9. publicvoidsetName(Stringname):changesthenameofthethread.
10. publicThreadcurrentThread():returnsthereferenceof currentlyexecutingthread.
11. publicintgetId():returnstheidofthethread.
12. publicThread.StategetState():returnsthestateofthethread.
13. publicbooleanisAlive():tests ifthethread isalive.
14. publicvoidyield():causesthecurrentlyexecutingthreadobjecttotemporarilypauseandallowotherthrea
ds to execute.
15. publicvoidsuspend():isusedtosuspendthethread(depricated).
16. publicvoidresume(): is usedtoresumethesuspendedthread(depricated).
17. publicvoidstop():isusedtostopthethread(depricated).
18. publicbooleanisDaemon(): testsifthethreadisadaemonthread.
19. publicvoidsetDaemon(booleanb): marksthethreadasdaemonoruserthread.
20. publicvoidinterrupt(): interruptsthethread.
21. publicbooleanisInterrupted():testsifthethreadhasbeeninterrupted.
22. publicstaticbooleaninterrupted(): testsifthecurrentthreadhasbeeninterrupted.
Runnableinterface:
The Runnable interface should be implemented by any class whose instances are intended to
beexecutedbyathread. Runnable interfacehaveonlyonemethod named run().
1. publicvoidrun(): isusedtoperformactionforathread.
Startingathread:
start() method of Thread class is used to start a newly created thread. It performs
followingtasks:
oAnewthread starts(withnew callstack).
oThethread moves fromNew state tothe Runnablestate.
oWhenthethreadgets achanceto execute, itstarget run() method will run.
JAVAPROGRAMMING Page87
JAVAPROGRAMMING Page88
JavaThreadExamplebyextendingThreadclass
classMultiextendsThread{
publicvoidrun(){System.out.println("threa
disrunning...");
}
public static void main(String
args[]){Multi t1=newMulti();
t1.start();
}}
Output:threadisrunning...
JavaThreadExamplebyimplementingRunnableinterface
classMulti3implementsRunnable{public
voidrun(){System.out.println("threadisru
nning...");
}
public static void main(String
args[]){Multi3m1=newMulti3();
Thread t1 =new
Thread(m1);t1.start();
}}
Output:threadisrunning...
PriorityofaThread(ThreadPriority):
Each thread have a priority. Priorities are represented by a number between 1 and 10. In
mostcases, thread schedular schedules the threads according to their priority (known as
preemptivescheduling). But it is not guaranteed because it depends on JVM specification that
whichschedulingit chooses.
3constantsdefinedinThreadclass:
1. publicstaticintMIN_PRIORITY
2. publicstaticintNORM_PRIORITY
3. publicstaticintMAX_PRIORITY
Defaultpriorityof athreadis5(NORM_PRIORITY).ThevalueofMIN_PRIORITYis1andthevalue
ofMAX_PRIORITY is 10.
Example of priority of a
Thread:class TestMultiPriority1 extends
Thread{publicvoidrun(){
System.out.println("running thread name
JAVAPROGRAMMING Page89
is:"+Thread.currentThread().getName());System.out.println("runningthreadpriorityis:"
+Thread.currentThread().getPriority());
}publicstaticvoid main(Stringargs[]){
JAVAPROGRAMMING Page90
TestMultiPriority1 m1=new
TestMultiPriority1();TestMultiPriority1 m2=new
TestMultiPriority1();m1.setPriority(Thread.MIN_
PRIORITY);m2.setPriority(Thread.MAX_PRIO
RITY);m1.start();
m2.start();
}}
Output:running thread name is:Thread-
0runningthread priorityis:10
running thread name is:Thread-
1runningthread priorityis:1
Javasynchronizedmethod
When a thread invokes a synchronized method, it automatically acquires the lock for that
objectandreleases it when the thread completes its task.
Exampleofinterthreadcommunicationinjava
classCustomer{
intamount=10000;
synchronized void withdraw(int
amount){System.out.println("going to
withdraw...");if(this.amount<amount){
System.out.println("Less balance;waitingfordeposit...");
try{wait();}catch(Exceptione){}
}
this.amount-
=amount;System.out.println("withdrawcomp
leted...");
}
synchronized void deposit(int
amount){System.out.println("going to
deposit...");this.amount+=amount;System.
out.println("deposit completed...
");notify();
}
}
classTest{
public static void main(String
args[]){final Customer c=new
Customer();newThread(){
publicvoidrun(){c.withdraw(15000);}
JAVAPROGRAMMING Page91
}.start();
newThread(){
JAVAPROGRAMMING Page92
publicvoid run(){c.deposit(10000);}
}
start();
}}
Output:goingto withdraw...
Lessbalance;waitingfordeposit...g
oingto deposit...
deposit
completed...withdra
ThreadGroupinJava
Javaprovidesaconvenientwaytogroupmultiplethreadsinasingleobject.Insuchway,wecansuspend,resume
orinterrupt groupofthreads byasingle method call.
Note:Nowsuspend(),resume()andstop()methodsaredeprecated.
class.ConstructorsofThreadGroupclass
ThreadGroup(String
name)ThreadGroup(ThreadGroupparent,Stringna
me)
Nowall3threadsbelongtoonegroup.Here,tg1isthethreadgroupname,MyRunnableistheclassthatimple
ments Runnableinterface and"one","two"and"three"arethethreadnames.
1. Thread.currentThread().getThreadGroup().interrupt();
JAVAPROGRAMMING Page93
Exploringjava.netandjava.text
java.net
The term network programming refers to writing programs that execute across multiple
devices(computers),in which thedevicesare all connected to eachotherusinganetwork.
The java.net package of the J2SE APIs contains a collection ofclasses and interfaces thatprovide
the low-level communication details, allowing you to write programs that focus onsolvingthe
problem at hand.
Thejava.netpackageprovides supportforthetwocommonnetworkprotocols−
TCP
−TCPstandsforTransmissionControlProtocol,whichallowsforreliablecommunicationbetwe
entwoapplications.TCPistypicallyusedovertheInternetProtocol,which is referred to as
TCP/IP.
UDP−UDPstandsforUserDatagramProtocol,aconnection-lessprotocolthatallowsforpackets
of data to betransmitted betweenapplications.
SocketProgramming−ThisisthemostwidelyusedconceptinNetworkingandithas
been explained inverydetail.
URLProcessing−This wouldbecoveredseparately.
java.text
The java.text package is necessary for every java developer to master because it has a lot
ofclassesthatishelpfulinformattingsuchasdates,numbers,andmessages.
java.textClasses
Thefollowingaretheclassesavailableforjava.textpackage[tabl
JAVAPROGRAMMING Page94
e]
Class|Description
SimpleDateFormat|is a concrete class that helps in formatting and parsing of
dates.[/table]
UNIT-4
CollectionFrameworkinJava
Collectionsinjavaisaframeworkthatprovidesanarchitecturetostoreandmanipulatethegroupof
objects.
All the operations that you perform on a data such as searching, sorting, insertion,
manipulation,deletion etc. can beperformed byJavaCollections.
Java Collection simply means a single unit of objects. Java Collection framework provides
manyinterfaces(Set,List,Queue,Dequeetc.)andclasses(ArrayList,Vector,LinkedList,PriorityQueue,
HashSet,LinkedHashSet, TreeSetetc).
Whatisframeworkinjava
o providesreadymadearchitecture.
o representssetofclassesandinterface.
o is optional.
WhatisCollectionframework
Collection framework represents a unified architecture for storing and manipulating group
ofobjects.It has:
1. Interfaces anditsimplementationsi.e.classes
2. Algorithm
JAVAPROGRAMMING Page95
JAVAPROGRAMMING Page96
HierarchyofCollectionFramework
JavaArrayListclass
JavaArrayListclassusesadynamicarrayforstoringthe
elements.ItinheritsAbstractListclassandimplementsList interface.
TheimportantpointsaboutJavaArrayListclassare:
o JavaArrayListclasscancontainduplicateelements.
o JavaArrayListclassmaintainsinsertionorder.
o JavaArrayListclassisnonsynchronized.
o JavaArrayListallowsrandomaccess becausearrayworksat theindexbasis.
o In Java ArrayList class, manipulation is slow because a lot of shifting needs to be
occurredif anyelement isremoved from thearraylist.
JAVAPROGRAMMING Page97
ArrayListclassdeclaration
Let'sseethedeclarationforjava.util.ArrayListclass.
ConstructorsofJavaArrayList
Constructor Description
ArrayList(Collectionc Itisusedtobuildanarraylistthatisinitializedwiththeelement
) sof the collection c.
ArrayList(int Itisusedtobuildanarraylistthathasthespecifiedinitialcapac
capacity) ity.
Java ArrayList
Exampleimportjava.util.*;
classTestCollection1{
publicstaticvoid main(Stringargs[]){
ArrayList<String> list=new ArrayList<String>();//Creating
arraylistlist.add("Ravi");//Addingobject in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through
IteratorIterator
itr=list.iterator();while(itr.hasNext()){
System.out.println(itr.next());}}}
Ravi
Vijay
Ravi
Ajay
JAVAPROGRAMMING Page98
JAVAPROGRAMMING Page99
vector
ArrayListandVectorbothimplementsListinterfaceandmaintainsinsertionorder.
ButtherearemanydifferencesbetweenArrayListandVector classesthataregivenbelow.
ArrayList Vector
1)ArrayListisnotsynchronized. Vectorissynchronized.
5)ArrayListusesIteratorinterfacetot VectorusesEnumerationinterfacetotraversetheeleme
raversetheelements. nts.But it canuseIterator also.
ExampleofJavaVector
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");
JAVAPROGRAMMING Page100
8. //traversingelements usingEnumeration
JAVAPROGRAMMING Page101
9. Enumeratione=v.elements();
10. while(e.hasMoreElements()){
11. System.out.println(e.nextElement());
12.}}}
Output:
umesh
irfank
umar
JavaHashtableclass
JavaHashtableclassimplementsahashtable,whichmapskeystovalues.ItinheritsDictionaryclassand
implements theMapinterface.
o A Hashtable is an array of list. Each list is known as a bucket. The position of bucket
isidentifiedbycallingthehashcode()method.AHashtablecontainsvaluesbasedonthekey.
o Itcontains onlyuniqueelements.
o It mayhavenothaveanynull keyor value.
o Itissynchronized.
Hashtableclassdeclaration
HashtableclassParameters
Let'sseetheParametersforjava.util.Hashtable class.
JAVAPROGRAMMING Page102
ConstructorsofJavaHashtableclass
Constructor Description
Hashtable() ItisthedefaultconstructorofhashtableitinstantiatestheHashtableclass.
Hashtable(intsize) Itisusedtoacceptanintegerparameterandcreatesahashtablethathas an
initial sizespecifiedbyinteger value size.
JavaHashtableExample
importjava.util.*;
classTestCollection16{
publicstaticvoidmain(Stringargs[]){Hashtable<Integer,String>
hm=new Hashtable<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:
103Rahul
102Ravi
101 Vijay
100 Amit
Stack
Stackisa subclassofVectorthat implementsastandardlast-in,first-outstack.
Stackonlydefinesthedefaultconstructor,whichcreatesanemptystack.Stackincludesallthemethods
definedbyVector, and adds several of its
JAVAPROGRAMMING Page103
own.
Stack()
Example
Thefollowingprogram illustrates several ofthemethods supported bythiscollection−
importjava.util.*;
publicclassStackDemo{
st.push(newInteger(a));
System.out.println("push("+ a+ ")");
System.out.println("stack:"+st);}
staticvoidshowpop(Stack st){
System.out.print("pop->");
Integera=(Integer)st.pop();
System.out.println(a);
System.out.println("stack:"+st);}
publicstaticvoidmain(Stringargs[]){
Stackst=new Stack();
System.out.println("stack:"+st);
showpush(st,42);
showpush(st,66);
showpush(st,99);
showpop(st);
showpop(st);
showpop(st);
try{
showpop(st);
JAVAPROGRAMMING Page104
}catch(EmptyStackException e){
System.out.println("emptystack");
}}}
Thiswillproducethefollowingresult −
Output
stack:[]push(4
2)stack:
[42]push(66)s
tack: [42,
66]push(99)
stack:[42, 66, 99]
pop->99
stack:[42, 66]
pop->66
stack:[42]
pop ->
42stack:[
]
pop ->emptystack
Enumeration
TheEnumerationInterface
The Enumeration interface defines the methods by which you can enumerate (obtain one at
atime)the elements in acollection ofobjects.
Themethods declared byEnumeration aresummarizedin thefollowingtable −
Sr.No. Method&Description
1
booleanhasMoreElements()
Whenimplemented,itmustreturntruewhiletherearestillmoreelementstoextract,andfalsewhena
ll the elements havebeenenumerated.
2
ObjectnextElement()
Thisreturnsthenextobjectintheenumeration asagenericObjectreference.
Example:Followingis anexampleshowingusageofEnumeration.
JAVAPROGRAMMING Page105
iswillproducethefollowingresult −
import
java.util.Vector;importjava.ut
il.Enumeration;
publicclassEnumerationTester{
{Enumerationdays;
VectordayNames=newVector();da
yNames.add("Sunday");dayName
s.add("Monday");dayNames.add("
Tuesday");dayNames.add("Wedn
esday");dayNames.add("Thursday
");dayNames.add("Friday");dayN
ames.add("Saturday");
days =
dayNames.elements();while(days.
hasMoreElements()){
System.out.println(days.nextElement());
} }}
Output
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Iterator
JAVAPROGRAMMING Page106
It is a universal iterator as we can apply it to any Collection object. By using Iterator, we
canperform both read and remove operations. It is improved version of Enumeration with
additionalfunctionalityofremove-abilityofaelement.
Iterator must be used whenever we want to enumerate elements in all Collection
frameworkimplemented interfaces like Set, List, Queue, Deque and also in all implemented
classes of Mapinterface.Iterator isthe only cursoravailableforentirecollection framework.
Iteratorobject canbecreatedbycallingiterator()methodpresent inCollection interface.
//Here "c"is anyCollection object. itr is of
//type
Iteratorinterfaceandrefersto"c"Iteratoritr
Iteratorinterfacedefinesthreemethods:
//Returns trueif theiteration hasmoreelements
publicbooleanhasNext();
publicvoidremove();
remove()methodcanthrow twoexceptions
UnsupportedOperationException:If theremove operationisnotsupportedbythisiterator
IllegalStateException:Ifthenextmethodhasnotyetbeencalled,ortheremovemethodhasalreadyb
eencalled after thelast call to thenext method
LimitationsofIterator:
Onlyforward direction iteratingispossible.
Replacementandadditionofnewelementisnotsupported byIterator.
StringTokenizerinJava
Thejava.util.StringTokenizer
classallowsyoutobreakastringintotokens.Itissimplewaytobreakstring.
ConstructorsofStringTokenizerclass
Thereare3constructorsdefinedintheStringTokenizerclass.
JAVAPROGRAMMING Page107
Constructor Description
StringTokenizer(Stringstr) createsStringTokenizerwithspecifiedstring.
MethodsofStringTokenizerclass
The6usefulmethodsof StringTokenizerclassareasfollows:
Publicmethod Description
StringnextToken() returnsthenexttokenfromtheStringTokenizerobject.
booleanhasMoreElements() sameashasMoreTokens()method.
SimpleexampleofStringTokenizerclass
Let'sseethesimpleexampleofStringTokenizerclassthattokenizesastring"mynameiskhan"onthe basis
of whitespace.
importjava.util.StringTokenizer;
publicclassSimple{
publicstaticvoid main(Stringargs[]){
JAVAPROGRAMMING Page108
StringTokenizerst=newStringTokenizer("mynameiskhan","");
while (st.hasMoreTokens())
{System.out.println(st.nextToken()
);
}}}
Output:my
name
iskh
an
ExampleofnextToken(Stringdelim)methodofStringTokenizerclass
importjava.util.*;
publicclassTest{
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
thisclass and then invoke methods such as nextInt(), nextDouble(), nextLong() etc using
thatinstance.
We can generate random numbers of types integers, float, double, long, booleans using
thisclass.
We can pass arguments to the methods for placing an upper bound on the range of
thenumbers to be generated. For example, nextInt(6) will generate numbers in the range 0
to 5bothinclusive.
//AJavaprogramtodemonstrate randomnumbergeneration
// using
java.util.Random;importj
ava.util.Random;
publicclass generateRandom{
//GenerateRandomdoubles
double rand_dub1 =
rand.nextDouble();doublerand_dub2=ra
nd.nextDouble();
//Printrandom doubles
System.out.println("Random Doubles:
"+rand_dub1);System.out.println("RandomDoubles:"
+rand_dub2);
}}
Output:
RandomIntegers:547
RandomIntegers:126
RandomDoubles: 0.8369779739988428
RandomDoubles: 0.5497554388209912
JavaScannerclass
There are various ways to read input from the keyboard, the java.util.Scanner class is one of
them.The JavaScanner classbreakstheinputintotokensusingadelimiterthatiswhitespacebydefault.It
provides manymethods toread and parsevarious primitive values.
Java Scanner class is widely used to parse text for string and primitive types using
regularexpression.
JavaScannerclassextendsObjectclassandimplements Iterator andCloseableinterfaces.
CommonlyusedmethodsofScannerclass
ThereisalistofcommonlyusedScannerclass methods:
Method Description
publicStringnextLine() itmovesthescannerpositiontothenextlineandr
JAVAPROGRAMMING Page110
publicbytenextByte() itscansthenexttokenasa byte.
JAVAPROGRAMMING Page111
publicshort nextShort() itscansthenexttoken asashort value.
JavaScannerExampleto getinputfromconsole
Let'sseethesimpleexampleoftheJavaScannerclasswhichreadstheint,stringanddoublevalueas an
input:
importjava.util.Scanner;
classScannerTest{
public static void main(String
args[]){Scanner sc=new
Scanner(System.in);System.out.println(
"Enter your rollno");int
rollno=sc.nextInt();System.out.println("
Enter your name");String
name=sc.next();System.out.println("Ent
er your
fee");doublefee=sc.nextDouble();
System.out.println("Rollno:"+rollno+" name:"+name+"
fee:"+fee);sc.close();
}}Output:
Enteryourrollno1
11
Enteryourname
Ratan
Enter4
50000
Rollno:111name:Ratanfee:450000
JAVAPROGRAMMING Page112
JAVAPROGRAMMING Page113
JavaCalendarClass
Java Calendar class is an abstract class that provides methods for converting date between
aspecific instant in time and a set of calendar fields such as MONTH, YEAR, HOUR, etc.
ItinheritsObject class andimplements theComparable interface.
JavaCalendarclassdeclaration
Let'sseethedeclarationofjava.util.Calendarclass.
1. publicabstractclass CalendarextendsObject
2. implementsSerializable,Cloneable,Comparable<Calendar>
JavaCalendarClassExample
importjava.util.Calendar;
publicclassCalendarExample1 {
public static void main(String[] args)
{Calendarcalendar=Calendar.getInstance();
System.out.println("The current date is : "+
calendar.getTime());calendar.add(Calendar.DATE,-15);
System.out.println("15 days ago: "+
calendar.getTime());calendar.add(Calendar.MONTH,4);
System.out.println("4 months later: "+
calendar.getTime());calendar.add(Calendar.YEAR, 2);
System.out.println("2yearslater:"+calendar.getTime());
}}
Output:
JAVAPROGRAMMING Page114
Java-FilesandI/O
The java.io package contains nearly every class you might ever need to perform input and
output(I/O)inJava.Allthesestreamsrepresentaninputsourceandanoutputdestination.Thestreaminthe
java.io packagesupportsmanydatasuch asprimitives, object,localizedcharacters, etc.
Stream
Astreamcanbedefinedasa sequenceofdata. Therearetwo kindsofStreams−
InPutStream−TheInputStreamisusedtoread datafromasource.
OutPutStream−TheOutputStream isusedforwritingdatatoadestination.
Java provides strong but flexible support for I/O related to files and networks but this
tutorialcovers very basic functionality related to streams and I/O. We will see the most
commonly usedexamplesonebyone−
ByteStreams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are
manyclasses related to byte streams but the most frequently used
classesare, FileInputStream and FileOutputStream. Following is an example which makes
useofthesetwo classesto copyan input fileinto an output file−
Example
importjava.io.*;
publicclassCopyFile {
{FileInputStream in =null;
FileOutputStream out =
null;try{
in=newFileInputStream("input.txt");
out=newFileOutputStream("output.txt");i
ntc;
while((c =in.read())!=-1){
JAVAPROGRAMMING Page115
out.write(c);
}finally{
if(in !=null){
in.close();
if (out != null)
{out.close();
}}}}
Thisistest forcopyfile.
As a next step, compile the above program and execute it, which will result in creating
output.txtfilewiththesamecontentaswehaveininput.txt.Solet'sputtheabovecodeinCopyFile.javafile
and do the following−
$javacCopyFile.java
$javaCopyFile
CharacterStreams
Java Byte streams are used to perform input and output of 8-bit bytes,
whereasJava Character streams are used to perform input and output for 16-bit unicode. Though
therearemanyclassesrelatedto character streams but the most frequently used
classesare, FileReader and
FileWriter.ThoughinternallyFileReaderusesFileInputStreamandFileWriter uses
FileOutputStream but here the major difference is thatFileReader reads twobytesatatime and
FileWriterwritestwo bytes at a time.
Wecanre-writetheaboveexample,whichmakestheuseofthesetwoclassestocopyaninput
file(havingunicodecharacters)intoanoutputfile−
Example
importjava.io.*;
publicclassCopyFile {
JAVAPROGRAMMING Page116
publicstaticvoid main(Stringargs[])throwsIOException{
FileReader in =
null;FileWriter out =
null;try{
in = new
FileReader("input.txt");out = new
FileWriter("output.txt");intc;
{out.write(c);}
}finally{
if(in !=null){
in.close();}
if (out != null)
{out.close();
}}}}
As a next step, compile the above program and execute it, which will result in creating
output.txtfile with the same content as we have in input.txt. So let's put the above code in
CopyFile.javafileand do the following−
$javacCopyFile.java
$javaCopyFile
StandardStreams
All the programming languages provide support for standard I/O where the user's program
cantake input from a keyboard and then produce an output on the computer screen. Java provides
thefollowingthreestandardstreams −
StandardInput−Thisisusedtofeedthedatatouser'sprogramandusuallyakeyboard
isusedasstandardinputstream andrepresentedasSystem.in.
JAVAPROGRAMMING Page117
Standard Output − This is used to output the data produced by the user's program
andusuallyacomputerscreenisusedforstandardoutputstreamandrepresentedasSystem.out.
Standard Error − This is used to output the error data produced by the user's
programandusuallyacomputerscreenisusedforstandarderrorstreamandrepresentedasSyste
m.err.
Example
importjava.io.*;
publicclassReadConsole {
{InputStreamReadercin =null;
try{
cin=newInputStreamReader(System.in);System.o
ut.println("Entercharacters,'q'toquit.");charc;
do{
c = (char)
cin.read();System.ou
t.print(c);
}while(c!='q');
}finally{
if(cin!=null){
cin.close();
}} }}
$javacReadConsole.java
$javaReadConsole
JAVAPROGRAMMING Page118
Enter characters, 'q' to
quit.1
1
e
e
q
q
ReadingandWritingFiles
Asdescribedearlier,astreamcanbedefinedasasequenceofdata.TheInputStreamisusedtoreaddatafro
m asourceandtheOutputStreamisusedforwritingdata toa destination.
ThetwoimportantstreamsareFileInputStreamandFileOutputStream
FileInputStream
Thisstreamisusedforreadingdatafromthefiles.Objectscanbecreatedusingthekeywordnewand
thereareseveral types ofconstructorsavailable.
Followingconstructortakesafilenameasastringtocreateaninputstreamobjecttoreadthe
file −
InputStreamf=newFileInputStream("C:/java/hello");
JAVAPROGRAMMING Page119
JAVAPROGRAMMING Page120
Following constructortakesafileobjecttocreateaninputstreamobjecttoreadthefile.Firstwe
createafileobject usingFile()methodasfollows−
File f = new
File("C:/java/hello");InputStreamf=new
ByteArrayInputStream
DataInputStream
FileOutputStream
FileOutputStreamisusedtocreateafileandwritedataintoit.Thestreamwouldcreateafile,ifit doesn't
alreadyexist, beforeopeningit foroutput.
HerearetwoconstructorswhichcanbeusedtocreateaFileOutputStreamobject.
Followingconstructortakesafilenameasastringtocreateaninputstreamobjecttowritethe
file −
OutputStreamf=newFileOutputStream("C:/java/hello")
Followingconstructortakesafileobjecttocreateanoutputstreamobjecttowritethefile.First,
wecreate afileobjectusingFile()methodasfollows−
File f = new
File("C:/java/hello");OutputStreamf=newFi
OnceyouhaveOutputStreamobjectinhand,thenthereisalistofhelpermethods,whichcanbeusedto
writeto stream orto doother operations on the stream.
ByteArrayOutputStream
DataOutputStream
Example
importjava.io.*;
publicclassfileStreamTest{
{try{
JAVAPROGRAMMING Page121
JAVAPROGRAMMING Page122
bytebWrite[]={11,21,3,40,5};
OutputStreamos=newFileOutputStream("test.txt");fo
bytes}os.close();
InputStreamis=newFileInputStream("test.txt");in
tsize=is.available();
{System.out.print((char)is.read()+ "");}
is.close();
} catch (IOException e)
{System.out.print("Exception");
} }}
Java.io.RandomAccessFileClass
TheJava.io.RandomAccessFileclassfilebehaveslikealargearrayofbytesstoredinthefilesystem.Instanceso
f thisclass supportboth reading andwritingtoarandomaccessfile.
Classdeclaration
FollowingisthedeclarationforJava.io.RandomAccessFileclass−
publicclassRandomAccessFilee
xtendsObject
implementsDataOutput,DataInput,Closeable
Classconstructors
S.N. Constructor& Description
1
RandomAccessFile(Filefile,Stringmode)
Thiscreatesarandomaccessfilestreamtoreadfrom,andoptionallytowriteto,thefilespecifiedbythe
Fileargument.
JAVAPROGRAMMING Page123
2
RandomAccessFile(Filefile,Stringmode)
Thiscreatesarandomaccessfilestreamtoreadfrom,andoptionallytowriteto,afilewiththespecifiedn
ame.
Methodsinherited
Thisclassinheritsmethodsfromthefollowingclasses−
Java.io.Object
Java.io.FileClassinJava
The File class is Java’s representation of a file or directory path name. Because file and
directorynames have different formats on different platforms, a simple string is not adequate to
name them.The File class contains several methods for working with the path name, deleting and
renamingfiles,creatingnewdirectories,listingthecontentsofadirectory,anddeterminingseveralcommo
nattributes of files anddirectories.
Itisan abstract representationoffileanddirectorypathnames.
A pathname, whether abstract or in string form can be either absolute or relative. The
parentofan abstract pathnamemaybeobtained byinvokingthegetParent()method ofthis class.
First of all, we should create the File class object by passing the filename or directory
nameto 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
collectivelyknownas access permissions.
Instances of the File class are immutable; that is, once created, the abstract
pathnamerepresentedbyaFileobject will neverchange.
How tocreateaFileObject?
A File object is created by passing in a String that represents the name of a file, or a String
oranotherFileobject. For example,
Filea=newFile("/usr/local/bin/geeks");
definesanabstractfilenameforthegeeksfileindirectory/usr/local/bin.Thisisanabsoluteabstractfilenam
e.
Programtocheckif afileordirectoryphysicallyexistornot.
//Inthis program,weacceptsa fileor directoryname from
//commandlinearguments.Then theprogramwillcheckif
// that fileordirectoryphysicallyexistor not and
//itdisplaysthe propertyofthat fileordirectory.
*importjava.io.File;
// Displaying file
propertyclassfileProperty
{
publicstaticvoidmain(String[] args){
JAVAPROGRAMMING Page124
//accept file name or directory name through command line
argsStringfname=args[0];
Output:
File name
:file.txtPath:file.
txt
Absolute
path:C:\Users\akki\IdeaProjects\codewriting\src\file.txtParent:nu
ll
Exists:true
Is
writeable:trueIsr
Connceting toDB
WhatisJDBCDriver?
JDBCdriversimplementthedefinedinterfacesintheJDBCAPI,forinteractingwithyourdatabaseserver.
Forexample,usingJDBCdriversenableyoutoopendatabaseconnectionsandtointeractwithitbysending
SQLor databasecommands then receivingresults with Java.
JAVAPROGRAMMING Page125
The Java.sql package that ships with JDK, contains various classes with their behaviours
definedand their actual implementaions are done in third-party drivers. Third party vendors
implementsthejava.sql.Driver interfacein their databasedriver.
JDBCDriversTypes
JDBCdriverimplementationsvarybecauseofthewidevarietyofoperatingsystemsandhardware
platforms in which Java operates. Sun has divided the implementation types into
fourcategories,Types1, 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
clientmachine. Using ODBC, requires configuring on your system a Data Source Name (DSN)
thatrepresentsthetarget database.
When Java first came out, this was a useful driver because most databases only supported
ODBCaccess but now this type of driver is recommended only for experimental use or when no
otheralternativeis available.
Type2:JDBC-NativeAPI
In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls, which are
uniqueto the database. These drivers are typically provided by the database vendors and used in
thesame manner as the JDBC-ODBC Bridge. The vendor-specific driver must be installed on
eachclientmachine.
JAVAPROGRAMMING Page126
If we change the Database, we have to change the native API, as it is specific to a database
andthey are mostly obsolete now, but you may realize some speed increase with a Type 2
driver,becauseit eliminates ODBC's overhead.
TheOracleCallInterface(OCI)driverisanexampleofaType2driver.
Type3:JDBC-NetpureJava
In a Type 3 driver, a three-tier approach is used to access databases. The JDBC clients
usestandard network sockets to communicate with a middleware application server. The
socketinformation is then translated by the middleware application server into the call format
requiredbythe DBMS, and forwarded to thedatabaseserver.
This kind of driver is extremely flexible, since it requires no code installed on the client and
asingledriver canactuallyprovide accessto multiple databases.
JAVAPROGRAMMING Page127
You can think of the application server as a JDBC "proxy," meaning that it makes calls for
theclient application. As a result, you need some knowledge of the application server's
configurationinorder to effectivelyusethis driver type.
Your application server might use a Type 1, 2, or 4 driver to communicate with the
database,understandingthe nuances will provehelpful.
Type4:100%PureJava
In a Type 4 driver, a pure Java-based driver communicates directly with the vendor's
databasethrough socket connection. This is the highest performance driver available for the
database andis usuallyprovided bythevendoritself.
Thiskindofdriverisextremelyflexible,youdon'tneedtoinstallspecialsoftwareontheclientorserver.
Further, thesedrivers can bedownloadeddynamically.
MySQL'sConnector/JdriverisaType4driver.Becauseoftheproprietarynatureoftheirnetworkprotocols,
databasevendors usuallysupplytype4 drivers.
WhichDrivershouldbeUsed?
Ifyouareaccessingonetypeofdatabase,suchasOracle,Sybase,orIBM,thepreferreddrivertypeis 4.
IfyourJavaapplicationisaccessingmultipletypesofdatabasesatthesametime,type3isthepreferreddriver.
Type2driversareusefulinsituations,whereatype3ortype4driverisnotavailableyetforyourdatabase.
JAVAPROGRAMMING Page128
Thetype1driverisnotconsideredadeployment-leveldriver,andistypicallyusedfordevelopmentand
testingpurposes only.
Exampletoconnecttothemysqldatabaseinjava
Forconnectingjavaapplicationwiththemysqldatabase,youneedtofollow5stepstoperformdatabase
connectivity.
InthisexampleweareusingMySqlasthedatabase.Soweneedtoknowfollowinginformationsforthe
mysql database:
Let'sfirstcreateatableinthemysqldatabase,butbeforecreatingtable,weneedtocreatedatabase first.
1. createdatabasesonoo;
2. usesonoo;
3. create table emp(id int(10),name varchar(40),age
int(3));ExampletoConnectJavaApplicationwithmysqldatab
ase
importjava.sql.*;
classMysqlCon{
public static void main(String
args[]){try{Class.forName("com.mysql.jd
bc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://l
JAVAPROGRAMMING Page129
ocalhost:3306/sonoo","root","root");
//heresonoo isdatabasename,rootisusernameand password
Statementstmt=con.createStatement();
ResultSetrs=stmt.executeQuery("select*fromemp");
while(rs.next())
System.out.println(rs.getInt(1)+""+rs.getString(2)+""+rs.getString(3));con.cl
ose();
}catch(Exceptione){System.out.println(e);}
}}
Toconnectjavaapplicationwiththemysqldatabasemysqlconnector.jarfileisrequiredtobeloaded.
2) setclasspath:
There are two ways to set the
classpath:1.temporary2.permane
nt
Howtosetthetemporaryclasspath
opencommand promptand write:
1.C:>setclasspath=c:\folder\mysql-connector-java-5.0.8-bin.jar;.;
How tosetthepermanentclasspath:
Go toenvironmentvariable then clickonnewtab.Invariable namewrite classpath andinvariable
value paste the path to the mysqlconnector.jar file by appending mysqlconnector.jar;.;
asC:\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.
TheSELECT statement is the standard way to select rows from a database and view them in a
JAVAPROGRAMMING Page130
resultset.Thejava.sql.ResultSetinterfacerepresents theresult setofadatabasequery.
JAVAPROGRAMMING Page131
AResultSetobjectmaintainsacursorthatpointstothecurrentrowintheresultset.Theterm"resultset"refer
s to therow and column data contained in a ResultSetobject.
Getmethods: Usedtoviewthedatainthecolumnsofthecurrentrowbeingpointedbythecursor.
Updatemethods: Usedtoupdatethedatainthecolumnsofthecurrentrow.Theupdatescanthen
beupdated in theunderlyingdatabaseaswell.
ThecursorismovablebasedonthepropertiesoftheResultSet.Thesepropertiesaredesignatedwhenthe
correspondingStatementthat generates the ResultSetis created.
JDBCprovidesthefollowingconnectionmethodstocreatestatementswithdesiredResultSet−
createStatement(intRSType,intRSConcurrency);
prepareStatement(StringSQL,intRSType,intRSConcurrency);
prepareCall(Stringsql,intRSType,intRSConcurrency);
The first argument indicates the type of a ResultSet object and the second argument is one of
twoResultSet constantsforspecifyingwhether aresult set is read-onlyor updatable.
TypeofResultSet
ThepossibleRSTypearegivenbelow.IfyoudonotspecifyanyResultSettype,youwillautomaticallyget one
that is TYPE_FORWARD_ONLY.
Type Description
JAVAPROGRAMMING Page132
ResultSet.TYPE_SCROLL_SENSITIVE. The cursor can scroll forward and backward,
andthe result set is sensitive to changes made
byotherstothedatabasethatoccurafter
theresultsetwascreated.
ConcurrencyofResultSet
ThepossibleRSConcurrencyaregivenbelow.IfyoudonotspecifyanyConcurrencytype,youwillautom
aticallyget onethat is CONCUR_READ_ONLY.
Concurrency Description
ViewingaResultSet
The ResultSet interface contains dozens of methods for getting the data of the current
Onethattakes inacolumnname.
Forexample,ifthecolumnyouareinterestedinviewingcontainsanint,youneedtouseoneof
thegetInt()methodsofResultSet−
S.N. Methods&Description
1 publicintgetInt(StringcolumnName)throwsSQLException
2 publicintgetInt(intcolumnIndex)throwsSQLException
Returnstheintinthecurrentrowinthespecifiedcolumnindex.Thecolumnindexstartsat1,
meaningthe first column of arow is 1, thesecond column of arow is 2, and so on.
JAVAPROGRAMMING Page133
Similarly, there are get methods in the ResultSet interface for each of the eight Java
primitivetypes,as wellascommontypessuchasjava.lang.String,java.lang.Object,andjava.net.URL.
TherearealsomethodsforgettingSQLdatatypesjava.sql.Date,java.sql.Time,java.sql.TimeStamp,jav
a.sql.Clob,andjava.sql.Blob.Checkthedocumentationformoreinformationabout
usingtheseSQLdata types.
UpdatingaResultSet
TheResultSetinterfacecontainsacollectionofupdatemethodsforupdatingthedataofaresultset.
Onethattakes inacolumnname.
JAVAPROGRAMMING Page134
Forexample,toupdateaStringcolumnofthecurrentrowofaresultset,youwoulduseoneof
thefollowingupdateString()methods−
S.N. Methods&Description
1 publicvoidupdateString(intcolumnIndex,Strings)throwsSQLException
ChangestheStringinthespecifiedcolumn tothevalueofs.
There are update methods for the eight primitive data types, as well as String, Object, URL,
andtheSQLdatatypes in thejava.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
needto invokeoneof thefollowingmethods.
S.N. Methods&Description
1 publicvoidupdateRow()
2 publicvoiddeleteRow()
Deletesthecurrentrowfromthedatabase
3 publicvoidrefreshRow()
Refreshesthe data in theresultset toreflect anyrecent changesin thedatabase.
4 publicvoidcancelRowUpdates()
Cancelsanyupdates madeon thecurrent row.
5 publicvoidinsertRow()
Insertsarowintothedatabase.Thismethodcanonlybeinvokedwhenthecursorispointingto
theinsert row.
JAVAPROGRAMMING Page135
UNIT-5
GUIProgrammingwithjava
TheAWTClass hierarchy
JavaAWTcomponentsareplatform-
dependenti.e.componentsaredisplayedaccordingtotheviewofoperatingsystem. AWTisheavyweight
i.e.itscomponents areusingthe resourcesofOS.
Thejava.awtpackageprovidesclassesforAWTapisuchasTextField,Label,TextArea,RadioButton,Che
ckBox, Choice,List etc.
JavaAWTHierarchy
JAVAPROGRAMMING Page136
Container
TheContainerisacomponentinAWTthatcancontainanothercomponentslikebuttons,textfields, labels
etc. The classes that extends Container class are known as container such asFrame, Dialogand
Panel.
Window
Thewindowisthecontainerthathavenobordersandmenubars.Youmustuseframe,dialogoranotherwind
owfor creatingawindow.
Panel
ThePanelisthecontainerthatdoesn'tcontaintitlebarandmenubars.Itcanhaveothercomponents
likebutton, textfield etc.
Frame
TheFrameisthecontainerthatcontaintitlebarandcanhavemenubars.Itcanhaveothercomponents likebutton,
textfield etc.
UsefulMethodsofComponentclass
Method Description
publicvoidsetVisible(booleanstatus) changesthevisibilityofthecomponent,bydefaultfalse.
JavaAWTExample
Tocreatesimpleawtexample,youneedaframe.TherearetwowaystocreateaframeinAWT.
o ByextendingFrameclass (inheritance)
o Bycreatingtheobject ofFrame class (association)
JAVAPROGRAMMING Page137
JAVAPROGRAMMING Page138
AWTExamplebyInheritance
Let'sseeasimpleexampleofAWTwhereweareinheritingFrameclass.Here,weareshowingButtoncomponent
on theFrame.
importjava.awt.*;
class First extends
Frame{First(){
Buttonb=newButton("clickme");b.setBounds(30,100,8
0,30);// setting button positionadd(b);//adding button
into framesetSize(300,300);//frame size 300 width and
300 heightsetLayout(null);//nolayoutmanager
setVisible(true);//nowframewill bevisible,bydefault notvisible
}
public static void main(String
args[]){Firstf=newFirst();
}}
The setBounds(int xaxis, int yaxis, int width, int height) method is used in the above example
thatsetstheposition ofthe 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
entirelywrittenin java.
UnlikeAWT,JavaSwingprovidesplatform-independent andlightweightcomponents.
Thejavax.swingpackageprovidesclassesforjavaswingAPIsuchasJButton,JTextField,JTextArea,JRa
dioButton, JCheckbox,JMenu, JColorChooseretc.
JAVAPROGRAMMING Page139
DifferencebetweenAWT and Swing.
3) AWTdoesn'tsupportpluggablelookand Swingsupportspluggablelookandfeel.
feel.
CommonlyusedMethodsofComponentclass
Method Description
publicvoidsetVisible(booleanb) setsthevisibilityofthecomponent.Itisbydefaultfalse.
JAVAPROGRAMMING Page140
HierarchyofJavaSwingclasses
JavaSwingExamples
Therearetwowaysto createaframe:
SimpleJavaSwingExample
Let'sseeasimpleswingexamplewherewearecreatingonebuttonandaddingitontheJFrameobjectinside
themain()method.
File:FirstSwingExample.java
JAVAPROGRAMMING Page141
JAVAPROGRAMMING Page142
importjavax.swing.*;
publicclassFirstSwingExample{
publicstaticvoidmain(String[] args){
JFramef=new JFrame();//creatinginstanceofJFrame
JButton b=new JButton("click");//creating instance of
JButtonb.setBounds(130,100,100, 40);//x axis, y axis, width,
heightf.add(b);//addingbutton in JFrame
f.setSize(400,500);//400 width and 500
heightf.setLayout(null);//using no layout
managersf.setVisible(true);//makingtheframe
visible
}}
Containers
JavaJFrame
UnlikeFrame,JFramehastheoptiontohideorclosethewindowwiththehelpofsetDefaultCloseOperation
(int)method.
JFrameExample
import
java.awt.FlowLayout;import
javax.swing.JButton;import
javax.swing.JFrame;import
javax.swing.JLabel;import
javax.swing.Jpanel;publicclass
JFrameExample{
publicstaticvoidmain(Strings[]){
JFrame frame = new JFrame("JFrame
Example");JPanel
panel=newJPanel();panel.setLayout(newFlowLay
out());
JLabel label = new JLabel("JFrame By
JAVAPROGRAMMING Page143
Example");JButton button = new
JButton();button.setText("Button");
panel.add(label);
JAVAPROGRAMMING Page144
panel.add(button);frame.add(panel)
;frame.setSize(200,
300);frame.setLocationRelativeTo(
null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisibl
e(true);
}}
JApplet
AswepreferSwingtoAWT.NowwecanuseJAppletthatcanhaveallthecontrolsofswing.TheJApplet
class extends the Applet class.
ExampleofEventHandlinginJApplet:
import
java.applet.*;import
javax.swing.*;importjav
a.awt.event.*;
public class EventJApplet extends JApplet implements
ActionListener{JButton b;
JTextFieldtf;
public void
init(){tf=newJTextF
ield();
tf.setBounds(30,40,150,20);
b=new
JButton("Click");b.setBoun
ds(80,150,70,40);add(b);ad
d(tf);b.addActionListener(t
his);setLayout(null);
}
public void actionPerformed(ActionEvent
e){tf.setText("Welcome");
}}Intheaboveexample,wehavecreatedallthecontrolsininit()methodbecauseitisinvokedonlyonce.
myapplet.html
1. <html>
2. <body>
3. <appletcode="EventJApplet.class"width="300"height="300">
JAVAPROGRAMMING Page145
JAVAPROGRAMMING Page146
</applet></body>
</html>
JDialog
TheJDialogcontrolrepresentsatoplevelwindowwithaborderandatitleusedtotakesomeformof input
from the user.It inherits theDialogclass.
UnlikeJFrame,itdoesn't havemaximizeandminimizebuttons.
JDialogclassdeclaration
Let'sseethedeclarationforjavax.swing.JDialogclass.
CommonlyusedConstructors:
Constructor Description
JDialog() Itisusedtocreateamodelessdialogwithoutatitleandwithout
aspecifiedFrameowner.
JDialog(Frameowner) ItisusedtocreateamodelessdialogwithspecifiedFrame as
its ownerand an emptytitle.
JDialog(Frameowner,Stringtitle,bo Itisusedtocreateadialogwiththespecifiedtitle,owner
oleanmodal) Frameand modality.
JAVAPROGRAMMING Page147
JavaJDialogExample
importjavax.swing.*;
importjava.awt.*;
import
java.awt.event.*;public class
DialogExample {private
static JDialog
d;DialogExample(){
JFramef=new JFrame();
d=newJDialog(f,"DialogExample",true);d.setL
ayout(newFlowLayout() );
JButton b = new JButton
("OK");b.addActionListener(newActionLis
tener()
{
publicvoidactionPerformed(ActionEvente)
{
DialogExample.d.setVisible(false);
}
}); Output:
JPanel
TheJPanelisasimplestcontainerclass.Itprovidesspaceinwhichanapplicationcanattachanyothercompo
nent.It inherits the JComponents class.
Itdoesn'thavetitlebar.
JAVAPROGRAMMING Page148
JAVAPROGRAMMING Page149
JPanelclassdeclaration
1.publicclassJPanel extendsJComponentimplementsAccessible
JavaJPanelExample
importjava.awt.*;
importjavax.swing.*;
public class PanelExample
{PanelExample()
{
JFrame f= new JFrame("Panel
Example");JPanel panel=new
JPanel();panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
JButton b1=new JButton("Button
1");b1.setBounds(50,100,80,30);b1.se
tBackground(Color.yellow);JButton
b2=new JButton("Button
2");b2.setBounds(100,100,80,30);b2.s
etBackground(Color.green);panel.add
(b1); panel.add(b2);f.add(panel);
f.setSize(400,400);
f.setLayout(null);f
.setVisible(true);
}
publicstaticvoidmain(Stringargs[])
{
newPanelExample();
}}
Overview of some Swing ComponentsJava
JButton
TheJButtonclassisusedtocreatealabeledbuttonthathasplatformindependentimplementation.Theapplicationresultins
ome actionwhenthebuttonis pushed.ItinheritsAbstractButtonclass.
JAVAPROGRAMMING Page150
JButtonclassdeclaration
Let'sseethedeclarationforjavax.swing.JButtonclass.
1.publicclassJButton extendsAbstractButtonimplementsAccessible
JavaJButtonExample
importjavax.swing.*;
publicclass ButtonExample {
public static void main(String[] args)
{JFrame f=new JFrame("Button
Example");JButton b=new JButton("Click
Here");b.setBounds(50,100,95,30);
f.add(b);f.setSize(400,4
00);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
asingle line of read only text. The text can be changed by an application but a user cannot edit
itdirectly.It inherits JComponent class.
JLabelclassdeclaration
Let'sseethedeclarationforjavax.swing.JLabelclass.
1.publicclassJLabelextendsJComponentimplementsSwingConstants,Accessible
CommonlyusedConstructors:
Constructor Description
JLabel() CreatesaJLabelinstancewithnoimageandwithanemptys
tringforthe title.
JLabel(Iconi) CreatesaJLabelinstancewiththespecifiedimage.
JAVAPROGRAMMING Page151
JLabel(String Icon i, int CreatesaJLabelinstancewiththespecifiedtext,image,an
s,ho d horizontal alignment.
rizontalAlignment)
JAVAPROGRAMMING Page152
CommonlyusedMethods:
Methods Description
void Itsetsthealignmentofthelabel'scontentsalongthe
setHorizontalAlignment(int Xaxis.
alignment)
JavaJLabelExample
importjavax.swing.*;
class LabelExample
{
publicstaticvoid main(Stringargs[])
{
JFrame f= new JFrame("Label
Example");JLabell1,l2;
l1=new JLabel("First
Label.");l1.setBounds(50,50,
100,30);l2=new JLabel("Second
Label.");l2.setBounds(50,100,10
0,30);f.add(l1);
f.add(l2);f.setSize(300,300);f.set
Layout(null);f.setVisible(true);
}
}
JAVAPROGRAMMING Page153
JTextField
TheobjectofaJTextFieldclassisatextcomponentthatallowstheeditingofasinglelinetext.ItinheritsJTextCom
ponentclass.
JTextFieldclassdeclaration
Let'sseethedeclarationforjavax.swing.JTextFieldclass.
1.publicclassJTextFieldextendsJTextComponentimplementsSwingConstants
JavaJTextFieldExample
importjavax.swing.*;
classTextFieldExample
{
publicstaticvoid main(Stringargs[])
{
JFrame f= new JFrame("TextField
Example");JTextFieldt1,t2;
t1=new JTextField("Welcome to
Javatpoint.");t1.setBounds(50,100,200,30);
t2=new JTextField("AWT
Tutorial");t2.setBounds(50,150,200,3
0);f.add(t1);
f.add(t2);f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
} }
JavaJTextArea
TheobjectofaJTextAreaclassisamultilineregionthatdisplaystext.Itallowstheeditingofmultipleline text.It
inherits JTextComponent class
JTextAreaclassdeclaration
Let'sseethedeclarationfor javax.swing.JTextAreaclass.
1. publicclassJTextAreaextendsJTextComponent
JAVAPROGRAMMING Page154
JavaJTextAreaExample
JAVAPROGRAMMING Page155
importjavax.swing.*;
publicclassTextAreaExample
{
TextAreaExample(){JFram
ef=newJFrame();
JTextArea area=new JTextArea("Welcome to
javatpoint");area.setBounds(10,30,200,200);
f.add(area);f.setSiz
e(300,300);f.setLa
yout(null);f.setVis
ible(true);
}
publicstaticvoidmain(Stringargs[])
{
newTextAreaExample();
}}
SimpleJavaApplications
importjavax.swing.JFrame;importj
avax.swing.SwingUtilities;
{publicExample(){
setTitle("Simple
example");setSize(300,
200);setLocationRelativeTo(
null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
JAVAPROGRAMMING Page156
JAVAPROGRAMMING Page157
LayoutManagement
JavaLayoutManagers
TheLayoutManagersareusedtoarrangecomponentsinaparticularmanner.LayoutManagerisaninterfac
ethat is implemented byallthe classesoflayout managers.
BorderLayout
1. publicstaticfinalint NORTH
2. publicstaticfinalintSOUTH
3. publicstaticfinalintEAST
4. publicstaticfinalintWEST
5. publicstaticfinalintCENTER
ConstructorsofBorderLayoutclass:
ExampleofBorderLayoutclass:
importjava.awt.*; Output:
importjavax.swing.*;
publicclassBorder
{
JFrame
f;Border(
)
{
f=newJFrame();
JButton b1=new
JButton("NORTH");;JButton b2=new
JButton("SOUTH");;JButton b3=new
JButton("EAST");;JButton b4=new
JButton("WEST");;JButton b5=new
JButton("CENTER");;f.add(b1,Border
Layout.NORTH);f.add(b2,BorderLayo
ut.SOUTH);f.add(b3,BorderLayout.EA
ST);f.add(b4,BorderLayout.WEST);f.a
dd(b5,BorderLayout.CENTER);f.setSiz
e(300,300);
f.setVisible(true);
}
publicstaticvoid main(String[] args)
JAVAPROGRAMMING Page158
{
newBorder();
}}
JAVAPROGRAMMING Page159
JavaGridLayout
TheGridLayoutisusedtoarrangethecomponentsinrectangulargrid.Onecomponentisdisplayedin
eachrectangle.
ConstructorsofGridLayoutclass
1. GridLayout(): createsagridlayoutwith one columnpercomponentinarow.
2. GridLayout(introws,intcolumns):createsagridlayoutwiththegivenrowsandcolumnsbut no
gaps between thecomponents.
3. GridLayout(introws,intcolumns,inthgap,intvgap):createsagridlayoutwiththegivenrows
andcolumnsalongwithgiven horizontaland vertical gaps.
ExampleofGridLayoutclass
1. importjava.awt.*;
2. import
javax.swing.*;public class
MyGridLayout{JFramef;
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");JButtonb9=newJ
Button("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));
//setting grid layout of 3 rows and 3
columnsf.setSize(300,300);
f.setVisible(true);
}
publicstaticvoidmain(String[] args){
new MyGridLayout();}}
JavaFlowLayout
FieldsofFlowLayoutclass
1. publicstaticfinalintLEFT
2. publicstaticfinalintRIGHT
3. publicstaticfinalintCENTER
4. publicstaticfinalintLEADING
JAVAPROGRAMMING Page160
5. publicstaticfinalintTRAILING
JAVAPROGRAMMING Page161
ConstructorsofFlowLayoutclass
1. FlowLayout():createsaflowlayoutwithcenteredalignmentandadefault5unithorizontaland
verticalgap.
2. FlowLayout(intalign):createsaflowlayoutwiththegivenalignmentandadefault5unithorizont
al and vertical gap.
3. FlowLayout(intalign,inthgap,intvgap):createsaflowlayoutwiththegivenalignmentand
thegivenhorizontal and verticalgap.
ExampleofFlowLayoutclass
importjava.awt.*;
importjavax.swing.*;public
class
MyFlowLayout{JFramef;
MyFlowLayout(){f
=newJFrame();
JButton b1=new
JButton("1");JButton b2=new
JButton("2");JButton b3=new
JButton("3");JButton b4=new
JButton("4");JButtonb5=newJ
Button("5");
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);f.s
etLayout(newFlowLayout(FlowLayout.RIGHT));
//setting flow layout of right
alignmentf.setSize(300,300);
f.setVisible(true);
}
publicstaticvoidmain(String[] args){
newMyFlowLayout();
}}
EventHandling
EventandListener(JavaEventHandling)
Changing the state of an object is known as an event. For example, click on button,
draggingmouse etc. The java.awt.event package provides many event classes and Listener
interfaces foreventhandling.
TypesofEvent
Foreground Events - Those events which require the direct interaction of user.They
aregenerated as consequences of a person interacting with the graphical components
inGraphicalUserInterface.Forexample,clickingonabutton,movingthemouse,enteringachara
cter throughkeyboard,selectinganitem fromlist, scrollingthepageetc.
BackgroundEvents-Thoseeventsthatrequiretheinteractionofenduserareknownas
JAVAPROGRAMMING Page162
JAVAPROGRAMMING Page163
backgroundevents.Operatingsysteminterrupts,hardwareorsoftwarefailure,timerexpires,ano
peration completionarethe example of backgroundevents.
EventHandling
Event Handling is the mechanism that controls the event and decides what should happen if
anevent occurs. This mechanism have the code which is known as event handler that is
executedwhen an event occurs. Java Uses the Delegation Event Model to handle the events. This
modeldefines the standard mechanism to generate and handle the events.Let's have a brief
introductionto thismodel.
TheDelegation EventModelhasthefollowingkeyparticipantsnamely:
Source -Thesourceisanobjectonwhicheventoccurs.Sourceisresponsibleforproviding
information of the occurred event to it's handler. Java provide as with
classesforsourceobject.
Listener -Itisalsoknownaseventhandler.Listenerisresponsibleforgeneratingresponse to an
event. From java implementation point of view the listener is also anobject. Listener
waits until it receives an event. Once the event is received , the listenerprocesstheevent an
thenreturns.
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 Page164
JAVAPROGRAMMING Page165
StepstoperformEvent Handling
Followingstepsarerequiredtoperformeventhandling:
1. ImplementtheListenerinterfaceandoverridesitsmethods
2. Registerthecomponent withtheListener
ForregisteringthecomponentwiththeListener,manyclassesprovidetheregistrationmethods.Forexamp
le:
o Button
o publicvoidaddActionListener(ActionListenera){}
o MenuItem
o publicvoidaddActionListener(ActionListenera){}
o TextField
o publicvoidaddActionListener(ActionListenera){}
o publicvoidaddTextListener(TextListenera){}
o TextArea
o publicvoidaddTextListener(TextListenera){}
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.*;
class AEvent extends Frame implements
ActionListener{TextFieldtf;
JAVAPROGRAMMING Page166
JAVAPROGRAMMING Page167
AEvent(){
tf=newTextField();tf.setBounds(6
0,50,170,20);Button b=new
Button("click
me");b.setBounds(100,120,80,30);
b.addActionListener(this);add(b);
add(tf);
setSize(300,300);
setLayout(null);s
etVisible(true);
}
public void actionPerformed(ActionEvent
e){tf.setText("Welcome");
}
publicstaticvoid main(Stringargs[]){
new AEvent();
}}
publicvoidsetBounds(intxaxis,intyaxis,intwidth,intheight);havebeenusedintheaboveexample
that setsthe position of thecomponent it maybebutton, textfield etc.
JavaeventhandlingbyimplementingActionListener
importjava.awt.*;
importjava.awt.event.*;
class AEvent extends Frame implements
ActionListener{TextField tf;
AEvent(){
//create
componentstf=new
TextField();
tf.setBounds(60,50,170,20);Button
b=new Button("click
me");b.setBounds(100,120,80,30);
//register
listenerb.addActionListener(this);//passingcurrentin
stance
//add components and set size, layout and
visibilityadd(b);add(tf);
setSize(300,300);
setLayout(null);s
etVisible(true);
}
public void actionPerformed(ActionEvent
e){tf.setText("Welcome");
}
}}
JAVAPROGRAMMING Page168
publicstaticvoid main(Stringargs[]){
new AEvent();
}}
JAVAPROGRAMMING Page169
JavaMouseListenerInterface
The Java MouseListener is notified whenever you change the state of mouse. It is notified
againstMouseEvent.TheMouseListenerinterfaceisfoundinjava.awt.eventpackage.Ithasfivemethods
.
MethodsofMouseListenerinterface
1. publicabstractvoidmouseClicked(MouseEvente);
2. publicabstractvoidmouseEntered(MouseEvent e);
3. publicabstractvoid mouseExited(MouseEvent e);
4. publicabstractvoid mousePressed(MouseEvent e);
5. publicabstractvoid mouseReleased(MouseEvente);
JavaMouseListenerExample
import
java.awt.*;importjava.a
wt.event.*;
public class MouseListenerExample extends Frame implements
MouseListener{Labell;
MouseListenerExample(){ad
dMouseListener(this);l=ne
w
Label();l.setBounds(20,50,
100,20);add(l);
setSize(300,300);
setLayout(null);s
etVisible(true);
}
public void mouseClicked(MouseEvent e)
{l.setText("MouseClicked");
}
public void mouseEntered(MouseEvent e)
{l.setText("MouseEntered");
}
public void mouseExited(MouseEvent e)
{l.setText("MouseExited");
}
public void mousePressed(MouseEvent e)
{l.setText("MousePressed");
}
public void mouseReleased(MouseEvent e)
{l.setText("MouseReleased");
}}
JAVAPROGRAMMING Page170
}
public static void main(String[] args)
{newMouseListenerExample();
}}
JAVAPROGRAMMING Page171
JavaKeyListenerInterface
TheJavaKeyListenerisnotifiedwheneveryouchangethestateofkey.ItisnotifiedagainstKeyEvent.The
KeyListenerinterfaceisfoundinjava.awt.eventpackage.Ithasthreemethods.
MethodsofKeyListenerinterface
Thesignatureof3methodsfoundinKeyListener interfacearegivenbelow:
1. publicabstractvoidkeyPressed(KeyEvente);
2. publicabstractvoidkeyReleased(KeyEvente);
3. publicabstractvoidkeyTyped(KeyEvent e);
JavaKeyListenerExample
import
java.awt.*;importjava.a
wt.event.*;
public class KeyListenerExample extends Frame implements
KeyListener{Labell;
TextArea
area;KeyListenerExamp
le(){
l=new
Label();l.setBounds(20,50,100,2
0);area=new
TextArea();area.setBounds(20,8
0,300,
300);area.addKeyListener(this);
add(l);add(area);setSize(400,40
0);setLayout(null);setVisible(tru
e);
}
public void keyPressed(KeyEvent e)
{l.setText("KeyPressed");
}
public void keyReleased(KeyEvent e)
{l.setText("KeyReleased");
}
public void keyTyped(KeyEvent e)
{l.setText("KeyTyped");
}
public static void main(String[] args)
{newKeyListenerExample();}}
JavaAdapterClasses
Java adapter classes provide the default implementation of listener interfaces. If you inherit
theadapter class, you will not be forced to provide the implementation of all the methods of
JAVAPROGRAMMING Page172
listenerinterfaces.So itsaves code.
JAVAPROGRAMMING Page173
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.*;
public class
AdapterExample{Framef;A
dapterExample(){
f=newFrame("WindowAdapter");f.addWindo
wListener(newWindowAdapter(){
public void windowClosing(WindowEvent e)
{f.dispose(); } });
f.setSize(400,400);
f.setLayout(null);f
.setVisible(true);
}
publicstaticvoidmain(String[] args){
newAdapterExample();
}}
JAVAPROGRAMMING Page174
Applets
Appletisaspecialtypeofprogramthatisembeddedinthewebpagetogeneratethedynamiccontent.Itruns
insidethe browserand works atclientside.
AdvantageofApplet
Drawbackof Applet
o Pluginisrequiredatclientbrowsertoexecuteapplet.
LifecycleofJavaApplet HierarchyofApplet
1. Appletisinitialized.
2. Appletisstarted.
3. Appletis painted.
4. Appletisstopped.
5. Appletisdestroyed.
LifecyclemethodsforApplet:
Thejava.applet.Appletclass4lifecyclemethodsandjava.awt.Componentclassprovides1lifecyclemeth
ods foran applet.
java.applet.Appletclass
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle
methodsofapplet.
JAVAPROGRAMMING Page176
java.awt.Componentclass
1.publicvoidpaint(Graphicsg):isusedtopainttheApplet.ItprovidesGraphicsclassobjectthat can
beusedfor drawingoval,rectangle, arcetc.
SimpleexampleofAppletby htmlfile:
To execute the applet by html file, create an applet and compile it. After that create an html
fileandplacetheapplet codein html file. Nowclick the html file.
1.//First.java
importjava.applet.Applet;
importjava.awt.Graphics;
public class First extends
Applet{public void paint(Graphics
g){g.drawString("welcome",150,1
50);
}
}
SimpleexampleofAppletbyappletviewertool:
To execute the applet by appletviewer tool, create an applet that contains applet tag in
commentand compile it. After that run it by: appletviewer First.java. Now Html file is not
required but it isfortestingpurposeonly.
1.//First.java
importjava.applet.Applet;
importjava.awt.Graphics;
publicclassFirstextends Applet{
publicvoidpaint(Graphics
g){g.drawString("welcometoapplet",150,150);
}
}
/*
<appletcode="First.class"width="300"height="300">
</applet>
JAVAPROGRAMMING Page177
*/
JAVAPROGRAMMING Page178
Toexecute theappletbyappletviewer tool,write in commandprompt:
c:\>javacFirst.java
c:\>appletviewerFirst.java
DifferencebetweenAppletandApplication programming
JAVAPROGRAMMING Page179
JAVAPROGRAMMING Page180
ParameterinApplet
WecangetanyinformationfromtheHTMLfileasaparameter.Forthispurpose,Appletclassprovidesamethod named
getParameter(). Syntax:
1.publicStringgetParameter(String parameterName)
Exampleofusing parameterinApplet:
1. importjava.applet.Applet;
2. importjava.awt.Graphics;
3. public class UseParam extends Applet4.{
5.public void paint(Graphics g)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>