0% found this document useful (0 votes)
30 views306 pages

Java Course File

Uploaded by

tejaswini reddy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
30 views306 pages

Java Course File

Uploaded by

tejaswini reddy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 306

Department of CSE(Data Science)

Course Name : Oop’sThroughJava Programming

Course Number : 0CS303PC

Course Designation : Core

Credits : 3

Prerequisites : Knowledge on programming C, C++

II B Tech – I Semester
(2023-24)

B.CHANDANA
Assistant Professor
Course Coordinator
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, Datatypes, Variables and Arrays, operators, expressions,
control statements, Introducing classes, Methods and Classes, String handling.
Unit – I
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.
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.
Unit – II StreambasedI/O(java.io)–The Stream classes-Bytestreams and Characterstreams, Reading
console Input and Writing Console Output, File class, Reading and writing Files, Random
access file operations,TheConsoleclass,Serialization,Enumerations,autoboxing,generics.
Exception handling - Fundamentals of exception handling, Exception types, Termination
or resumptive models,Uncaughtexceptions,usingtryandcatch,multiplecatchclauses,nestedtry
statements,throw,throwsandfinally,built-inexceptions,creatingownexceptionsubclasses.
Unit – III
Multithreading- Differences between thread-based multitasking and process-based
multitasking, Java thread model, creating threads, thread priorities, synchronizing threads ,
interthread communication.
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,
Unit – IV
Map Interfaces and Classes, Comparators, Collection algorithms, Arrays, The Legacy
Classes and Interfaces- Dictionary, Hash table ,Properties, Stack, Vector More Utility
classes, String Tokenizer, Bit Set, Date, Calendar, Random, Formatter, Scanner
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,
Unit – V 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 ImageIcon, JTextField.
The Swing Buttons- JButton, JToggle Button, JCheck Box, JRadio Button, JTabbed Pane,
JScroll Pane, JList, JCombo Box, Swing Menus, Dialogs.
Text Books & Reference Books

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.
Suggested / 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. RadhaKrishna, UniversityPress.

4 ProgramminginJava,S.Malhotra,S.Chudhary,2ndedition,OxfordUniv.Press.

Java Programming and Object-oriented Application Development, R. A. Johnson, Cengage


5
Learning.
Time Table for Academic Year 2022-23
Semester: III Section: C,G Class Teacher: B.CHANDANA RooM-143,144
With effect from:10-10-2022
Day /
9:2010:20 10:2011:20 11:20-12.20 1:002:00 2:00-3:00 3:00-4:00
Time
MON <----CRT------> JAVA-CSD JAVA-
CSD-C
LUNCH BREAK
12:20- 1:00 PM
TUE JAVA- <-----JAVA Lab CSD-C----->
CSD-C
WED
THU <-----JAVA Lab CSD----->

FRI JAVA- JAVA-


CSD CSD-C
SAT <-----PP Lab CSD-----> JAVA-CSD
*Program Educational Objectives (PEO)*:

*PEO1* Graduates use concepts of computer science, mathematics, and scientific studies to
assess issues, create industry-accepted solutions utilizing cutting-edge technology.

*PEO2* Graduates perform well in supportive and leadership roles on interdisciplinary teams,
demonstrating good communication and collaboration abilities while adhering to strict legal and
ethical guidelines.

*PEO3* Graduates encourage professional growth in order to keep up with ever-changing


technologies

*Program Specific Outcomes (PSO)*

*PSO1* Problem Solving Skill: The capacity to use industry-standard software development
concepts, processes, and strategies.

*PSO2* Professional Skill: The capacity to comprehend, evaluate, and create software solutions.

*PSO3* Successful Career: The capacity to work as an employee, an entrepreneur, or a lifelong


learner in the field of computer science.
Programme Outcomes (PO’s)

1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization for the solution of complex engineering
problems.
2. Problem analysis: Identify, formulate, research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering problems
and design system components or processes that meet the specified needs with
appropriate consideration for public health and safety, and cultural, societal, and
environmental considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and
research methods including design of experiments, analysis and interpretation of data,
and synthesis of the information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools, including prediction and modelling to complex
engineering activities, with an understanding of the limitations.
6. The engineer and society: Apply to reason informed by the contextual knowledge to
assess societal, health, safety, legal, and cultural issues and the consequent
responsibilities relevant to the professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional
engineering solutions in societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.
9. Individual and teamwork: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with the society at large, such as being able to comprehend
and write effective reports and design documentation, make effective presentations, and
give and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological
change.
Course Objectives

Students will learn:

1. To introduce the object-oriented programming concepts.


2. To understand object-oriented programming concepts, and apply them in solving problems.
3. To introduce the principles of inheritance and polymorphism; and demonstrate how they relate to
the design of abstract classes .
4. To introduce the implementation of packages and interfaces.
5. To introduce the concepts of exception handling and multithreading.
6. TointroducethedesignofGraphicalUserInterfaceusingappletsandswingcontrols

Course Outcomes:

Students will be able to:

1. Able to solve real world problems using OOPtechniques.


2. Able to understand the use of abstractclasses.
3. Able to solve problems using java collection framework and I/o classes.
4. Able to develop multithreaded applications withsynchronization.
5. Able to develop applets for webapplications.
6. Able to design GUI basedapplications
Mapping of Course outcomes with PO’s, PSO’s & PEO’s

Course Outcomes PO’s PSOs PEO’s


1,2,3,4,5,6, 8, 9, 11 1,2 1, 2
CO1
1,2,3,5,6,7,12 1, 2 1, 2
CO2
1,2,3,5,6,8,9 1, 2 1, 2
CO3
1,2,3,4,5,6
CO4 2 1, 2, 3
1,2,3,4,5,8,11
CO5 1, 2 1, 2, 3

Articulation matrix of Course outcomes with PO’s

PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
CO1 3 3 2 3 2 2 2 3 2
CO2 3 3 3 3 2 2 2
CO3 3 3 2 3 2 2 2
CO4 3 3 3 2 2 2
CO5 3 3 3 2 2 2 2
Course Schedule

Distribution of Hours in Unit – Wise

Unit Topic Chapters Total No.


of Hours
Book1 Book2

Object-Oriented Thinking Summary


of Object-Oriented concepts. Java
I buzzwords , An Overview of Java Ch1, Ch2 10
Inheritance & Introduction to
Packages, Streambased I/O(java.io)
Exception handling, Multithreading
II & Introduction to The collection Ch3, Ch4 8
framework.
The Collections Framework
III (java.util), GUI Programming with Ch5, Ch19 6
Swing
Event Handling-Event Listeners,
IV Handling mouse and keyboard Ch16, Ch17, Ch18 6
events, Applets and HTML
A Simple Swing Application, The
V Ch8, Ch9, Ch10 10
Swing Buttons,
Total contact classes for Syllabus coverage 50

Assignment Tests : 02 (Before Mid1 & Mid2 Examinations)

Number of hours/lectures available in Semester / Year: 64

The number of topics in each unit is not the same – because of the variation, all the units have
unequal distribution of hours
Lecture Plan

Expected Actual Date Teaching Learning


S.
Topic Date of of Process
No.
Completion Completion
Unit-I
A way of viewing world – 18.09.2023 20.09.2023
1 PPT & Digital Board
Agents and Communities
messages and methods, 20.09.2023 21.09.2023 PPT & Digital Board
2
Responsibilities
3 Classes and Instances, 21.09.2023 22.09.2023 PPT & Digital Board

4 Class Hierarchies- Inheritance 22.09.2023 23.09.2023 PPT & Digital Board

5 Method binding 23.09.2023 25.09.2023 PPT & Digital Board


Overriding and Exceptions, 25.09.2023 07.10.2023
6 Summary of Object-Oriented PPT & Digital Board
concepts
Java buzzwords, An Overview 07.10.2023 09.10.2023 PPT & Digital Board
7
of Java
8 Data types, Variables 09.10.2023 11.10.2023 PPT & Digital Board
9 Arrays, operators, expressions 11.10.2023 12.10.2023 PPT & Digital Board
10 control statements 12.10.2023 13.10.2023 PPT & Digital Board
Introducing classes, Methods 13.10.2023 16.10.2023
11 PPT & Digital Board
and Classes, String handling.
Inheritance– Inheritance 16.10.2023 19.10.2023
12 PPT & Digital Board
concept, Inheritance basics
Member access, Constructors, 19.10.2023 21.10.2023
13 PPT & Digital Board
Creating Multilevel hierarchy
14 super uses 21.10.2023 30.10.2023 PPT & Digital Board
15 using final with inheritance 30.10.2023 01.11.2023 PPT & Digital Board
Polymorphism-ad hoc 01.11.2023 07.10.2023
polymorphism, pure PPT & Digital Board
16
polymorphism, method Tutorial - 1
overriding
17 abstract classes, Object class 07.10.2023 09.10.2023 PPT & Digital Board
forms of inheritance- 09.10.2023 09.10.2023
specialization, specification,
18 PPT & Digital Board
construction, extension,
limitation, combination, benefits
of inheritance, costs of
inheritance.

Unit-II
1 Packages- Defining a Package 02.11.2023 02.11.2023 PPT & Digital Board
CLASSPATH, Access 03.11.2023 03.11.2023 PPT & Digital Board
2
protection
04.11.2023 04.11.2023 PPT & Digital Board
3 importing packages
Interfaces- defining an interface, 06.11.2023 06.11.2023 PPT & Digital Board
4
implementing interfaces Tutorial - 2
Nested interfaces, applying 08.11.2023 08.11.2023 PPT & Digital Board
interfaces, variables in
5
interfaces and extending
interfaces
Stream based I/O (java.io) – The 09.11.2023 09.11.2023 PPT & Digital Board
6
Stream classes
Byte streams and Character 10.11.2023 10.11.2023 PPT & Digital Board
7 streams, Reading console Input
and Writing Console Output
File class, Reading and writing 11.11.2023 11.11.2023 PPT & Digital Board
8 Files, Random access file
operations
The Console class, Serialization, 13.11.2023 13.11.2023 PPT & Digital Board
9 Enumerations, auto boxing
generics.
Unit-III
Exception handling - 15.11.2023 16.11.2023 PPT & Digital Board
1 Fundamentals of exception
handling, Exception types
Termination or resumptive 16.11.2023 29.11.2023 PPT & Digital Board
2
models, Uncaught exceptions
using try and catch, multiple 29.11.2023
catch clauses, nested try
3 01.12.2023
statements, throw, throws and PPT & Digital Board
finally.
built- in exceptions, creating 02.12.2023 PPT & Digital Board
4 01.12.2023
own exception sub classes
Multithreading- Differences 02.12.2023 04.12.2023 PPT & Digital Board
between thread-based
5
multitasking and process-based
multitasking
Java thread model, creating 04.12.2023 06.12.2023 PPT & Digital Board
6
threads, thread priorities
synchronizing threads, inter 06.12.2023 PPT & Digital Board
7 06.12.2023
thread communication Tutorial - 3
Unit-IV
The Collections Framework 08.12.2023 09.12.2023
PPT & Digital Board
1 (java.util)- Collections overview,
Tutorial -4
Collection Interface
TheCollection classes- Array 09.12.2023 11.12.2023 PPT & Digital Board
2
List, Linked List
Hash Set, Tree Set, Priority 11.12.2023 14.12.2023 PPT & Digital Board
3
Queue, Array Deque
Accessing a Collection via an 14.12.2023 18.12.2023 PPT & Digital Board
4 Iterator, Using an Iterator, The
For-Each alternative
Map Interfaces and Classes, 18.12.2023 PPT & Digital Board
5 Comparators, Collection 20.12.2023
algorithms, Arrays
The Legacy Classes and 22.12.2023 PPT & Digital Board
Interfaces- Dictionary,
6 20.12.2023
Hashtable ,Properties, Stack,
Vector
More Utility classes, String 22.12.2023 22.12.2023 PPT & Digital Board
7
Tokenizer, Bit Set
Date, Calendar, Random, 22.12.2023 22.12.2023 PPT & Digital Board
8
Formatter, Scanner
Unit-V
GUI Programming with Swing – 22.12.2023 27.12.2023 PPT & Digital Board
1 Introduction, limitations of
AWT, MVC architecture
components, containers. 27.12.2023 30.12.2023 PPT & Digital Board
Understanding Layout
2 Managers, Flow Layout, Border
Layout, Grid Layout, Card
Layout, Grid Bag Layout.
Event Handling- The Delegation 30.12.2023 01.01.2024 PPT & Digital Board
event model- Events, Event
3
sources, Event Listeners, Event
classes
Handling mouse and keyboard 01.01.2024 03.01.2024 PPT & Digital Board
4
events Tutorial - 5
Adapter classes, Inner classes, 03.01.2024 05.01.2024 PPT & Digital Board
5
Anonymous Inner classes.
A Simple Swing Application, 05.01.2024 08.01.2024 PPT & Digital Board
6 Applets – Applets and HTML,
Security Issues
Applets and Applications, 08.01.2024 27.12.2023 PPT & Digital Board
7
passing parameters to applets.
Creating a Swing Applet
Painting in Swing, A Paint 10.01.2024 10.01.2024 PPT & Digital Board
8
example
Exploring Swing Controls- 10.01.2024 10.01.2024 PPT & Digital Board
9 JLabel and Image Icon, JText
Field
The Swing Buttons- JButton, 10.01.2024 10.01.2024 PPT & Digital Board
10
JToggle Button, JCheck Box
JRadio Button, JTabbed Pane, 15.01.2024 15.01.2024 PPT & Digital Board
11
JScroll Pane
JList, JCombo Box, Swing 18.01.2024 18.01.2024 PPT & Digital Board
12
Menus, Dialogs
Total No of classes: 50

Date of Unit completion & Remarks

Unit – I
Date: 09-10-2023
Remarks: Syllabus completed intime

Unit – II
Date: 13.11.2023
Remarks: Syllabus completed intime

Unit – III
Date: 06.12.2023
Remarks: Syllabus completed intime

Unit – IV
Date: 22.12.2023
Remarks: Syllabus completed intime

Unit – V
Date: 18.01.2024
Remarks: Syllabus completed intime
Unit Wise Questions (With different Levels of thinking – Blooms Taxonomy and Course
Outcomes)

Question Bank for Mid -1

Short Answer Questions


1. Explain the need for object-oriented programming paradigm? [L2,CO1]
2. Describe about the usage of super keyword. [L2,CO1]
3. What is the need of Generics? [L1,CO2]
4. What is constructor explain with example. [L2,CO2]
5. Explain the advantages of Exception Handling? [L2,CO3]
6. List the java Buzzwards. ? [L2,CO1]
7. Explain about the this keyword? [L2,CO1]
8. Define a package? [L1,CO2]
9. Describe AUTO BOXING? [L2,C02]
10. Describe and Draw the General form of Exception handling [L1,C03]
Long Answer Questions

1. Explain abstract class with example? [L2,C01]


2. Explain method overriding with a suitable example program.? [L2,C01]

3. Explain .? [L2,C01]
4. Explain how multiple inheritance implemented through interfaces with example?
[L2,C02]
5. Implement a program to copy the contents of file into another file? [L3,C02]
6. Differentiate between Checked and unchecked Exceptions with examples? [L4,CO3]
7. Explain the following [L2,C03]
a) try b) catch c) finally
8. Explain about final classes, final methods and final variables? [L2,CO1]
9. Define Array? Explain about Multi Dimensional array with example? [L3,CO1]
10. Explain different forms of inheritance with example? [L2,CO1]
11. Explain about method overriding and method overloading? [L2,CO1]
12. Define package? How many ways to import a package with example? [L1,CO2]
13. Explain about Nested interfaces and applying interfaces? [L3,CO2]
14. Define File class? Explain Random Access File operations with access modes . [L5,CO3]
15. Explain about Byte stream and character streams? [L3,CO3]
16. Explain the checked Exceptions with example? [L1,CO4]
17. What is an exception? Explain How to handle exceptions . [L2,CO4]
Assignment Questions for Mid -1
1. Explain OOPs concepts. ? [CO1, L2]
2. Explain how multiple inheritance implemented through interfaces with example?
[CO1, L1]
3. Define package? How many ways to importing a package with example.
[CO2, L2]
4. What is an interface? Give the general form of interface and also discuss the
implementation details of interfaces. [CO1,L2]
5. Explain the following.
try b) catch c) finally [CO2, L4]

Question Bank for Mid II

Short Answer Questions


1. List the thread states and give state transition diagram. [L1,CO3]
2. What is the difference between List and Set? [L2,CO4]
3. What is the difference between Set and Map? [L1,CO4]
4. Explain the life cycle of applet. [L1,CO5]
5. What is an Event Listener in JAVA programming? [L1,CO5]
6. Summarize the differences between thread-based multitasking and process-based
multitasking. [L2,CO3]
7. What are the advantages of the Collection Framework in Java? [L1,CO4]
8. Explain about String Tokenizer? [L2,CO4]
9. What are the methods of component class in Java Swing? [L1,CO5]
10. List out the differences between AWT and Swings. [L2,CO5]

Long Answer Questions


1. Analyze the need of thread synchronization. How is it achieved in Java programming?
[L4,CO3]
2. What is Producer Consumer Problem in Java. [L2,CO3]
3. How to create multiple threads in a program? Explain with an example. [L6,CO3]
4. Summarize the differences between thread-based multitasking and process-based
multitasking. [L2,CO3]
5. Explain the java collection framework hierarchy. [L2,CO4]
6. Show the differences between Array List and Vector in Collection framework.[L1.CO4]
7. List down the primary interfaces provided by Java Collections Framework?[L1,CO4]
8. Illustrate the applications of Map, HashMap utilities. [L2,CO4]
9. Demonstrates the different types of Event Listeners supported by java. [L2,CO5]
10. Write a simple Java Swing program to create a JButton and adding it on the JFrame
object inside the main () method? [L2,CO5]
11. What is multithreading in Java? Explain the inter thread communication with the help of
suitable example. [L2,CO3]
12. List the different stages in the life cycles of a thread. [L1,CO3]
13. Show the differences between Array List and Vector in Collection framework.[L2,CO3]
14. Illustrate the applications of Map, HashMap utilities. [L2,CO3]
15. Explain the java collection framework hierarchy. [L2,CO4]
16. What is the difference between Array List and LinkedList? [L2,CO4]
17. What is a Layout manager? Explain in brief about various layout managers supported by
JAVA. [L1,CO4]
18. What is the container class in JAVA and also mention its subclasses. [L1,CO4]
19. Explain the different types of Event Listeners supported by java. [L2,CO5]
20. How the events of the mouse and keyboard can be handled? Explain with an example.
i. [L1,CO5]

Assignment Questions for Mid -2

1.Illustrate functional dependency with example? Demonstrate transitive dependency? Give an


example? [CO3, L3]

2.Define a Transaction? List the properties of transaction? Discuss different phases of


transaction? [CO4, L1]

3.Discuss the Procedure to test Serializability? Demonstrate Conflict Serializability?


[CO4, L2]
4. Explain about locking protocols? Define timestamp-based protocol? [CO4, L4]

5. Write in detail about Static Hashing? Explain in detail about Extendible Hashing?
[CO5, L6]

Case Studies (With Higher Levels of thinking – Blooms Taxonomy) for the academic year
2022-23 II B Tech I semester

# 1 Designing Conceptual Schema for Real Time Applications


1. Write a program such that it should have three classes, Person and Student
and the Main class where Person is the base class and Student is the derived
class.
2. Create an abstract class Shape with length, width, radius, 3 sides as data
members and two abstract methods to calculate area and perimeter. Create
constructors and getter setters.

# 2 (Covering Entire Syllabus)


NeoColab Case Studies
Previous Question papers
Tutorial Sheet

Unit-I Topics Revised


Topic Name Date
Polymorphism-ad hoc polymorphism, pure polymorphism, method 23.09.2023
overriding

Unit-II Topics Revised


Topic Name Date
Interfaces- defining an interface, implementing interfaces 14.10.2023

Unit-III Topics Revised


Topic Name Date
synchronizing threads, inter thread communication 14.12.2023

Unit-IV Topics Revised


Topic Name Date
The Collections Framework (java.util)- Collections overview, 08.01.2024
Collection Interface

Unit-V Topics Revised


Topic Name Date
Handling mouse and keyboard events 14.12.2023
Topics beyond Syllabus

S. No Name of the Topic

1 JDBC Connection, NetBeans IDE, EclipsIDE


2
3
Course Assessment Sheet

Batch: II B.TECH II SEMESTER

Academic Year/Sem: 2022-2023

Course Name: OOPs Through Java

Course Number: 20CS303PC

Course Attainment (75% of Direct + 25% of Indirect) on a scale of 1 to 3.

Remarks and suggestions:

Course Coordinaton
Blooms Taxonomy Direct

Level 1 Remembering Exhibit memory of previously learned material by recalling


facts, terms, basic concepts, and answers.
Level 2 Understanding Demonstrate understanding of facts and ideas by organizing,
comparing, translating, interpreting, giving descriptions, and
stating main ideas.
Level 3 Applying Solve problems to new situations by applying acquired
knowledge, facts, techniques and rules in a different way.
Level 4 Analyzing Examine and break information into parts by identifying
motives or causes. Make inferences and find evidence to
support generalizations.
Level 5 Evaluating Present and defend opinions by making judgments about
information, validity of ideas, or quality of work based on a
set of criteria.
Level 6 Creating Compile information together in a different way by
combining elements in a new pattern or proposing alternative
solutions.
Direct Course Assessment Sheet

a) Internal Examination

Course assessment sheet Mid1

Subjective (30 Marks) Total


Total (35
Assignmen Part-A (10Marks) Part-B (20Marks)
S.NO ROLL NO Marks Marks)
t 5 Marks
Q1
1B 1C 1D 1E Q2 Q3 Q4 Q5 Q6 Q7
A
227R1A6
1 5 2 2 2 2 2 4 6 20 25
765
227R1A6
2 5 2 2 2 2 1 4 6 19 24
766
227R1A6
3 5 2 1 7 7 3 20 25
767
227R1A6
4 5 2 2 2 2 2 7 7 3 27 32
768
227R1A6
5 5 2 2 0 2 2 1 9 14
769
227R1A6
6 5 2 2 2 2 2 4 7 2 23 28
770
227R1A6
7 5 2 2 2 2 2 6 7 2 25 30
771
227R1A6
8 5 2 2 2 2 7 4 19 24
772
227R1A6
9 5 2 2 1 1 4 3 1 14 19
773
227R1A6
10 5 1 2 2 1 1 3 10 15
774
227R1A6
11 5 1 2 3 8
775
227R1A6
12 5 2 2 2 2 2 6 7 4 27 32
776
227R1A6
13 5 2 2 2 2 5 6 3 22 27
777
227R1A6
14 5 2 2 2 2 1 5 4 2 20 25
778
227R1A6
15 5 2 2 2 2 2 4 2 3 19 24
779
227R1A6
16 5 1 1 2 2 2 2 2 12 17
780
227R1A6
17 5 1 1 2 1 3 5 3 16 21
781
227R1A6
18 5 2 2 2 2 2 7 7 4 28 33
782
227R1A6
19 5 2 1 1 2 2 6 6 2 22 27
783
227R1A6
20 5 2 2 2 2 2 6 7 4 27 32
784
227R1A6
21 5 1 2 2 5 10
785
227R1A6
22 5 2 1 1 2 1 6 7 3 23 28
786
227R1A6
23 5 1 1 2 4 2 10 15
787
227R1A6
24 5 2 2 2 2 2 6 8 4 28 33
788
227R1A6
25 5 2 2 2 1 1 6 6 4 24 29
789
227R1A6
26 5 2 2 2 2 4 1 2 15 20
790
227R1A6
27 5 2 2 2 2 2 6 7 3 26 31
791
227R1A6
28 5 2 2 2 2 2 7 6 23 28
793
227R1A6
29 5 2 2 2 2 2 3 6 4 23 28
794
227R1A6
30 5 2 2 2 2 2 3 6 1 20 25
795
227R1A6
31 5 2 2 2 2 2 5 15 20
796
227R1A6
32 5 2 1 2 1 1 4 6 3 20 25
797
227R1A6
33 5 2 2 2 2 2 4 5 3 22 27
798
227R1A6
34 5 2 1 2 1 2 5 8 2 23 28
799
227R1A6
35 5 2 1 2 1 2 4 8 1 21 26
7A0
227R1A6
36 5 2 2 2 2 2 6 7 23 28
7A1
227R1A6
37 5 2 2 2 2 2 7 7 2 26 31
7A2
227R1A6
38 5 2 1 2 2 2 7 8 3 27 32
7A3
227R1A6
39 5 2 1 2 1 2 2 3 2 15 20
7A4
227R1A6
40 5 2 1 1 1 4 2 11 16
7A5
227R1A6
41 5 2 2 2 3 2 11 16
7A6
42 227R1A6 5 2 1 3 3 9 14
7A7
227R1A6
43 5 2 2 1 1 1 3 2 12 17
7A8
227R1A6
44 5 2 2 2 4 5 3 18 23
7A9
227R1A6
45 5 2 2 2 2 2 6 5 3 24 29
7B0
227R1A6
46 5 2 1 2 2 2 6 7 4 26 31
7B1
227R1A6
47 5 2 2 2 2 2 7 8 3 28 33
7B2
227R1A6
48 5 2 2 2 1 2 2 7 2 20 25
7B3
227R1A6
49 5 2 1 2 2 3 10 15
7B4
227R1A6
50 5 2 2 2 5 2 3 16 21
7B5
227R1A6
51 5 2 2 1 2 7 8 2 24 29
7B6
227R1A6
52 5 2 2 2 7 7 3 23 28
7B7
227R1A6
53 5 2 2 1 4 7 2 18 23
7B8
227R1A6
54 5 2 2 2 2 1 5 7 2 23 28
7B9
227R1A6
55 5 2 2 2 2 2 4 8 2 24 29
7C0
227R1A6
56 5 2 1 1 2 4 7 3 20 25
7C1
227R1A6
57 5 2 1 1 2 1 4 3 14 19
7C2
227R1A6
58 5 2 1 2 2 7 8 3 25 30
7C3
227R1A6
59 5 2 1 2 2 2 3 8 3 23 28
7C4
227R1A6
60 5 2 2 2 6 6 18 23
7C5
227R1A6
61 5 2 1 2 1 2 4 7 2 21 26
7C6
227R1A6
62 5 2 2 2 2 2 6 7 1 24 29
7C7
227R1A6
63 5 2 2 2 1 2 5 6 20 25
7C8
237R5A6
64 5 2 2 2 1 1 2 6 2 18 23
707
237R5A6
65 5 2 2 2 2 2 7 7 3 27 32
708
237R5A6
66 5 2 2 2 2 2 1 3 2 16 21
709
237R5A6
67 5 2 1 2 2 2 1 7 2 19 24
710
237R5A6
68 5 2 0 1 6 1 3 13 18
711
237R5A6
69 5 2 2 2 2 2 4 5 2 21 26
712

Course assessment sheet Mid2

Total
Subjective (30 Marks) (35
Assign
ment
Marks)
5 Tot
S.NO ROLL NO Marks al
Part-A (10Marks) Part-B (20Marks) Ma
rks
Q1A 1B 1C 1D 1E Q2 Q3 Q4 Q5 Q6 Q7

1 227R1A6765 5 2 2 2 2 1 6 15 20

2 227R1A6766 5 2 2 2 2 2 4 14 19

3 227R1A6767 5 2 2 2 2 2 4 6 2 22 27

4 227R1A6768 5 2 2 2 2 2 4 8 4 26 31

5 227R1A6769 5 2 2 2 8 14 19

6 227R1A6770 5 2 2 2 2 2 4 8 8 30 35

7 227R1A6771 5 2 2 2 2 2 4 7 3 24 29

8 227R1A6772 5 2 2 2 2 2 4 8 8 30 35

9 227R1A6773 5 2 2 2 2 2 3 6 7 26 31

10 227R1A6774 5 2 2 2 2 2 2 5 3 20 25

A
11 227R1A6775 Ab Ab Ab Ab Ab Ab Ab Ab Ab Ab Ab Ab Ab
b
12 227R1A6776 5 2 2 2 2 2 4 8 3 25 30

13 227R1A6777 5 2 2 3 5 2 14 19

14 227R1A6778 5 2 2 2 2 3 5 3 19 24

15 227R1A6779 5 2 2 2 2 2 6 4 20 25
16 227R1A6780 5 2 1 2 2 2 2 5 6 22 27

17 227R1A6781 5 1 1 1 2 2 2 4 3 16 21

18 227R1A6782 5 2 2 2 2 2 4 7 8 29 34

19 227R1A6783 5 2 2 2 2 2 3 5 2 20 25

20 227R1A6784 5 2 2 2 2 2 3 7 7 27 32

21 227R1A6785 5 2 1 2 2 2 3 2 14 19

22 227R1A6786 5 2 2 2 2 2 3 6 8 27 32

23 227R1A6787 5 1 1 2 1 3 5 3 16 21

24 227R1A6788 5 2 2 2 2 2 3 8 6 27 32

25 227R1A6789 5 2 2 2 2 2 1 7 3 21 26

26 227R1A6790 5 2 2 2 2 2 4 4 2 20 25

27 227R1A6791 5 2 2 2 2 2 4 8 8 30 35

28 227R1A6793 5 2 2 2 2 2 2 7 7 26 31

29 227R1A6794 5 2 2 2 2 2 3 7 8 28 33

30 227R1A6795 5 2 2 2 2 2 3 6 5 24 29

31 227R1A6796 5 2 2 2 2 2 4 7 5 26 31

32 227R1A6797 5 2 2 2 2 2 3 5 5 23 28

33 227R1A6798 5 2 2 2 2 2 3 7 4 24 29

34 227R1A6799 5 2 2 2 2 2 4 7 3 24 29

35 227R1A67A0 5 2 2 2 2 2 3 8 6 27 32

36 227R1A67A1 5 2 2 2 2 2 4 6 3 23 28

37 227R1A67A2 5 2 2 2 2 2 4 7 6 27 32

38 227R1A67A3 5 2 2 2 2 2 4 7 7 28 33

39 227R1A67A4 5 2 2 2 2 2 4 8 7 29 34

40 227R1A67A5 5 2 2 2 1 2 3 7 4 23 28

41 227R1A67A6 5 2 2 2 1 2 3 8 4 24 29
42 227R1A67A7 5 2 2 2 2 - 3 6 3 20 25

43 227R1A67A8 5 2 2 2 2 2 3 7 6 26 31

44 227R1A67A9 5 2 2 2 2 2 3 7 7 27 32

45 227R1A67B0 5 2 2 2 2 2 3 8 6 27 32

46 227R1A67B1 5 2 2 2 2 2 3 8 21 26

47 227R1A67B2 5 2 2 2 2 2 4 8 6 28 33

48 227R1A67B3 5 2 2 2 2 2 4 7 6 27 32

49 227R1A67B4 5 2 2 2 2 1 1 4 5 19 24

50 227R1A67B5 5 2 2 2 2 1 3 8 7 27 32

51 227R1A67B6 5 2 2 2 2 2 3 8 4 25 30

52 227R1A67B7 5 1 2 2 2 2 2 7 3 21 26

53 227R1A67B8 5 - - 2 - 2 7 3 14 19

54 227R1A67B9 5 2 2 2 2 2 4 6 4 24 29

55 227R1A67C0 5 2 2 2 1 1 3 7 2 20 25

56 227R1A67C1 5 2 2 1 2 2 4 8 5 26 31

57 227R1A67C2 5 - 2 2 - 1 3 6 14 19

58 227R1A67C3 5 2 1 2 2 2 3 6 6 24 29

59 227R1A67C4 5 2 2 2 2 2 4 8 8 30 35

60 227R1A67C5 5 2 1 2 1 2 5 3 16 21

61 227R1A67C6 5 2 2 2 2 2 4 7 21 26

62 227R1A67C7 5 2 2 2 2 2 4 8 4 26 31

63 227R1A67C8 5 2 2 2 2 2 3 6 4 23 28

64 237R5A6707 5 2 2 2 2 2 3 5 7 25 30

65 237R5A6708 5 2 2 2 2 2 4 8 8 30 35

66 237R5A6709 5 2 2 2 2 2 3 4 17 22

67 237R5A6710 5 2 2 2 2 2 4 7 2 23 28
68 237R5A6711 5 - 2 - 2 2 3 6 5 20 25

69 237R5A6712 5 2 2 2 2 2 3 3 7 23 28
CSP Rubric
S.No. Criteria LEVEL ( Level: 3-Excellent Level: 2-Good Level: 1-Poor)
Student speaks in phase with the given topic confidently using Audio-
Communicati

3
Visual aids. Vocabulary is good
Student speaking without proper planning, fair usage of Audio-Visual
Oral

on

1 2
aids. Vocabulary is not good
Student speaks vaguely not in phase with the given topic. No
1
synchronization among the talk and Visual Aids
Proper structuring of the document with relevant subtitles, readability
Writing Skills

3 of document is high with correct use of grammar. Work is genuine and


not published anywhere else
2 Information is gathered without continuity of topic, sentences were not
2
framed properly. Few topics are copied from other documents
Information gathered was not relevant to the given task, vague
1
collection of sentences. Content is copied from other documents
Student identifies most potential ethical or societal issues and tries to
3
Awareness
Social and

provide solutions for them discussing with peers


Ethical

Student identifies the societal and ethical issues but fails to provide any
3 2
solutions discussing with peers
1 Student makes no attempt in identifying the societal and ethical issues
3 Student uses appropriate methods, techniques to model and solve the
Knowled
Content

problem accurately
ge

4 2 Student tries to model the problem but fails to solve the problem
1 Student fails to model the problem and also fails to solve the problem
3 Listens carefully to the class and tries to answer questions confidently
Participati
Student

Listens carefully to the lecture but doesn’t attempt to answer the


2
on

5 questions
1 Student neither listens to the class nor attempts to answer the questions
The program structure is well organized with appropriate use of
Technical and analytical

technologies and methodology. Code is easy to read and well


3
documented. Student is able to implement the algorithm producing
accurate results
Program structure is well organized with appropriate use of
Skills

6 technologies and methodology. Code is quite difficult to read and not


2
properly documented. Student is able to implement the algorithm
providing accurate results.
Program structure is not well organized with mistakes in usage of
1 appropriate technologies and methodology. Code is difficult to read
and student is not able to execute the program
Independently able to write programs to strengthen the concepts
3
Knowledge
Practical covered in theory
Independently able to write programs but not able to strengthen the
7 2
concepts learned in theory
Not able to write programs and not able to strengthen the concepts
1
learned in theory
Student uses appropriate methods, techniques to model and solve the
Understandin

3
Engineering

problem accurately in the context of multidisciplinary projects


Student tries to model the problem but fails to solve the problem in the
core
g of

8 2
context of multidisciplinary projects
Student fails to model the problem and also fails to solve the problem
1
in the context of multidisciplinary projects
OBJECT-ORIENTED THINKING:
A way of viewing the world is an idea to illustrate the object-oriented programming concept with an
example of a real-world situation.

Let us consider a situation, I am at my office and I wish to get food to my family members who are at
my home from a hotel. Because of the distance from my office to home, there is no possibility of
getting food from a hotel myself. So, how do we solve the issue?

To solve the problem, let me call zomato (an agent in food delevery community), tell them the variety
and quantity of food and the hotel name from which I wish to delever the food to my family members.
Look at the following image.

Agents and Communities


To solve my food delivery problem, I used a solution by finding an appropriate agent (Zomato) and
pass a message containing my request. It is the responsibility of the agent (Zomato) to satisfy my
request. Here, the agent uses some method to do this. I do not need to know the method that the
agent has used to solve my request. This is usually hidden from me.
So, in object-oriented programming, problem-solving is the solution to our problem which requires
the help of many individuals in the community. We may describe agents and communities as follows.

An object-oriented program is structured as a community of interacting agents, called objects.


Where each object provides a service (data and methods) that is used by other members of the
community.

In our example, the online food delivery system is a community in which the agents are zomato and
set of hotels. Each hotel provides a variety of services that can be used by other members like zomato,
myself, and my family in the community.

Messages and Methods


To solve my problem, I started with a request to the agent zomato, which led to still more requestes
among the members of the community until my request has done. Here, the members of a community
interact with one another by making requests until the problem has satisfied.

In object-oriented programming, every action is initiated by passing a message to an agent (object),


which is responsible for the action. The receiver is the object to whom the message was sent. In
response to the message, the receiver performs some method to carry out the request. Every
message may include any additional information as arguments.

In our example, I send a request to zomato with a message that contains food items, the quantity of
food, and the hotel details. The receiver uses a method to food get delivered to my home.

Responsibilities
In object-oriented programming, behaviors of an object described in terms of responsibilities.

In our example, my request for action indicates only the desired outcome (food delivered to my
family). The agent (zomato) free to use any technique that solves my problem. By discussing a problem
in terms of responsibilities increases the level of abstraction. This enables more independence
between the objects in solving complex problems.

Classes and Instances


In object-oriented programming, all objects are instances of a class. The method invoked by an object
in response to a message is decided by the class. All the objects of a class use the same method in
response to a similar message.
In our example, the zomato a class and all the hotels are sub-classes of it. For every request (message),
the class creates an instance of it and uses a suitable method to solve the problem.

Classes Hierarchies
A graphical representation is often used to illustrate the relationships among the classes (objects) of
a community. This graphical representation shows classes listed in a hierarchical tree-like structure. In
this more abstract class listed near the top of the tree, and more specific classes in the middle of the
tree, and the individuals listed near the bottom.

In object-oriented programming, classes can be organized into a hierarchical inheritance structure.


A child class inherits properties from the parent class that higher in the tree.

Method Binding, Overriding, and Exception

In the class hierarchy, both parent and child classes may have the same method which implemented
individually. Here, the implementation of the parent is overridden by the child. Or a class may provide
multiple definitions to a single method to work with different arguments (overloading).

The search for the method to invoke in response to a request (message) begins with the class of this
receiver. If no suitable method is found, the search is performed in the parent class of it. The search
continues up the parent class chain until either a suitable method is found or the parent class chain is
exhausted. If a suitable method is found, the method is executed. Otherwise, an error message is
issued.
Summary of OOP Concepts:
OOP stands for Object-Oriented Programming. OOP is a programming paradigm in which every
program is follows the concept of object. In other words, OOP is a way of writing programs based on
the object concept.

Simula is considered the first object-oriented programming language. The programming paradigm
where everything is represented as an object is known as a truly object-oriented programming
language.

Smalltalk is considered the first truly object-oriented programming language.

The popular object-oriented languages are Java

, C#

, PHP

, Python

, C++

, etc.

The main aim of object-oriented programming is to implement real-world entities, for example,
object, classes, abstraction, inheritance, polymorphism, etc.

OOPs (Object-Oriented Programming System)

Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and objects. It simplifies
software development and maintenance by providing some concepts:

Object

Class

Inheritance

Polymorphism

Abstraction

Encapsulation

Object:
Any entity that has state and behavior is known as an object. For example, a chair, pen, table,
keyboard, bike, etc. It can be physical or logical.

An Object can be defined as an instance of a class. An object contains an address and takes up some
space in memory. Objects can communicate without knowing the details of each other's data or code.
The only necessary thing is the type of message accepted and the type of response returned by the
objects.
Example: A dog is an object because it has states like color, name, breed, etc. as well as behaviors like
wagging the tail, barking, eating, etc.

Class:Collection of objects is called class. It is a logical entity.


A class can also be defined as a blueprint from which you can create an individual object. Class doesn't
consume any space.

Inheritance
When one object acquires all the properties and behaviors of a parent object, it is known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

Polymorphism in Java
Polymorphism

If one task is performed in different ways, it is known as polymorphism. For example: to convince the
customer differently, to draw something, for example, shape, triangle, rectangle, etc.

In Java, we use method overloading and method overriding to achieve polymorphism.

Another example can be to speak something; for example, a cat speaks meow, dog barks woof, etc.

Abstraction

Hiding internal details and showing functionality is known as abstraction. For example phone call, we
don't know the internal processing.

In Java, we use abstract class and interface to achieve abstraction.

Encapsulation: Encapsulation is the process of combining data and code into a single unit (object /
class). In OOP, every object is associated with its data and code. In programming, data is defined as
variables and code is defined as methods. The java programming language uses the class concept to
implement encapsulation.
OR
Encapsulation:Binding (or wrapping) code and data together into a single unit are known as
encapsulation. For example, a capsule, it is wrapped with different medicines.

A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the
data members are private here.

Apart from these concepts, there are some other terms which are used in
Object-Oriented design:
Coupling

Cohesion

Association

Aggregation

Composition

Coupling:Coupling refers to the knowledge or information or dependency of another class. It arises


when classes are aware of each other. If a class has the details information of another class, there is
strong coupling. In Java, we use private, protected, and public modifiers to display the visibility level
of a class, method, and field. You can use interfaces for the weaker coupling because there is no
concrete implementation.

Cohesion:Cohesion refers to the level of a component which performs a single well-defined task. A
single well-defined task is done by a highly cohesive method. The weakly cohesive method will split
the task into separate parts. The java.io package is a highly cohesive package because it has I/O related
classes and interface. However, the java.util package is a weakly cohesive package because it has
unrelated classes and interfaces.

Association:Association represents the relationship between the objects. Here, one object can be
associated with one object or many objects. There can be four types of association between the
objects:

One to One

One to Many

Many to One, and

Many to Many
Let's understand the relationship with real-time examples. For example, One country can have one
prime minister (one to one), and a prime minister can have many ministers (one to many). Also, many
MP's can have one prime minister (many to one), and many ministers can have many departments
(many to many).

Association can be undirectional or bidirectional.

Aggregation:Aggregation is a way to achieve Association. Aggregation represents the relationship


where one object contains other objects as a part of its state. It represents the weak relationship
between objects. It is also termed as a has-a relationship in Java. Like, inheritance represents the is-a
relationship. It is another way to reuse objects.

Composition:The composition is also a way to achieve Association. The composition represents the
relationship where one object contains other objects as a part of its state. There is a strong
relationship between the containing object and the dependent object. It is the state where containing
objects do not have an independent existence. If you delete the parent object, all the child objects will
be deleted automatically.

Advantage of OOPs over Procedure-oriented programming language

1) OOPs makes development and maintenance easier, whereas, in a procedure-oriented programming


language, it is not easy to manage if code grows as project size increases.

2) OOPs provides data hiding, whereas, in a procedure-oriented programming language, global data
can be accessed from anywhere.

3) OOPs provides the ability to simulate real-world event much more effectively. We can provide the
solution of real word problem if we are using the Object-Oriented Programming language.

What is the difference between an object-oriented programming language and object-based


programming language?

Object-based programming language follows all the features of OOPs except Inheritance. JavaScript
and VBScript are examples of object-based programming languages.

Java buzzwords:

Java is the most popular object-oriented programming language. Java has many advanced features, a
list of key features is known as Java Buzz Words. The java team has listed the following terms as java
buzz words.

Simple

Secure

Portable

Object-oriented

Robust

Architecture-neutral
Platform Independent

Multi-threaded

Interpreted

High performance

Distributed

Dynamic

Simple

Java programming language is very simple and easy to learn, understand, and code. Most of the
syntaxes in java follow basic programming language C and object-oriented programming concepts are
similar to C++. In a java programming language, many complicated features like pointers, operator
overloading, structures, unions, etc. have been removed. One of the most useful features is the
garbage collector it makes java more simple.

Platform Independent
Java is platform independent because it is different from other languages like C
, C++, etc. which are compiled into platform specific machines while Java is a write once, run
anywhere language. A platform is the hardware or software environment in which a program
runs.
There are two types of platforms software-based and hardware-based. Java provides a software-
based platform.
The Java platform differs from most other platforms in the sense that it is a software-based
platform that runs on top of other hardware-based platforms. It has two components:
Runtime Environment
API(Application Programming Interface)
Java code can be executed on multiple platforms, for example, Windows, Linux, Sun Solaris,
Mac/OS, etc. Java code is compiled by the compiler and converted into bytecode. This
bytecode is a platform-independent code because it can be run on multiple platforms, i.e., Write
Once and Run Anywhere (WORA).
Platform Independent:Java has invented to archive "write once; run anywhere, any time, forever".
The java provides JVM (Java Virtual Machine) to to archive architectural-neutral or platform-
independent. The JVM allows the java program created using one operating system can be executed
on any other operating system.

Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:
No explicit pointer
Java Programs run inside a virtual machine sandbox
Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE) which is
used to load Java classes into the Java Virtual Machine dynamically. It adds security by
separating the package for the classes of the local file system from those that are imported from
network sources.
Bytecode Verifier: It checks the code fragments for illegal code that can violate access rights
to objects.
Security Manager: It determines what resources a class can access such as reading and writing
to the local disk.
Java is said to be more secure programming language because it does not have pointers concept, java
provides a feature "applet" which can be embedded into a web application. The applet in java does
not allow access to other parts of the computer, which keeps away from harmful programs like viruses
and unauthorized access.

Robust:
The English meaning of Robust is strong. Java is robust because:
It uses strong memory management.There is a lack of pointers that avoids security problems.
Java provides automatic garbage collection which runs on the Java Virtual Machine to get rid
of objects which are not being used by a Java application anymore.
There are exception handling and the type checking mechanism in Java. All these points make
Java robust.
Java is more robust because the java code can be executed on a variety of environments, java has a
strong memory management mechanism (garbage collector), java is a strictly typed language, it has a
strong set of exception handling mechanism, and many more.

Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for
example, the size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes
of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32 and 64-
bit architectures in Java.
Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't
require any implementation.
Portability is one of the core features of java which enables the java programs to run on any computer
or operating system. For example, an applet developed using java runs on a wide variety of CPUs,
operating systems, and browsers connected to the Internet.

High-performance
Java is faster than other traditional interpreted programming languages because Java bytecode
is "close" to native code. It is still a little bit slower than a compiled language (e.g., C++). Java
is an interpreted language that is why it is slower than compiled languages, e.g., C, C++, etc.
Distributed
Java is distributed because it facilitates users to create distributed applications in Java. RMI
and EJB are used for creating distributed applications. This feature of Java makes us able to
access files by calling the methods from any machine on the internet.
Distributed:Java programming language supports TCP/IP protocols which enable the java to support
the distributed environment of the Internet. Java also supports Remote Method Invocation (RMI), this
feature enables a program to invoke methods across a network.

Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that
deal with many tasks at once by defining multiple threads. The main advantage of multi-
threading is that it doesn't occupy memory for each thread. It shares a common memory area.
Threads are important for multi-media, Web applications, etc.
Dynamic
Java is a dynamic language. It supports the dynamic loading of classes. It means classes are
loaded on demand. It also supports functions from its native languages, i.e., C and C++.
Java is said to be dynamic because the java byte code may be dynamically updated on a running system
and it has a dynamic memory allocation and deallocation (objects and garbage collector).

Object-oriented

Java is said to be a pure object-oriented programming language. In java, everything is an object. It


supports all the features of the object-oriented programming paradigm. The primitive data types java
also implemented as objects using wrapper classes, but still, it allows primitive data types to archive
high-performance.

Multi-threaded

Java supports multi-threading programming, which allows us to write programs that do multiple
operations simultaneously.

Interpreted

Java enables the creation of cross-platform programs by compiling into an intermediate


representation called Java bytecode. The byte code is interpreted to any machine code so that it runs
on the native machine.

High performance

Java provides high performance with the help of features like JVM, interpretation, and its simplicity.
Overview of Java
Java is a computer programming language. Java was created based on C and C++. Java uses C syntax
and many of the object-oriented features are taken from C++. Before Java was invented there were
other languages like COBOL, FORTRAN, C, C++, Small Talk, etc. These languages had few disadvantages
which were corrected in Java. Java also innovated many new features to solve the fundamental
problems which the previous languages could not solve. Java was invented by a team of 13 employees
of Sun Microsystems, Inc. which is lead by James Gosling, in 1991. The team includes persons like
Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan, etc., Java was developed as a part of the
Green project. Initially, it was called Oak, later it was changed to Java in 1995.

History of Java
The C language developed in 1972 by Dennis Ritchie had taken a decade to become the most popular
language.

In 1979, Bjarne Stroustrup developed C++, an enhancement to the C language with included OOP
fundamentals and features.

A project named “Green” was initiated in December of 1990, whose aim was to create a programming
tool that could render obsolete the C and C++ programming languages.

Finally in the year of 1991 the Green Team was created a new Programming language named “OAK”.

After some time they found that there is already a programming language with the name “OAK”.

So, the green team had a meeting to choose a new name. After so many discussions they want to have
a coffee. They went to a Coffee Shop which is just outside of the Gosling’s office and there they have
decided name as “JAVA

Execution Process of Java Program

The following three steps are used to create and execute a java program.

Create a source code (.java file).

Compile the source code using javac command.

Run or execute .class file uisng java command.


Java Data Types
Java programming language has a rich set of data types. The data type is a category of data stored in
variables. In java, data types are classified into two types and they are as follows.

Primitive Data Types

Non-primitive Data Types


Data type Meaning Memory size Range Default Value

byte Whole numbers 1 byte -128 to +127 0

short Whole numbers 2 bytes -32768 to +32767 0

int Whole numbers 4 bytes -2,147,483,648 to +2,147,483,647 0

long Whole numbers 8 bytes -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807 0L

float Fractional numbers 4 bytes - 0.0f

double Fractional numbers 8 bytes - 0.0d

char Single character 2 bytes 0 to 65535 \u0000

boolean unsigned char 1 bit 0 or 1 0 (false)

Primitive Data Types


The primitive data types are built-in data types and they specify the type of value stored in a variable
and the memory size. The primitive data types do not have any additional methods.

In java, primitive data types includes byte, short, int, long, float, double, char, and boolean.

The following table provides more description of each primitive data type.

Example:

public class PrimitiveDataTypes {

byte i;
short j;
int k;
long l;
float m;
double n;
char ch;
boolean p;

public static void main(String[] args) {

PrimitiveDataTypes obj = new PrimitiveDataTypes();

System.out.println("i = " + obj.i + ", j = " + obj.j + ", k = " + obj.k + ", l = " + obj.l);
System.out.println("m = " + obj.m + ", n = " + obj.n);
System.out.println("ch = " + obj.ch);
System.out.println("p = " + obj.p);

}
}

Non-primitive Data Types


In java, non-primitive data types are the reference data types or user-created data types. All non-
primitive data types are implemented using object concepts. Every variable of the non-primitive data
type is an object. The non-primitive data types may use additional methods to perform certain
operations. The default value of non-primitive data type variable is null.

In java, examples of non-primitive data types are String, Array, List, Queue, Stack, Class, Interface, etc.

public class NonPrimitiveDataTypes {

String str;
public static void main(String[] args) {

String name = "BTech Smart Class!";


String wish = "Hello, ";

NonPrimitiveDataTypes obj = new NonPrimitiveDataTypes();

System.out.println("str = " + obj.str);

//using addition method


System.out.println(wish.concat(name));
}
}

Primitive Vs Non-primitive Data Types


Primitive Data Type Non-primitive Data Type

These are built-in data types These are created by the users

Does not support additional methods Support additional methods

Always has a value It can be null

Starts with lower-case letter Starts with upper-case letter

Size depends on the data type Same size fo


Java Variables
A variable is a named memory location used to store a data value. A variable can be defined as a
container that holds a data value.

In java, we use the following syntax to create variables.

Syntax:

data_type variable_name;

(or)

data_type variable_name_1, variable_name_2,...;

(or)

data_type variable_name = value;

(or)

data_type variable_name_1 = value, variable_name_2 = value,...;

In java programming language variables are clasiffied as follows.

Local variables

Instance variables or Member variables or Global variables

Static variables or Class variables

Final variables

Local variables

The variables declared inside a method or a block are known as local variables. A local variable is visible
within the method in which it is declared. The local variable is created when execution control enters
into the method or block and destroyed after the method or block execution completed.

Let's look at the following example java program to illustrate local variable in java.

Example

public class LocalVariables {

public void show() {

int a = 10;

//static int x = 100;

System.out.println("Inside show method, a = " + a);

public void display() {

int b = 20;
System.out.println("Inside display method, b = " + b);

// trying to access variable 'a' - generates an ERROR

System.out.println("Inside display method, a = " + a);

public static void main(String args[]) {

LocalVariables obj = new LocalVariables();

obj.show();

obj.display();

Output:

Inside show method, a =10

Inside display method, b =20

Instance variables or member variables or global variables

The variables declared inside a class and outside any method, constructor or block are known as
instance variables or member variables. These variables are visible to all the methods of the class. The
changes made to these variables by method affects all the methods in the class. These variables are
created separate copy for every object of that class.

Let's look at the following example java program to illustrate instance variable in java.

Example

public class ClassVariables {

int x = 100;

public void show() {

System.out.println("Inside show method, x = " + x);

x = x + 100;

public void display() {

System.out.println("Inside display method, x = " + x);

public static void main(String[] args) {

ClassVariables obj = new ClassVariables();

obj.show();
obj.display();

Output:

Inside show method x=100

Inside display method, x =200

Static variables or Class variables

A static variable is a variable that declared using static keyword. The instance variables can be static
variables but local variables can not. Static variables are initialized only once, at the start of the
program execution. The static variable only has one copy per class irrespective of how many objects
we create.

The static variable is access by using class name.

Let's look at the following example java program to illustrate static variable in java.

Example

public class StaticVariablesExample

int x, y; // Instance variables

static int z; // Static variable

StaticVariablesExample(int x, int y){

this.x = x;

this.y = y;

public void show() {

int a; // Local variables

System.out.println("Inside show method,");

System.out.println("x = " + x + ", y = " + y + ", z = " + z);

public static void main(String[] args) {

StaticVariablesExample obj_1 = new StaticVariablesExample(10, 20);

StaticVariablesExample obj_2 = new StaticVariablesExample(100, 200);

obj_1.show();
StaticVariablesExample.z = 1000;

obj_2.show();

Output:

Inside show method

X=10 y=20 z=0

Inside show method

X=100 y=200 z=1000

Final variables

A final variable is a variable that declared using final keyword. The final variable is initialized only once,
and does not allow any method to change it's value again. The variable created using final keyword
acts as constant. All variables like local, instance, and static variables can be final variables.

Let's look at the following example java program to illustrate final variable in java.

Example

public class FinalVariableExample {

final int a = 10;

void show() {

System.out.println("a = " + a);

a = 20; //Error due to final variable cann't be modified

public static void main(String[] args) {

FinalVariableExample obj = new FinalVariableExample();

obj.show();

Output:

No console display-erorr
Java Arrays
An array is a collection of similar data values with a single name. An array can also be defined as, a
special type of variable that holds multiple values of the same data type at a time.

In java, arrays are objects and they are created dynamically using new operator. Every array in java is
organized using index values. The index value of an array starts with '0' and ends with 'size-1'. We use
the index value to access individual elements of an array.

In java, there are two types of arrays and they are as follows.

One Dimensional Array

Multi Dimensional Array

Creating an array

In the java programming language, an array must be created using new operator and with a specific
size. The size must be an integer value but not a byte, short, or long. We use the following syntax to
create an array.

Syntax

data_type array_name[ ] = new data_type[size];

(or)

data_type[ ] array_name = new data_type[size];

Example

public class ArrayExample {

public static void main(String[] args) {

int list[] = new int[5];

list[0] = 10;

System.out.println("Value at index 0 - " + list[0]);

System.out.println("Length of the array - " + list.length);

Output:

Value at index 0 -10

Length of the array -5

In java, an array can also be initialized at the time of its declaration. When an array is initialized at the
time of its declaration, it need not specify the size of the array and use of the new operator. Here, the
size is automatically decided based on the number of values that are initialized.

Example
int list[ ] = {10, 20, 30, 40, 50};

NullPointerException with Arrays

In java, an array created without size and initialized to null remains null only. It does not allow us to
assign a value. When we try to assign a value it generates a NullPointerException.

Look at the following example program.

Example

public class ArrayExample {

public static void main(String[] args) {

short list[] = null;

list[0] = 10;

System.out.println("Value at index 0 - " + list[0]);

ArrayIndexOutOfBoundsException with Arrays

In java, the JVM (Java Virtual Machine) throws ArrayIndexOutOfBoundsException when an array is
trying to access with an index value of negative value, value equal to array size, or value more than
the array size.

Look at the following example program.

Example

public class ArrayExample {

public static void main(String[] args) {

short list[] = {10, 20, 30};

list[4] = 10;

System.out.println("Value at index 0 - " + list[0]);

Looping through an array


An entire array is accessed using either simple for statement or for-each statement. Look at the
following example program to display sum of all the lements in a list.

Example

import java.util.Scanner;

public class ArrayExample {

public static void main(String[] args) {

Scanner read = new Scanner(System.in);

int size, sum = 0;

System.out.print("Enter the size of the list: ");

size = read.nextInt();

short list[] = new short[size];

System.out.println("Enter any " + size + " numbers: ");

for(int i = 0; i < size; i++) // Simple for statement

list[i] = read.nextShort();

for(int i : list) // for-each statement

sum = sum + i;

System.out.println("Sum of all elements: " + sum);

Multidimensional Array

In java, we can create an array with multiple dimensions. We can create 2-dimensional, 3-dimensional,
or any dimensional array.

In Java, multidimensional arrays are arrays of arrays. To create a multidimensional array variable,
specify each additional index using another set of square brackets. We use the following syntax to
create two-dimensional array.

Syntax

data_type array_name[ ][ ] = new data_type[rows][columns];

(or)

data_type[ ][ ] array_name = new data_type[rows][columns];


When we create a two-dimensional array, it created with a separate index for rows and columns. The
individual element is accessed using the respective row index followed by the column index. A
multidimensional array can be initialized while it has created using the following syntax.

Syntax

data_type array_name[ ][ ] = {{value1, value2}, {value3, value4}, {value5, value6},...};

When an array is initialized at the time of declaration, it need not specify the size of the array and use
of the new operator. Here, the size is automatically decided based on the number of values that are
initialized.

Example

int matrix_a[ ][ ] = {{1, 2},{3, 4},{5, 6}};

The above statement creates a two-dimensional array of three rows and two columns.

Operators in Java
Operator in Java

is a symbol that is used to perform operations. For example: +, -, *, / etc.

There are many types of operators in Java which are given below:

Unary Operator,

Arithmetic Operator,

Shift Operator,

Relational Operator,

Bitwise Operator,

Logical Operator,

Ternary Operator and

Assignment Operator.

Java Operator Precedence

Operator Type Category Precedence

Unary postfix expr++ expr--

prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative * / %

additive + -
Shift shift << >> >>>

Relational comparison < > <= >= instanceof

equality == !=

Bitwise bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

Logical logical AND &&

logical OR ||

Ternary ternary ? :

Assignment assignment = += -= *= /= %= &= ^= |= <<=


>>= >>>=

Java Unary Operator

The Java unary operators require only one operand. Unary operators are used to perform various
operations i.e.:

incrementing/decrementing a value by one

negating an expression

inverting the value of a boolean

Java Unary Operator Example: ++ and --

public class OperatorExample{

public static void main(String args[]){

int x=10;

System.out.println(x++);//10 (11)

System.out.println(++x);//12

System.out.println(x--);//12 (11)

System.out.println(--x);//10

}}

Output:
10

12

12

10

Java Unary Operator Example: ~ and !

public class OperatorExample{

public static void main(String args[]){

int a=10;

int b=-10;

boolean c=true;

boolean d=false;

System.out.println(~a);//-11 (minus of total positive value which starts from 0)

System.out.println(~b);//9 (positive of total minus, positive starts from 0)

System.out.println(!c);//false (opposite of boolean value)

System.out.println(!d);//true

}}

Output:

-11

false

true

Java Arithmetic Operators

Java arithmetic operators are used to perform addition, subtraction, multiplication, and division. They
act as basic mathematical operations.

Java Arithmetic Operator Example

public class OperatorExample{

public static void main(String args[]){

int a=10;

int b=5;

System.out.println(a+b);//15

System.out.println(a-b);//5
System.out.println(a*b);//50

System.out.println(a/b);//2

System.out.println(a%b);//0

}}

Output:

15

50

Java Arithmetic Operator Example: Expression

public class OperatorExample{

public static void main(String args[]){

System.out.println(10*10/5+3-1*4/2);

}}

Output:

21

Java Left Shift Operator

The Java left shift operator << is used to shift all of the bits in a value to the left side of a specified
number of times.

Java Left Shift Operator Example

public class OperatorExample{

public static void main(String args[]){

System.out.println(10<<2);//10*2^2=10*4=40

System.out.println(10<<3);//10*2^3=10*8=80

System.out.println(20<<2);//20*2^2=20*4=80

System.out.println(15<<4);//15*2^4=15*16=240

}}

Output:

40

80
80

240

Java Right Shift Operator

The Java right shift operator >> is used to move the value of the left operand to right by the number
of bits specified by the right operand.

Java Right Shift Operator Example

public OperatorExample{

public static void main(String args[]){

System.out.println(10>>2);//10/2^2=10/4=2

System.out.println(20>>2);//20/2^2=20/4=5

System.out.println(20>>3);//20/2^3=20/8=2

}}

Output:

Java Shift Operator Example: >> vs >>>

public class OperatorExample{

public static void main(String args[]){

//For positive number, >> and >>> works same

System.out.println(20>>2);

System.out.println(20>>>2);

//For negative number, >>> changes parity bit (MSB) to 0

System.out.println(-20>>2);

System.out.println(-20>>>2);

}}

Output:

-5

1073741819
Java AND Operator Example: Logical && and Bitwise &

The logical && operator doesn't check the second condition if the first condition is false. It checks the
second condition only if the first one is true.

The bitwise & operator always checks both conditions whether first condition is true or false.

public class OperatorExample{

public static void main(String args[]){

int a=10;

int b=5;

int c=20;

System.out.println(a<b&&a<c);//false && true = false

System.out.println(a<b&a<c);//false & true = false

}}

Output:

false

false

Java AND Operator Example: Logical && vs Bitwise &

public class OperatorExample{

public static void main(String args[]){

int a=10;

int b=5;

int c=20;

System.out.println(a<b&&a++<c);//false && true = false

System.out.println(a);//10 because second condition is not checked

System.out.println(a<b&a++<c);//false && true = false

System.out.println(a);//11 because second condition is checked

}}

Output:

false

10

false
11

Java OR Operator Example: Logical || and Bitwise |

The logical || operator doesn't check the second condition if the first condition is true. It checks the
second condition only if the first one is false.

The bitwise | operator always checks both conditions whether first condition is true or false.

public class OperatorExample{

public static void main(String args[]){

int a=10;

int b=5;

int c=20;

System.out.println(a>b||a<c);//true || true = true

System.out.println(a>b|a<c);//true | true = true

//|| vs |

System.out.println(a>b||a++<c);//true || true = true

System.out.println(a);//10 because second condition is not checked

System.out.println(a>b|a++<c);//true | true = true

System.out.println(a);//11 because second condition is checked

}}

Output:

true

true

true

10

true

11

Java Ternary Operator

Java Ternary operator is used as one line replacement for if-then-else statement and used a lot in Java
programming. It is the only conditional operator which takes three operands.

Java Ternary Operator Example

public class OperatorExample{

public static void main(String args[]){

int a=2;
int b=5;

int min=(a<b)?a:b;

System.out.println(min);

}}

Output:

Another Example:

public class OperatorExample{

public static void main(String args[]){

int a=10;

int b=5;

int min=(a<b)?a:b;

System.out.println(min);

}}

Output:

Java Assignment Operator

Java assignment operator is one of the most common operators. It is used to assign the value on its
right to the operand on its left.

Java Assignment Operator Example

public class OperatorExample{

public static void main(String args[]){

int a=10;

int b=20;

a+=4;//a=a+4 (a=10+4)

b-=4;//b=b-4 (b=20-4)

System.out.println(a);

System.out.println(b);

}}

Output:

14
16

Java Assignment Operator Example

public class OperatorExample{

public static void main(String[] args){

int a=10;

a+=3;//10+3

System.out.println(a);

a-=4;//13-4

System.out.println(a);

a*=2;//9*2

System.out.println(a);

a/=2;//18/2

System.out.println(a);

}}

Output:

13

18

Java Assignment Operator Example: Adding short

public class OperatorExample{

public static void main(String args[]){

short a=10;

short b=10;

//a+=b;//a=a+b internally so fine

a=a+b;//Compile time error because 10+10=20 now int

System.out.println(a);

}}

Output:

Compile time error

After type cast:


public class OperatorExample{

public static void main(String args[]){

short a=10;

short b=10;

a=(short)(a+b);//20 which is int now converted to short

System.out.println(a);

}}

Output:

20

Java Expressions

In any programming language, if we want to perform any calculation or to frame any condition etc.,
we use a set of symbols to perform the task. These set of symbols makes an expression.

In the java programming language, an expression is defined as follows.

An expression is a collection of operators and operands that represents a


specific value.
In the above definition, an operator is a symbol that performs tasks like arithmetic operations, logical
operations, and conditional operations, etc.

Operands are the values on which the operators perform the task. Here operand can be a direct value
or variable or address of memory location.

Expression Types
In the java programming language, expressions are divided into THREE types. They are as follows.

Infix Expression

Postfix Expression

Prefix Expression

The above classification is based on the operator position in the expression.

Infix Expression

The expression in which the operator is used between operands is called infix expression.

The infix expression has the following general structure.

Example
Postfix Expression

The expression in which the operator is used after operands is called postfix expression.

The postfix expression has the following general structure.

Example

Prefix Expression

The expression in which the operator is used before operands is called a prefix expression.

The prefix expression has the following general structure.

Example

Java Control Statements


In java, the default execution flow of a program is a sequential order. But the sequential order of
execution flow may not be suitable for all situations. Sometimes, we may want to jump from line to
another line, we may want to skip a part of the program, or sometimes we may want to execute a part
of the program again and again. To solve this problem, java provides control statements.
In java, the control statements are the statements which will tell us that in which order the instructions
are getting executed. The control statements are used to control the order of execution according to
our requirements. Java provides several control statements, and they are classified as follows.

Types of Control Statements

In java, the control statements are classified as follows.

Selection Control Statements ( Decision Making Statements )

Iterative Control Statements ( Looping Statements )

Jump Statements

Let's look at each type of control statements in java.

Selection Control Statements

In java, the selection statements are also known as decision making statements or branching
statements. The selection statements are used to select a part of the program to be executed based
on a condition. Java provides the following selection statements.

if statement

if-else statement

if-elif statement

nested if statement

switch statement

Iterative Control Statements

In java, the iterative statements are also known as looping statements or repetitive statements. The
iterative statements are used to execute a part of the program repeatedly as long as the given
condition is True. Using iterative statements reduces the size of the code, reduces the code
complexity, makes it more efficient, and increases the execution speed. Java provides the following
iterative statements.

while statement
do-while statement

for statement

for-each statement

Jump Statements

In java, the jump statements are used to terminate a block or take the execution control to the next
iteration. Java provides the following jump statements.

break

continue

return

Java Selection Statements

In java, the selection statements are also known as decision making statements or branching
statements or conditional control statements. The selection statements are used to select a part of
the program to be executed based on a condition. Java provides the following selection statements.

if statement

if-else statement

nested if statement

if-else if statement

switch statement

if statement in java

In java, we use the if statement to test a condition and decide the execution of a block of statements
based on that condition result. The if statement checks, the given condition then decides the execution
of a block of statements. If the condition is True, then the block of statements is executed and if it is
False, then the block of statements is ignored. The syntax and execution flow of if the statement is as
follows.

if statement in java

Let's look at the following example java code.


Let's look at the following example java code.

Java Program

import java.util.Scanner;

public class IfElseStatementTest {

public static void main(String[] args) {

Scanner read = new Scanner(System.in);

System.out.print("Enter any number: ");

int num = read.nextInt();

if((num % 2) == 0) {

System.out.println("We are inside the true-block!");

System.out.println("Given number is EVEN number!!");

else {

System.out.println("We are inside the false-block!");

System.out.println("Given number is ODD number!!");

System.out.println("We are outside the if-block!!!");

}
}

if-else statement in java

In java, we use the if-else statement to test a condition and pick the execution of a block of statements
out of two blocks based on that condition result. The if-else statement checks the given condition then
decides which block of statements to be executed based on the condition result. If the condition is
True, then the true block of statements is executed and if it is False, then the false block of statements
is executed. The syntax and execution flow of if-else statement is as follows.

Let's look at the following example java code.

Java Program

import java.util.Scanner;

public class IfElseStatementTest {

public static void main(String[] args) {

Scanner read = new Scanner(System.in);

System.out.print("Enter any number: ");

int num = read.nextInt();

if((num % 2) == 0) {

System.out.println("We are inside the true-block!");

System.out.println("Given number is EVEN number!!");

else {

System.out.println("We are inside the false-block!");

System.out.println("Given number is ODD number!!");


}

System.out.println("We are outside the if-block!!!");

Nested if statement in java

Writing an if statement inside another if-statement is called nested if statement. The general syntax
of the nested if-statement is as follows.

Syntax

if(condition_1){

if(condition_2){

inner if-block of statements;

...

...

Java Program

import java.util.Scanner;

public class NestedIfStatementTest {

public static void main(String[] args) {

Scanner read = new Scanner(System.in);

System.out.print("Enter any number: ");

int num = read.nextInt();

if (num < 100) {

System.out.println("\nGiven number is below 100");

if (num % 2 == 0)

System.out.println("And it is EVEN");

else

System.out.println("And it is ODD");
} else

System.out.println("Given number is not below 100");

System.out.println("\nWe are outside the if-block!!!");

if-else if statement in java

Writing an if-statement inside else of an if statement is called if-else-if statement. The general syntax
of the an if-else-if statement is as follows.

Syntax

if(condition_1){

condition_1 true-block;

...

else if(condition_2){

condition_2 true-block;

condition_1 false-block too;

...

Let's look at the following example java code.

Java Program

import java.util.Scanner;

public class IfElseIfStatementTest {

public static void main(String[] args) {

int num1, num2, num3;

Scanner read = new Scanner(System.in);

System.out.print("Enter any three numbers: ");

num1 = read.nextInt();
num2 = read.nextInt();

num3 = read.nextInt();

if( num1>=num2 && num1>=num3)

System.out.println("\nThe largest number is " + num1) ;

else if (num2>=num1 && num2>=num3)

System.out.println("\nThe largest number is " + num2) ;

else

System.out.println("\nThe largest number is " + num3) ;

System.out.println("\nWe are outside the if-block!!!");

switch statement in java

Using the switch statement, one can select only one option from more number of options very easily.
In the switch statement, we provide a value that is to be compared with a value associated with each
option. Whenever the given value matches the value associated with an option, the execution starts
from that option. In the switch statement, every option is defined as a case.

The switch statement has the following syntax and execution flow diagram.

Let's look at the following example java code.


Java Program

import java.util.Scanner;

public class SwitchStatementTest {

public static void main(String[] args) {

Scanner read = new Scanner(System.in);

System.out.print("Press any digit: ");

int value = read.nextInt();

switch( value )

case 0: System.out.println("ZERO") ; break ;

case 1: System.out.println("ONE") ; break ;

case 2: System.out.println("TWO") ; break ;

case 3: System.out.println("THREE") ; break ;

case 4: System.out.println("FOUR") ; break ;

case 5: System.out.println("FIVE") ; break ;

case 6: System.out.println("SIX") ; break ;

case 7: System.out.println("SEVEN") ; break ;

case 8: System.out.println("EIGHT") ; break ;

case 9: System.out.println("NINE") ; break ;

default: System.out.println("Not a Digit") ;

Java Iterative Statements

The java programming language provides a set of iterative statements that are used to execute a
statement or a block of statements repeatedly as long as the given condition is true. The iterative
statements are also known as looping statements or repetitive statements. Java provides the following
iterative statements.

while statement
do-while statement

for statement

for-each statement

while statement in java

The while statement is used to execute a single statement or block of statements repeatedly as long
as the given condition is TRUE. The while statement is also known as Entry control looping statement.
The syntax and execution flow of while statement is as follows.

Let's look at the following example java code.

Java Program

ipublic class WhileTest {

public static void main(String[] args) {

int num = 1;

while(num <= 10) {

System.out.println(num);

num++;

System.out.println("Statement after while!");

}
do-while statement in java

The do-while statement is used to execute a single statement or block of statements repeatedly as
long as given the condition is TRUE. The do-while statement is also known as the Exit control looping
statement. The do-while statement has the following syntax.

Let's look at the following example java code.

Java Program

public class DoWhileTest {

public static void main(String[] args) {

int num = 1;

do {

System.out.println(num);

num++;

}while(num <= 10);

System.out.println("Statement after do-while!");

for statement in java


The for statement is used to execute a single statement or a block of statements repeatedly as long
as the given condition is TRUE. The for statement has the following syntax and execution flow diagram.

In for-statement, the execution begins with the initialization statement. After the initialization
statement, it executes Condition. If the condition is evaluated to true, then the block of statements
executed otherwise it terminates the for-statement. After the block of statements execution, the
modification statement gets executed, followed by condition again.

Let's look at the following example java code.

Java Program

public class ForTest {

public static void main(String[] args) {

for(int i = 0; i < 10; i++) {

System.out.println("i = " + i);

System.out.println("Statement after for!");

}
}

for-each statement in java

The Java for-each statement was introduced since Java 5.0 version. It provides an approach to traverse
through an array or collection in Java. The for-each statement also known as enhanced for statement.
The for-each statement executes the block of statements for each element of the given array or
collection.

Note: In for-each statement, we can not skip any element of given array or collection.

Let's look at the following example java code.

Java Program

public class ForEachTest {

public static void main(String[] args) {

int[] arrayList = {10, 20, 30, 40, 50};

for(int i : arrayList) {

System.out.println("i = " + i);

System.out.println("Statement after for-each!");

}
}

Java Jump Statements

The java programming language supports jump statements that used to transfer execution control
from one line to another line. The java programming language provides the following jump
statements.

break statement

continue statement

labelled break and continue statements

return statement

break statement in java

The break statement in java is used to terminate a switch or looping statement. That means the break
statement is used to come out of a switch statement and a looping statement like while, do-while, for,
and for-each.

Note: Using the break statement outside the switch or loop statement is not allowed.

The floowing picture depictes the execution flow of the break statement.

Let's look at the following example java code.

Java Program

public class JavaBreakStatement {

public static void main(String[] args) {


int list[] = {10, 20, 30, 40, 50};

for(int i : list) {

if(i == 30)

break;

System.out.println(i);

continue statement in java

The continue statement is used to move the execution control to the beginning of the looping
statement. When the continue statement is encountered in a looping statement, the execution
control skips the rest of the statements in the looping block and directly jumps to the beginning of the
loop. The continue statement can be used with looping statements like while, do-while, for, and for-
each.

When we use continue statement with while and do-while statements, the execution control directly
jumps to the condition. When we use continue statement with for statement the execution control
directly jumps to the modification portion (increment/decrement/any modification) of the for loop.
The continue statement flow of execution is as shown in the following figure.

Let's look at the following example java code.

Java Program

public class JavaContinueStatement {


public static void main(String[] args) {

int list[] = {10, 20, 30, 40, 50};

for(int i : list) {

if(i == 30)

continue;

System.out.println(i);

Labelled break and continue statement in java

The java programming langauge does not support goto statement, alternatively, the break and
continue statements can be used with label.

The labelled break statement terminates the block with specified label. The labbeled contonue
statement takes the execution control to the beginning of a loop with specified label.

Let's look at the following example java code.

Java Program

import java.util.Scanner;

public class JavaLabelledStatement {

public static void main(String args[]) {

Scanner read = new Scanner(System.in);

reading: for (int i = 1; i <= 3; i++) {

System.out.print("Enter a even number: ");

int value = read.nextInt();

verify: if (value % 2 == 0) {

System.out.println("\nYou won!!!");

System.out.println("Your score is " + i*10 + " out of 30.");

break reading;
} else {

System.out.println("\nSorry try again!!!");

System.out.println("You let with " + (3-i) + " more options...");

continue reading;

return statement in java

In java, the return statement used to terminate a method with or without a value. The return
statement takes the execution control to the calling function. That means the return statement
transfer the execution control from called function to the calling function by carrying a value.

Note:Java allows the use of return-statement with both, with and without return type methods.

In java, the return statement used with both methods with and without return type. In the case of a
method with the return type, the return statement is mandatory, and it is optional for a method
without return type.

When a return statement used with a return type, it carries a value of return type. But, when it is used
without a return type, it does not carry any value. Instead, simply transfers the execution control.

Let's look at the following example java code.

Java Program

import java.util.Scanner;

public class JavaReturnStatementExample {

int value;

int readValue() {

Scanner read = new Scanner(System.in);

System.out.print("Enter any number: ");

return this.value=read.nextInt();

}
void showValue(int value) {

for(int i = 0; i <= value; i++) {

if(i == 5)

return;

System.out.println(i);

public static void main(String[] args) {

JavaReturnStatementExample obj = new JavaReturnStatementExample();

obj.showValue(obj.readValue());

Java Classes

Java is an object-oriented programming language, so everything in java program must be based on


the object concept. In a java programming language, the class concept defines the skeleton of an
object.

The java class is a template of an object. The class defines the blueprint of an object. Every class in
java forms a new data type. Once a class got created, we can generate as many objects as we want.
Every class defines the properties and behaviors of an object. All the objects of a class have the same
properties and behaviors that were defined in the class.

Every class of java programming language has the following characteristics.

Identity - It is the name given to the class.

State - Represents data values that are associated with an object.

Behavior - Represents actions can be performed by an object.

Look at the following picture to understand the class and object concept.
Creating a Class

In java, we use the keyword class to create a class. A class in java contains properties as variables and
behaviors as methods. Following is the syntax of class in the java.

Syntax

class <ClassName>{

data members declaration;

methods defination;

🔔 The ClassName must begin with an alphabet, and the Upper-case letter is preferred.

🔔 The ClassName must follow all naming rules.

Creating an Object

In java, an object is an instance of a class. When an object of a class is created, the class is said to be
instantiated. All the objects that are created using a single class have the same properties and
methods. But the value of properties is different for every object. Following is the syntax of class in
the java.

Syntax

<ClassName> <objectName> = new <ClassName>( );

🔔 The objectName must begin with an alphabet, and a Lower-case letter is preferred.

🔔 The objectName must follow all naming rules.

Java Methods
A method is a block of statements under a name that gets executes only when it is called. Every
method is used to perform a specific task. The major advantage of methods is code re-usability (define
the code once, and use it many times).

In a java programming language, a method defined as a behavior of an object. That means, every
method in java must belong to a class.

Every method in java must be declared inside a class.

Every method declaration has the following characteristics.

returnType - Specifies the data type of a return value.

name - Specifies a unique name to identify it.

parameters - The data values it may accept or recieve.

{ } - Defienes the block belongs to the method.

Creating a method

A method is created inside the class and it may be created with any access specifier. However,
specifying access specifier is optional.

Following is the syntax for creating methods in java.

Syntax

class <ClassName>{

<accessSpecifier> <returnType> <methodName>( parameters ){

...

block of statements;

...

🔔 The methodName must begin with an alphabet, and the Lower-case letter is preferred.

🔔 The methodName must follow all naming rules.

🔔 If you don't want to pass parameters, we ignore it.

🔔 If a method defined with return type other than void, it must contain the return statement,
otherwise, it may be ignored.

Calling a method

In java, a method call precedes with the object name of the class to which it belongs and a dot
operator. It may call directly if the method defined with the static modifier. Every method call must
be made, as to the method name with parentheses (), and it must terminate with a semicolon.

Syntax
<objectName>.<methodName>( actualArguments );

🔔 The method call must pass the values to parameters if it has.

🔔 If the method has a return type, we must provide the receiver.

Let's look at the following example java code.

Example

import java.util.Scanner;

public class JavaMethodsExample {

int sNo;

String name;

Scanner read = new Scanner(System.in);

void readData() {

System.out.print("Enter Serial Number: ");

sNo = read.nextInt();

System.out.print("Enter the Name: ");

name = read.next();

static void showData(int sNo, String name) {

System.out.println("Hello, " + name + "! your serial number is " + sNo);

public static void main(String[] args) {

JavaMethodsExample obj = new JavaMethodsExample();

obj.readData(); // method call using object

showData(obj.sNo, obj.name); // method call without using object

}
}

Output:

methods and classes in java

🔔 The objectName must begin with an alphabet, and a Lower-case letter is preferred.

🔔 The objectName must follow all naming rules.

Variable arguments of a method

In java, a method can be defined with a variable number of arguments. That means creating a method
that receives any number of arguments of the same data type.

Syntax

<returnType> <methodName>(dataType...parameterName);

Let's look at the following example java code.

Example

public class JavaMethodWithVariableArgs {

void diaplay(int...list) {

System.out.println("\nNumber of arguments: " + list.length);

for(int i : list) {

System.out.print(i + "\t");

public static void main(String[] args) {

JavaMethodWithVariableArgs obj = new JavaMethodWithVariableArgs();

obj.diaplay(1, 2);

obj.diaplay(10, 20, 30, 40, 50);

🔔 When a method has both the normal parameter and variable-argument, then the variable
argument must be specified at the end in the parameters list.

Constructor
A constructor is a special method of a class that has the same name as the class name. The constructor
gets executes automatically on object creation. It does not require the explicit method call. A
constructor may have parameters and access specifiers too. In java, if you do not provide any
constructor the compiler automatically creates a default constructor.

Let's look at the following example java code.

Example

public class ConstructorExample {

ConstructorExample() {

System.out.println("Object created!");

public static void main(String[] args) {

ConstructorExample obj1 = new ConstructorExample();

ConstructorExample obj2 = new ConstructorExample();

🔔 A constructor can not have return value.

Java String Handling


A string is a sequence of characters surrounded by double quotations. In a java programming
language, a string is the object of a built-in class String.

In the background, the string values are organized as an array of a character data type.

The string created using a character array can not be extended. It does not allow to append more
characters after its definition, but it can be modified.

Let's look at the following example java code.

Example

char[] name = {'J', 'a', 'v', 'a', ' ', 'T', 'u', 't', 'o', 'r', 'i', 'a', 'l', 's'};

//name[14] = '@'; //ArrayIndexOutOfBoundsException

name[5] = '-';

System.out.println(name);
The String class defined in the package java.lang package. The String class implements Serializable,
Comparable, and CharSequence interfaces.

The string created using the String class can be extended. It allows us to add more characters after its
definition, and also it can be modified.

Let's look at the following example java code.

Example

String siteName = "btechsmartclass.com";

siteName = "www.btechsmartclass.com";

Creating String object in java

In java, we can use the following two ways to create a string object.

Using string literal

Using String constructor

Let's look at the following example java code.

Example

String title = "Java Tutorials"; // Using literals

String siteName = new String("www.btechsmartclass.com"); // Using constructor

🔔 The String class constructor accepts both string and character array as an argument.

String handling methods:In java programming language, the String class contails various methods that
can be used to handle string data values. It containg methods like concat( ), compareTo( ), split( ),
join( ), replace( ), trim( ), length( ), intern( ), equals( ), comparison( ), substring( ), etc.

The following table depicts all built-in methods of String class in java.
Method Description Return Value

charAt(int) Finds the character at given index char

length() Finds the length of given string int

compareTo(String) Compares two strings int

compareToIgnoreCase(String) Compares two strings, ignoring case int

concat(String) Concatenates the object string with argument string. String

contains(String) Checks whether a string contains sub-string boolean

contentEquals(String) Checks whether two strings are same boolean

equals(String) Checks whether two strings are same boolean

equalsIgnoreCase(String) Checks whether two strings are same, ignoring case boolean

startsWith(String) Checks whether a string starts with the specified string boolean

endsWith(String) Checks whether a string ends with the specified string boolean

getBytes() Converts string value to bytes byte[]

hashCode() Finds the hash code of a string int

indexOf(String) Finds the first index of argument string in object string int

lastIndexOf(String) Finds the last index of argument string in object string int

isEmpty() Checks whether a string is empty or not boolean

replace(String, String) Replaces the first string with second string String

replaceAll(String, String) Replaces the first string with second string at all occurrences. String
substring(int, int) Extracts a sub-string from specified start and end index values String

toLowerCase() Converts a string to lower case letters String

toUpperCase() Converts a string to upper case letters String

trim() Removes whitespace from both ends String

toString(int) Converts the value to a String object String

split(String) splits the string matching argument string String[]

intern() returns string from the pool String

join(String, String, ...) Joins all strings, first string as delimiter. String

Let's look at the following example java code.

Java Program

public class JavaStringExample {

public static void main(String[] args) {

String title = "Java Tutorials";

String siteName = "www.btechsmartclass.com";

System.out.println("Length of title: " + title.length());

System.out.println("Char at index 3: " + title.charAt(3));

System.out.println("Index of 'T': " + title.indexOf('T'));

System.out.println("Last index of 'a': " + title.lastIndexOf('a'));

System.out.println("Empty: " + title.isEmpty());

System.out.println("Ends with '.com': " + siteName.endsWith(".com"));

System.out.println("Equals: " + siteName.equals(title));

System.out.println("Sub-string: " + siteName.substring(9, 14));


System.out.println("Upper case: " + siteName.toUpperCase());

When we run this code, it produce the following output.

string handling in java


Inheritance Concept
The inheritance is a very useful and powerful concept of object-oriented programming. In
java, using the inheritance concept, we can use the existing features of one class in another
class. The inheritance provides a greate advantage called code re-usability. With the help of
code re-usability, the commonly used code in an application need not be written again and
again.

The inheritance can be defined as follows.


The inheritance is the process of acquiring the properties of one class to another class.
Inheritance Basics
In inheritance, we use the terms like parent class, child class, base class, derived class,
superclass, and subclass.
The Parent class is the class which provides features to another class. The parent class is also
known as Base class or Superclass.
The Child class is the class which receives features from another class. The child class is also
known as the Derived Class or Subclass.
In the inheritance, the child class acquires the features from its parent class. But the
parent class never acquires the features from its child class.
There are five types of inheritances, and they are as follows.
Simple Inheritance (or) Single Inheritance
Multiple Inheritance
Multi-Level Inheritance
Hierarchical Inheritance
Hybrid Inheritance

The following picture illustrates how various inheritances are implemented.


The java programming language does not support multiple inheritance type. However,
it provides an alternate with the concept of interfaces.
Creating Child Class in java
In java, we use the keyword extends to create a child class. The following syntax used to
create a child class in java.
Syntax
class <ChildClassName> extends <ParentClassName>{
...
//Implementation of child class
...
}
In a java programming language, a class extends only one class. Extending multiple classes is
not allowed in java.
Let's look at individual inheritance types and how they get implemented in java with an
example.
Single Inheritance in java
In this type of inheritance, one child class derives from one parent class. Look at the
following example code.
Example
class ParentClass{
int a;
void setData(int a) {
this.a = a;
}
}
class ChildClass extends ParentClass{
void showData() {
System.out.println("Value of a is " + a);
}
}
public class SingleInheritance {
public static void main(String[] args) {

ChildClass obj = new ChildClass();


obj.setData(100);
obj.showData();

}
Multi-level Inheritance in java
In this type of inheritance, the child class derives from a class which already derived from
another class. Look at the following example java code.
Example
class ParentClass{
int a;
void setData(int a) {
this.a = a;
}
}
class ChildClass extends ParentClass{
void showData() {
System.out.println("Value of a is " + a);
}
}
class ChildChildClass extends ChildClass{
void display() {
System.out.println("Inside ChildChildClass!");
}
}
public class MultipleInheritance {
public static void main(String[] args) {

ChildChildClass obj = new ChildChildClass();


obj.setData(100);
obj.showData();
obj.display();

}
Hierarchical Inheritance in java
In this type of inheritance, two or more child classes derive from one parent class. Look at the
following example java code.
Example
class ParentClass{
int a;
void setData(int a) {
this.a = a;
}
}
class ChildClass extends ParentClass{
void showData() {
System.out.println("Inside ChildClass!");
System.out.println("Value of a is " + a);
}
}
class ChildClassToo extends ParentClass{
void display() {
System.out.println("Inside ChildClassToo!");
System.out.println("Value of a is " + a);
}
}
public class HierarchicalInheritance {

public static void main(String[] args) {

ChildClass child_obj = new ChildClass();


child_obj.setData(100);
child_obj.showData();

ChildClassToo childToo_obj = new ChildClassToo();


childToo_obj.setData(200);
childToo_obj.display();

}
Hybrid Inheritance in java
The hybrid inheritance is the combination of more than one type of inheritance. We may use
any combination as a single with multiple inheritances, multi-level with multiple
inheritances, etc.,
Java Access Modifiers
In Java, the access specifiers (also known as access modifiers) used to restrict the scope or
accessibility of a class, constructor, variable, method or data member of class and interface.
There are four access specifiers, and their list is below.
default (or) no modifier
public
protected
private
In java, we can not employ all access specifiers on everything. The following table describes
where we can apply the access specifiers.
In java, we can not employ all access specifiers on everything. The following table describes
where we can apply the access specifiers.

Let's look at the following example java code, which generates an error because a class does
not allow private access specifier unless it is an inner class.
Example
private class Sample{
...
}
In java, the accessibility of the members of a class or interface depends on its access
specifiers. The following table provides information about the visibility of both data members
and methods.
🔔 The public members can be accessed everywhere.

🔔 The private members can be accessed only inside the same class.

🔔 The protected members are accessible to every child class (same package or other
packages).

🔔 The default members are accessible within the same package but not outside the package.
Let's look at the following example java code.
Example
class ParentClass{
int a = 10;
public int b = 20;
protected int c = 30;
private int d = 40;
void showData() {
System.out.println("Inside ParentClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
class ChildClass extends ParentClass{
void accessData() {
System.out.println("Inside ChildClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
//System.out.println("d = " + d); // private member can't be accessed
}

}
public class AccessModifiersExample {

public static void main(String[] args) {

ChildClass obj = new ChildClass();


obj.showData();
obj.accessData();

Java Constructors in Inheritance


It is very important to understand how the constructors get executed in the inheritance
concept. In the inheritance, the constructors never get inherited to any child class.
In java, the default constructor of a parent class called automatically by the constructor of its
child class. That means when we create an object of the child class, the parent class
constructor executed, followed by the child class constructor executed.
Let's look at the following example java code.

Example
class ParentClass{
int a;
ParentClass(){
System.out.println("Inside ParentClass constructor!");
}
}
class ChildClass extends ParentClass{

ChildClass(){
System.out.println("Inside ChildClass constructor!!");
}
}
class ChildChildClass extends ChildClass{

ChildChildClass(){
System.out.println("Inside ChildChildClass constructor!!");
}
}
public class ConstructorInInheritance {

public static void main(String[] args) {

ChildChildClass obj = new ChildChildClass();

However, if the parent class contains both default and parameterized constructor, then only
the default constructor called automatically by the child class constructor.

Let's look at the following example java code.


class ParentClass{
int a;
ParentClass(int a){
System.out.println("Inside ParentClass parameterized constructor!");
this.a = a;
}
ParentClass(){
System.out.println("Inside ParentClass default constructor!");
}
}
class ChildClass extends ParentClass{

ChildClass(){
System.out.println("Inside ChildClass constructor!!");
}
}
public class ConstructorInInheritance {

public static void main(String[] args) {

ChildClass obj = new ChildClass();

NOTE: The parameterized constructor of parent class must be called explicitly using the
super keyword.

Constructors in Java
Types of constructors
Default Constructor
Parameterized Constructor
Constructor Overloading
Does constructor return any value?
Copying the values of one object into another
Does constructor perform other tasks instead of the initialization
In Java, a constructor is a block of codes similar to the method. It is called when an instance
of the class is created. At the time of calling constructor, memory for the object is allocated in
the memory.
It is a special type of method which is used to initialize the object.
Every time an object is created using the new() keyword, at least one constructor is called.
It calls a default constructor if there is no constructor available in the class. In such case, Java
compiler provides a default constructor by default.

There are two types of constructors in Java: no-arg constructor, and parameterized
constructor.

Note: It is called constructor because it constructs the values at the time of object creation. It
is not necessary to write a constructor for a class. It is because java compiler creates a default
constructor if your class doesn't have any.
Rules for creating Java constructor
There are two rules defined for the constructor.
Constructor name must be the same as its class name
A Constructor must have no explicit return type
A Java constructor cannot be abstract, static, final, and synchronized
Note: We can use access modifiers while declaring a constructor. It controls the object
creation. In other words, we can have private, protected, public or default constructor in Java.
Types of Java constructors
There are two types of constructors in Java:
Default constructor (no-arg constructor)
Parameterized constructor
Java Constructors
Java Default Constructor
A constructor is called "Default Constructor" when it doesn't have any parameter.
Syntax of default constructor:
<class_name>(){}
Example of default constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at
the time of object creation.
//Java Program to create and call a default constructor
class Bike1{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
Test it Now
Output:
Bike is created
Rule: If there is no constructor in a class, compiler automatically creates a default
constructor.

Q) What is the purpose of a default constructor?


The default constructor is used to provide the default values to the object like 0, null,
etc., depending on the type.

Example of default constructor that displays the default values


//Let us see another example of default constructor
//which displays the default values
class Student3{
int id;
String name;
//method to display the value of id and name
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


//creating objects
Student3 s1=new Student3();
Student3 s2=new Student3();
//displaying values of the object
s1.display();
s2.display();
}
}
Test it Now
Output:
0 null
0 null
Explanation:In the above class,you are not creating any constructor so compiler
provides you a default constructor. Here 0 and null values are provided by default
constructor.

Java Parameterized Constructor


A constructor which has a specific number of parameters is called a parameterized
constructor.

Why use the parameterized constructor?


The parameterized constructor is used to provide different values to distinct objects.
However, you can provide the same values also.

Example of parameterized constructor


In this example, we have created the constructor of Student class that have two
parameters. We can have any number of parameters in the constructor.

//Java Program to demonstrate the use of the parameterized constructor.


class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}
Test it Now
Output:
111 Karan
222 Aryan
Constructor Overloading in Java
In Java, a constructor is just like a method but without return type. It can also be
overloaded like Java methods.
Constructor overloading in Java
is a technique of having more than one constructor with different parameter lists. They
are arranged in a way that each constructor performs a different task. They are
differentiated by the compiler by the number of parameters in the list and their types.
Example of Constructor Overloading
//Java program to overload constructors
class Student5{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){


Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}
Test it Now
Output:
111 Karan 0
222 Aryan 25
Difference between constructor and method in Java
There are many differences between constructors and methods. They are given below.

Java Constructor Java Method

A constructor is used to initialize the state of an A method is used to expose the


object. behavior of an object.

A constructor must not have a return type. A method must have a return type.

The constructor is invoked implicitly. The method is invoked explicitly.

The Java compiler provides a default constructor if The method is not provided by the
you don't have any constructor in a class. compiler in any case.

The constructor name must be same as the class The method name may or may not
name. be same as the class name.
Java Copy Constructor
There is no copy constructor in Java. However, we can copy the values from one object
to another like copy constructor in C++.
There are many ways to copy the values of one object into another in Java. They are:
By constructor
By assigning the values of one object into another
By clone() method of Object class
In this example, we are going to copy the values of one object into another using Java
constructor.

//Java program to initialize the values from one object to another object.
class Student6{
int id;
String name;
//constructor to initialize integer and string
Student6(int i,String n){
id = i;
name = n;
}
//constructor to initialize another object
Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}
}
Test it Now
Output:
111 Karan
111 Karan

Copying values without constructor


We can copy the values of one object into another by assigning the objects values to another
object. In this case, there is no need to create the constructor.

class Student7{
int id;
String name;
Student7(int i,String n){
id = i;
name = n;
}
Student7(){}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student7 s1 = new Student7(111,"Karan");
Student7 s2 = new Student7();
s2.id=s1.id;
s2.name=s1.name;
s1.display();
s2.display();
}
}
Test it Now
Output:
111 Karan
111 Karan
Q) Does constructor return any value?
Yes, it is the current class instance (You cannot use return type yet it returns a value).

Can constructor perform other tasks instead of initialization?


Yes, like object creation, starting a thread, calling a method, etc. You can perform any
operation in the constructor as you perform in the method.
Is there Constructor class in Java?
Yes.
What is the purpose of Constructor class?
Java provides a Constructor class which can be used to get the internal information of a
constructor in the class. It is found in the java.lang.reflect package.
Java super keyword
In java, super is a keyword used to refers to the parent class object. The super keyword came
into existence to solve the naming conflicts in the inheritance. When both parent class and
child class have members with the same name, then the super keyword is used to refer to the
parent class version.
In java, the super keyword is used for the following purposes.
To refer parent class data members
To refer parent class methods
To call parent class constructor
NOTE:The super keyword is used inside the child class only.
super to refer parent class data members
When both parent class and child class have data members with the same name, then the
super keyword is used to refer to the parent class data member from child class.
Let's look at the following example java code.
Example
class ParentClass{
int num = 10;
}
class ChildClass extends ParentClass{
int num = 20;
void showData() {
System.out.println("Inside the ChildClass");
System.out.println("ChildClass num = " + num);
System.out.println("ParentClass num = " + super.num);
}
}

public class SuperKeywordExample {

public static void main(String[] args) {


ChildClass obj = new ChildClass();

obj.showData();

System.out.println("\nInside the non-child class");


System.out.println("ChildClass num = " + obj.num);
//System.out.println("ParentClass num = " + super.num); //super can't be used
here
}
}
OUTPUT:

super to refer parent class method


When both parent class and child class have method with the same name, then the super
keyword is used to refer to the parent class method from child class.
Let's look at the following example java code.
Example
class ParentClass{

int num1 = 10;

void showData() {
System.out.println("\nInside the ParentClass showData method");
System.out.println("ChildClass num = " + num1);
}
}
class ChildClass extends ParentClass{
int num2 = 20;
void showData() {
System.out.println("\nInside the ChildClass showData method");
System.out.println("ChildClass num = " + num2);
super.showData();
}
}
public class SuperKeywordExample {
public static void main(String[] args) {
ChildClass obj = new ChildClass();

obj.showData();
//super.showData(); // super can't be used here
}
}
OUTPUT:

super to call parent class constructor


When an object of child class is created, it automatically calls the parent class default-
constructor before it's own. But, the parameterized constructor of parent class must be called
explicitly using the super keyword inside the child class constructor.

Let's look at the following example java code.


Example
class ParentClass{

int num1;

ParentClass(){
System.out.println("\nInside the ParentClass default constructor");
num1 = 10;
}

ParentClass(int value){
System.out.println("\nInside the ParentClass parameterized constructor");
num1 = value;
}
}

class ChildClass extends ParentClass{

int num2;

ChildClass(){
super(100);
System.out.println("\nInside the ChildClass constructor");
num2 = 200;
}
}
public class SuperKeywordExample {

public static void main(String[] args) {

ChildClass obj = new ChildClass();

}
}
OUTPUT:

NOTE: To call the parameterized constructor of the parent class, the super keyword must be
the first statement inside the child class constructor, and we must pass the parameter values.
Final Keyword In Java
The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be:
variable
method
class
The final keyword can be applied with the variables, a final variable that have no value it is
called blank final variable or uninitialized final variable. It can be initialized in the
constructor only. The blank final variable can be static also which will be initialized in the
static block only. We will have detailed learning of these. Let's first learn the basics of final
keyword.
final keyword in java
1) Java final variable
If you make any variable as final, you cannot change the value of final variable(It will be
constant).
Example of final variable
There is a final variable speedlimit, we are going to change the value of this variable, but It
can't be changed because final variable once assigned a value can never be changed.
Let's look at the following example java code.
Example
public class FinalVariableExample {
public static void main(String[] args) {
final int a = 10;
System.out.println("a = " + a);
a = 100; // Can't be modified
}
}
OUTPUT:

final with methods


When a method defined with the final keyword, it does not allow it to override. The final
method extends to the child class, but the child class can not override or re-define it. It must
be used as it has implemented in the parent class.

Let's look at the following example java code.


Example
class ParentClass{

int num = 10;

final void showData() {


System.out.println("Inside ParentClass showData() method");
System.out.println("num = " + num);
}

class ChildClass extends ParentClass{

void showData() {
System.out.println("Inside ChildClass showData() method");
System.out.println("num = " + num);
}
}

public class FinalKeywordExample {

public static void main(String[] args) {

ChildClass obj = new ChildClass();


obj.showData();
}
}
OUTPUT:

final with class


When a class defined with final keyword, it can not be extended by any other class.
Let's look at the following example java code.
Example
final class ParentClass{
int num = 10;
void showData() {
System.out.println("Inside ParentClass showData() method");
System.out.println("num = " + num);
}
}
class ChildClass extends ParentClass{

}
public class FinalKeywordExample {
public static void main(String[] args) {
ChildClass obj = new ChildClass();
}
}

OUTPUT:

Q) Is final method inherited?


Ans) Yes, final method is inherited but you cannot override it. For Example:
class Bike{
final void run(){System.out.println("running...");}
}
class Honda2 extends Bike{
public static void main(String args[]){
new Honda2().run();
}
}
Q) What is blank or uninitialized final variable?
A final variable that is not initialized at the time of declaration is known as blank final
variable.
If you want to create a variable that is initialized at the time of creating object and once
initialized may not be changed, it is useful. For example PAN CARD number of an
employee.

It can be initialized only in constructor.


Example of blank final variable
class Student{
int id;
String name;
final String PAN_CARD_NUMBER;
...
}
Que) Can we initialize blank final variable?
Yes, but only in constructor.
For example:
class Bike10{
final int speedlimit;//blank final variable
Bike10(){
speedlimit=70;
System.out.println(speedlimit);
}
public static void main(String args[]){
new Bike10();
}
}

static blank final variable


A static final variable that is not initialized at the time of declaration is known as static blank
final variable. It can be initialized only in static block.
Example of static blank final variable
class A{
static final int data;//static blank final variable
static{ data=50;}
public static void main(String args[]){
System.out.println(A.data);
}
}
Q) What is final parameter?
If you declare any parameter as final, you cannot change the value of it.
class Bike11{
int cube(final int n){
n=n+2;//can't be changed as n is final
n*n*n;
}
public static void main(String args[]){
Bike11 b=new Bike11();
b.cube(5);
}
}
Q) Can we declare a constructor final?
No, because constructor is never inherited.
Java Polymorphism
The polymorphism is the process of defining same method with different implementation.
That means creating multiple methods with different behaviors.
In java, polymorphism implemented using method overloading and method overriding.

Ad hoc polymorphism
The ad hoc polymorphism is a technique used to define the same method with different
implementations and different arguments. In a java programming language, ad hoc
polymorphism carried out with a method overloading concept.
In ad hoc polymorphism the method binding happens at the time of compilation. Ad hoc
polymorphism is also known as compile-time polymorphism. Every function call binded with
the respective overloaded method based on the arguments.
Method Overloading in Java
If a class has multiple methods having same name but different in parameters, it is known as
Method Overloading.
If we have to perform only one operation, having same name of the methods increases
the readability of the program
Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for
three parameters then it may be difficult for you as well as other programmers to understand
the behavior of the method because its name differs.
Advantage of method overloading
Method overloading increases the readability of the program.
Different ways to overload the method
There are two ways to overload the method in java
1)By changing number of arguments
2)By changing the data type
Note:In Java, Method Overloading is not possible by changing the return type of the method
only.

1) Method Overloading: changing no. of arguments

In this example, we have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers.

In this example, we are creating static methods

so that we don't need to create instance for calling methods.

1. class Adder{
2. static int add(int a,int b){return a+b;}
3. static int add(int a,int b,int c){return a+b+c;}
4. }
5. class TestOverloading1{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(11,11,11));
9. }}
10. Output:
11. 22
12. 33

2) Method Overloading: changing data type of arguments

In this example, we have created two methods that differs in data type

. The first add method receives two integer arguments and second add method receives two
double arguments.

1. class Adder{
2. static int add(int a, int b){return a+b;}
3. static double add(double a, double b){return a+b;}
4. }
5. class TestOverloading2{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(12.3,12.6));
9. }}

Output:

22
24.9

Q) Why Method Overloading is not possible by changing the return type of method only?

In java, method overloading is not possible by changing the return type of the method only
because of ambiguity. Let's see how ambiguity may occur:

1. class Adder{
2. static int add(int a,int b){return a+b;}
3. static double add(int a,int b){return a+b;}
4. }
5. class TestOverloading3{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));//ambiguity
8. }}

Output:

Compile Time Error: method add(int,int) is already defined in class Adder


System.out.println(Adder.add(11,11)); //Here, how can java determine which sum() method
should be called?

Note: Compile Time Error is better than Run Time Error. So, java compiler renders
compiler time error if you declare the same method having same parameters.

Can we overload java main() method?

Yes, by method overloading. You can have any number of main methods in a class by
method overloading. But JVM

calls main() method which receives string array as arguments only. Let's see the simple
example:

1. class TestOverloading4{
2. public static void main(String[] args){System.out.println("main with String[]");}
3. public static void main(String args){System.out.println("main with String");}
4. public static void main(){System.out.println("main without args");}
5. }

Output:

main with String[]

Pure polymorphism
The pure polymorphism is a technique used to define the same method with the same
arguments but different implementations. In a java programming language, pure
polymorphism carried out with a method overriding concept.

In pure polymorphism, the method binding happens at run time. Pure polymorphism is also
known as run-time polymorphism. Every function call binding with the respective overridden
method based on the object reference.
When a child class has a definition for a member function of the parent class, the parent class
function is said to be overridden.
The pure polymorphism implemented in the inheritance concept only.
Method Overriding in Java
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.
In other words, If a subclass provides the specific implementation of the method that has been
declared by one of its parent class, it is known as method overriding.
Usage of Java Method Overriding
Method overriding is used to provide the specific implementation of a method which is
already provided by its superclass.
Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
The method must have the same name as in the parent class
The method must have the same parameter as in the parent class.
There must be an IS-A relationship (inheritance).
Example

class ParentClass{

int num = 10;

void showData() {
System.out.println("Inside ParentClass showData() method");
System.out.println("num = " + num);
}

class ChildClass extends ParentClass{

void showData() {
System.out.println("Inside ChildClass showData() method");
System.out.println("num = " + num);
}
}

public class PurePolymorphism {

public static void main(String[] args) {

ParentClass obj = new ParentClass();


obj.showData();
obj = new ChildClass();
obj.showData();

}
}

Output:

The method overriding is also known as dynamic method dispatch or run time
polymorphism or pure polymorphism.
Method Overriding

The method overriding is the process of re-defining a method in a child class that is already

defined in the parent class. When both parent and child classes have the same method, then

that method is said to be the overriding method.


The method overriding enables the child class to change the implementation of the method

which aquired from parent class according to its requirement.

In the case of the method overriding, the method binding happens at run time. The method

binding which happens at run time is known as late binding. So, the method overriding

follows late binding.

The method overriding is also known as dynamic method dispatch or run time

polymorphism or pure polymorphism.

Let's look at the following example java code.

Example

class ParentClass{

int num = 10;

void showData() {
System.out.println("Inside ParentClass showData() method");
System.out.println("num = " + num);
}

class ChildClass extends ParentClass{

void showData() {
System.out.println("Inside ChildClass showData() method");
System.out.println("num = " + num);
}
}

public class PurePolymorphism {

public static void main(String[] args) {


ParentClass obj = new ParentClass();
obj.showData();

obj = new ChildClass();


obj.showData();

}
}

Output:

Rules for method overriding:


While overriding a method, we must follow the below list of rules.

 Static methods can not be overridden.


 Final methods can not be overridden.
 Private methods can not be overridden.
 Constructor can not be overridden.
 An abstract method must be overridden.
 Use super keyword to invoke overridden method from child class.
 The return type of the overriding method must be same as the parent has it.
 The access specifier of the overriding method can be changed, but the visibility must
increase but not decrease. For example, a protected method in the parent class can be
made public, but not private, in the child class.
 If the overridden method does not throw an exception in the parent class, then the
child class overriding method can only throw the unchecked exception, throwing a
checked exception is not allowed.
 If the parent class overridden method does throw an exception, then the child class
overriding method can only throw the same, or subclass exception, or it may not
throw any exception.

Can we override static method?

No, a static method cannot be overridden. It can be proved by runtime polymorphism, so we


will learn it later.

Why can we not override static method?

It is because the static method is bound with class whereas instance method is bound with an
object. Static belongs to the class area, and an instance belongs to the heap area.

Can we override java main method?

No, because the main is a static method.

Difference between method Overloading and Method Overriding in java


There are many differences between method overloading and method overriding in java. A
list of differences between method overloading and method overriding are given below:

o. Method Overloading Method Overriding

1) Method overloading is used to increase the Method overriding is used to provide


readability of the program. the specific implementation of the
method that is already provided by its
super class.
2) Method overloading is performed within class. Method overriding occurs in two
classes that have IS-A (inheritance)
relationship.

3) In case of method overloading, parameter must be In case of method


different. overriding, parameter must be same.

4) Method overloading is the example of compile time Method overriding is the example
polymorphism. of run time polymorphism.

5) In java, method overloading can't be performed by


changing return type of the method only. Return
type can be same or different in method
overloading. But you must have to change the
parameter.

Abstarct class:

An abstract class is a class that created using abstract keyword. In other words, a class
prefixed with abstract keyword is known as an abstract class.

In java, an abstract class may contain abstract methods (methods without


implementation) and also non-abstract methods (methods with implementation).

We use the following syntax to create an abstract class.

Syntax

abstract class <ClassName>{

...

Let's look at the following example java code.

Example

import java.util.*;

abstract class Shape {


int length, breadth, radius;
Scanner input = new Scanner(System.in);
abstract void printArea();

class Rectangle extends Shape {


void printArea() {
System.out.println("*** Finding the Area of Rectangle ***");
System.out.print("Enter length and breadth: ");
length = input.nextInt();
breadth = input.nextInt();
System.out.println("The area of Rectangle is: " + length * breadth);
}
}

class Triangle extends Shape {


void printArea() {
System.out.println("\n*** Finding the Area of Triangle ***");
System.out.print("Enter Base And Height: ");
length = input.nextInt();
breadth = input.nextInt();
System.out.println("The area of Triangle is: " + (length * breadth) / 2);
}
}

class Cricle extends Shape {


void printArea() {
System.out.println("\n*** Finding the Area of Cricle ***");
System.out.print("Enter Radius: ");
radius = input.nextInt();
System.out.println("The area of Cricle is: " + 3.14f * radius * radius);
}
}
public class AbstractClassExample {
public static void main(String[] args) {
Rectangle rec = new Rectangle();
rec.printArea();

Triangle tri = new Triangle();


tri.printArea();

Cricle cri = new Cricle();


cri.printArea();
}
}

Output:

Note:
An abstract class can not be instantiated but can be referenced. That means we can not
create an object of an abstract class, but base reference can be created.

In the above example program, the child class objects are created to invoke the
overridden abstract method. But we may also create base class reference and assign it
with child class instance to invoke the same. The main method of the above program
can be written as follows that produce the same output.

Example

public static void main(String[] args) {


Shape obj = new Rectangle(); //Base class reference to Child class
instance
obj.printArea();

obj = new Triangle();


obj.printArea();

obj = new Cricle();


obj.printArea();
}

An abstract class must follow the below list of rules.

An abstract class must be created with abstract keyword.

An abstract class can be created without any abstract method.

An abstract class may contain abstract methods and non-abstract methods.

An abstract class may contain final methods that can not be overridden.

An abstract class may contain static methods, but the abstract method can not be
static.

An abstract class may have a constructor that gets executed when the child class
object created.

An abstract method must be overridden by the child class, otherwise, it must be


defined as an abstract class.
An abstract class can not be instantiated but can be referenced.

Java Object Class

In java, the Object class is the super most class of any class hierarchy. The Object
class in the java programming language is present inside the java.lang package.

Every class in the java programming language is a subclass of Object class by default.

The Object class is useful when you want to refer to any object whose type you don't
know. Because it is the superclass of all other classes in java, it can refer to any type
of object.

Methods of Object class

The following table depicts all built-in methods of Object class in java.

Method Description

getClass() Returns Class class object

hashCode() returns the hashcode number for object being used.

equals(Object compares the argument object to calling object.


obj)

clone() Compares two strings, ignoring case

concat(String) Creates copy of invoking object

toString() eturns the string representation of invoking object.

notify() wakes up a thread, waiting on invoking object's monitor.


Method Description

notifyAll() wakes up all the threads, waiting on invoking object's monitor.

wait() causes the current thread to wait, until another thread notifies.

wait(long,int) causes the current thread to wait for the specified milliseconds and nanoseconds, until an
thread notifies.

finalize() It is invoked by the garbage collector before an object is being garbage collected.

Java Forms of Inheritance


The inheritance concept used for the number of purposes in the java programming language.
One of the main purposes is substitutability. The substitutability means that when a child
class acquires properties from its parent class, the object of the parent class may be
substituted with the child class object. For example, if B is a child class of A, anywhere we
expect an instance of A we can use an instance of B.
The substitutability can achieve using inheritance, whether using extends or implements
keywords.
The following are the differnt forms of inheritance in java.
Specialization
Specification
Construction
Eextension
Limitation
Combination
Specialization
It is the most ideal form of inheritance. The subclass is a special case of the parent class. It
holds the principle of substitutability.
Specification
This is another commonly used form of inheritance. In this form of inheritance, the parent
class just specifies which methods should be available to the child class but doesn't
implement them. The java provides concepts like abstract and interfaces to support this form
of inheritance. It holds the principle of substitutability.

Construction
This is another form of inheritance where the child class may change the behavior defined by
the parent class (overriding). It does not hold the principle of substitutability.
Eextension
This is another form of inheritance where the child class may add its new properties. It holds
the principle of substitutability.
Limitation
This is another form of inheritance where the subclass restricts the inherited behavior. It does
not hold the principle of substitutability.
Combination
This is another form of inheritance where the subclass inherits properties from multiple
parent classes. Java does not support multiple inheritance type.
Benefits and Costs of Inheritance in java
The inheritance is the core and more usful concept Object Oriented Programming. It proWith
inheritance, we will be able to override the methods of the base class so that the meaningful
implementation of the base class method can be designed in the derived class. An inheritance
leads to less development and maintenance costs.vides lot of benefits and few of them
are listed below.
Benefits of Inheritance
Inheritance helps in code reuse. The child class may use the code defined in the parent class
without re-writing it.
Inheritance can save time and effort as the main code need not be written again.
Inheritance provides a clear model structure which is easy to understand.
An inheritance leads to less development and maintenance costs.
With inheritance, we will be able to override the methods of the base class so that the
meaningful implementation of the base class method can be designed in the derived class. An
inheritance leads to less development and maintenance costs.
In inheritance base class can decide to keep some data private so that it cannot be altered by
the derived class.
Costs of Inheritance
Inheritance decreases the execution speed due to the increased time and effort it takes, the
program to jump through all the levels of overloaded classes.
Inheritance makes the two classes (base and inherited class) get tightly coupled. This means
one cannot be used independently of each other.The changes made in the parent class will
affect the behavior of child class too.
The overuse of inheritance makes the program more complex.
Defining Packages in java
`In java, a package is a container of classes, interfaces, and sub-packages. We may think of it
as a folder in a file directory.
We use the packages to avoid naming conflicts and to organize project-related classes,
interfaces, and sub-packages into a bundle.
In java, the packages have divided into two types.
Built-in Packages
User-defined Packages
Built-in Packages
The built-in packages are the packages from java API. The Java API is a library of pre-
defined classes, interfaces, and sub-packages. The built-in packages were included in the
JDK.
There are many built-in packages in java, few of them are as java, lang, io, util, awt, javax,
swing, net, sql, etc.
We need to import the built-in packages to use them in our program. To import a package, we
use the import statement.
User-defined Packages
The user-defined packages are the packages created by the user. User is free to create their
own packages.
Definig a Package in java
We use the package keyword to create or define a package in java programming language.
Syntax

package packageName;

The package statement must be the first statement in the program.


The package name must be a single word.
The package name must use Camel case notation.
Example

package myPackage;

public class DefiningPackage {


public static void main(String[] args) {

System.out.println("This class belongs to myPackage.");

Now, save the above code in a file DefiningPackage.java, and compile it using the following
command.
javac -d . DefiningPackage.java

The above command creates a directory with the package name myPackage, and
the DefiningPackage.class is saved into it.
Run the program use the following command.
java myPackage.DefiningPackage

🔔 When we use IDE like Eclipse, Netbeans, etc. the package structure is created
automatically.

Access protection in java packages


In java, the access modifiers define the accessibility of the class and its members. For
example, private members are accessible within the same class members only. Java has four
access modifiers, and they are default, private, protected, and public.
In java, the package is a container of classes, sub-classes, interfaces, and sub-packages. The
class acts as a container of data and methods. So, the access modifier decides the accessibility
of class members across the different packages.
In java, the accessibility of the members of a class or interface depends on its access
specifiers. The following table provides information about the visibility of both data members
and methods.
🔔 The public members can be accessed everywhere.
🔔 The private members can be accessed only inside the same class.
🔔 The protected members are accessible to every child class (same package or other
packages).
🔔 The default members are accessible within the same package but not outside the package.
Let's look at the following example java code.
Example

class ParentClass{
int a = 10;
public int b = 20;
protected int c = 30;
private int d = 40;

void showData() {
System.out.println("Inside ParentClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
class ChildClass extends ParentClass{

void accessData() {
System.out.println("Inside ChildClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
//System.out.println("d = " + d); // private member can't be accessed
}

}
public class AccessModifiersExample {

public static void main(String[] args) {

ChildClass obj = new ChildClass();


obj.showData();
obj.accessData();

}
Importing Packages in java
In java, the import keyword used to import built-in and user-defined packages. When a
package has imported, we can refer to all the classes of that package using their name
directly.
The import statement must be after the package statement, and before any other statement.
Using an import statement, we may import a specific class or all the classes from a package.

🔔 Using one import statement, we may import only one package or a class.

🔔 Using an import statement, we can not import a class directly, but it must be a part of a
package.

🔔 A program may contain any number of import statements.

Importing specific class


Using an importing statement, we can import a specific class. The following syntax is
employed to import a specific class.
Syntax

import packageName.ClassName;

Let's look at an import statement to import a built-in package and Scanner class.
Example

package myPackage;

import java.util.Scanner;

public class ImportingExample {

public static void main(String[] args) {

Scanner read = new Scanner(System.in);

int i = read.nextInt();

System.out.println("You have entered a number " + i);


}
}

In the above code, the class ImportingExample belongs to myPackage package, and it also
importing a class called Scanner from java.util package.

Importing all the classes


Using an importing statement, we can import all the classes of a package. To import all the
classes of the package, we use * symbol. The following syntax is employed to import all the
classes of a package.
Syntax

import packageName.*;

Let's look at an import statement to import a built-in package.


Example

package myPackage;

import java.util.*;

public class ImportingExample {

public static void main(String[] args) {

Scanner read = new Scanner(System.in);

int i = read.nextInt();

System.out.println("You have entered a number " + i);

Random rand = new Random();

int num = rand.nextInt(100);

System.out.println("Randomly generated number " + num);


}
}

In the above code, the class ImportingExample belongs to myPackage package, and it also
importing all the classes like Scanner, Random, Stack, Vector, ArrayList, HashSet, etc. from
the java.util package.
🔔 The import statement imports only classes of the package, but not sub-packages and its
classes.
🔔 We may also import sub-packages by using a symbol '.' (dot) to separate parent package
and sub-package.

Consider the following import statement.

import java.util.*;

The above import statement util is a sub-package of java package. It imports all the classes
of util package only, but not classes of java package.
Defining an interface in java
In java, an interface is similar to a class, but it contains abstract methods and static final
variables only. The interface in Java is another mechanism to achieve abstraction.
We may think of an interface as a completely abstract class. None of the methods in the
interface has an implementation, and all the variables in the interface are constants.
All the methods of an interface, implemented by the class that implements it.
The interface in java enables java to support multiple-inheritance. An interface may extend
only one interface, but a class may implement any number of interfaces.
🔔 An interface is a container of abstract methods and static final variables.
🔔 An interface, implemented by a class. (class implements interface).
🔔 An interface may extend another interface. (Interface extends Interface).
🔔 An interface never implements another interface, or class.
🔔 A class may implement any number of interfaces.
🔔 We can not instantiate an interface.
🔔 Specifying the keyword abstract for interface methods is optional, it automatically added.
🔔 All the members of an interface are public by default.
Defining an interface in java
Defining an interface is similar to that of a class. We use the keyword interface to define an
interface. All the members of an interface are public by default. The following is the syntax for
defining an interface.
Syntax

interface InterfaceName{
...
members declaration;
...
}

Let's look at an example code to define an interface.


Example

interface HumanInterfaceExample {

void learn(String str);


void work();

int duration = 10;

In the above code defines an interface HumanInterfaceExample that contains two abstract
methods learn(), work() and one constant duration.
Every interface in Java is auto-completed by the compiler. For example, in the above example
code, no member is defined as public, but all are public automatically.
The above code automatically converted as follows.
Converted code

interface HumanInterfaceExample {

public abstract void learn(String str);


public abstract void work();

public static final int duration = 10;

In the next tutorial, we will learn how a class implements an interface to make use of the
interface concept.
Implementing an Interface in java
In java, an interface is implemented by a class. The class that implements an interface must
provide code for all the methods defined in the interface, otherwise, it must be defined as an
abstract class.
The class uses a keyword implements to implement an interface. A class can implement any
number of interfaces. When a class wants to implement more than one interface, we use the
implements keyword is followed by a comma-separated list of the interfaces implemented by
the class.
The following is the syntax for defineing a class that implements an interface.
Syntax

class className implements InterfaceName{


...
boby-of-the-class
...
}

Let's look at an example code to define a class that implements an interface.


Example

interface Human {

void learn(String str);


void work();

int duration = 10;


}

class Programmer implements Human{


public void learn(String str) {
System.out.println("Learn using " + str);
}
public void work() {
System.out.println("Develop applications");
}
}

public class HumanTest {

public static void main(String[] args) {


Programmer trainee = new Programmer();
trainee.learn("coding");
trainee.work();
}
}

In the above code defines an interface Human that contains two abstract methods learn(),
work() and one constant duration. The class Programmer implements the interface. As it
implementing the Human interface it must provide the body of all the methods those defined
in the Human interface.

Implementing multiple Interfaces


When a class wants to implement more than one interface, we use the implements keyword is
followed by a comma-separated list of the interfaces implemented by the class.
The following is the syntax for defineing a class that implements multiple interfaces.
Syntax

class className implements InterfaceName1, InterfaceName2, ...{


...
boby-of-the-class
...
}

Let's look at an example code to define a class that implements multiple interfaces.
Example

interface Human {
void learn(String str);
void work();
}
interface Recruitment {
boolean screening(int score);
boolean interview(boolean selected);
}
class Programmer implements Human, Recruitment {
public void learn(String str) {
System.out.println("Learn using " + str);
}
public boolean screening(int score) {
System.out.println("Attend screening test");
int thresold = 20;
if(score > thresold)
return true;
return false;
}
public boolean interview(boolean selected) {
System.out.println("Attend interview");
if(selected)
return true;
return false;
}
public void work() {
System.out.println("Develop applications");
}
}
public class HumanTest {
public static void main(String[] args) {
Programmer trainee = new Programmer();
trainee.learn("Coding");
trainee.screening(30);
trainee.interview(true);
trainee.work();
}
}

In the above code defines two interfaces Human and Recruitment, and a class Programmer
implements both the interfaces.

Nested Interfaces in java


In java, an interface may be defined inside another interface, and also inside a class. The
interface that defined inside another interface or a class is konwn as nested interface. The
nested interface is also refered as inner interface.

🔔 The nested interface declared within an interface is public by default.


🔔 The nested interface declared within a class can be with any access modifier.

🔔 Every nested interface is static by default.


The nested interface cannot be accessed directly. We can only access the nested interface by
using outer interface or outer class name followed by dot( . ), followed by the nested interface
name.

Nested interface inside another interface


The nested interface that defined inside another interface must be accessed
as OuterInterface.InnerInterface.
Let's look at an example code to illustrate nested interfaces inside another interface.
Example

interface OuterInterface{
void outerMethod();

interface InnerInterface{
void innerMethod();
}
}

class OnlyOuter implements OuterInterface{


public void outerMethod() {
System.out.println("This is OuterInterface method");
}
}

class OnlyInner implements OuterInterface.InnerInterface{


public void innerMethod() {
System.out.println("This is InnerInterface method");
}
}

public class NestedInterfaceExample {

public static void main(String[] args) {


OnlyOuter obj_1 = new OnlyOuter();
OnlyInner obj_2 = new OnlyInner();

obj_1.outerMethod();
obj_2.innerMethod();
}

OUTPUT:

Nested interface inside a class


The nested interface that defined inside a class must be accessed
as ClassName.InnerInterface.
Let's look at an example code to illustrate nested interfaces inside a class.
Example

class OuterClass{

interface InnerInterface{
void innerMethod();
}
}

class ImplementingClass implements OuterClass.InnerInterface{


public void innerMethod() {
System.out.println("This is InnerInterface method");
}
}

public class NestedInterfaceExample {

public static void main(String[] args) {


ImplementingClass obj = new ImplementingClass();

obj.innerMethod();
}

}
Variables in Java Interfaces
In java, an interface is a completely abstract class. An interface is a container of abstract
methods and static final variables. The interface contains the static final variables. The
variables defined in an interface can not be modified by the class that implements the
interface, but it may use as it defined in the interface.

🔔 The variable in an interface is public, static, and final by default.

🔔 If any variable in an interface is defined without public, static, and final keywords then,
the compiler automatically adds the same.

🔔 No access modifier is allowed except the public for interface variables.

🔔 Every variable of an interface must be initialized in the interface itself.

🔔 The class that implements an interface can not modify the interface variable, but it may
use as it defined in the interface.
Example

interface SampleInterface{

int UPPER_LIMIT = 100;

//int LOWER_LIMIT; // Error - must be initialised

public class InterfaceVariablesExample implements SampleInterface{

public static void main(String[] args) {

System.out.println("UPPER LIMIT = " + UPPER_LIMIT);

// UPPER_LIMIT = 150; // Can not be modified


}

}
OUTPUT:

Extending an Interface in java


In java, an interface can extend another interface. When an interface wants to extend another
interface, it uses the keyword extends. The interface that extends another interface has its
own members and all the members defined in its parent interface too. The class which
implements a child interface needs to provide code for the methods defined in both child and
parent interfaces, otherwise, it needs to be defined as abstract class.

🔔 An interface can extend another interface.

🔔 An interface can not extend multiple interfaces.

🔔 An interface can implement neither an interface nor a class.

🔔 The class that implements child interface needs to provide code for all the methods
defined in both child and parent interfaces.
Let's look at an example code to illustrate extending an interface.
Example

interface ParentInterface{
void parentMethod();
}

interface ChildInterface extends ParentInterface{


void childMethod();
}

class ImplementingClass implements ChildInterface{

public void childMethod() {


System.out.println("Child Interface method!!");
}

public void parentMethod() {


System.out.println("Parent Interface mehtod!");
}
}

public class ExtendingAnInterface {

public static void main(String[] args) {

ImplementingClass obj = new ImplementingClass();

obj.childMethod();
obj.parentMethod();

When we run the above program, it produce the following output.


Stream in java

In java, the IO operations are performed using the concept of streams. Generally, a stream means
a continuous flow of data. In java, a stream is a logical container of data that allows us to read
from and write to it. A stream can be linked to a data source, or data destination, like a console,
file or network connection by java IO system. The stream-based IO operations are faster than
normal IO operations.

The Stream is defined in the java.io package.

To understand the functionality of java streams, look at the following picture.

In java, the stream-based IO operations are performed using two separate streams input stream
and output stream. The input stream is used for input operations, and the output stream is used
for output operations. The java stream is composed of bytes.

In Java, every program creates 3 streams automatically, and these streams are attached to the
console.

System.out: standard output stream for console output operations.

System.in: standard input stream for console input operations.

System.err: standard error stream for console error output operations.


The Java streams support many different kinds of data, including simple bytes, primitive data
types, localized

characters, and objects.

Java provides two types of streams, and they are as follows.

Byte Stream

Character Stream

The following picture shows how streams are categorized, and various built-in classes used by
the java IO system.

Both character and byte streams essentially provides a convenient and efficient way to handle
data streams in Java.

Byte Stream in java

In java, the byte stream is an 8 bits carrier. The byte stream in java allows us to transmit 8 bits of
data.

In Java 1.0 version all IO operations were byte oriented, there was no other stream (character
stream).
The java byte stream is defined by two abstract classes, InputStream and OutputStream. The
InputStream class used for byte stream based input operations, and the OutputStream class used
for byte stream based output operations.

The InputStream and OutputStream classes have several concreate classes to perform various IO
operations based on the byte stream.

The following picture shows the classes used for byte stream operations.

InputStream class

The InputStream class has defined as an abstract class, and it has the following methods which
have implemented by its concrete classes.

S.No. Method with Description

1 int available()

It returns the number of bytes that can be read from the input stream.
S.No. Method with Description

2 int read()
It reads the next byte from the input stream.

3 int read(byte[] b)
It reads a chunk of bytes from the input stream and store them in its byte array, b.

4 void close()
It closes the input stream and also frees any resources connected with this input stream.

OutputStream class

The OutputStream class has defined as an abstract class, and it has the following methods which
have implemented by its concrete classes.

S.No. Method with Description

1 void write(int n)

It writes byte(contained in an int) to the output stream.

2 void write(byte[] b)
It writes a whole byte array(b) to the output stream.

3 void flush()
It flushes the output steam by forcing out buffered bytes to be written out.

4 void close()
It closes the output stream and also frees any resources connected with this output stream.

Reading data using BufferedInputStream

We can use the BufferedInputStream class to read data from the console. The
BufferedInputStream class use a method read( ) to read a value from the console, or file, or
socket.
Let's look at an example code to illustrate reading data using BufferedInputStream.

Example 1 - Reading from console

import java.io.*;

public class ReadingDemo {

public static void main(String[] args) throws IOException {

BufferedInputStream read = new BufferedInputStream(System.in);

try {
System.out.print("Enter any character: ");
char c = (char)read.read();
System.out.println("You have entered '" + c + "'");
}
catch(Exception e) {
System.out.println(e);
}
finally {
read.close();
}
}

Output:
Example 2 - Reading from a file

import java.io.*;

public class ReadingDemo {

public static void main(String[] args) throws IOException {

FileInputStream fileInputStream = new FileInputStream(new


File("C:\\Raja\\dataFile.txt"));
BufferedInputStream input = new BufferedInputStream(fileInputStream);

try {
char c = (char)input.read();
System.out.println("Data read from a file - '" + c + "'");
}
catch(Exception e) {
System.out.println(e);
}
finally {
input.close();
}
}
}

Output:

Writing data using BufferedOutputStream

We can use the BufferedOutputStream class to write data into the console, file, socket. The
BufferedOutputStream class use a method write( ) to write data.

Let's look at an example code to illustrate writing data into a file using BufferedOutputStream.

Example - Writing data into a file

import java.io.*;
public class WritingDemo {

public static void main(String[] args) throws IOException {

String data = "Java tutorials by BTech Smart Class";


BufferedOutputStream out = null;
try {
FileOutputStream fileOutputStream = new FileOutputStream(new
File("C:\\Raja\\dataFile.txt"));
out = new BufferedOutputStream(fileOutputStream);

out.write(data.getBytes());
System.out.println("Writing data into a file is success!");

}
catch(Exception e) {
System.out.println(e);
}
finally {
out.close();
}
}
}

Output:
Character Stream in java

In java, when the IO stream manages 16-bit Unicode characters, it is called a character stream.
The unicode set is basically a type of character set where each character corresponds to a specific
numeric value within the given character set, and every programming language has a character
set.

In java, the character stream is a 16 bits carrier. The character stream in java allows us to
transmit 16 bits of data.

The character stream was introduced in Java 1.1 version. The charater stream

The java character stream is defined by two abstract classes, Reader and Writer. The Reader
class used for character stream based input operations, and the Writer class used for charater
stream based output operations.

The Reader and Writer classes have several concreate classes to perform various IO operations
based on the character stream.

The following picture shows the classes used for character stream operations.
Reader class

The Reader class has defined as an abstract class, and it has the following methods which have
implemented by its concrete classes.

S.No. Method with Description

1 int read()

It reads the next character from the input stream.

2 int read(char[] cbuffer)


It reads a chunk of charaters from the input stream and store them in its byte array, cbuffer.

3 int read(char[] cbuf, int off, int len)


It reads charaters into a portion of an array.

4 int read(CharBuffer target)


It reads charaters into into the specified character buffer.
S.No. Method with Description

5 String readLine()
It reads a line of text. A line is considered to be terminated by any oneof a line feed ('\n'), a
carriage return ('\r'), or a carriage returnfollowed immediately by a linefeed.

6 boolean ready()
It tells whether the stream is ready to be read.

7 void close()
It closes the input stream and also frees any resources connected with this input stream.

Writer class

The Writer class has defined as an abstract class, and it has the following methods which have
implemented by its concrete classes.

S.No. Method with Description

1 void flush()

It flushes the output steam by forcing out buffered bytes to be written out.

2 void write(char[] cbuf)


It writes a whole array(cbuf) to the output stream.

3 void write(char[] cbuf, int off, int len)


It writes a portion of an array of characters.

4 void write(int c)
It writes single character.

5 void write(String str)


It writes a string.

6 void write(String str, int off, int len)


It writes a portion of a string.
S.No. Method with Description

7 Writer append(char c)
It appends the specified character to the writer.

8 Writer append(CharSequence csq)


It appends the specified character sequence to the writer

9 Writer append(CharSequence csq, int start, int end)


It appends a subsequence of the specified character sequence to the writer.

10 void close()
It closes the output stream and also frees any resources connected with this output stream.

Reading data using BufferedReader

We can use the BufferedReader class to read data from the console. The BufferedInputStream
class needs InputStreamReaderclass. The BufferedReader use a method read( ) to read a value
from the console, or file, or socket.

Let's look at an example code to illustrate reading data using BufferedReader.

Example 1 - Reading from console

import java.io.*;

public class ReadingDemo {

public static void main(String[] args) throws IOException {

InputStreamReader isr = new InputStreamReader(System.in);


BufferedReader in = new BufferedReader(isr);

String name = "";

System.out.print("Please enter your name: ");


name = in.readLine();

System.out.println("Hello, " + name + "!");


}
}

Output:

Example 2 - Reading from a file

import java.io.*;

public class ReadingDemo {

public static void main(String[] args) throws IOException {


Reader in = new FileReader();

try {
char c = (char)input.read();
System.out.println("Data read from a file - '" + c + "'");
}
catch(Exception e) {
System.out.println(e);
}
finally {
input.close();
}
}
}

Output:
Writing data using FileWriter

We can use the FileWriter class to write data into the file. The FileWriter class use a method
write( ) to write data.

Let's look at an example code to illustrate writing data into a file using FileWriter.

Example - Writing data into a file

import java.io.*;

public class WritingDemo {

public static void main(String[] args) throws IOException {

Writer out = new FileWriter("C:\\Raja\\dataFile.txt");

String msg = "The sample data";


try {
out.write(msg);
System.out.println("Writing done!!!");
}
catch(Exception e) {
System.out.println(e);
}
finally {
out.close();
}
}
}

Output:

Console IO Operations in Java

Reading console input in java


In java, there are three ways to read console input. Using the 3 following ways, we can read
input data from the console.

Using BufferedReader class

Using Scanner class

Using Console class

Let's explore the each method to read data with example.

1. Reading console input using BufferedReader class in java

Reading input data using the BufferedReader class is the traditional technique. This way of the
reading method is used by wrapping the System.in (standard input stream) in an
InputStreamReader which is wrapped in a BufferedReader, we can read input from the console.

The BufferedReader class has defined in the java.io package.

Consider the following example code to understand how to read console input using
BufferedReader class.

Example

import java.io.*;

public class ReadingDemo {

public static void main(String[] args) throws IOException {

BufferedReader in = new BufferedReader(new


InputStreamReader(System.in));

String name = "";

try {
System.out.print("Please enter your name : ");
name = in.readLine();
System.out.println("Hello, " + name + "!");
}
catch(Exception e) {
System.out.println(e);
}
finally {
in.close();
}
}
}

Output:

2. Reading console input using Scanner class in java

Reading input data using the Scanner class is the most commonly used method. This way of the
reading method is used by wrapping the System.in (standard input stream) which is wrapped in a
Scanner, we can read input from the console.

The Scanner class has defined in the java.util package.


Consider the following example code to understand how to read console input using Scanner
class.

Example

import java.util.Scanner;

public class ReadingDemo {

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

String name = "";


System.out.print("Please enter your name : ");
name = in.next();
System.out.println("Hello, " + name + "!");

}
}

Output:
3. Reading console input using Console class in java

Reading input data using the Console class is the most commonly used method. This class was
introduced in Java 1.6 version.

The Console class has defined in the java.io package.

Consider the following example code to understand how to read console input using Console
class.

Example

import java.io.*;

public class ReadingDemo {

public static void main(String[] args) {

String name;
Console con = System.console();
if(con != null) {
name = con.readLine("Please enter your name : ");
System.out.println("Hello, " + name + "!!");
}
else {
System.out.println("Console not available.");
}
}
}

Writing console output in java

In java, there are two methods to write console output. Using the 2 following methods, we can
write output data to the console.

Using print() and println() methods

Using write() method

Let's explore the each method to write data with example.

1. Writing console output using print() and println() methods

The PrintStream is a bult-in class that provides two methods print() and println() to write console
output. The print() and println() methods are the most widely used methods for console output.

Both print() and println() methods are used with System.out stream.

The print() method writes console output in the same line. This method can be used with console
output only.

The println() method writes console output in a separete line (new line). This method can be used
with console ans also with other output sources.

Let's look at the following code to illustrate print() and println() methods.

Example

public class WritingDemo {


public static void main(String[] args) {

int[] list = new int[5];

for(int i = 0; i < 5; i++)


list[i] = i*10;

for(int i:list)
System.out.print(i); //prints in same line

System.out.println("");
for(int i:list)
System.out.println(i); //Prints in separate lines

}
}

Output:
2. Writing console output using write() method

Alternatively, the PrintStream class provides a method write() to write console output.

The write() method take integer as argument, and writes its ASCII equalent character on to the
console, it also acept escape sequences.

Let's look at the following code to illustrate write() method.

Example

public class WritingDemo {

public static void main(String[] args) {

int[] list = new int[26];

for(int i = 0; i < 26; i++) {


list[i] = i + 65;
}

for(int i:list) {
System.out.write(i);
System.out.write('\n');
}
}
}

Output:
File class in Java

The File is a built-in class in Java. In java, the File class has been defined in the java.io package.
The File class represents a reference to a file or directory. The File class has various methods to
perform operations like creating a file or directory, reading from a file, updating file content, and
deleting a file or directory.

The File class in java has the following constructors.

S.No. Constructor with Description

1 File(String pathname)

It creates a new File instance by converting the givenpathname string into an abstract
pathname. If the given string isthe empty string, then the result is the empty abstract
pathname.
S.No. Constructor with Description

2 File(String parent, String child)


It Creates a new File instance from a parent abstractpathname and a child pathname string. If
parent is null then the new File instance is created as if by invoking thesingle-argument File
constructor on the given child pathname string.

3 File(File parent, String child)


It creates a new File instance from a parent abstractpathname and a child pathname string. If
parent is null then the new File instance is created as if by invoking thesingle-argument File
constructor on the given child pathname string.

4 File(URI uri)
It creates a new File instance by converting the given file: URI into an abstract pathname.

The File class in java has the following methods.

S.No. Methods with Description

1 String getName()

It returns the name of the file or directory that referenced by the current File object.

2 String getParent()
It returns the pathname of the pathname's parent, or null if the pathname does not name a parent
directory.

3 String getPath()
It returns the path of curent File.

4 File getParentFile()
It returns the path of the current file's parent; or null if it does not exist.

5 String getAbsolutePath()
It returns the current file or directory path from the root.

6 boolean isAbsolute()
S.No. Methods with Description

It returns true if the current file is absolute, false otherwise.

7 boolean isDirectory()
It returns true, if the current file is a directory; otherwise returns false.

8 boolean isFile()
It returns true, if the current file is a file; otherwise returns false.

9 boolean exists()
It returns true if the current file or directory exist; otherwise returns false.

10 boolean canRead()
It returns true if and only if the file specified exists and can be read by the application; false
otherwise.

11 boolean canWrite()
It returns true if and only if the file specified exists and the application is allowed to write to the
file; false otherwise.

12 long length()
It returns the length of the current file.

13 long lastModified()
It returns the time that specifies the file was last modified.

14 boolean createNewFile()
It returns true if the named file does not exist and was successfully created; false if the named file
already exists.

15 boolean delete()
It deletes the file or directory. And returns true if and only if the file or directory is successfully
deleted; false otherwise.

16 void deleteOnExit()
It sends a requests that the file or directory needs be deleted when the virtual machine terminates.
S.No. Methods with Description

17 boolean mkdir()
It returns true if and only if the directory was created; false otherwise.

18 boolean mkdirs()
It returns true if and only if the directory was created, along with all necessary parent directories;
false otherwise.

19 boolean renameTo(File dest)


It renames the current file. And returns true if and only if the renaming succeeded; false
otherwise.

20 boolean setLastModified(long time)


It sets the last-modified time of the file or directory. And returns true if and only if the operation
succeeded; false otherwise.

21 boolean setReadOnly()
It sets the file permission to only read operations; Returns true if and only if the operation
succeeded; false otherwise.

22 String[] list()
It returns an array of strings containing names of all the files and directories in the current
directory.

23 String[] list(FilenameFilter filter)


It returns an array of strings containing names of all the files and directories in the current
directory that satisfy the specified filter.

24 File[] listFiles()
It returns an array of file references containing names of all the files and directories in the current
directory.

25 File[] listFiles(FileFilter filter)


It returns an array of file references containing names of all the files and directories in the current
directory that satisfy the specified filter.

26 boolean equals(Object obj)


It returns true if and only if the argument is not null and is an abstract pathname that denotes the
same file or directory as this abstract pathname.
S.No. Methods with Description

27 int compareTo(File pathname)


It Compares two abstract pathnames lexicographically. It returns zero if the argument is equal to
this abstract pathname, a value less than zero if this abstract pathname is lexicographically less
than the argument, or a value greater than zero if this abstract pathname is lexicographically
greater than the argument.

28 int compareTo(File pathname)


Compares this abstract pathname to another object. Returns zero if the argument is equal to this
abstract pathname, a value less than zero if this abstract pathname is lexicographically less than
the argument, or a value greater than zero if this abstract pathname is lexicographically greater
than the argument.

Let's look at the following code to illustrate file operations.

Example

import java.io.*;
public class FileClassTest {

public static void main(String args[]) {


File f = new File("C:\\Raja\\datFile.txt");

System.out.println("Executable File : " + f.canExecute());


System.out.println("Name of the file : " + f.getName());
System.out.println("Path of the file : " + f.getAbsolutePath());
System.out.println("Parent name : " + f.getParent());
System.out.println("Write mode : " + f.canWrite());
System.out.println("Read mode : " + f.canRead());
System.out.println("Existance : " + f.exists());
System.out.println("Last Modified : " + f.lastModified());
System.out.println("Length : " + f.length());
//f.createNewFile()
//f.delete();
//f.setReadOnly()
}

Output:

Let's look at the following java code to list all the files in a directory including the files present in
all its subdirectories.

Example

import java.util.Scanner;
import java.io.*;

public class ListingFiles {


public static void main(String[] args) {

String path = null;


Scanner read = new Scanner(System.in);
System.out.print("Enter the root directory name: ");
path = read.next() + ":\\";
File f_ref = new File(path);
if (!f_ref.exists()) {
printLine();
System.out.println("Root directory does not exists!");
printLine();
} else {
String ch = "y";
while (ch.equalsIgnoreCase("y")) {
printFiles(path);
System.out.print("Do you want to open any sub-directory
(Y/N): ");
ch = read.next().toLowerCase();
if (ch.equalsIgnoreCase("y")) {
System.out.print("Enter the sub-directory name:
");
path = path + "\\\\" + read.next();
File f_ref_2 = new File(path);
if (!f_ref_2.exists()) {
printLine();
System.out.println("The sub-directory
does not exists!");
printLine();
int lastIndex = path.lastIndexOf("\\");
path = path.substring(0, lastIndex);
}
}
}
}
System.out.println("***** Program Closed *****");
}
public static void printFiles(String path) {
System.out.println("Current Location: " + path);
File f_ref = new File(path);
File[] filesList = f_ref.listFiles();
for (File file : filesList) {
if (file.isFile())
System.out.println("- " + file.getName());
else
System.out.println("> " + file.getName());
}
}
public static void printLine() {
System.out.println("----------------------------------------");
}
}

Output:
File Reading & Writing in Java

In java, there multiple ways to read data from a file and to write data to a file. The most
commonly used ways are as follows.

Using Byte Stream (FileInputStream and FileOutputStream)

Using Character Stream (FileReader and FileWriter)

Let's look each of these ways.

File Handling using Byte Stream

In java, we can use a byte stream to handle files. The byte stream has the following built-in
classes to perform various operations on a file.

FileInputStream - It is a built-in class in java that allows reading data from a file. This class has
implemented based on the byte stream. The FileInputStream class provides a method read() to
read data from a file byte by byte.

FileOutputStream - It is a built-in class in java that allows writing data to a file. This class has
implemented based on the byte stream. The FileOutputStream class provides a method write() to
write data to a file byte by byte.

Let's look at the following example program that reads data from a file and writes the same to
another file using FileInoutStream and FileOutputStream classes.

Example

import java.io.*;
public class FileReadingTest {

public static void main(String args[]) throws IOException {


FileInputStream in = null;
FileOutputStream out = null;

try {
in = new FileInputStream("C:\\Raja\\Input-File.txt");
out = new FileOutputStream("C:\\Raja\\Output-File.txt");

int c;
while ((c = in.read()) != -1) {
out.write(c);
}
System.out.println("Reading and Writing has been success!!!");
}
catch(Exception e){
System.out.println(e);
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}

Output:
File Handling using Character Stream

In java, we can use a character stream to handle files. The character stream has the following
built-in classes to perform various operations on a file.

FileReader - It is a built-in class in java that allows reading data from a file. This class has
implemented based on the character stream. The FileReader class provides a method read() to
read data from a file character by character.

FileWriter - It is a built-in class in java that allows writing data to a file. This class has
implemented based on the character stream. The FileWriter class provides a method write() to
write data to a file character by character.

Let's look at the following example program that reads data from a file and writes the same to
another file using FIleReader and FileWriter classes.

Example

import java.io.*;
public class FileIO {

public static void main(String args[]) throws IOException {


FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("C:\\Raja\\Input-File.txt");
out = new FileWriter("C:\\Raja\\Output-File.txt");

int c;
while ((c = in.read()) != -1) {
out.write(c);
}
System.out.println("Reading and Writing in a file is done!!!");
}
catch(Exception e) {
System.out.println(e);
}
finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}

Output:
RandomAccessFile in Java

In java, the java.io package has a built-in class RandomAccessFile that enables a file to be
accessed randomly. The RandomAccessFile class has several methods used to move the cursor
position in a file.

A random access file behaves like a large array of bytes stored in a file.

RandomAccessFile Constructors

The RandomAccessFile class in java has the following constructors

S.No. Constructor with Description

1 RandomAccessFile(File fileName, String mode)

It creates a random access file stream to read from, and optionally to write to, the file specified by the Fi

2 RandomAccessFile(String fileName, String mode)


It creates a random access file stream to read from, and optionally to write to, a file with the specified fil

Access Modes

Using the RandomAccessFile, a file may created in th following modes.

r - Creates the file with read mode; Calling write methods will result in an IOException.

rw - Creates the file with read and write mode.

rwd - Creates the file with read and write mode - synchronously. All updates to file content is
written to the disk synchronously.

rws - Creates the file with read and write mode - synchronously. All updates to file content or
meta data is written to the disk synchronously.

RandomAccessFile methods

The RandomAccessFile class in java has the following methods.


S.No. Methods with Description

1 int read()

It reads byte of data from a file. The byte is returned as an integer in the range 0-255.

2 int read(byte[] b)
It reads byte of data from file upto b.length, -1 if end of file is reached.

3 int read(byte[] b, int offset, int len)


It reads bytes initialising from offset position upto b.length from the buffer.

4 boolean readBoolean()
It reads a boolean value from from the file.

5 byte readByte()
It reads signed eight-bit value from file.

6 char readChar()
It reads a character value from file.

7 double readDouble()
It reads a double value from file.

8 float readFloat()
It reads a float value from file.

9 long readLong()
It reads a long value from file.

10 int readInt()
It reads a integer value from file.

11 void readFully(byte[] b)
It reads bytes initialising from offset position upto b.length from the buffer.

12 void readFully(byte[] b, int offset, int len)


It reads bytes initialising from offset position upto b.length from the buffer.
S.No. Methods with Description

13 String readUTF()
t reads in a string from the file.

14 void seek(long pos)


It sets the file-pointer(cursor) measured from the beginning of the file, at which the next read or write oc

15 long length()
It returns the length of the file.

16 void writeFloat(float v)
It converts the float argument to an int using the floatToIntBits method in class Float, and then writes tha
file as a four-byte quantity, high byte first.

17 void writeDouble(double v)
It converts the double argument to a long using the doubleToLongBits method in class Double, and then
value to the file as an eight-byte quantity, high byte first.

18
Let's look at the following example program.
Example

import java.io.*;

public class RandomAccessFileDemo


{
public static void main(String[] args)
{
try
{
double d = 1.5;
float f = 14.56f;

// Creating a new RandomAccessFile - "F2"


RandomAccessFile f_ref = new RandomAccessFile("C:\\Raja\\Input-File.txt", "rw");

// Writing to file
f_ref.writeUTF("Hello, Good Morning!");

// File Pointer at index position - 0


f_ref.seek(0);

// read() method :
System.out.println("Use of read() method : " + f_ref.read());

f_ref.seek(0);

byte[] b = {1, 2, 3};

// Use of .read(byte[] b) method :


System.out.println("Use of .read(byte[] b) : " + f_ref.read(b));
// readBoolean() method :
System.out.println("Use of readBoolean() : " + f_ref.readBoolean());

// readByte() method :
System.out.println("Use of readByte() : " + f_ref.readByte());

f_ref.writeChar('c');
f_ref.seek(0);

// readChar() :
System.out.println("Use of readChar() : " + f_ref.readChar());

f_ref.seek(0);
f_ref.writeDouble(d);
f_ref.seek(0);

// read double
System.out.println("Use of readDouble() : " + f_ref.readDouble());

f_ref.seek(0);
f_ref.writeFloat(f);
f_ref.seek(0);

// readFloat() :
System.out.println("Use of readFloat() : " + f_ref.readFloat());

f_ref.seek(0);
// Create array upto geek.length
byte[] arr = new byte[(int) f_ref.length()];
// readFully() :
f_ref.readFully(arr);
String str1 = new String(arr);
System.out.println("Use of readFully() : " + str1);

f_ref.seek(0);

// readFully(byte[] b, int off, int len) :


f_ref.readFully(arr, 0, 8);

String str2 = new String(arr);


System.out.println("Use of readFully(byte[] b, int off, int len) : " + str2);
}
catch (IOException ex)
{
System.out.println("Something went Wrong");
ex.printStackTrace();
}
}
}

When we run the above program, it produce the following output.


Console class in Java

In java, the java.io package has a built-in class Console used to read from and write to the
console, if one exists. This class was added to the Java SE 6. The Console class implements teh
Flushable interface.

In java, most the input functionalities of Console class available through System.in, and the
output functionalities available through System.out.

Console class Constructors

The Console class does not have any constructor. We can obtain the Console class object by
calling System.console().

Console class methods

The Console class in java has the following methods.


S.No. Methods with Description

1 void flush( )

It causes buffered output to be written physically to the console.

2 String readLine( )
It reads a string value from the keyboard, the input is terminated on pressing enter key.

3 String readLine(String promptingString, Object...args)


It displays the given promptingString, and reads a string fron the keyboard; input is terminated
on pressng Enter key.

4 char[ ] readPassword( )
It reads a string value from the keyboard, the string is not displayed; the input is terminated on
pressing enter key.

5 char[ ] readPassword(String promptingString, Object...args)


It displays the given promptingString, and reads a string value from the keyboard, the string is
not displayed; the input is terminated on pressing enter key.

6 Console printf(String str, Object....args)


It writes the given string to the console.

7 Console format(String str, Object....args)


It writes the given string to the console.

8 Reader reader( )
It returns a reference to a Reader connected to the console.

9 PrintWriter writer( )
It returns a reference to a Writer connected to the console.

let's look at the following example program for reading a string using Console class.

Example

import java.io.*;
public class ReadingDemo {

public static void main(String[] args) {

String name;
Console con = System.console();

if(con != null) {
name = con.readLine("Please enter your name : ");
System.out.println("Hello, " + name + "!!");
}
else {
System.out.println("Console not available.");
}
}
}

Let's look at the following example program for writing to the console using Console class.
Example

import java.io.*;

public class WritingDemo {

public static void main(String[] args) {

int[] list = new int[26];

for(int i = 0; i < 26; i++) {


list[i] = i + 65;
}
for(int i:list) {
System.out.write(i);
System.out.write('\n');
}
}
}

Serialization and Deserialization in Java

In java, the Serialization is the process of converting an object into a byte stream so that it can

be stored on to a file, or memory, or a database for future access. The deserialization is reverse of

serialization. The deserialization is the process of reconstructing the object from the serialized

state.

Using serialization and deserialization, we can transfer the Object Code from one Java Virtual

machine to another.

Serialization in Java

In a java programming language, the Serialization is achieved with the help of

interface Serializable. The class whose object needs to be serialized must implement the

Serializable interface.

We use the ObjectOutputStream class to write a serialized object to write to a destination. The

ObjectOutputStream class provides a method writeObject() to serializing an object.


We use the following steps to serialize an object.

 Step 1 - Define the class whose object needs to be serialized; it must implement

Serializable interface.

 Step 2 - Create a file reference with file path using FileOutputStream class.

 Step 3 - Create reference to ObjectOutputStream object with file reference.

 Step 4 - Use writeObject(object) method by passing the object that wants to be serialized.

 Step 5 - Close the FileOutputStream and ObjectOutputStream.

Let's look at the following example program for serializing an object.

Example

import java.io.*;

public class SerializationExample {

public static void main(String[] args) {

Student stud = new Student();


stud.studName = "Rama";
stud.studBranch = "IT";

try {
FileOutputStream fos = new FileOutputStream("my_data.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);

oos.writeObject(stud);
oos.close();
fos.close();
System.out.println("The object has been saved to my_data file!");
}
catch(Exception e) {
System.out.println(e);
}
}
}

When we run the above program, it produce the following output.

Deserialization in Java
In a java programming language, the Deserialization is achieved with the help of

class ObjectInputStream. This class provides a method readObject() to deserializing an object.

We use the following steps to deserialize an object.

 Step 1 - Create a file reference with file path in which serialized object is available using

FileInputStream class.

 Step 2 - Create reference to ObjectInputStream object with file reference.

 Step 3 - Use readObject() method to access serialized object, and typecaste it to

destination type.

 Step 4 - Close the FileInputStream and ObjectInputStream.

Let's look at the following example program for deserializing an object.

Example

import java.io.*;
public class DeserializationExample {

public static void main(String[] args) throws Exception{

try {
FileInputStream fis = new FileInputStream("my_data.txt");
ObjectInputStream ois = new ObjectInputStream(fis);

Student stud2 = (Student) ois.readObject();


System.out.println("The object has been deserialized.");

fis.close();
ois.close();

System.out.println("Name = " + stud2.studName);


System.out.println("Department = " + stud2.studBranch);
}
catch(Exception e) {
System.out.println(e);
}
}
}

When we run the above program, it produce the following output.

Enum in Java
In java, an Enumeration is a list of named constants. The enum concept was introduced in Java
SE 5 version. The enum in Java programming the concept of enumeration is greatly expanded
with lot more new features compared to the other languages like C, and C++.
In java, the enumeration concept was defined based on the class concept. When we create an
enum in java, it converts into a class type. This concept enables the java enum to have
constructors, methods, and instance variables.
All the constants of an enum are public, static, and final. As they are static, we can access
directly using enum name.
The main objective of enum is to define our own data types in Java, and they are said to be
enumeration data types.

Creating enum in Java


To create enum in Java, we use the keyword enum. The syntax for creating enum is similar to
that of class.
In java, an enum can be defined outside a class, inside a class, but not inside a method.
Let's look at the following example program for creating a basic enum.
Example

enum WeekDay{
MONDAY, TUESDAY, WEDNESSDAY, THURSDAY, FRIDAY, SATURDAY,
SUNDAY;
}

public class EnumerationExample {

public static void main(String[] args) {

WeekDay day = WeekDay.FRIDAY;

System.out.println("Today is " + day);

System.out.println("\nAll WeekDays: ");


for(WeekDay d:WeekDay.values())
System.out.println(d);

}
}

When we run the above program, it produce the following output.

Every enum is converted to a class that extends the built-in class Enum.
🔔 Every constant of an enum is defined as an object.
🔔 As an enum represents a class, it can have methods, constructors. It also gets a few extra
methods from the Enum class, and one of them is the values() method.

Constructors in Java enum


In a java programming language, an enum can have both the type of constructors default and
parameterized. The execution of constructor depends on the constants we defined in the enum.
For every constant in an enum, the constructor is executed.
If an enum has a parameterized constructor, the parameter value should be passed when we
define constant.
Let's look at the following example program for illustrating constructors in enum.
Example

enum WeekDay{
MONDAY, TUESDAY, WEDNESSDAY, THURSDAY, FRIDAY, SATURDAY,
SUNDAY("Holiday");

String msg;

WeekDay(){
System.out.println("Default constructor!");
}

WeekDay(String str){
System.out.println("Parameterized constructor!");
msg = str;
}
}

public class EnumerationExample {

public static void main(String[] args) {

WeekDay day = WeekDay.SUNDAY;

System.out.println("\nToday is " + day + " and its " + day.msg);

}
When we run the above program, it produce the following output.

In the above example, the constant SUNDAY is created by calling the parameterized constructor,
other constants created by calling default constructor.

Methods in Java enum


In a java programming language, an enum can have methods. These methods are similar to the
methods of a class. All the methods defined in an enum can be used with all the constants
defined by the same enum.
Let's look at the following example program for illustrating methods in enum.
Example

enum WeekDay{
MONDAY, TUESDAY, WEDNESSDAY, THURSDAY, FRIDAY, SATURDAY,
SUNDAY("Holiday");

String msg;

WeekDay(){
System.out.println("Default constructor!");
}

WeekDay(String str){
System.out.println("Parameterized constructor!");
msg = str;
}

void printMessage() {
System.out.println("Today is also " + msg);
}
}

public class EnumerationExample {

public static void main(String[] args) {

WeekDay day = WeekDay.SUNDAY;

System.out.println("\nToday is " + day);


day.printMessage();
}
}

When we run the above program, it produce the following output.


🔔 In java, enum can not extend another enum and a class.
🔔 In java, enum can implement interfaces.
🔔 In java, enum does not allow to create an object of it.
🔔 In java, every enum extends a built-in class Enum by default.

Autoboxing and Unboxing in Java

In java, all the primitive data types have defined using the class concept, these classes known

as wrapper classes. In java, every primitive type has its corresponding wrapper class.

All the wrapper classes in Java were defined in the java.lang package.

The following table shows the primitive type and its corresponding wrapper class.

S.No. Primitive Type Wrapper class


S.No. Primitive Type Wrapper class

1 byte Byte

2 short Short

3 int Interger

4 long Long

5 float Float

6 double Double

7 char Character

8 boolean Boolean

The Java 1.5 version introduced a concept that converts primitive type to corresponding wrapper

type and reverses of it.

Autoboxing in Java

In java, the process of converting a primitive type value into its corresponding wrapper class

object is called autoboxing or simply boxing. For example, converting an int value to an Integer

class object.

The compiler automatically performs the autoboxing when a primitive type value has assigned to

an object of the corresponding wrapper class.

🔔 We can also perform autoboxing manually using the method valueOf( ), which is provided

by every wrapper class.

Let's look at the following example program for autoboxing.


Example - Autoboxing

import java.lang.*;

public class AutoBoxingExample {

public static void main(String[] args) {

// Auto boxing : primitive to Wrapper


int num = 100;
Integer i = num;
Integer j = Integer.valueOf(num);

System.out.println("num = " + num + ", i = " + i + ", j = " + j);


}
}

Auto un-boxing in Java

In java, the process of converting an object of a wrapper class type to a primitive type value is

called auto un-boxing or simply unboxing. For example, converting an Integer object to an int
value.

The compiler automatically performs the auto un-boxing when a wrapper class object has

assigned to aprimitive type.

🔔 We can also perform auto un-boxing manually using the method intValue( ), which is

provided by Integer wrapper class. Similarly every wrapper class has a method for auto un-

boxing.

Let's look at the following example program for autoboxing.


Example - Auto unboxing

import java.lang.*;

public class AutoUnboxingExample {

public static void main(String[] args) {

// Auto un-boxing : Wrapper to primitive


Integer num = 200;
int i = num;
int j = num.intValue();

System.out.println("num = " + num + ", i = " + i + ", j = " + j);

Generics in Java

The java generics is a language feature that allows creating methods and

class which can handle any type of data values. The generic programming is

a way to write generalized programs, java supports it by java generics.

The java generics is similar to the templates in the C++ programming

language.
🔔 Most of the collection framework classes are generic classes.

🔔 The java generics allows only non-primitive type, it does not support

primitive types like int, float, char, etc.

The java generics feature was introduced in Java 1.5 version. In java,

generics used angular brackets “< >”. In java, the generics feature

implemented using the following.

 Generic Method

 Generic Classe

Generic methods in Java


The java generics allows creating generic methods which can work with a

different type of data values.

Using a generic method, we can create a single method that can be called

with arguments of different types. Based on the types of the arguments

passed to the generic method, the compiler handles each method call

appropriately.

Let's look at the following example program for generic method.

Example - Generic method

public class GenericFunctions {

public <T, U> void displayData(T value1, U value2) {

System.out.println("(" + value1.getClass().getName() + ", " +


value2.getClass().getName() + ")");
}

public static void main(String[] args) {

GenericFunctions obj = new GenericFunctions();

obj.displayData(45.6f, 10);

obj.displayData(10, 10);

obj.displayData("Hi", 'c');

In the above example code, the method displayData( ) is a generic method

that allows a different type of parameter values for every function call.

Generic Class in Java


In java, a class can be defined as a generic class that allows creating a class

that can work with different types.

A generic class declaration looks like a non-generic class declaration, except

that the class name is followed by a type parameter section.

Let's look at the following example program for generic class.

Example - Generic class


public class GenericsExample<T> {

T obj;

public GenericsExample(T anotherObj) {

this.obj = anotherObj;

public T getData() {

return this.obj;

public static void main(String[] args) {

GenericsExample<Integer> actualObj1 = new


GenericsExample<Integer>(100);

System.out.println(actualObj1.getData());

GenericsExample<String> actualObj2 = new


GenericsExample<String>("Java");

System.out.println(actualObj2.getData());

GenericsExample<Float> actualObj3 = new


GenericsExample<Float>(25.9f);

System.out.println(actualObj3.getData());

}
UNIT-3
Exception Handling in Java
An exception in java programming is an abnormal situation that is araised during the program
execution. In simple words, an exception is a problem that arises at the time of program
execution.
When an exception occurs, it disrupts the program execution flow. When an exception occurs,
the program execution gets terminated, and the system generates an error. We use the exception
handling mechanism to avoid abnormal termination of program execution.
Java programming language has a very powerful and efficient exception handling mechanism
with a large number of built-in classes to handle most of the exceptions automatically.
Java programming language has the following class hierarchy to support the exception
handling mechanism.
Reasons for Exception Occurrence
Several reasons lead to the occurrence of an exception. A few of them are as follows.
When we try to open a file that does not exist may lead to an exception.
When the user enters invalid input data, it may lead to an exception.
When a network connection has lost during the program execution may lead to an exception.
When we try to access the memory beyond the allocated range may lead to an exception.
The physical device problems may also lead to an exception.
Types of Exception
In java, exceptions have categorized into two types, and they are as follows.
Checked Exception - An exception that is checked by the compiler at the time of compilation
is called a checked exception.
Unchecked Exception - An exception that can not be caught by the compiler but occurrs at
the time of program execution is called an unchecked exception.
Exception Models in Java
In java, there are two exception models. Java programming language has two models of
exception handling. The exception models that java suports are as follows.
Termination Model
Resumptive Model
Let's look into details of each exception model.
Termination Model
In the termination model, when a method encounters an exception, further processing in that
method is terminated and control is transferred to the nearest catch block that can handle the
type of exception encountered.
In other words we can say that in termination model the error is so critical there is no way to
get back to where the exception occurred.
Resumptive Model
The alternative of termination model is resumptive model. In resumptive model, the exception
handler is expected to do something to stable the situation, and then the faulting method is
retried. In resumptive model we hope to continue the execution after the exception is handled.
In resumptive model we may use a method call that want resumption like behavior. We may
also place the try block in a while loop that keeps re-entering the try block util the result is
satisfactory.
Uncaught Exceptions in Java
In java, assume that, if we do not handle the exceptions in a program. In this case, when an
exception occurs in a particular function, then Java prints a exception message with the help of
uncaught exception handler.
The uncaught exceptions are the exceptions that are not caught by the compiler but
automatically caught and handled by the Java built-in exception handler.
Java programming language has a very strong exception handling mechanism. It allow us to
handle the exception use the keywords like try, catch, finally, throw, and throws.
When an uncaught exception occurs, the JVM calls a special private method known
dispatchUncaughtException( ), on the Thread class in which the exception occurs and
terminates the thread.
The Division by zero exception is one of the example for uncaught exceptions. Look at the
following code.
Example

import java.util.Scanner;

public class UncaughtExceptionExample {

public static void main(String[] args) {

Scanner read = new Scanner(System.in);


System.out.println("Enter the a and b values: ");
int a = read.nextInt();
int b = read.nextInt();
int c = a / b;
System.out.println(a + "/" + b +" = " + c);

}
}

In the above example code, we are not used try and catch blocks, but when the value of b is
zero the division by zero exception occurs and it caught by the default exception handler.
try and catch in Java
In java, the trytry and catch, both are the keywords used for exception handling.
The keyword try is used to define a block of code that will be tests the occurence of an
exception. The keyword catch is used to define a block of code that handles the exception
occured in the respective try block.
The uncaught exceptions are the exceptions that are not caught by the compiler but
automatically caught and handled by the Java built-in exception handler.
Both try and catch are used as a pair. Every try block must have one or more catch blocks. We
can not use try without atleast one catch, and catch alone can be used (catch without try is not
allowed).
The following is the syntax of try and catch blocks.
Syntax

try{
...
code to be tested
...
}
catch(ExceptionType object){
...
code for handling the exception
...
}

Consider the following example code to illustrate try and catch blocks in Java.
Example

import java.util.Scanner;

public class TryCatchExample {

public static void main(String[] args) {

Scanner read = new Scanner(System.in);


System.out.println("Enter the a and b values: ");
try {
int a = read.nextInt();
int b = read.nextInt();
int c = a / b;
System.out.println(a + "/" + b +" = " + c);
}
catch(ArithmeticException ae) {
System.out.println("Problem info: Value of divisor can not be ZERO");
}
}
}

In the above example code, when an exception occurs in the try block the execution control
transfered to the catch block and the catch block handles it.

Multiple catch clauses


In java programming language, a try block may has one or more number of catch blocks. That
means a single try statement can have multiple catch clauses.
When a try block has more than one catch block, each catch block must contain a different
exception type to be handled.
The multipe catch clauses are defined when the try block contains the code that may lead to
different type of exceptions.
🔔 The try block generates only one exception at a time, and at a time only one catch block is
executed.
🔔 When there are multiple catch blocks, the order of catch blocks must be from the most
specific exception handler to most general.
🔔 The catch block with Exception class handler must be defined at the last.

Let's look at the following example Java code to illustrate multiple catch clauses.
Example

public class TryCatchExample {

public static void main(String[] args) {


try {
int list[] = new int[5];
list[2] = 10;
list[4] = 2;
list[10] = list[2] / list[4];
}
catch(ArithmeticException ae) {
System.out.println("Problem info: Value of divisor can not be ZERO.");
}
catch(ArrayIndexOutOfBoundsException aie) {
System.out.println("Problem info: ArrayIndexOutOfBoundsException has occured.");
}
catch(Exception e) {
System.out.println("Problem info: Unknown exception has occured.");
}
}
}

Nested try statements


The java allows to write a try statement inside another try statement. A try block within another
try block is known as nested try block.
When there are nested try blocks, each try block must have one or more seperate catch blocks.
Let's look at the following example Java code to illustrate nested try statements.
Example

public class TryCatchExample {

public static void main(String[] args) {

try {
int list[] = new int[5];
list[2] = 10;
list[4] = 2;
list[0] = list[2] / list[4];
try {
list[10] = 100;
}
catch(ArrayIndexOutOfBoundsException aie) {
System.out.println("Problem info: ArrayIndexOutOfBoundsException has
occured.");
}
}
catch(ArithmeticException ae) {
System.out.println("Problem info: Value of divisor can not be ZERO.");
}
catch(Exception e) {
System.out.println("Problem info: Unknown exception has occured.");
}
}
}

🔔 In case of nested try blocks, if an exception occured in the inner try block and it's catch
blocks are unable to handle it then it transfers the control to the outer try's catch block to handle
it.
throw, throws, and finally keywords in Java
In java, the keywords throw, throws, and finally are used in the exception handling concept.
Let's look at each of these keywords.
throw keyword in Java
The throw keyword is used to throw an exception instance explicitly from a try block to
corresponding catch block. That means it is used to transfer the control from try block to
corresponding catch block.

The throw keyword must be used inside the try blcok. When JVM encounters the throw
keyword, it stops the execution of try block and jump to the corresponding catch block.

🔔 Using throw keyword only object of Throwable class or its sub classes can be thrown.
🔔 Using throw keyword only one exception can be thrown.
🔔 The throw keyword must followed by an throwable instance.
The following is the general syntax for using throw keyword in a try block.
Syntax

throw instance;

Here the instace must be throwable instance and it can be created dynamically using new
operator.
Let's look at the following example Java code to illustrate throw keyword.
Example

import java.util.Scanner;

public class Sample {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);


int num1, num2, result;
System.out.print("Enter any two numbers: ");
num1 = input.nextInt();
num2 = input.nextInt();
try {
if(num2 == 0)
throw new ArithmeticException("Division by zero is not posible");
result = num1 / num2;
System.out.println(num1 + "/" + num2 + "=" + result);
}
catch(ArithmeticException ae) {
System.out.println("Problem info: " + ae.getMessage());
}
System.out.println("End of the program");
}
}

throws keyword in Java


The throws keyword specifies the exceptions that a method can throw to the default handler
and does not handle itself. That means when we need a method to throw an exception
automatically, we use throws keyword followed by method declaration

🔔 When a method throws an exception, we must put the calling statement of method in try-
catch block.

Example

import java.util.Scanner;

public class ThrowsExample {


int num1, num2, result;
Scanner input = new Scanner(System.in);
void division() throws ArithmeticException {
System.out.print("Enter any two numbers: ");
num1 = input.nextInt();
num2 = input.nextInt();
result = num1 / num2;
System.out.println(num1 + "/" + num2 + "=" + result);
}
public static void main(String[] args) {
try {
new ThrowsExample().division();
}
catch(ArithmeticException ae) {
System.out.println("Problem info: " + ae.getMessage());
}
System.out.println("End of the program");
}
}

Built-in Exceptions in Java


The Java programming language has several built-in exception class that support exception
handling. Every exception class is suitable to explain certain error situations at run time.
All the built-in exception classes in Java were defined a package java.lang.
Few built-in exceptions in Java are shown in the following image.

List of checked exceptions in Java


The following table shows the list of several checked exceptions.
S.
No. Exception Class with Description

1 ClassNotFoundException

It is thrown when the Java Virtual Machine (JVM) tries to load a particular class and the
specified class cannot be found in the classpath.

2 CloneNotSupportedException
Used to indicate that the clone method in class Object has been called to clone an object,
but that the object's class does not implement the Cloneable interface.

3 IllegalAccessException
It is thrown when one attempts to access a method or member that visibility qualifiers do
not allow.

4 InstantiationException
It is thrown when an application tries to create an instance of a class using the newInstance
method in class Class , but the specified class object cannot be instantiated because it is an
interface or is an abstract class.

5 InterruptedException
It is thrown when a thread that is sleeping, waiting, or is occupied is interrupted.

6 NoSuchFieldException
It indicates that the class doesn't have a field of a specified name.

7 NoSuchMethodException
It is thrown when some JAR file has a different version at runtime that it had at compile
time, a NoSuchMethodException occurs during reflection when we try to access a method
that does not exist.

List of unchecked exceptions in Java


The following table shows the list of several unchecked exceptions.
S.
No. Exception Class with Description

1 ArithmeticException

It handles the arithmetic exceptions like dividion by zero

2 ArrayIndexOutOfBoundsException
It handles the situations like an array has been accessed with an illegal index. The index is
either negative or greater than or equal to the size of the array.

3 ArrayStoreException
It handles the situations like when an attempt has been made to store the wrong type of object
into an array of objects

4 AssertionError
It is used to indicate that an assertion has failed

5 ClassCastException
It handles the situation when we try to improperly cast a class from one type to another.

6 IllegalArgumentException
This exception is thrown in order to indicate that a method has been passed an illegal or
inappropriate argument.

7 IllegalMonitorStateException
This indicates that the calling thread has attempted to wait on an object's monitor, or has
attempted to notify other threads that wait on an object's monitor, without owning the specified
monitor.

8 IllegalStateException
It signals that a method has been invoked at an illegal or inappropriate time.

9 IllegalThreadStateException
It is thrown by the Java runtime environment, when the programmer is trying to modify the
state of the thread when it is illegal.

10 IndexOutOfBoundsException
It is thrown when attempting to access an invalid index within a collection, such as an array ,
vector , string , and so forth.

11 NegativeArraySizeException
It is thrown if an applet tries to create an array with negative size.
S.
No. Exception Class with Description

12 NullPointerException
it is thrown when program attempts to use an object reference that has the null value.

13 NumberFormatException
It is thrown when we try to convert a string into a numeric value such as float or integer, but
the format of the input string is not appropriate or illegal.

14 SecurityException
It is thrown by the Java Card Virtual Machine to indicate a security violation.

15 StringIndexOutOfBounds
It is thrown by the methods of the String class, in order to indicate that an index is either
negative, or greater than the size of the string itself.

16 UnsupportedOperationException
It is thrown to indicate that the requested operation is not supported.

Creating Own Exceptions in Java


The Java programming language allow us to create our own exception classes which are
basically subclasses built-in class Exception.
To create our own exception class simply create a class as a subclass of built-in Exception
class.
We may create constructor in the user-defined exception class and pass a string to Exception
class constructor using super(). We can use getMessage() method to access the string.
Let's look at the following Java code that illustrates the creation of user-defined exception.
Example

import java.util.Scanner;

class NotEligibleException extends Exception{


NotEligibleException(String msg)
{
super(msg);
}
}
class VoterList{
int age;
VoterList(int age){
this.age = age;
}

void checkEligibility() {
try {
if(age < 18) {
throw new NotEligibleException("Error: Not eligible for vote due to under age.");
}
System.out.println("Congrates! You are eligible for vote.");
}
catch(NotEligibleException nee) {
System.out.println(nee.getMessage());
}
}
public static void main(String args[]) {

Scanner input = new Scanner(System.in);


System.out.println("Enter your age in years: ");
int age = input.nextInt();
VoterList person = new VoterList(age);
person.checkEligibility();
}
}

Multithreading in java
The java programming language allows us to create a program that contains one or more parts
that can run simultaneously at the same time. This type of program is known as a multithreading
program. Each part of this program is called a thread. Every thread defines a separate path of
execution in java. A thread is explained in different ways, and a few of them are as specified
below.
A thread is a light wieght process.
A thread may also be defined as follows.
A thread is a subpart of a process that can run individually.

In java, multiple threads can run at a time, which enables the java to write multitasking
programs. The multithreading is a specialized form of multitasking. All modern operating
systems support multitasking.
There are two types of multitasking, and they are as follows.
Process-based multitasking
Thread-based multitasking
It is important to know the difference between process-based and thread-based multitasking.
Let's distinguish both.

Process-based multitasking Thread-based multitasking

It allows the computer to run two or more It allows the computer to run two or more
programs concurrently threads concurrently

In this process is the smallest unit. In this thread is the smallest unit.

Process is a larger unit. Thread is a part of process.

Process is heavy weight. Thread is light weight.

Process requires seperate address space for each. Threads share same address space.

Process never gain access over idle time of CPU. Thread gain access over idle time of CPU.

Inter process communication is expensive. Inter thread communication is not expensive.

Java Thread Model


The java programming language allows us to create a program that contains one or more parts
that can run simultaneously at the same time. This type of program is known as a multithreading
program. Each part of this program is called a thread. Every thread defines a separate path of
execution in java. A thread is explained in different ways, and a few of them are as specified
below.
A thread is a light wieght process.

A thread may also be defined as follows.


A thread is a subpart of a process that can run individually.
In java, a thread goes through different states throughout its execution. These stages are called
thread life cycle states or phases. A thread may in any of the states like new, ready or runnable,
running, blocked or wait, and dead or terminated state. The life cycle of a thread in java is
shown in the following figure.

Let's look at each phase indetailed.

New
When a thread object is created using new, then the thread is said to be in the New state. This
state is also known as Born state.

Example
Thread t1 = new Thread();

Runnable / Ready
When a thread calls start( ) method, then the thread is said to be in the Runnable state. This
state is also known as a Ready state.

Example
t1.start( );

Running
When a thread calls run( ) method, then the thread is said to be Running. The run( ) method of
a thread called automatically by the start( ) method.

Blocked / Waiting
A thread in the Running state may move into the blocked state due to various reasons like sleep(
) method called, wait( ) method called, suspend( ) method called, and join( ) method called,
etc.
When a thread is in the blocked or waiting state, it may move to Runnable state due to reasons
like sleep time completed, waiting time completed, notify( ) or notifyAll( ) method called,
resume( ) method called, etc.

Example
Thread.sleep(1000);
wait(1000);
wait();
suspened();
notify();
notifyAll();
resume();

Dead / Terminated
A thread in the Running state may move into the dead state due to either its execution
completed or the stop( ) method called. The dead state is also known as the terminated state.

Creating threads in java


In java, a thread is a lightweight process. Every java program executes by a thread called the
main thread. When a java program gets executed, the main thread created automatically. All
other threads called from the main thread.
The java programming language provides two methods to create threads, and they are listed
below.

 Using Thread class (by extending Thread class)


 Uisng Runnable interface (by implementing Runnable interface)

Let's see how to create threads using each of the above.

Extending Thread class


The java contains a built-in class Thread inside the java.lang package. The Thread class
contains all the methods that are related to the threads.
To create a thread using Thread class, follow the step given below.

 Step-1: Create a class as a child of Thread class. That means, create a class that extends
Thread class.
 Step-2: Override the run( ) method with the code that is to be executed by the thread.
The run( ) method must be public while overriding.
 Step-3: Create the object of the newly created class in the main( ) method.
 Step-4: Call the start( ) method on the object created in the above step.

Look at the following example program.

Example
class SampleThread extends Thread{

public void run() {


System.out.println("Thread is under Running...");
for(int i= 1; i<=10; i++) {
System.out.println("i = " + i);
}
}
}

public class My_Thread_Test {

public static void main(String[] args) {


SampleThread t1 = new SampleThread();
System.out.println("Thread about to start...");
t1.start();
}
}

Implementng Runnable interface


The java contains a built-in interface Runnable inside the java.lang package. The Runnable
interface implemented by the Thread class that contains all the methods that are related to the
threads.
To create a thread using Runnable interface, follow the step given below.

 Step-1: Create a class that implements Runnable interface.


 Step-2: Override the run( ) method with the code that is to be executed by the thread.
The run( ) method must be public while overriding.
 Step-3: Create the object of the newly created class in the main( ) method.
 Step-4: Create the Thread class object by passing above created object as parameter to
the Thread class constructor.
 Step-5: Call the start( ) method on the Thread class object created in the above step.

Look at the following example program.

Example
class SampleThread implements Runnable{

public void run() {


System.out.println("Thread is under Running...");
for(int i= 1; i<=10; i++) {
System.out.println("i = " + i);
}
}
}

public class My_Thread_Test {

public static void main(String[] args) {


SampleThread threadObject = new SampleThread();
Thread thread = new Thread(threadObject);
System.out.println("Thread about to start...");
thread.start();
}
}

More about Thread class


The Thread class in java is a subclass of Object class and it implements Runnable interface.
The Thread class is available inside the java.lang package. The Thread class has the following
syntax.

class Thread extends Object implements Runnable{


...
}

The Thread class has the following consructors.

 Thread( )
 Thread( String threadName )
 Thread( Runnable objectName )
 Thread( Runnable objectName, String threadName )

The Thread classs contains the following methods.


Return
Method Description Value

run( ) Defines actual task of the thread. void

start( ) It moves thre thread from Ready state to Running state by void
calling run( ) method.

setName(String) Assigns a name to the thread. void

getName( ) Returns the name of the thread. String

setPriority(int) Assigns priority to the thread. void

getPriority( ) Returns the priority of the thread. int

getId( ) Returns the ID of the thread. long

activeCount() Returns total number of thread under active. int

currentThread( ) Returns the reference of the thread that currently in running void
state.

sleep( long ) moves the thread to blocked state till the specified number void
of milliseconds.

isAlive( ) Tests if the thread is alive. boolean

yield( ) Tells to the scheduler that the current thread is willing to void
yield its current use of a processor.

join( ) Waits for the thread to end. void


The Thread class in java also contains methods like stop( ), destroy( ), suspend( ),
and resume( ). But they are depricated.

Java Thread Priority


In a java programming language, every thread has a property called priority. Most of the
scheduling algorithms use the thread priority to schedule the execution sequence. In java, the
thread priority range from 1 to 10. Priority 1 is considered as the lowest priority, and priority
10 is considered as the highest priority. The thread with more priority allocates the processor
first.
The java programming language Thread class provides two methods setPriority(int),
and getPriority( ) to handle thread priorities.
The Thread class also contains three constants that are used to set the thread priority, and they
are listed below.

 MAX_PRIORITY - It has the value 10 and indicates highest priority.


 NORM_PRIORITY - It has the value 5 and indicates normal priority.
 MIN_PRIORITY - It has the value 1 and indicates lowest priority.

🔔 The default priority of any thread is 5 (i.e. NORM_PRIORITY).

setPriority( ) method
The setPriority( ) method of Thread class used to set the priority of a thread. It takes an integer
range from 1 to 10 as an argument and returns nothing (void).
The regular use of the setPriority( ) method is as follows.

Example
threadObject.setPriority(4);
or
threadObject.setPriority(MAX_PRIORITY);

getPriority( ) method
The getPriority( ) method of Thread class used to access the priority of a thread. It does not
takes anyargument and returns name of the thread as String.
The regular use of the getPriority( ) method is as follows.

Example
String threadName = threadObject.getPriority();

Look at the following example program.

Example
class SampleThread extends Thread{
public void run() {
System.out.println("Inside SampleThread");
System.out.println("Current Thread: " +
Thread.currentThread().getName());
}
}

public class My_Thread_Test {

public static void main(String[] args) {


SampleThread threadObject1 = new SampleThread();
SampleThread threadObject2 = new SampleThread();
threadObject1.setName("first");
threadObject2.setName("second");

threadObject1.setPriority(4);
threadObject2.setPriority(Thread.MAX_PRIORITY);

threadObject1.start();
threadObject2.start();

}
}
The java programming language supports multithreading. The problem of shared resources
occurs when two or more threads get execute at the same time. In such a situation, we need
some way to ensure that the shared resource will be accessed by only one thread at a time, and
this is performed by using the concept called synchronization.
🔔 The synchronization is the process of allowing only one thread to access a shared resource
at a time.
In java, the synchronization is achieved using the following concepts.

 Mutual Exclusion
 Inter thread communication

Mutual Exclusion
Using the mutual exclusion process, we keep threads from interfering with one another while
they accessing the shared resource. In java, mutual exclusion is achieved using the following
concepts.

 Synchronized method
 Synchronized block

Synchronized method
When a method created using a synchronized keyword, it allows only one object to access it at
a time. When an object calls a synchronized method, it put a lock on that method so that other
objects or thread that are trying to call the same method must wait, until the lock is released.
Once the lock is released on the shared resource, one of the threads among the waiting threads
will be allocated to the shared resource.

In the above image, initially the thread-1 is accessing the synchronized method and other threads
(thread-2, thread-3, and thread-4) are waiting for the resource (synchronized method). When thread-1
completes it task, then one of the threads that are waiting is allocated with the synchronized method, in
the above it is thread-3.

Example
class Table{
synchronized void printTable(int n) {
for(int i = 1; i <= 10; i++)
System.out.println(n + " * " + i + " = " + i*n);
}
}
class MyThread_1 extends Thread{
Table table = new Table();
int number;
MyThread_1(Table table, int number){
this.table = table;
this.number = number;
}
public void run() {
table.printTable(number);
}
}

class MyThread_2 extends Thread{

Table table = new Table();


int number;
MyThread_2(Table table, int number){
this.table = table;
this.number = number;
}
public void run() {
table.printTable(number);
}
}
public class ThreadSynchronizationExample {

public static void main(String[] args) {


Table table = new Table();
MyThread_1 thread_1 = new MyThread_1(table, 5);
MyThread_2 thread_2 = new MyThread_2(table, 10);
thread_1.start();
thread_2.start();
}
}

Output:

Synchronized block
The synchronized block is used when we want to synchronize only a specific sequence of lines
in a method. For example, let's consider a method with 20 lines of code where we want to
synchronize only a sequence of 5 lines code, we use the synchronized block.
The folllowing syntax is used to define a synchronized block.

Syntax
synchronized(object){
...
block code
...
}

Example
import java.util.*;

class NameList {
String name = "";
public int count = 0;

public void addName(String name, List<String> namesList){


synchronized(this){
this.name = name;
count++;
}
namesList.add(name);
}

public int getCount(){


return count;
}
}
public class SynchronizedBlockExample {
public static void main (String[] args)
{
NameList namesList_1 = new NameList();
NameList namesList_2 = new NameList();
List<String> list = new ArrayList<String>();
namesList_1.addName("Rama", list);
namesList_2.addName("Seetha", list);
System.out.println("Thread1: " + namesList_1.name + ", " +
namesList_1.getCount() + "\n");
System.out.println("Thread2: " + namesList_2.name + ", " +
namesList_2.getCount() + "\n");
}
}

Output:

🔔 The complete code of a method may be written inside the synchronized block, where it works
similarly to the synchronized method.

Java Inter Thread Communication


Inter thread communication is the concept where two or more threads communicate to solve
the problem of polling. In java, polling is the situation to check some condition repeatedly, to
take appropriate action, once the condition is true. That means, in inter-thread communication,
a thread waits until a condition becomes true such that other threads can execute its task. The
inter-thread communication allows the synchronized threads to communicate with each other.
Java provides the following methods to achieve inter thread communication.

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

The following table gives detailed description about the above methods.
Method Description

void wait( ) It makes the current thread to pause its execution until other thread in the same monitor

void notify( ) It wakes up the thread that called wait( ) on the same object.

void notifyAll() It wakes up all the threads that called wait( ) on the same object.

🔔 Calling notify( ) or notifyAll( ) does not actually give up a lock on a resource.


Let's look at an example problem of producer and consumer. The producer produces the item
and the consumer consumes the same. But here, the consumer can not consume until the
producer produces the item, and producer can not produce until the consumer consumes the
item that already been produced. So here, the consumer has to wait until the producer produces
the item, and the producer also needs to wait until the consumer consumes the same. Here we
use the inter-thread communication to implement the producer and consumer problem.
The sample implementation of producer and consumer problem is as follows.

Example
class ItemQueue {
int item;
boolean valueSet = false;

synchronized int getItem()

{
while (!valueSet)
try {
wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Consummed:" + item);
valueSet = false;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
notify();
return item;
}

synchronized void putItem(int item) {


while (valueSet)
try {
wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
this.item = item;
valueSet = true;
System.out.println("Produced: " + item);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
notify();
}
}

class Producer implements Runnable{


ItemQueue itemQueue;
Producer(ItemQueue itemQueue){
this.itemQueue = itemQueue;
new Thread(this, "Producer").start();
}
public void run() {
int i = 0;
while(true) {
itemQueue.putItem(i++);
}
}
}
class Consumer implements Runnable{

ItemQueue itemQueue;
Consumer(ItemQueue itemQueue){
this.itemQueue = itemQueue;
new Thread(this, "Consumer").start();
}
public void run() {
while(true) {
itemQueue.getItem();
}
}
}

class ProducerConsumer{
public static void main(String args[]) {
ItemQueue itemQueue = new ItemQueue();
new Producer(itemQueue);
new Consumer(itemQueue);

}
}

Output:
🔔 All the methods wait( ), notify( ), and notifyAll( ) can be used only inside the synchronized methods
only.
StringTokenizer
The java.util.StringTokenizer class allows you to break a String into tokens.

It is simple way to break a String. It is a legacy class of Java.

It doesn't provide the facility to differentiate numbers, quoted strings, identifiers

etc. like StreamTokenizer class.

In the StringTokenizer class, the delimiters can be provided at the time of creation

or one by one to the tokens.

Constructors of the StringTokenizer Class


There are 3 constructors defined in the StringTokenizer class.

StringTokenizer(String str)---- It creates StringTokenizer with specified string.

StringTokenizer(String str, String delim)---- It creates StringTokenizer with specified string and
delimiter.

StringTokenizer(String str, String delim, boolean returnValue)

---It creates StringTokenizer with specified string, delimiter and returnValue. If return value is true,
delimiter characters are considered to be tokens. If it is false, delimiter characters serve to separate

tokens.
Methods of the StringTokenizer Class
The six useful methods of the StringTokenizer class are as follows:

boolean hasMoreTokens() It checks if there is more tokens available.

String nextToken() It returns the next token from the StringTokenizer object.

String nextToken(String delim) It returns the next token based on the delimiter.

boolean hasMoreElements() It is the same as hasMoreTokens() method.

Object nextElement() It is the same as nextToken() but its return type is Object.

int countTokens() It returns the total number of tokens.

Example of StringTokenizer Class

Let's see an example of the StringTokenizer class that tokenizes a string "my name is Praveen" on the
basis of whitespace.

import java.util.StringTokenizer;
public class Simple{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("my name is praveen"," ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}

Java BitSet Class

The Java BitSet class implements a vector of bits. The BitSet grows automatically as more bits are
needed. The BitSet class comes under java.util package. The BitSet class extends the Object class and
provides the implementation of Serializable and Cloneable interfaces.

Each component of bit set contains at least one Boolean value. The contents of one BitSet may be
changed by other BitSet using logical AND, logical OR and logical exclusive OR operations. The index
of bits of BitSet class is represented by positive integers.

Each element of bits contains either true or false value. Initially, all bits of a set have the false value. A
BitSet is not safe for multithreaded use without using external synchronization.

Java BitSet and() method

The and() method of Java BitSet class is used to perform a logical AND operation of this target bit set
with the specified set argument. The value of bit set is true if and only if the bit set of both initially and
the corresponding bit argument has the true value.

Syntax:
public void and(BitSet set)

import java.util.BitSet;
public class BitSetAndExample1 {
public static void main(String[] args) {
// create 2 bitsets
BitSet bitset1 = new BitSet();
BitSet bitset2 = new BitSet();

// assign values to bitset1


bitset1.set(0);
bitset1.set(1);
bitset1.set(2);
bitset1.set(3);
bitset1.set(4);

// assign values to bitset2


bitset2.set(2);
bitset2.set(4);
bitset2.set(6);
bitset2.set(8);
bitset2.set(10);

// print the sets


System.out.println("bitset1: " + bitset1);
System.out.println("bitset2: " + bitset2);

// perform and operation between two bitsets


bitset1.and(bitset2);
// print the new bitset1
System.out.println("result bitset: " + bitset1);
}
}

Java BitSet or() method

The or(BitSet set) method of Java BitSet class is used to perform a logical OR operation of this bit set
with the specified set argument. The value of bit set is modified so that each bit in it has true if and only
if the bit set of either initially or the corresponding bit argument has the true value.

Syntax:
1. public void or(BitSet set)

import java.util.BitSet;

public class BitSetOrExample1 {

public static void main(String[] args) {

// create 2 bitsets

BitSet bitset1 = new BitSet();

BitSet bitset2 = new BitSet();


// assign values to bitset1

bitset1.set(0);

bitset1.set(1);

bitset1.set(4);

bitset1.set(6);

bitset1.set(7);

// assign values to bitset2

bitset2.set(2);

bitset2.set(4);

bitset2.set(6);

bitset2.set(8);

bitset2.set(10);

// print the sets

System.out.println("bitset1: " + bitset1);

System.out.println("bitset2: " + bitset2);

// perform or operation between two bitsets

bitset1.or(bitset2);

// print the new bitset1

System.out.println("or operation between bitsets: " + bitset1);

Java BitSet xor() method

The xor(BitSet set) method of Java BitSet class is used to perform a logical XOR operation on the set
bits of this set with specified set argument. The value of bit set is modified so that each bit in it has true
if and only if any one of the following statements satisfies:

o If the initial bit value holds true and the corresponding bit in the argument holds false value.
o If the initial bit value holds false and the corresponding bit in the argument holds true value.
Syntax:
public void xor(BitSet set)

import java.util.BitSet;
public class BitSetXorExample1 {
public static void main(String[] args) {
BitSet bitset1 = new BitSet();
BitSet bitset2 = new BitSet();

bitset1.set(0);
bitset1.set(1);
bitset1.set(4);
bitset1.set(6);
bitset1.set(7);

bitset2.set(2);
bitset2.set(4);
bitset2.set(6);
bitset2.set(8);
bitset2.set(10);

System.out.println("bitset1: " + bitset1);


System.out.println("bitset2: " + bitset2);

// perform xor operation between two bitsets


bitset1.xor(bitset2);
// print the new bitset1
System.out.println("xor operation between bitsets: " + bitset1);
}
}

java.util.Date
The java.util.Date class represents date and time in java. It provides constructors and methods
to deal with date and time in java.

The java.util.Date class implements Serializable, Cloneable and Comparable<Date> interface. It


is inherited by java.sql.Date, java.sql.Time and java.sql.Timestamp interfaces.

After Calendar class, most of the constructors and methods of java.util.Date class has been
deprecated. Here, we are not giving list of any deprecated constructor and method.
java.util.Date Constructors

No. Constructor Description

1) Date() Creates a date object representing current date and time.

2) Date(long Creates a date object for the given milliseconds since January 1,
milliseconds) 1970, 00:00:00 GMT.

Java.util.Date Methods

1. boolean after (Date date)---- tests if current date is after the given date.

2. boolean before (Date date)--- tests if current date is before the given date.

3. void setTime(long time)--- changes the current date and time to given time.

4. int compareTo(Date date)-- compares current date with given date.

public class UtilDateExample1{

public static void main(String args[]){

java.util.Date date=new java.util.Date();

System.out.println(date);

}}

public class UtilDateExample1{

public static void main(String args[]){

java.util.Date date=new java.util.Date();

System.out.println(date);

}}
Java Calendar Class
Java Calendar class is an abstract class that provides methods for converting date between a
specific instant in time and a set of calendar fields such as MONTH, YEAR, HOUR, etc. It inherits
Object class and implements the Comparable interface.

import java.util.Calendar;

public class CalendarExample1 {

public static void main(String[] args) {

Calendar calendar = 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("2 years later: " + calendar.getTime());

Java Calendar Class Example: get()

import java.util.*;

public class CalendarExample2{

public static void main(String[] args) {

Calendar calendar = Calendar.getInstance();

System.out.println("At present Calendar's Year: " + calendar.get(Calendar.YEAR));

System.out.println("At present Calendar's Day: " + calendar.get(Calendar.DATE));

}
Random class in java

The Random class is a part of java.util package.

🔔 The Random class provides several methods to generate random numbers of type integer, double,
long, float etc.

🔔 The Random class is thread-safe.

Random()

It creates a new random number generator.

Random(long seedValue)

It creates a new random number generator using a single long seedValue.

import java.util.Random;

public class RandomClassExample {

public static void main(String[] args) {

Random rand = new Random();

System.out.println("Integer random number - " + rand.nextInt());

System.out.println("Integer random number from 0 to 100 - " + rand.nextInt(100));

System.out.println("Boolean random value - " + rand.nextBoolean());

System.out.println("Double random number - " + rand.nextDouble());

System.out.println("Float random number - " + rand.nextFloat());

System.out.println("Long random number - " + rand.nextLong());

System.out.println("Gaussian random number - " + rand.nextGaussian());

}
Formatter class in java
The Formatter is a built-in class in java used for layout justification and alignment, common formats for
numeric, string, and date/time data, and locale-specific output in java programming. The Formatter class
is defined as final class inside the java.util package.

Constructors:
Formatter()
It creates a new formatter.

Formatter(Appendable a)
It creates a new formatter with the specified destination.

Formatter(Appendable a, Locale l)
It creates a new formatter with the specified destination and locale.

Formatter(File file)
It creates a new formatter with the specified file.

Methods:

Formatter format(String format, Object... args)


It writes a formatted string to the invoking object's destination using the specified format string and
arguments.

void flush()
It flushes the invoking formatter.

Appendable out()
It returns the destination for the output.

Locale locale()
It returns the locale set by the construction of the invoking formatter.

String toString()
It converts the invoking object to string.

IOException ioException()
It returns the IOException last thrown by the invoking formatter's Appendable.
void close()
It closes the invoking

Using Formatter
Once the Formatter object is created, it may be used in many ways. The format specifier
specifies the way the data is formatted. Refer to the Java API Documentation for complete
documentation on them. A few common format specifiers are:

 %S or %s: Specifies String


 %X or %x: Specifies hexadecimal integer
 %o: Specifies Octal integer
 %d: Specifies Decimal integer
 %c: Specifies character
 %T or %t: Specifies Time and date
 %n: Inserts newline character
 %B or %b: Specifies Boolean
 %A or %a: Specifies floating point hexadecimal
 %f: Specifies Decimal floating point

import java.util.*;

public class FormatterClassExample {

public static void main(String[] args) {

Formatter formatter=new Formatter();

formatter.format("%2$5s %1$5s %3$5s", "Smart", "BTech", "Class");

System.out.println(formatter);

formatter = new Formatter();

formatter.format(Locale.FRANCE,"%.5f", -1325.789);

System.out.println(formatter);
String name = "Java";

formatter = new Formatter();

formatter.format(Locale.US,"Hello %s !", name);

System.out.println("" + formatter + " " + formatter.locale());

formatter = new Formatter();

formatter.format("%.4f", 123.1234567);

System.out.println("Decimal floating-point notation to 4 places: " + formatter);

formatter = new Formatter();

formatter.format("%010d", 88);

System.out.println("value in 10 digits: " + formatter);

}
Scanner class in java
The Scanner is a built-in class in java used for read the input from the user in java programming. The
Scanner class is defined inside the java.util package.

The Scanner class implements Iterator interface.

The Scanner class provides the easiest way to read input in a Java program.

The Scanner object breaks its input into tokens using a delimiter pattern, the default delimiter is
whitespace.

The Scanner class in java has the following constructors.

S.No. Constructor with Description

1 Scanner(InputStream source)

It creates a new Scanner that produces values read from the specified input stream.

2 Scanner(InputStream source, String charsetName)

It creates a new Scanner that produces values read from the specified input stream.

3 Scanner(File source)

It creates a new Scanner that produces values scanned from the specified file.

4 Scanner(File source, String charsetName)

It creates a new Scanner that produces values scanned from the specified file.

5 Scanner(String source)

It creates a new Scanner that produces values scanned from the specified string.

6 Scanner(Readable source)

It creates a new Scanner that produces values scanned from the specified source.

7 Scanner(ReadableByteChannel source)

It creates a new Scanner that produces values scanned from the specified channel.
8 Scanner(ReadableByteChannel source, String charsetName)

It creates a new Scanner that produces values scanned from the specified channel.

The Scanner class in java has the following methods.

S.No. Methods with Description

1 String next()

It reads the next complete token from the invoking scanner.

2 String next(Pattern pattern)

It reads the next token if it matches the specified pattern.

3 String next(String pattern)

It reads the next token if it matches the pattern constructed from the specified string.

4 boolean nextBoolean()

It reads a boolean value from the user.

5 byte nextByte()

It reads a byte value from the user.

6 double nextDouble()

It reads a double value from the user.

7 float nextFloat()

It reads a floating-point value from the user.

8 int nextInt()

It reads an integer value from the user.

9 long nextLong()

It reads a long value from the user.

10 short nextShort()

It reads a short value from the user.

11 String nextLine()
It reads a string value from the user.

12 boolean hasNext()

It returns true if the invoking scanner has another token in its input.

13 void remove()

It is used when remove operation is not supported by this implementation of Iterator.

14 void close()

It closes the invoking scanner.

import java.util.Scanner;

public class ScannerClassExample {

public static void main(String[] args) {

Scanner read = new Scanner(System.in); // Input stream is used

System.out.print("Enter any name: ");

String name = read.next();

System.out.print("Enter your age in years: ");

int age = read.nextInt();

System.out.print("Enter your salary: ");

double salary = read.nextDouble();

System.out.print("Enter any message: ");

read = new Scanner(System.in);

String msg = read.nextLine();

System.out.println("\n------------------------------------------");

System.out.println("Hello, " + name);

System.out.println("You are " + age + " years old.");


System.out.println("You are earning Rs." + salary + " per month.");

System.out.println("Words from " + name + " - " + msg);

}
Java AWT
Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface
(GUI) or windows-based applications in Java.
Java AWT components are platform-dependent i.e. components are displayed according to
the view of operating system. AWT is heavy weight i.e. its components are using the
resources of underlying operating system (OS).
The java.awt package provides classes for AWT API such as TextField, Label,
TextArea, RadioButton, CheckBox, Choice, List etc.
Why AWT is platform independent?
Java AWT calls the native platform calls the native platform (operating systems) subroutine
for creating API components like TextField, ChechBox, button, etc.
For example, an AWT GUI with components like TextField, label and button will have
different look and feel for the different platforms like Windows, MAC OS, and Unix. The
reason for this is the platforms have different view for their native components and AWT
directly calls the native subroutine that creates those components.

Java AWT Hierarchy

The hierarchy of Java AWT classes are given below.


Components
All the elements like the button, text fields, scroll bars, etc. are called components. In Java
AWT, there are classes for each component as shown in above diagram. In order to place
every component in a particular position on a screen, we need to add them to a container.
Container
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container
such as Frame, Dialog and Panel.
It is basically a screen where the where the components are placed at their specific locations.
Thus it contains and controls the layout of components.
There are four types of containers in Java AWT:
Window
Panel
Frame
Dialog
Window
The window is the container that have no borders and menu bars. You must use frame, dialog
or another window for creating a window. We need to create an instance of Window class to
create this container.
Panel
The Panel is the container that doesn't contain title bar, border or menu bar. It is generic
container for holding the components. It can have other components like button, text field etc.
An instance of Panel class creates a container, in which we can add components.
Frame
The Frame is the container that contain title bar and border and can have menu bars. It can
have other components like button, text field, scrollbar etc. Frame is most widely used
container while developing an AWT application
Useful Methods of Component Class

Method Description

public void add(Component c) Inserts a component on this component.

public void setSize(int width,int height) Sets the size (width and height) of the component.

public void setLayout(LayoutManager m) Defines the layout manager for the component.

public void setVisible(boolean status) Changes the visibility of the component, by


default false.

Java AWT Example


To create simple AWT example, you need a frame. There are two ways to create a GUI using
Frame in AWT.
1.By extending Frame class (inheritance)
2.By creating the object of Frame class (association)
AWT Example by Inheritance

1. // importing Java AWT class


2. import java.awt.*;

3. // extending Frame class to our class AWTExample1


4. public class AWTExample1 extends Frame {
5. // initializing using constructor
6. AWTExample1() {
7. // creating a button
8. Button b = new Button("Click Me!!");
9. // setting button position on screen
10. b.setBounds(30,100,80,30);
11. // adding button into frame
12. add(b);
13. // frame size 300 width and 300 height
14. setSize(300,300);
15. // setting the title of Frame
16. setTitle("This is our basic AWT example");
17.
18. // no layout manager
19. setLayout(null);
20.
21. // now frame will be visible, by default it is not visible
22. setVisible(true);
23. }
24. // main method
25. public static void main(String args[]) {
26. // creating instance of Frame class
27. AWTExample1 f = new AWTExample1();
28. }
29. }

Output:

AWT Example by Association


Let's see a simple example of AWT where we are creating instance of Frame class. Here, we
are creating a TextField, Label and Button component on the Frame.
AWTExample2.java

1. // importing Java AWT class


2. import java.awt.*;
3.
4. // class AWTExample2 directly creates instance of Frame class
5. class AWTExample2 {
6.
7. // initializing using constructor
8. AWTExample2() {
9.
10. // creating a Frame
11. Frame f = new Frame();
12.
13. // creating a Label
14. Label l = new Label("Employee id:");
15.
16. // creating a Button
17. Button b = new Button("Submit");
18.
19. // creating a TextField
20. TextField t = new TextField();
21.
22. // setting position of above components in the frame
23. l.setBounds(20, 80, 80, 30);
24. t.setBounds(20, 100, 80, 30);
25. b.setBounds(100, 100, 80, 30);
26.
27. // adding components into frame
28. f.add(b);
29. f.add(l);
30. f.add(t);
31.
32. // frame size 300 width and 300 height
33. f.setSize(400,300);
34.
35. // setting the title of frame
36. f.setTitle("Employee info");
37.
38. // no layout
39. f.setLayout(null);
40.
41. // setting visibility of frame
42. f.setVisible(true);
43. }
44.
45. // main method
46. public static void main(String args[]) {
47.
48. // creating instance of Frame class
49. AWTExample2 awt_obj = new AWTExample2();
50.
51. }
52.
53. }
Output:
MVC Architecture in Java
The Model-View-Controller (MVC) is a well-known design pattern in the web development
field. It is way to organize our code. It specifies that a program or application shall consist of
data model, presentation information and control information. The MVC pattern needs all
these components to be separated as different objects.
In this section, we will discuss the MVC Architecture in Java, along with its advantages and
disadvantages and examples to understand the implementation of MVC in Java.
What is MVC architecture in Java?
The model designs based on the MVC architecture follow MVC design pattern. The
application logic is separated from the user interface while designing the software using
model designs.
The MVC pattern architecture consists of three layers:
Model: It represents the business layer of application. It is an object to carry the data that can
also contain the logic to update controller if data is changed.
View: It represents the presentation layer of application. It is used to visualize the data that
the model contains.
Controller: It works on both the model and view. It is used to manage the flow of
application, i.e. data flow in the model object and to update the view whenever data is
changed.
In Java Programming, the Model contains the simple Java classes, the View used to display
the data and the Controller contains the servlets. Due to this separation the user requests are
processed as follows:

1.A client (browser) sends a request to the controller on the server side, for a page.
2.The controller then calls the model. It gathers the requested data.
3.Then the controller transfers the data retrieved to the view layer.
4.Now the result is sent back to the browser (client) by the view.
Advantages of MVC Architecture
The advantages of MVC architecture are as follows:
MVC has the feature of scalability that in turn helps the growth of application.
The components are easy to maintain because there is less dependency.
A model can be reused by multiple views that provides reusability of code.
The developers can work with the three layers (Model, View, and Controller) simultaneously.
Using MVC, the application becomes more understandable.
Using MVC, each layer is maintained separately therefore we do not require to deal with
massive code.
The extending and testing of application is easier.

Implementation of MVC using Java

To implement MVC pattern in Java, we are required to create the following three classes.

o Employee Class, will act as model layer


o EmployeeView Class, will act as a view layer
o EmployeeContoller Class, will act a controller layer

MVC Architecture Layers

Model Layer

The Model in the MVC design pattern acts as a data layer for the application. It represents the
business logic for application and also the state of application. The model object fetch and store
the model state in the database. Using the model layer, rules are applied to the data that
represents the concepts of application.

Let's consider the following code snippet that creates a which is also the first step to implement
MVC pattern.

Employee.java

1. // class that represents model


2. public class Employee {
3.
4. // declaring the variables
5. private String EmployeeName;
6. private String EmployeeId;
7. private String EmployeeDepartment;
8.
9. // defining getter and setter methods
10. public String getId() {
11. return EmployeeId;
12. }
13.
14. public void setId(String id) {
15. this.EmployeeId = id;
16. }
17.
18. public String getName() {
19. return EmployeeName;
20. }
21.
22. public void setName(String name) {
23. this.EmployeeName = name;
24. }
25.
26. public String getDepartment() {
27. return EmployeeDepartment;
28. }
29.
30. public void setDepartment(String Department) {
31. this.EmployeeDepartment = Department;
32. }
33.
34. }

The above code simply consists of getter and setter methods to the Employee class.

View Layer

As the name depicts, view represents the visualization of data received from the model. The
view layer consists of output of application or user interface. It sends the requested data to the
client, that is fetched from model layer by controller.
Let's take an example where we create a view using the EmployeeView class.

EmployeeView.java

1. // class which represents the view


2. public class EmployeeView {
3.
4. // method to display the Employee details
5. public void printEmployeeDetails (String EmployeeName, String EmployeeId, String
EmployeeDepartment){
6. System.out.println("Employee Details: ");
7. System.out.println("Name: " + EmployeeName);
8. System.out.println("Employee ID: " + EmployeeId);
9. System.out.println("Employee Department: " + EmployeeDepartment);
10. }
11. }
Controller Layer

The controller layer gets the user requests from the view layer and processes them, with the
necessary validations. It acts as an interface between Model and View. The requests are then
sent to model for data processing. Once they are processed, the data is sent back to the
controller and then displayed on the view.

Let's consider the following code snippet that creates the controller using the
EmployeeController class.

EmployeeController.java

1. // class which represent the controller


2. public class EmployeeController {
3.
4. // declaring the variables model and view
5. private Employee model;
6. private EmployeeView view;
7.
8. // constructor to initialize
9. public EmployeeController(Employee model, EmployeeView view) {
10. this.model = model;
11. this.view = view;
12. }
13.
14. // getter and setter methods
15. public void setEmployeeName(String name){
16. model.setName(name);
17. }
18.
19. public String getEmployeeName(){
20. return model.getName();
21. }
22.
23. public void setEmployeeId(String id){
24. model.setId(id);
25. }
26.
27. public String getEmployeeId(){
28. return model.getId();
29. }
30.
31. public void setEmployeeDepartment(String Department){
32. model.setDepartment(Department);
33. }
34.
35. public String getEmployeeDepartment(){
36. return model.getDepartment();
37. }
38.
39. // method to update view
40. public void updateView() {
41. view.printEmployeeDetails(model.getName(), model.getId(), model.getDepart
ment());
42. }
43. }
Main Class Java file

The following example displays the main file to implement the MVC architecture. Here, we
are using the MVCMain class.

MVCMain.java
1. // main class
2. public class MVCMain {
3. public static void main(String[] args) {
4.
5. // fetching the employee record based on the employee_id from the database
6. Employee model = retriveEmployeeFromDatabase();
7.
8. // creating a view to write Employee details on console
9. EmployeeView view = new EmployeeView();
10.
11. EmployeeController controller = new EmployeeController(model, view);
12.
13. controller.updateView();
14.
15. //updating the model data
16. controller.setEmployeeName("Nirnay");
17. System.out.println("\n Employee Details after updating: ");
18.
19. controller.updateView();
20. }
21.
22. private static Employee retriveEmployeeFromDatabase(){
23. Employee Employee = new Employee();
24. Employee.setName("Anu");
25. Employee.setId("11");
26. Employee.setDepartment("Salesforce");
27. return Employee;
28. }
29. }

The MVCMain class fetches the employee data from the method where we have entered the
values. Then it pushes those values in the model. After that, it initializes the view
(EmployeeView.java). When view is initialized, the Controller (EmployeeController.java) is
invoked and bind it to Employee class and EmployeeView class. At last the updateView()
method (method of controller) update the employee details to be printed to the console.

Output:

Employee Details:
Name: Anu
Employee ID: 11
Employee Department: Salesforce

Employee Details after updating:


Name: Nirnay
Employee ID: 11
Employee Department: Salesforce

In this way, we have learned about MVC Architecture, significance of each layer and its
implementation in Java.

Java Swing
Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create window-
based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and
entirely written in java.
Unlike AWT, Java Swing provides platform-independent and lightweight components.
The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc
Difference between AWT and Swing

No. Java AWT Java Swing

1) AWT components are platform- Java swing components are platform-independent.


dependent.

2) AWT components Swing components are lightweight.


are heavyweight.

3) AWT doesn't support pluggable Swing supports pluggable look and feel.
look and feel.

4) AWT provides less Swing provides more powerful components


components than Swing. such as tables,
lists, scrollpanes, colorchooser, tabbedpane etc.

5) AWT doesn't follows Swing follows MVC.


MVC(Model View Controller)
where model represents data, view
represents presentation and
controller acts as an interface
between model and view.
What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.
Hierarchy of Java Swing classes
The hierarchy of java swing API is given below.

The methods of Component class are widely used in java swing that are given below.

Method Description

public void add(Component c) add a component on another component.

public void setSize(int width,int height) sets size of the component.

public void setLayout(LayoutManager m) sets the layout manager for the component.

public void setVisible(boolean b) sets the visibility of the component. It is by default false.
Java Swing Examples
There are two ways to create a frame:
By creating the object of Frame class (association)
By extending Frame class (inheritance)
EXAMPLE: By creating the object of Frame class (association

1. import javax.swing.*;
2. public class FirstSwingExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame();//creating instance of JFrame
5.
6. JButton b=new JButton("click");//creating instance of JButton
7. b.setBounds(130,100,100, 40);//x axis, y axis, width, height
8.
9. f.add(b);//adding button in JFrame
10.
11. f.setSize(400,500);//400 width and 500 height
12. f.setLayout(null);//using no layout managers
13. f.setVisible(true);//making the frame visible
14. }
15. }
Output:
Simple example of Swing by inheritance
1. import javax.swing.*;
2. public class Simple2 extends JFrame{//inheriting JFrame
3. JFrame f;
4. Simple2(){
5. JButton b=new JButton("click");//create button
6. b.setBounds(130,100,100, 40);
7.
8. add(b);//adding button on frame
9. setSize(400,500);
10. setLayout(null);
11. setVisible(true);
12. }
13. public static void main(String[] args) {
14. new Simple2();
15. }}
Java JButton
The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. It inherits
AbstractButton class.
JButton class declaration
Let's see the declaration for javax.swing.JButton class.

public class JButton extends AbstractButton implements Accessible


Commonly used Constructors:
Constructor Description

JButton() It creates a button with no text and icon.

JButton(String s) It creates a button with the specified text.

JButton(Icon i) It creates a button with the specified icon object.

Commonly used Methods of AbstractButton class:

Methods Description

void setText(String s) It is used to set specified text on button

String getText() It is used to return the text of the button.

void setEnabled(boolean b) It is used to enable or disable the button.

void setIcon(Icon b) It is used to set the specified Icon on the button.

Icon getIcon() It is used to get the Icon of the button.

void setMnemonic(int a) It is used to set the mnemonic on the button.

void addActionListener(ActionListener a) It is used to add the action listener to this object.

Java JButton Example

1. import javax.swing.*;
2. public class ButtonExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame("Button Example");
5. JButton b=new JButton("Click Here");
6. b.setBounds(50,100,95,30);
7. f.add(b);
8. f.setSize(400,400);
9. f.setLayout(null);
10. f.setVisible(true);
11. }
Java JLabel
The object of JLabel class is a component for placing text in a container. It is used to display
a single line of read only text. The text can be changed by an application but a user cannot
edit it directly. It inherits JComponent class.

JLabel class declaration


Let's see the declaration for javax.swing.JLabel class.
public class JLabel extends JComponent implements SwingConstants, Accessible
Commonly used Constructors:

Constructor Description

JLabel() Creates a JLabel instance with no image and with an empty string for the
title.

JLabel(String s) Creates a JLabel instance with the specified text.

JLabel(Icon i) Creates a JLabel instance with the specified image.

JLabel(String s, Icon i, Creates a JLabel instance with the specified text, image, and horizontal
int horizontalAlignment) alignment

Commonly used Methods:


Methods Description

String getText() t returns the text string that a label displays.

void setText(String text) It defines the single line of text this component will display.
void setHorizontalAlignment(int It sets the alignment of the label's contents along the X axis.
alignment)

Icon getIcon() It returns the graphic image that the label displays.

int getHorizontalAlignment() It returns the alignment of the label's contents along the X axis.

Java JLabel Example

1. import javax.swing.*;
2. class LabelExample
3. {
4. public static void main(String args[])
5. {
6. JFrame f= new JFrame("Label Example");
7. JLabel l1,l2;
8. l1=new JLabel("First Label.");
9. l1.setBounds(50,50, 100,30);
10. l2=new JLabel("Second Label.");
11. l2.setBounds(50,100, 100,30);
12. f.add(l1); f.add(l2);
13. f.setSize(300,300);
14. f.setLayout(null);
15. f.setVisible(true);
16. }
17. }
Output:
Java JTextField
The object of a JTextField class is a text component that allows the editing of a single line
text. It inherits JTextComponent class.
JTextField class declaration
Let's see the declaration for javax.swing.JTextField class.
public class JTextField extends JTextComponent implements SwingConstants

Commonly used Constructors:

Constructor Description

JTextField() Creates a new TextField

JTextField(String text) Creates a new TextField initialized with the specified text

JTextField(String text, int columns) Creates a new TextField initialized with the specified text

JTextField(int columns) Creates a new empty TextField with the specified number

Commonly used Methods:


Methods Description

void It is used to add the specified action listener to receive action


addActionListener(ActionListener l) events from this textfield.

Action getAction() It returns the currently set Action for this ActionEvent source,
or null if no Action is set.

void setFont(Font f) It is used to set the current font.


void It is used to remove the specified action listener so that it no
removeActionListener(ActionListener longer receives action events from this textfield.
l)

Java JTextField Example

1. import javax.swing.*;
2. class TextFieldExample
3. {
4. public static void main(String args[])
5. {
6. JFrame f= new JFrame("TextField Example");
7. JTextField t1,t2;
8. t1=new JTextField("Welcome to Javatpoint.");
9. t1.setBounds(50,100, 200,30);
10. t2=new JTextField("AWT Tutorial");
11. t2.setBounds(50,150, 200,30);
12. f.add(t1); f.add(t2);
13. f.setSize(400,400);
14. f.setLayout(null);
15. F.setVisible(true);
16. }

Java JTextField Example with ActionListener

1. import javax.swing.*;
2. import java.awt.event.*;
3. public class TextFieldExample implements ActionListener{
4. JTextField tf1,tf2,tf3;
5. JButton b1,b2;
6. TextFieldExample(){
7. JFrame f= new JFrame();
8. tf1=new JTextField();
9. tf1.setBounds(50,50,150,20);
10. tf2=new JTextField();
11. tf2.setBounds(50,100,150,20);
12. tf3=new JTextField();
13. tf3.setBounds(50,150,150,20);
14. tf3.setEditable(false);
15. b1=new JButton("+");
16. b1.setBounds(50,200,50,50);
17. b2=new JButton("-");
18. b2.setBounds(120,200,50,50);
19. b1.addActionListener(this);
20. b2.addActionListener(this);
21. f.add(tf1);
22. f.add(tf2);
23. f.add(tf3);
24. f.add(b1);f.add(b2);
25. f.setSize(300,300);
26. f.setLayout(null);
27. f.setVisible(true);
28. }
29. public void actionPerformed(ActionEvent e) {
30. String s1=tf1.getText();
31. String s2=tf2.getText();
32. int a=Integer.parseInt(s1);
33. int b=Integer.parseInt(s2);
34. int c=0;
35. if(e.getSource()==b1){
36. c=a+b;
37. }else if(e.getSource()==b2){
38. c=a-b;
39. }
40. String result=String.valueOf(c);
41. tf3.setText(result);
42. }
43. public static void main(String[] args) {
44. new TextFieldExample();
45. } }

Output:

Java JCheckBox
The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off
(false). Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on ".It
inherits JToggleButton class.
JCheckBox class declaration
Let's see the declaration for javax.swing.JCheckBox class.
public class JCheckBox extends JToggleButton implements Accessible
Commonly used Constructors

Constructor Description

JJCheckBox() Creates an initially unselected check box button with no t

JChechBox(String s) Creates an initially unselected check box with text.

JCheckBox(String text, boolean selected) Creates a check box with text and specifies whether or no

JCheckBox(Action a) Creates a check box where properties are taken from the
Commonly used Methods:
Methods Description

AccessibleContext getAccessibleContext() It is used to get the AccessibleContext associated wi

protected String paramString() It returns a string representation of this JCheckBox.

Java JCheckBox Example

1. import javax.swing.*;
2. public class CheckBoxExample
3. {
4. CheckBoxExample(){
5. JFrame f= new JFrame("CheckBox Example");
6. JCheckBox checkBox1 = new JCheckBox("C++");
7. checkBox1.setBounds(100,100, 50,50);
8. JCheckBox checkBox2 = new JCheckBox("Java", true);
9. checkBox2.setBounds(100,150, 50,50);
10. f.add(checkBox1);
11. f.add(checkBox2);
12. f.setSize(400,400);
13. f.setLayout(null);
14. f.setVisible(true);
15. }
16. public static void main(String args[])
17. {
18. new CheckBoxExample();
19. }}
Output:
Java JRadioButton
The JRadioButton class is used to create a radio button. It is used to choose one option from
multiple options. It is widely used in exam systems or quiz.
It should be added in ButtonGroup to select one radio button only.
JRadioButton class declaration
Let's see the declaration for javax.swing.JRadioButton class.
public class JRadioButton extends JToggleButton implements Accessible

Commonly used Constructors:


Constructor Description

JRadioButton() Creates an unselected radio button with no text.

JRadioButton(String s) Creates an unselected radio button with specified text.

JRadioButton(String s, boolean Creates a radio button with the specified text and selected status.
selected)

Commonly used Methods:


Methods Description

void setText(String s) It is used to set specified text on button.

String getText() It is used to return the text of the button.


void setEnabled(boolean b) It is used to enable or disable the button.

void setIcon(Icon b) It is used to set the specified Icon on the button.

Icon getIcon() It is used to get the Icon of the button.

void setMnemonic(int a) It is used to set the mnemonic on the button.

void addActionListener(ActionListener It is used to add the action listener to this object.


a)

Java JRadioButton Example

1. import javax.swing.*;
2. public class RadioButtonExample {
3. JFrame f;
4. RadioButtonExample(){
5. f=new JFrame();
6. JRadioButton r1=new JRadioButton("A) Male");
7. JRadioButton r2=new JRadioButton("B) Female");
8. r1.setBounds(75,50,100,30);
9. r2.setBounds(75,100,100,30);
10. ButtonGroup bg=new ButtonGroup();
11. bg.add(r1);bg.add(r2);
12. f.add(r1);f.add(r2);
13. f.setSize(300,300);
14. f.setLayout(null);
15. f.setVisible(true);
16. }
17. public static void main(String[] args) {
18. new RadioButtonExample();
19. }
20. }
Output:
Java JRadioButton Example with ActionListener

1. import javax.swing.*;
2. import java.awt.event.*;
3. class RadioButtonExample extends JFrame implements ActionListener{
4. JRadioButton rb1,rb2;
5. JButton b;
6. RadioButtonExample(){
7. rb1=new JRadioButton("Male");
8. rb1.setBounds(100,50,100,30);
9. rb2=new JRadioButton("Female");
10. rb2.setBounds(100,100,100,30);
11. ButtonGroup bg=new ButtonGroup();
12. bg.add(rb1);bg.add(rb2);
13. b=new JButton("click");
14. b.setBounds(100,150,80,30);
15. b.addActionListener(this);
16. add(rb1);add(rb2);add(b);
17. setSize(300,300);
18. setLayout(null);
19. setVisible(true);
20. }
21. public void actionPerformed(ActionEvent e){
22. if(rb1.isSelected()){
23. JOptionPane.showMessageDialog(this,"You are Male.");
24. }
25. if(rb2.isSelected()){
26. JOptionPane.showMessageDialog(this,"You are Female.");
27. }
28. }
29. public static void main(String args[]){
30. new RadioButtonExample();
31. }}

Output:

Java JComboBox

The object of Choice class is used to show popup menu of choices. Choice selected by user is
shown on the top of a menu. It inherits JComponent class.

JComboBox class declaration

Let's see the declaration for javax.swing.JComboBox class.

public class JComboBox extends JComponent implements ItemSelectable, ListDataListener,


ActionListener, Accessible

Commonly used Constructors:


Constructor Description

JComboBox() Creates a JComboBox with a default data model.

JComboBox(Object[] items) Creates a JComboBox that contains the elements in the specified array.
JComboBox(Vector<?> items) Creates a JComboBox that contains the elements in the specified Vector.

C
ommonly used Methods:
Methods Description

void addItem(Object anObject) It is used to add an item to the item list.

void removeItem(Object anObject) It is used to delete an item to the item list.

void removeAllItems() It is used to remove all the items from the list.

void setEditable(boolean b) It is used to determine whether the JComboBox is editable.

void addActionListener(ActionListener It is used to add the ActionListener.


a)

void addItemListener(ItemListener i) It is used to add the ItemListener.

Java JComboBox Example

1. import javax.swing.*;
2. public class ComboBoxExample {
3. JFrame f;
4. ComboBoxExample(){
5. f=new JFrame("ComboBox Example");
6. String country[]={"India","Aus","U.S.A","England","Newzealand"};
7. JComboBox cb=new JComboBox(country);
8. cb.setBounds(50, 50,90,20);
9. f.add(cb);
10. f.setLayout(null);
11. f.setSize(400,500);
12. f.setVisible(true);
13. }
14. public static void main(String[] args) {
15. new ComboBoxExample();
16. }
17. }
Output:

Java JList
The object of JList class represents a list of text items. The list of text items can be set up so
that the user can choose either one item or multiple items. It inherits JComponent class.

JList class declaration

Let's see the declaration for javax.swing.JList class.

1. public class JList extends JComponent implements Scrollable, Accessible


Commonly used Constructors:
Constructor Description

JList() Creates a JList with an empty, read-only, model.

JList(ary[] listData) Creates a JList that displays the elements in the specified array.

JList(ListModel<ary> Creates a JList that displays elements from the specified, non-null, model.
dataModel)

Commonly used Methods:


Methods Description
Void It is used to add a listener to the list, to be notified each time a
addListSelectionListener(ListSelection
change to the selection occurs.
Listener listener)

int getSelectedIndex() It is used to return the smallest selected cell index.

ListModel getModel() It is used to return the data model that holds a list of items displayed by
the JList component.

void setListData(Object[] listData) It is used to create a read-only ListModel from an array of objects.

Java JList Example

1. import javax.swing.*;
2. public class ListExample
3. {
4. ListExample(){
5. JFrame f= new JFrame();
6. DefaultListModel<String> l1 = new DefaultListModel<>();
7. l1.addElement("Item1");
8. l1.addElement("Item2");
9. l1.addElement("Item3");
10. l1.addElement("Item4");
11. JList<String> list = new JList<>(l1);
12. list.setBounds(100,100, 75,75);
13. f.add(list);
14. f.setSize(400,400);
15. f.setLayout(null);
16. f.setVisible(true);
17. }
18. public static void main(String args[])
19. {
20. new ListExample();
21. }}

Output:
Java JScrollBar

The object of JScrollbar class is used to add horizontal and vertical scrollbar. It is an
implementation of a scrollbar. It inherits JComponent class.

JScrollBar class declaration

Let's see the declaration for javax.swing.JScrollBar class.

1. public class JScrollBar extends JComponent implements Adjustable, Accessible


Commonly used Constructors:
Constructor Description

JScrollBar() Creates a vertical scrollbar with the initial values.

JScrollBar(int orientation) Creates a scrollbar with the specified orientation and


the initial values.

JScrollBar(int orientation, int value, int extent, int min, int max) Creates a scrollbar with the specified orientation, value
and maximum.

Java JScrollBar Example

1. import javax.swing.*;
2. class ScrollBarExample
3. {
4. ScrollBarExample(){
5. JFrame f= new JFrame("Scrollbar Example");
6. JScrollBar s=new JScrollBar();
7. s.setBounds(100,100, 50,100);
8. f.add(s);
9. f.setSize(400,400);
10. f.setLayout(null);
11. f.setVisible(true);
12. }
13. public static void main(String args[])
14. {
15. new ScrollBarExample();
16. }}

Output:

Java JToggleButton

JToggleButton is used to create toggle button, it is two-states button to switch on or off.

Nested Classes
Modifier and Type Class Description

protected class JToggleButton.AccessibleJToggleButton This class implements accessibility su

static class JToggleButton.ToggleButtonModel The ToggleButton model

Constructors
Constructor Description

JToggleButton() It creates an initially unselected toggle button without setting the te

JToggleButton(Action a) It creates a toggle button where properties are taken from the Actio

JToggleButton(Icon icon) It creates an initially unselected toggle button with the specified im
JToggleButton(Icon icon, boolean selected) It creates a toggle button with the specified image and selection sta

JToggleButton(String text) It creates an unselected toggle button with the specified text.

JToggleButton(String text, boolean selected) It creates a toggle button with the specified text and selection state.

JToggleButton(String text, Icon icon) It creates a toggle button that has the specified text and image,
unselected.

JToggleButton(String text, Icon icon, boolean It creates a toggle button with the specified text, image, and selectio
selected)

Methods
Modifier and Type Method Description

AccessibleContext getAccessibleContext() It gets the AccessibleContext associated with


this JToggleButton.

String getUIClassID() It returns a string that specifies the name of the l&f class that r
this component.

protected String paramString() It returns a string representation of this JToggleButton.

void updateUI() It resets the UI property to a value from the current look and fe

JToggleButton Example
1. import java.awt.FlowLayout;
2. import java.awt.event.ItemEvent;
3. import java.awt.event.ItemListener;
4. import javax.swing.JFrame;
5. import javax.swing.JToggleButton;
6.
7. public class JToggleButtonExample extends JFrame implements ItemListener
{
8. public static void main(String[] args) {
9. new JToggleButtonExample();
10. }
11. private JToggleButton button;
12. JToggleButtonExample() {
13. setTitle("JToggleButton with ItemListener Example");
14. setLayout(new FlowLayout());
15. setJToggleButton();
16. setAction();
17. setSize(200, 200);
18. setVisible(true);
19. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
20. }
21. private void setJToggleButton() {
22. button = new JToggleButton("ON");
23. add(button);
24. }
25. private void setAction() {
26. button.addItemListener(this);
27. }
28. public void itemStateChanged(ItemEvent eve) {
29. if (button.isSelected())
30. button.setText("OFF");
31. else
32. button.setText("ON");
33. }
34. }

Output:
Java JTabbedPane
The JTabbedPane class is used to switch between a group of components by clicking on a tab
with a given title or icon. It inherits JComponent class.
JTabbedPane class declaration
Let's see the declaration for javax.swing.JTabbedPane class.
public class JTabbedPane extends JComponent implements Serializable, Accessible,
SwingConstants

Commonly used Constructors:


Constructor Description

JTabbedPane() Creates an empty TabbedPane with a default tab placement

of JTabbedPane.Top.

JTabbedPane(int tabPlacement) Creates an empty TabbedPane with a specified tab placement.

JTabbedPane(int tabPlacement, int Creates an empty TabbedPane with a specified tab placement and tab layout policy.
tabLayoutPolicy)

Java JTabbedPane Example


1. import javax.swing.*;
2. public class TabbedPaneExample {
3. JFrame f;
4. TabbedPaneExample(){
5. f=new JFrame();
6. JTextArea ta=new JTextArea(200,200);
7. JPanel p1=new JPanel();
8. p1.add(ta);
9. JPanel p2=new JPanel();
10. JPanel p3=new JPanel();
11. JTabbedPane tp=new JTabbedPane();
12. tp.setBounds(50,50,200,200);
13. tp.add("main",p1);
14. tp.add("visit",p2);
15. tp.add("help",p3);
16. f.add(tp);
17. f.setSize(400,400);
18. f.setLayout(null);
19. f.setVisible(true);
20. }
21. public static void main(String[] args) {
22. new TabbedPaneExample();
23. }}
Output:

Java JScrollPane
A JscrollPane is used to make scrollable view of a component. When screen size is limited,
we use a scroll pane to display a large component or a component whose size can change
dynamically.

Constructors
Constructor Purpose
JScrollPane() It creates a scroll pane. The Component parameter, when present, sets the scroll pane
present, set the vertical and horizontal scroll bar policies (respectively).
JScrollPane(Component)

JScrollPane(int, int)

JScrollPane(Component, int,
int)

Useful Methods
Modif Method Description
ier

void setColumnHeaderView(Compo It sets the column header for the scroll pane.
nent)

void setRowHeaderView(Component It sets the row header for the scroll pane.
)

void setCorner(String, Component) It sets or gets the specified corner. The int parameter
specifies which corner and must be one of the following constants defined in
Compo getCorner(String) UPPER_LEFT_CORNER, UPPER_RIGHT_CORNER,LOW
nent LOWER_RIGHT_CORNER, LOWER_LEADING_CORNER,LOWER_T
UPPER_LEADING_CORNER, UPPER_TRAILING_CORNER.

void setViewportView(Component) Set the scroll pane's client.

JScrollPane Example
1. import java.awt.FlowLayout;
2. import javax.swing.JFrame;
3. import javax.swing.JScrollPane;
4. import javax.swing.JtextArea;
5.
6. public class JScrollPaneExample {
7. private static final long serialVersionUID = 1L;
8.
9. private static void createAndShowGUI() {
10.
11. // Create and set up the window.
12. final JFrame frame = new JFrame("Scroll Pane Example");
13.
14. // Display the window.
15. frame.setSize(500, 500);
16. frame.setVisible(true);
17. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
18.
19. // set flow layout for the frame
20. frame.getContentPane().setLayout(new FlowLayout());
21.
22. JTextArea textArea = new JTextArea(20, 20);
23. JScrollPane scrollableTextArea = new JScrollPane(textArea);
24.
25. scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL
_SCROLLBAR_ALWAYS);
26. scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROL
LBAR_ALWAYS);
27.
28. frame.getContentPane().add(scrollableTextArea);
29. }
30. public static void main(String[] args) {
31.
32.
33. javax.swing.SwingUtilities.invokeLater(new Runnable() {
34.
35. public void run() {
36. createAndShowGUI();
37. }
38. });
39. }
40. }
Output:

You might also like