Java Course File
Java Course File
Credits : 3
II B Tech – I Semester
(2023-24)
B.CHANDANA
Assistant Professor
Course Coordinator
Syllabus
Text Books
1 Java The complete reference, 9th edition, Herbert Schildt, McGraw Hill Education (India) Pvt.
Ltd.
1 An Introduction to programming and OO design using Java, J. Nino and F.A. Hosch , John
Wiley &sons
4 ProgramminginJava,S.Malhotra,S.Chudhary,2ndedition,OxfordUniv.Press.
*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.
*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.
Course Outcomes:
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
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
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
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)
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]
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
Course Coordinaton
Blooms Taxonomy Direct
a) Internal Examination
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
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
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
3
Engineering
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.
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.
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 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 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.
, 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.
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.
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.
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.
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
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 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).
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.
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.
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
Multi-threaded
Java supports multi-threading programming, which allows us to write programs that do multiple
operations simultaneously.
Interpreted
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
The following three steps are used to create and execute a java program.
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:
byte i;
short j;
int k;
long l;
float m;
double n;
char ch;
boolean p;
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);
}
}
In java, examples of non-primitive data types are String, Array, List, Queue, Stack, Class, Interface, etc.
String str;
public static void main(String[] args) {
These are built-in data types These are created by the users
Syntax:
data_type variable_name;
(or)
(or)
(or)
Local 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
int a = 10;
int b = 20;
System.out.println("Inside display method, b = " + b);
obj.show();
obj.display();
Output:
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
int x = 100;
x = x + 100;
obj.show();
obj.display();
Output:
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.
Let's look at the following example java program to illustrate static variable in java.
Example
this.x = x;
this.y = y;
obj_1.show();
StaticVariablesExample.z = 1000;
obj_2.show();
Output:
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
void show() {
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.
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
(or)
Example
list[0] = 10;
Output:
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};
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.
Example
list[0] = 10;
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.
Example
list[4] = 10;
Example
import java.util.Scanner;
size = read.nextInt();
list[i] = read.nextShort();
sum = sum + i;
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
(or)
Syntax
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
The above statement creates a two-dimensional array of three rows and two columns.
Operators in Java
Operator in Java
There are many types of operators in Java which are given below:
Unary Operator,
Arithmetic Operator,
Shift Operator,
Relational Operator,
Bitwise Operator,
Logical Operator,
Assignment Operator.
Arithmetic multiplicative * / %
additive + -
Shift shift << >> >>>
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
Ternary ternary ? :
The Java unary operators require only one operand. Unary operators are used to perform various
operations i.e.:
negating an expression
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
int a=10;
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(!d);//true
}}
Output:
-11
false
true
Java arithmetic operators are used to perform addition, subtraction, multiplication, and division. They
act as basic mathematical operations.
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
System.out.println(10*10/5+3-1*4/2);
}}
Output:
21
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.
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
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.
public OperatorExample{
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:
System.out.println(20>>2);
System.out.println(20>>>2);
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.
int a=10;
int b=5;
int c=20;
}}
Output:
false
false
int a=10;
int b=5;
int c=20;
}}
Output:
false
10
false
11
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.
int a=10;
int b=5;
int c=20;
//|| vs |
}}
Output:
true
true
true
10
true
11
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.
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}
Output:
Another Example:
int a=10;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}
Output:
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.
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
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
short a=10;
short b=10;
System.out.println(a);
}}
Output:
short a=10;
short b=10;
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.
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
Infix Expression
The expression in which the operator is used between operands is called infix expression.
Example
Postfix Expression
The expression in which the operator is used after operands is called postfix expression.
Example
Prefix Expression
The expression in which the operator is used before operands is called a prefix expression.
Example
Jump 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
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
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
Java Program
import java.util.Scanner;
if((num % 2) == 0) {
else {
}
}
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.
Java Program
import java.util.Scanner;
if((num % 2) == 0) {
else {
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){
...
...
Java Program
import java.util.Scanner;
if (num % 2 == 0)
System.out.println("And it is EVEN");
else
System.out.println("And it is ODD");
} else
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;
...
Java Program
import java.util.Scanner;
num1 = read.nextInt();
num2 = read.nextInt();
num3 = read.nextInt();
else
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.
import java.util.Scanner;
switch( value )
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
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.
Java Program
int num = 1;
System.out.println(num);
num++;
}
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.
Java Program
int num = 1;
do {
System.out.println(num);
num++;
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.
Java Program
}
}
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.
Java Program
for(int i : arrayList) {
}
}
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
return statement
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.
Java Program
for(int i : list) {
if(i == 30)
break;
System.out.println(i);
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.
Java Program
for(int i : list) {
if(i == 30)
continue;
System.out.println(i);
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.
Java Program
import java.util.Scanner;
verify: if (value % 2 == 0) {
System.out.println("\nYou won!!!");
break reading;
} else {
continue reading;
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.
Java Program
import java.util.Scanner;
int value;
int readValue() {
return this.value=read.nextInt();
}
void showValue(int value) {
if(i == 5)
return;
System.out.println(i);
obj.showValue(obj.readValue());
Java Classes
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.
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>{
methods defination;
🔔 The ClassName must begin with an alphabet, and the Upper-case letter is preferred.
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
🔔 The objectName must begin with an alphabet, and a Lower-case letter is preferred.
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.
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.
Syntax
class <ClassName>{
...
block of statements;
...
🔔 The methodName must begin with an alphabet, and the Lower-case letter is preferred.
🔔 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 );
Example
import java.util.Scanner;
int sNo;
String name;
void readData() {
sNo = read.nextInt();
name = read.next();
}
}
Output:
🔔 The objectName must begin with an alphabet, and a Lower-case letter is preferred.
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);
Example
void diaplay(int...list) {
for(int i : list) {
System.out.print(i + "\t");
obj.diaplay(1, 2);
🔔 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.
Example
ConstructorExample() {
System.out.println("Object created!");
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.
Example
char[] name = {'J', 'a', 'v', 'a', ' ', 'T', 'u', 't', 'o', 'r', 'i', 'a', 'l', 's'};
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.
Example
siteName = "www.btechsmartclass.com";
In java, we can use the following two ways to create a string object.
Example
🔔 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
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
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
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
join(String, String, ...) Joins all strings, first string as delimiter. String
Java Program
}
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) {
}
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 {
}
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 {
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 {
However, if the parent class contains both default and parameterized constructor, then only
the default constructor called automatically by the child class constructor.
ChildClass(){
System.out.println("Inside ChildClass constructor!!");
}
}
public class ConstructorInInheritance {
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.
A constructor must not have a return type. A method must have a return type.
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);}
class Student7{
int id;
String name;
Student7(int i,String n){
id = i;
name = n;
}
Student7(){}
void display(){System.out.println(id+" "+name);}
obj.showData();
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:
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;
}
}
int num2;
ChildClass(){
super(100);
System.out.println("\nInside the ChildClass constructor");
num2 = 200;
}
}
public class SuperKeywordExample {
}
}
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:
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();
}
}
OUTPUT:
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.
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.
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
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:
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.
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:
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{
void showData() {
System.out.println("Inside ParentClass showData() method");
System.out.println("num = " + num);
}
void showData() {
System.out.println("Inside ChildClass showData() method");
System.out.println("num = " + num);
}
}
}
}
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
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
The method overriding is also known as dynamic method dispatch or run time
Example
class ParentClass{
void showData() {
System.out.println("Inside ParentClass showData() method");
System.out.println("num = " + num);
}
void showData() {
System.out.println("Inside ChildClass showData() method");
System.out.println("num = " + num);
}
}
}
}
Output:
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.
4) Method overloading is the example of compile time Method overriding is the example
polymorphism. of run time polymorphism.
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.
Syntax
...
Example
import java.util.*;
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
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.
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.
The following table depicts all built-in methods of Object class in java.
Method Description
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.
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;
package 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.
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 {
}
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.
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;
int i = read.nextInt();
In the above code, the class ImportingExample belongs to myPackage package, and it also
importing a class called Scanner from java.util package.
import packageName.*;
package myPackage;
import java.util.*;
int i = read.nextInt();
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.
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;
...
}
interface HumanInterfaceExample {
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 {
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
interface Human {
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.
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.
interface OuterInterface{
void outerMethod();
interface InnerInterface{
void innerMethod();
}
}
obj_1.outerMethod();
obj_2.innerMethod();
}
OUTPUT:
class OuterClass{
interface InnerInterface{
void innerMethod();
}
}
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.
🔔 If any variable in an interface is defined without public, static, and final keywords then,
the compiler automatically adds the same.
🔔 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{
}
OUTPUT:
🔔 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();
}
obj.childMethod();
obj.parentMethod();
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.
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.
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.
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.
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.
1 void write(int n)
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.
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.
import java.io.*;
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.*;
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:
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.
import java.io.*;
public class WritingDemo {
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.
1 int read()
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.
1 void flush()
It flushes the output steam by forcing out buffered bytes to be written out.
4 void write(int c)
It writes single character.
7 Writer append(char c)
It appends the specified character to the writer.
10 void close()
It closes the output stream and also frees any resources connected with this output stream.
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.
import java.io.*;
Output:
import java.io.*;
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.
import java.io.*;
Output:
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.
Consider the following example code to understand how to read console input using
BufferedReader class.
Example
import java.io.*;
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:
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.
Example
import java.util.Scanner;
}
}
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.
Consider the following example code to understand how to read console input using Console
class.
Example
import java.io.*;
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.");
}
}
}
In java, there are two methods to write console output. Using the 2 following methods, we can
write output data to the console.
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
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.
Example
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.
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
4 File(URI uri)
It creates a new File instance by converting the given file: URI into an abstract pathname.
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
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.
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.
24 File[] listFiles()
It returns an array of file references containing names of all the files and directories in the current
directory.
Example
import java.io.*;
public class FileClassTest {
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.*;
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.
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 {
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 {
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
It creates a random access file stream to read from, and optionally to write to, the file specified by the Fi
Access Modes
r - Creates the file with read mode; Calling write methods will result in an IOException.
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
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.
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.
13 String readUTF()
t reads in a string from the file.
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.*;
// Writing to file
f_ref.writeUTF("Hello, Good Morning!");
// read() method :
System.out.println("Use of read() method : " + f_ref.read());
f_ref.seek(0);
// 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);
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.
The Console class does not have any constructor. We can obtain the Console class object by
calling System.console().
1 void flush( )
2 String readLine( )
It reads a string value from the keyboard, the input is terminated on pressing 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.
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 {
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.*;
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
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
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 4 - Use writeObject(object) method by passing the object that wants to be serialized.
Example
import java.io.*;
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);
}
}
}
Deserialization in Java
In a java programming language, the Deserialization is achieved with the help of
Step 1 - Create a file reference with file path in which serialized object is available using
FileInputStream class.
destination type.
Example
import java.io.*;
public class DeserializationExample {
try {
FileInputStream fis = new FileInputStream("my_data.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
fis.close();
ois.close();
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.
enum WeekDay{
MONDAY, TUESDAY, WEDNESSDAY, THURSDAY, FRIDAY, SATURDAY,
SUNDAY;
}
}
}
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.
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;
}
}
}
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.
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);
}
}
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.
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
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
🔔 We can also perform autoboxing manually using the method valueOf( ), which is provided
import java.lang.*;
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
🔔 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.
import java.lang.*;
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
language.
🔔 Most of the collection framework classes are generic classes.
🔔 The java generics allows only non-primitive type, it does not support
The java generics feature was introduced in Java 1.5 version. In java,
generics used angular brackets “< >”. In java, the generics feature
Generic Method
Generic Classe
Using a generic method, we can create a single method that can be called
passed to the generic method, the compiler handles each method call
appropriately.
obj.displayData(45.6f, 10);
obj.displayData(10, 10);
obj.displayData("Hi", 'c');
that allows a different type of parameter values for every function call.
T obj;
this.obj = anotherObj;
public T getData() {
return this.obj;
System.out.println(actualObj1.getData());
System.out.println(actualObj2.getData());
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;
}
}
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;
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.
Let's look at the following example Java code to illustrate multiple catch clauses.
Example
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;
🔔 When a method throws an exception, we must put the calling statement of method in try-
catch block.
Example
import java.util.Scanner;
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.
1 ArithmeticException
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.
import java.util.Scanner;
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[]) {
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.
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 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.
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.
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.
Example
class SampleThread extends Thread{
Example
class SampleThread implements Runnable{
Thread( )
Thread( String threadName )
Thread( Runnable objectName )
Thread( Runnable objectName, String threadName )
start( ) It moves thre thread from Ready state to Running state by void
calling run( ) method.
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.
yield( ) Tells to the scheduler that the current thread is willing to void
yield its current use of a processor.
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();
Example
class SampleThread extends Thread{
public void run() {
System.out.println("Inside SampleThread");
System.out.println("Current Thread: " +
Thread.currentThread().getName());
}
}
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);
}
}
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;
Output:
🔔 The complete code of a method may be written inside the synchronized block, where it works
similarly to the synchronized method.
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.
Example
class ItemQueue {
int item;
boolean valueSet = false;
{
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;
}
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.
In the StringTokenizer class, the delimiters can be provided at the time of creation
StringTokenizer(String str, String delim)---- It creates StringTokenizer with specified string and
delimiter.
---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:
String nextToken() It returns the next token from the StringTokenizer object.
String nextToken(String delim) It returns the next token based on the delimiter.
Object nextElement() It is the same as nextToken() but its return type is Object.
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());
}
}
}
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.
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();
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;
// create 2 bitsets
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);
bitset1.or(bitset2);
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);
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.
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
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.
System.out.println(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;
calendar.add(Calendar.DATE, -15);
calendar.add(Calendar.MONTH, 4);
calendar.add(Calendar.YEAR, 2);
import java.util.*;
}
Random class in java
🔔 The Random class provides several methods to generate random numbers of type integer, double,
long, float etc.
Random()
Random(long seedValue)
import java.util.Random;
}
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:
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:
import java.util.*;
System.out.println(formatter);
formatter.format(Locale.FRANCE,"%.5f", -1325.789);
System.out.println(formatter);
String name = "Java";
formatter.format("%.4f", 123.1234567);
formatter.format("%010d", 88);
}
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 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.
1 Scanner(InputStream source)
It creates a new Scanner that produces values read from the specified input stream.
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.
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.
1 String next()
It reads the next token if it matches the pattern constructed from the specified string.
4 boolean nextBoolean()
5 byte nextByte()
6 double nextDouble()
7 float nextFloat()
8 int nextInt()
9 long nextLong()
10 short nextShort()
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()
14 void close()
import java.util.Scanner;
System.out.println("\n------------------------------------------");
}
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.
Method Description
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.
Output:
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.
To implement MVC pattern in Java, we are required to create the following three classes.
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
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
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
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
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
3) AWT doesn't support pluggable Swing supports pluggable look and feel.
look and feel.
The methods of Component class are widely used in java swing that are given below.
Method Description
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.
Methods Description
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.
Constructor Description
JLabel() Creates a JLabel instance with no image and with an empty string for the
title.
JLabel(String s, Icon i, Creates a JLabel instance with the specified text, image, and horizontal
int horizontalAlignment) alignment
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.
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
Constructor Description
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
Action getAction() It returns the currently set Action for this ActionEvent source,
or null if no Action is set.
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. }
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
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
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
JRadioButton(String s, boolean Creates a radio button with the specified text and selected status.
selected)
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(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 removeAllItems() It is used to remove all the items from the list.
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(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)
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.
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(int orientation, int value, int extent, int min, int max) Creates a scrollbar with the specified orientation, value
and maximum.
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
Nested Classes
Modifier and Type Class Description
Constructors
Constructor Description
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
String getUIClassID() It returns a string that specifies the name of the l&f class that r
this component.
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
of JTabbedPane.Top.
JTabbedPane(int tabPlacement, int Creates an empty TabbedPane with a specified tab placement and tab layout policy.
tabLayoutPolicy)
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.
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: