12. OOP Module
12. OOP Module
Institute of Technology
Werabe Ethiopia
Table of Contents
Chapter 1 ....................................................................................................................1
Introduction to Object-Oriented Programming (OOP) ..............................................1
1.1 What is OOP? ........................................................................................................ .………...1
1.2 Basic Concepts of Object-Oriented Programming ................................................ …………2
1.2.1 Objects..............................................................................................................................3
1.2.2 Classes ..............................................................................................................................3
1.2.3 Encapsulation ...................................................................................................................4
1.2.5 Inheritance .......................................................................................................................4
1.2.4 Abstraction.......................................................................................................................4
1.2.6 Polymorphism..................................................................................................................4
1.3 Java ........................................................................................................................................ 5
1.4. The JVM, Byte Code and Code Execution in Java .............................................................. 9
1.5 Review question .................................................................................................................. 11
Chapter 2 ....................................................................................................................................... 13
2. Basics in Java Programming .................................................................................................... 13
2.1 Java syntax; Variable and identifiers, Data types and constants ......................................... 13
2.1.1 Java Identifiers ............................................................................................................... 14
2.2. Output and Input statements in java ................................................................................... 15
2.3. Type Conversion/ Casting .................................................................................................. 18
2.4 Implicit Type Casting in Java.............................................................................................. 19
2.5 Explicit Type casting (Narrowing conversion) in Java ....................................................... 19
2.6 If-else statement in Java? .................................................................................................... 20
2.7 Java Ternary Operator if-else Statement: ............................................................................ 26
2.8 Review question .................................................................................................................. 34
Chapter 3 ....................................................................................................................................... 36
3. Class and Objects................................................................................................................... 36
3.1 What is an object in Java ..................................................................................................... 36
3 Ways to initialize object ......................................................................................................... 38
3.2. Instantiating and using objects ........................................................................................... 39
3.3. Contractor, types of constructor and constructor overloading ........................................... 40
i
3.4. Member methods and their components ............................................................................ 44
3.5. Members of class ................................................................................................................ 47
3.5.1. Static members (variables, methods) .............................................................................. 49
3.5.2. Instance members (variables, methods) ....................................................................... 50
3.6. Method in java.................................................................................................................... 52
3.7. Object-Oriented Concept.................................................................................................... 56
3.7.1. Encapsulation ............................................................................................................... 56
3.7.2. Inheritance .................................................................................................................... 57
3.7.3. Polymorphism, Method overloading and overriding.................................................... 65
3.8 Review question .................................................................................................................. 69
Chapter 4 ....................................................................................................................................... 71
4. Exception Handling .................................................................................................................. 71
4.1. What is Exception in Java? ................................................................................................ 71
4.2. The causes of exceptions .................................................................................................... 76
4.3. The throw statement and the finally clause ........................................................................ 76
4.4. User defined exceptions ..................................................................................................... 80
4.5 Review question .................................................................................................................. 83
Chapter 5 ....................................................................................................................................... 83
5. Graphic User Interface (GUI) and JDBC ................................................................................. 83
5.1. Overview of GUI ................................................................................................................ 83
5.2. Elements of GUI: Component and container ..................................................................... 86
5.3. Concepts of GUI................................................................................................................. 86
2.3 AWT Container Classes .................................................................................................... 88
2.4 AWT Component Classes ................................................................................................. 91
5.4. Java Database Connectivity (JDBC) ................................................................................ 116
5.5 Review question ................................................................................................................ 124
Chapter 6 ..................................................................................................................................... 125
6. Files and Streams ................................................................................................................... 125
6.1 Files and Streams .............................................................................................................. 125
6.2. Review question ............................................................................................................... 139
Chapter 7 ..................................................................................................................................... 141
ii
7. Overview of Java Advanced Concepts ................................................................................ 141
7.1 About the Advanced Java Course ..................................................................................... 141
7.2 What is Multithreading? .................................................................................................... 143
7.3. Java Networking ............................................................................................................... 144
7.4. RMI (Remote Method Invocation) ................................................................................... 146
7.5. Servlets | Servlet Tutorial ................................................................................................. 154
7.5.1 What is a Servlet? ........................................................................................................ 155
7.5.2. What is a web application? ........................................................................................ 155
REVIEW QUESTIONS .......................................................................................................... 157
iii
Chapter 1
The focus of procedural programming is to break down a programming task into a collection of
variables, data structures, and subroutines, whereas in object-oriented programming it is to break
down a programming task into objects that expose behavior (methods) and data (fields) using
interfaces. The most important distinction is that while procedural programming uses procedures
to operate on data structures, object-oriented programming bundles the two together, soan
object, which is an instance of a class, operates on its "own" data structure.
1
Object-oriented programming (OOP) is a fundamental programming paradigm used by nearly
every developer at some point in their career. OOP is the most popular programming paradigm
used for software development and is taught as the standard way to code for most of a
programmer’s educational career. Another popular programming paradigm is functional
programming, but we won’t get into that right now.
OOP languages are not necessarily restricted to the object-oriented programming paradigm. Some
languages, such as JavaScript, Python, and PHP, all allow for both procedural and object- oriented
programming styles.
• Objects
• Classes
2
• Inheritance
• Polymorphism
1.2.1 Objects
Objects are the basic run time entities in an object-oriented system. They may represent a person,
a place, a bank account, a table of data or any item that the program has to handle. They may
also represent user-defined data such as vectors, time and lists. Programming problem is analyzed
in term of objects and the nature of communication between them. Program objects should be
chosen such that they match closely with the real-world objects. Objects take up space in the
memory and have an associated address like a record in Pascal, or a structure in c. When a program
is executed, the objects interact by sending messages to one another. For example, if “customer”
and “account” are to object in a program, then the customer object may send a message to the
count object requesting for the bank balance. Each object contain data, and code to manipulate
data. Objects can interact without having to know details of each other’s data or code. It is a
sufficient to know the type of message accepted, and the type of response returnedby the objects.
1.2.2 Classes
This is another important term in object-oriented programming. A class is like a template from
which new objects are created. Any class you create will always have a head and a body. A head
typically includes modifiers and the keyword of the class while the body includes data members
and member functions.
3
A single program can contain any number of classes.
1.2.3 Encapsulation
The wrapping up of data and function into a single unit (called class) is known as encapsulation.
Data and encapsulation is the most striking feature of a class. The data is not accessible to the
outside world, and only those functions which are wrapped in the class can access it. These
functions provide the interface between the object’s data and the program. This insulation of the
data from direct access by the program is called data hiding or information hiding.
1.2.4 Abstraction
Abstraction refers to the act of representing essential features without including the
background details or explanation. Classes use the concept of abstraction and are defined as
a list of abstract attributes such as size, wait, and cost, and function operate on theseattributes.
They encapsulate all the essential properties of the object that are to be created. The attributes
are sometime called data members because they hold information. The functions that operate
on these data are sometimes called methods or member function.
1.2.5 Inheritance
Inheritance is the process by which objects of one class acquired the properties of objects of
another classes. It supports the concept of hierarchical classification. For example, the bird,
‘robin’ is a part of class ‘flying bird’ which is again a part of the class ‘bird’. The principal
behind this sort of division is that each derived class shares common characteristics with the
class from which it is derived.
In OOP, the concept of inheritance provides the idea of reusability. This means that we can add
additional features to an existing class without modifying it. This is possible by deriving a new
class from the existing one. The new class will have the combined feature of both the classes.
1.2.6 Polymorphism
4
Polymorphism is another important OOP concept. Polymorphism, a Greek term, means the
ability to take more than on form. An operation may exhibit different behavior is different
instances. The behavior depends upon the types of data used in the operation. For example,
consider the operation of addition. For two numbers, the operation will generate a sum. If the
operands are strings, then the operation would produce a third string by concatenation. The
process of making an operator to exhibit different behaviors in different instances is known as
operator overloading.
1.3 Java
Java features
Simple
Java is a simple programming language and easy to understand because it does not contain
complexities that exist in prior programming languages. In fact, simplicity was the design aim
of Javasoft peoples, because it has to work on electronic devices where less memory/resources
are available. Java contains the same syntax as in C, C++, so the programmers who are
switching to Java will not face any problem in terms of syntax. Secondly, the concept of
pointers have been completely removed from Java which leads to confusion for a programmer
and pointers are also vulnerable to security.
Object-Oriented
5
represented by variables. Also mobile is associated with actions like, calling, messaging,
photography, etc and these actions are represented by methods in Java.
Now, we saw what an object is and also learned about the state and behavior associated with the
object. What is Class? A collection of objects that exhibits the same state and behavior will come
under the same group called class. For example, Samsung, Apple, Vivo, Oppo, Xiaomi, etc are
different brands making various models of smartphones, but they all come under the same group
known as Mobile Phone. The main concepts of any Object Oriented Programming language are
given below:
Platform Independent
The design objective of java soft people is to develop a language that must work on anyplatform.
Here platform means a type of operating system and hardware technology. Java allows
programmers to write their program on any machine with any configuration and to execute it on
any other machine having different configurations.
In Java, Java source code is compiled to bytecode and this bytecode is not bound to any
platform. In Fact, this bytecode is only understandable by the Java Virtual Machine which is
installed in our system. What I meant to say is that every operating system has its own version of
JVM, which is capable of reading and converting bytecode to an equivalent machine native
language. This reduces the overhead of programmers writing system specific code. Now
programmers write programs only once, compile it, to generate the bytecode and then export it
anywhere.
6
Portable
The WORA (Write Once Run Anywhere) concept and platform independent feature make Java
portable. Now using the Java programming language, developers can yield the same result on any
machine, by writing code only once. The reason behind this is JVM and bytecode. Suppose you
wrote any code in Java, then that code is first converted to equivalent bytecode which is only
readable by JVM. We have different versions of JVM for different platforms. Windows machines
have their own version of JVM, linux has its own and macOS has its own version of JVM. So if
you distribute your bytecode to any machine, the JVM of that machine would translate the
bytecode into respective machine code. In this way portability lets the programmers focus on
development and productivity rather than writing different code for different platforms.
All these functionalities happen inside the following 3 Java platform components:
JDK is a software development environment used for making applets and Java applications. The
full form of JDK is Java Development Kit. Java developers can use it on Windows, macOS,
Solaris, and Linux. JDK helps them to code and run Java programs. It is possible to install more
than one JDK version on the same computer.
7
The main reasons for using JDK:
JDK contains tools required to write Java programs and JRE to execute them.
It includes a compiler, Java application launcher, Apple viewer, etc.
Compiler converts code written in Java into byte code.
Java application launcher opens a JRE, loads the necessary class, and executes its
main method.
Java Virtual Machine (JVM) is an engine that provides a runtime environment to drive the Java
Code or applications. It converts Java bytecode into machine language. JVM is a part of the Java
Run Environment (JRE). In other programming languages, the compiler produces machine code
for a particular system. However, the Java compiler produces code for a Virtual Machine known
as Java Virtual Machine.
JRE is a piece of software that is designed to run other software. It contains the class libraries,
loader class, and JVM. In simple terms, if you want to run a Java program, you need JRE. If you
are not a programmer, you don’t need to install JDK, but just JRE to run Java programs.
JRE contains class libraries, JVM, and other supporting files. It does not include any tool
for Java development like a debugger, compiler, etc.
It uses important package classes like math, swing, util, lang, awt, and runtime libraries.
8
If you have to run Java applets, then JRE must be installed in your system.
1. Java Platform, Standard Edition (Java SE): Java SE’s API offers the Java programming
language’s core functionality. It defines all the basis of type and object to high-level classes. It is
used for networking, security, database access, graphical user interface (GUI) development, and
XML parsing.
2. Java Platform, Enterprise Edition (Java EE): The Java EE platform offers an API and
runtime environment for developing and running highly scalable, large-scale, multi-tiered,
reliable, and secure network applications.
3. Java Programming Language Platform, Micro Edition (Java ME): The Java ME platform
offers an API and a small-footprint virtual machine running Java programming language
applications on small devices, like mobile phones.
4. Java FX: JavaFX is a platform for developing rich internet applications using a lightweight
user-interface API. It user hardware-accelerated graphics and media engines that help Java take
advantage of higher-performance clients and a modern look-and-feel and high-level APIs for
connecting to networked data sources.
There are a lot of processes that go on while a program in Java gets executed. One such concept is
Bytecode in Java which is one of the reasons how Java becomes platform-independent. So,this
article on ‘What is Bytecode in Java’ will help you in understanding Java Bytecode along with its
working and advantages.
9
A bytecode in Java is the instruction set for Java Virtual Machine and acts similar to an
assembler.
When a Java program is executed, the compiler compiles that piece of code and a Bytecode is
generated for each method in that program in the form of a .class file.We can run this bytecode
10
on any other platform as well. But the bytecode is a non-runnable code that requires or relies on
an interpreter. This is where JVM plays an important part.
The bytecode generated after the compilation is run by the Java virtual machine. Resources
required for the execution are made available by the Java virtual machine for smooth execution
which calls the processor to allocate the resources.
The main difference between the machine code and the bytecode is that the machine code is a set
of instructions in machine language or binary which can be directly executed by the CPU.While
the bytecode is a non-runnable code generated by compiling a source code that relies on
an interpreter to get executed.
Advantages of Bytecode
1. What is OOP?
2. Which is an instance of a class, operates on its "own" data structure?
3. What is Class?
4. How Java Programming Language Works?
11
6. What is Bytecode in Java?
7. Byte code vs Machine code?
8. The important reasons of using JVM?
9. What is the need for OOPs?
10. What are some major Object Oriented Programming languages?
11. What are some other programming paradigms other than OOPs?
12. What is meant by Structured Programming?
13. What are the main features of OOPs?
14. What is Compile time Polymorphism and how is it different from Runtime
Polymorphism?
15. How does C++ support Polymorphism?
16. What is meant by Inheritance?
17. What is Abstraction?
18. How much memory does a class occupy?
19. Is it always necessary to create objects from class?
20. Are class and structure the same? If not, what's the difference between a class and a
structure?
21. What are the various types of inheritance?
22. What is meant by Garbage Collection in OOPs world?
23. Can we run a Java application without implementing the OOPs concept?
12
Chapter 2:
Basic Syntax
About Java programs, it is very important to keep in mind the following points.
Case Sensitivity − Java is case sensitive, which means identifier Hello and hello would
have different meaning in Java.
Class Names − For all class names the first letter should be in Upper Case. If several words
are used to form a name of the class, each inner word's first letter should be in Upper Case.
Example: class MyFirstJavaClass
Method Names − All method names should start with a Lower Case letter. If several words
are used to form the name of the method, then each inner word's first letter should be in
Upper Case.
Example: public void myMethodName()
Program File Name − Name of the program file should exactly match the class name.
When saving the file, you should save it using the class name (Remember Java is case
sensitive) and append '.java' to the end of the name (if the file name and the class name
do not match, your program will not compile).
But please make a note that in case you do not have a public class present in the file then
file name can be different than class name. It is also not mandatory to have a public class
in the file.
Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should
be saved as 'MyFirstJavaProgram.java'
public static void main(String args[]) − Java program processing starts from the main()
method which is a mandatory part of every Java program.
13
2.1.1 Java Identifiers
All Java components require names. Names used for classes, variables, and methods are
called identifiers.
In Java, there are several points to remember about identifiers. They are as follows −
All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an
underscore (_).
After the first character, identifiers can have any combination of characters.
A key word cannot be used as an identifier.
Most importantly, identifiers are case sensitive.
Examples of legal identifiers: age, $salary, _value, 1_value.
Examples of illegal identifiers: 123abc, -salary.
Java Modifiers
Like other languages, it is possible to modify classes, methods, etc., by using modifiers. There
are two categories of modifiers −
We will be looking into more details about modifiers in the next section.
Java Variables
A variable is a container which holds the value while the Java program is executed. A variable is
assigned with a data type.
Variable is a name of memory location. There are three types of variables in java: local, instance
and static.
Local Variables A variable declared inside the body of the method is called localvariable.
You can use this variable only within that method and the other methods in the class aren't
even aware that the variable exists.
14
A local variable cannot be defined with "static" keyword.
Class Variables (Static Variables) A variable that is declared as static is called a static
variable. It cannot be local. You can create a single copy of the static variable and share it
among all the instances of the class. Memory allocation for static variables happens only
once when the class is loaded in the memory.
Instance Variables (Non-static Variables) A variable declared inside the class but
outside the body of the method, is called an instance variable. It is not declared as static.
It is called an instance variable because its value is instance-specific and is not shared among
instances.
Parameters You've already seen examples of parameters, both in the Bicycle class and in
the main method of the "Hello World!" application. Recall that the signature for the
main method is public static void main(String[] args). Here, the args variable is the
parameter to this method. The important thing to remember is that parameters are always
classified as "variables" not "fields". This applies to other parameter-accepting constructs
as well (such as constructors and exception handlers) that you'll learn about later in the
tutorial.
One really useful class that handles input from a user is called the Scanner class. Scanner class is
present in the “java.util” package, so we import this package into our program. It also converts
the Bytes (from the input stream) into characters using the platform’s default charset. To use the
Scanner class, you need to reference it in your code.
This is done with the keyword import. We create an object of the class to use its methods.
import java.util.Scanner;
15
The Syntax is given below.
import java.util.Scanner;
public class StringVariables {
}
This tells Java that you want to use a particular Scanner class that is located in java.util library.
The next thing you need to do is to create an object from the Scanner class.
Syntax to create a new Scanner object in Java:
Scanner sc = new Scanner(System.in); Here, sc is the name of the object, the new
keyword is used to allocate memory, and System.in is the input stream.
Program for Java Input:
In the below example we are getting input String, integer, and a float number. For this we are
using the following methods:
Program for Java Input:
In the below example we are getting input String, integer, and a float number.
For this we are using the following methods:
1) public String next(): Getting the next String of text that a user types
2) public int nextInt(): For integer input
3) public float nextFloat(): For float input
Methods Of Java scanner Class:
int nextInt(): It is used to scan the next token of the input as an integer.
float nextFloat(): It is used to scan the next token of the input as the float.
double nextDouble(): It is used to scan the next token of the input as a double.
byte nextByte(): It is used to scan the next token of the input as a byte.
String nextLine() : Advances this scanner past the current line.
boolean nextBoolean(): It is used to scan the next token of the input into a boolean
value.
long nextLong(): It is used to scan the next token of the input as the long.
short nextShort(): It is used to scan the next token of the input as a Short.
16
BigInteger nextBigInteger(): It is used to scan the next token of the input as a
BigInteger.
BigDecimal nextBigDecimal(): It is used to scan the next token of the input as a
BigDecimal.
Java Output:
In Java, to display output to the users you can simply use
System.out.println(); or System.out.print(); It will simply send output to the standard output
screen.
System: is a final class in java. Lang package. The facilities provided by the System class are
standard input, standard output, and error output streams; access to externally defined properties
and environment variables.
Out: is an instance of Print Stream type, which is a public and static member field of the System
class. Its access specifiers are public final. This gets instantiated during startup and gets mapped
with the standard output console of the host. This stream is open by itself immediately after its
instantiation and ready to accept data.
Println (): is a method of java.io.PrintStream. This method is overloaded to print the message to
the output destination, which is typically a console and a new line.
17
Java print () Method:
It prints string inside the quotes. The print () method does not move the cursor to the next line after
printing the result. It is used when you want the result in one separate line.
The process of converting a value from one data type to another is known as type conversion in
Java.
Type conversion is also known as type casting in java or simply ‘casting’.
If two data types are compatible with each other, Java will perform such conversion
automatically or implicitly for you.
We can easily convert a primitive data type into another primitive data type by using type
casting.
Similarly, it is also possible to convert a non-primitive data type (referenced data type)
into another non-primitive data type by using type casting.
But we cannot convert a primitive data type into an advanced (referenced) data type by
using type casting. For this case, we will have to use methods of Java Wrapper classes.
Type Casting in Java
18
What is a type casting?
When a data type is converted into another data type by a programmer or user while writing a
program code of any programming language, the mechanism is known as type casting. The
programmer manually uses it to convert one data type into another. It is used if we want to change
the target data type to another data type. Remember that the destination data type must besmaller
than the source data type. Hence it is also called a narrowing conversion.
Implicit casting is performed to convert a lower data type into a higher data type. It is
also known as automatic type promotion in Java.
For example, if we assign an int value to a long variable, it is compatible with each other
but an int value cannot be assigned to a byte variable.
For example, if you will assign a double value to an int variable, this conversion cannot
be performed automatically because an int is smaller than a double.
In this case, we must use explicit type casting to create a conversion between two
incompatible types. This kind of conversion is also known as narrowing conversion in
java.
The conversion of a higher data type into a lower data type is called narrowing conversion.
19
Since this type of conversion is performed by the programmer, not by the compiler
automatically, therefore, it is also called explicit type casting in java. It is done to convert
from a higher data type to a lower data type.
The following diagram is useful to perform the narrowing conversion or explicit type casting in
Java program.
To perform this kind of type casting, we will have to use a cast operator. A cast operator is used
to cast a primitive value from one type to another. Using a cast operator is simply an explicit
type conversion.
Syntax:
(type_name) expression;
When you will use type casting in Java, you can lose some information or data.
Accuracy can be lost while using type casting.
When a double is cast to an int, the fractional part of a double is discarded which causes
the loss of fractional part of data.
Mentioned below are the four types of ‘if else’ statements in the Java programming language.
20
If statement
If-else statement
If-else-if ladder
Nested if statement
If statement:
The ‘If statement’ is a rule that is performed when the condition is satisfied or true.
Syntax:
If (condition){
//code to be executed
Code 1:
if(age>18)
21
}
Output:
Age is greater than 18.
If with String:
The if string rule is used to compare two constant dates which cannot be changed, and it will
give the result if the condition is true.
Code 2:
22
Output:
Location is the same.
In Java, the if-else condition is a set of rules or statements that perform a distinct set ofconditions.
Depending on rules, it will display true if the condition is satisfied, and the outputwill be false
if the condition is not true.
Syntax:
If(condition){
}else{
Code 4:
int checkingNumber=13;
23
//Check if the number is divisible by 2 or not
if(checkingNumber%2==0){
}else{
Output:
13 is an odd number.
The if else ladder statement is a set of conditions which is based on “Nested if condition”. The if-
else ladder condition performs the expressions from top to down. Once the condition is true, the
statement for the same is executed, and the balance ladder rules are skipped.
Syntax:
If(condition1){
}else if(condition2){
24
}
Else if(condition3){
Else{
Code 5:
int internalMarks=65;
// if we want check more than one condition we will use this if and else if
System.out.println("fail");
25
else if(internalMarks>=50 && internalMarks<60) //checks if previous condition is false
System.out.println("C grade");
System.out.println("B grade");
System.out.println("A grade");
Output:
B grade.
26
versa of the second, which will give the result by comparing the false statement. If the conditions
help in a shorter way of writing if else statement.
Code 6:
int checkingNumber=13;
System.out.println(output);
// ternary operator ?: if the condition is true it will take before colon values
Output:
Odd number.
27
Java in Nested Ternary Operators if-else statement:
It is the nested ternary operator in Java. Here, it is possible to use one ternary operator inside
another ternary operator.
In the Java nested if statement, it is also possible to use the if-else statements inside an if-else
statement.
Syntax:
If(condition){
//code to be executed
If(condition){
//code to executed
Code 7:
28
// applying condition on age and weight
if (personweight > 50) //here we check the person weight is greater than 50
else
else
System.out.println("Age must be greater than 18");// if age is less than 18 this condition will
execute
29
}
Output:
In this tutorial, you will learn to use the switch statement in Java to control the flow of your
program’s execution with the help of examples.
The switch statement allows us to execute a block of code among many alternatives.
How does the switch-case statement work?
The expression is evaluated once and compared with the values of each case.
If expression matches with value1, the code of case value1 are executed. Similarly, the code
of case value2 is executed if expression matches with value2.
If there is no match, the code of the default case is executed.
break statement in Java switch...case
Notice that we have been using break in each case block.
Loops in Java
The Java for loop is used to iterate a part of the program several times. If the number of iteration
is fixed, it is recommended to use for loop.
30
o Simple for Loop
o For-each or Enhanced for Loop
o Labeled for Loop
A simple for loop is the same as C/C++. We can initialize the variable, check condition and
increment/decrement value. It consists of four parts:
1. Initialization: It is the initial condition which is executed once when the loop starts. Here,
we can initialize the variable, or we can use an already initialized variable. It is an optional
condition.
31
2. Condition: It is the second condition which is executed each time to test the condition of
the loop. It continues execution until the condition is false. It must return Boolean value
either true or false. It is an optional condition.
3. Increment/Decrement: It increments or decrements the variable value. It is an optional
condition.
4. Statement: The statement of the loop is executed each time until the second condition is
false.
If we have a for loop inside the another loop, it is known as nested for loop. The inner loop
executes completely whenever outer loop executes.
32
33
2.8 Review question
1. Type conversion in Java?
2. What is a type casting?
3. Implicit Type Casting in Java and Explicit Type casting (Narrowing conversion) in Java
4. If-else statement in Java?
5. How does it work in the ternary operator?
6. How does Java achieve platform independence?
7. What is Class Loader in Java?
8. Write a Java program to check if a number is Even or Odd?
9. Difference between Array List and HashSet in Java?
10. What is double checked locking in Singleton?
34
31. How does Autoboxing of Integer work in Java?
32. Difference between PATH and Classpath in Java?
33. Difference between method overloading and overriding in Java?.
34. How do you prevent a class from being sub-classed in Java?
35. How do you restrict your class from being used by your client?
36. Difference between String Builder and StringBuffer in Java?
37. Difference between Polymorphism and Inheritance in Java?
38. Can we override static method in Java?
39. Can we access the private method in Java?
40. Difference between interface and abstract class in Java?
41. Difference between DOM and SAX parser in Java?
42. Difference between throw and throws keyword in Java?
35
Chapter 3:
An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table, car,
etc. It can be physical or logical (tangible and intangible). The example of an intangible object is
the banking system.
For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It is used
to write, so writing is its behavior.
36
An object is an instance of a class. A class is a template or blueprint from which objects are
created. So, an object is the instance(result) of a class.
Object Definitions:
A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created. It is a logical entity. It can't be physical.
o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface
A variable which is created inside the class but outside the method is known as an instance variable.
Instance variable doesn't get memory at compile time. It gets memory at runtime when an object
or instance is created. That is why it is known as an instance variable.
Method in Java
In Java, a method is like a function which is used to expose the behavior of an object.
Advantage of Method
37
o Code Reusability
o Code Optimization
1. By reference variable
2. By method
3. By constructor
Initializing an object means storing data into the object. Let's see a simple example where we are
going to initialize the object through a reference variable.
In this example, we are creating the two objects of Student class and initializing the value to these
objects by invoking the insertRecord method. Here, we are displaying the state (data) of theobjects
by invoking the displayInformation() method.
o By new keyword
o By newInstance() method
o By clone() method
o By deserialization
o By factory method etc.
38
We will learn these ways to create object later.
In Java, an OOP language, the object that is instantiated from a class is, confusingly enough, called
a class instead of an object. In other words, using Java, a class is instantiated to create a specific
class that is also an executable file that can run on a computer. However, Java'sequivalent of a
class attribute is a static attribute. Generally, static variables are referred to with the Java class
name.
What is an object?
It is a runtime entity.
It contains the blueprint of the class.
Or
1. ClassName cn;
What is an object?
39
It is a runtime entity.
Or
ClassName cn;
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.
The parameterized constructor is used to provide different values to distinct objects. However, you
can provide the same values also.
In Java, a constructor is just like a method but without return type. It can also be overloaded like
Java methods.
Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a different
task. They are differentiated by the compiler by the number of parameters in the list and their types.
class Student5{
int id;
41
String name;
int age;
id = i;
name = n;
id = i;
name = n;
age=a;
s1.display();
s2.display();
42
There are many differences between constructors and methods. They are given below.
A constructor is used to initialize the state A method is used to expose the behavior of an
of an object. object.
A constructor must not have a return type. A method must have a return type.
The Java compiler provides a default The method is not provided by the compiler in
constructor if you don't have any any case.
constructor in a class.
The constructor name must be same as The method name may or may not be same as
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
43
We can copy the values of one object into another by assigning the objects values to another object.
In this case, there is no need to create the constructor.
Access Modifier: In java, there exist four different types of access modifiers:
Public: Methods declared as public are accessible from all classes within an application.
Protected: Methods declared as protected are accessible from the class within which it is defined
and all subclasses of that class.
Private: Methods declared as private are only accessible from the class within which it is defined.
Default: Methods declared as default are accessible from the class within which it is defined and
from classes declared within the same package as the class enclosing the method.
Return Type: This contains the data type of the value the method is supposed to return, or it is
void if the method does not return anything.
Method Name: This is the name assigned to the method, which may or may not be unique. It is
to be noted that the method name should be verbs, and words used show follow camel case
notation.
Parameters: This includes a list of input parameters separated by commas with their data types.
If the method does not require any input parameters, then () is used.
44
Exceptions: In case a method may throw one or more exceptions, we can list exceptions
separated by commas.
Method Body: It is the programming content enclosed between braces. The method body
contains one or more logical statements for executing a particular task.
Syntax:
return s3;
Build-in Methods: These methods are available in the java library and do not need to be created
by a developer. For example, the max() method is present in Math class in java.
45
When a calling program calls a method, the control goes into the method body. After control
goes to the method body, it returns to the calling program under the following three conditions:
All statements written inside the method body are executed successfully.
Any return statement is encountered.
An Exception is thrown.
Static methods are called using the class name, and non-static methods are called using object
instance.
Example #1
Now we will see java code examples show how methods are declared and called using java. In
this example, we will see how to create a static method and how is it called.
Code:
package com.edubca.methods;
if(a>b){
return a;
}else {
return b;
46
System.out.println("Out of 10 and 23, " + maxvalue1 + " is greater" );
Linkable current;
47
// The constructor uses the private head field of the containing class
current = current.getNext();
return value;
Like instance fields and instance methods, every member class is associated with an instance of
the class within which it is defined (i.e., every instance of a member class is associated with an
instance of the containing class). This means that the code of a member class has access to all the
instance fields and instance methods (as well as the
static members) of the containing class, including any that are declared private.
This crucial feature is illustrated in Example Here is the body of the LinkedStack.Enumerator()
constructor again:
current = head;
A member class cannot have the same name as any containing class or package. This is
an important rule, and one not shared by fields and methods.
48
Member classes cannot contain any static fields, methods, or classes (with the exception of
constant fields declared both static and final). static fields, methods, and classes are top-
level constructs not associated with any particular object, while every member classis
associated with an instance of its enclosing class. Defining a static top-level member within
a non-top-level member class simply promotes confusion and bad programming style, so
you are required to define all static members within a top-level or static member class or
interface.
Interfaces cannot be defined as member classes. An interface cannot be instantiated, so
there is no object to associate with an instance of the enclosing class. If you declare an
interface as a member of a class, the interface is implicitly static, making it a static member
class.
Syntax:
<class-name>.<variable-name>
Static method in Java is a method which belongs to the class and not to the object. A static method
can access only static data. It is a method which belongs to the class and not to the object(instance).
A static method can access only static data. It cannot access non-static data (instance variables).
A static method can call only other static methods and can not call a non-static method
from it.
A static method can be accessed directly by the class name and doesn’t need any object
A static method cannot refer to “this” or “super” keywords in anyway
49
Syntax:
<class-name>.<method-name>
Instance variables in Java are non-static variables which are defined in a class outside any method,
constructor or a block. Each instantiated object of the class has a separate copy or instance of that
variable. An instance variable belongs to a class.
You must be wondering about what exactly is an Instance? Let me help you by simplifying it.
When you create a new object of the class you create an instance. Consider, if you have a
STUDENT class, then
1 class Student
2{
3 String studentName;
4 int studentScore;
5}
Now each student would have his own name and score right? So the value that is stored inside
‘studentName’ and ‘studentScore’ would vary for different students, they are called ‘variables’.
And like you saw that these variables hold their own value for each instance, they are called
Instance Variables in Java.
The life of an instance variable depends on the life of an Object, i.e., when the object is created,
an instance variable also gets created and the same happens when an object is destroyed.
50
Instance Variable can be used only by creating objects
Every object will have its own copy of Instance variables
Initialization of instance variable is not compulsory. The default value is zero
The declaration is done in a class outside any method, constructor or block
Instance variables are used when the variable has to be known to different methods in a
class
Access modifiers can be assigned to instance variables
After attaining theoretical knowledge, you might be pondering on how to implement Instance
variables in Java! Let’s understand that in our next topic.
Implementation of Instance variables in Java is quite easy. I have written a simple code that will
help you to grasp the technical usage.
To clarify the differences, I have jotted down a few points that will help you to discard any
ambiguity between the two.
Every object will have its own copy of instance Class variables are common to all objects of a
variables, hence changes made to these variables class, if any changes are made to these
through one object will not reflect in another variables through object, it will reflect in
object. other objects as well.
Instance variables are declared Class variables are declared
without static keyword. with keyword static
Instance variables can be used only via object Class variables can be used through either
reference. class name or object reference.
51
3.6. Method in java
In general, a method is a way to perform some task. Similarly, the method in Java is a collection
of instructions that performs a specific task. It provides the reusability of code. We canalso easily
modify code using methods. In this section, we will learn what is a method in Java, types of
methods, method declaration, and how to call a method in Java.
The most important method in Java is the main() method. If you want to read more about the
main() method, go through the link https://www.javatpoint.com/java-main-method.
Method Declaration
The method declaration provides information about method attributes, such as visibility, return-
type, name, and arguments. It has six components that are known as method header, as we have
shown in the following figure.
52
Method Signature: Every method has a method signature. It is a part of the method declaration.
It includes the method name and parameter list.
Access Specifier: Access specifier or modifier is the access type of the method. It specifies the
visibility of the method. Java provides four types of access specifier:
o Public: The method is accessible by all classes when we use public specifier in our
application.
o Private: When we use a private access specifier, the method is accessible only in the
classes in which it is defined.
o Protected: When we use protected access specifier, the method is accessible within the
same package or subclasses in a different package.
o Default: When we do not use any access specifier in the method declaration, Java uses
default access specifier by default. It is visible only from the same package only.
Return Type: Return type is a data type that the method returns. It may have a primitive data
type, object, collection, void, etc. If the method does not return anything, we use void keyword.
53
Method Name: It is a unique name that is used to define the name of a method. It must be
corresponding to the functionality of the method. Suppose, if we are creating a method for
subtraction of two numbers, the method name must be subtraction(). A method is invoked by its
name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of
parentheses. It contains the data type and variable name. If the method has no parameter, left the
parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to be performed.
It is enclosed within the pair of curly braces
Naming a Method
While defining a method, remember that the method name must be a verb and start with
a lowercase letter. If the method name has more than two words, the first name must be a verb
followed by adjective or noun. In the multi-word method name, the first letter of each word must
be in uppercase except the first word. For example:
It is also possible that a method has the same name as another method name in the same class, it
is known as method overloading.
Types of Method
o Predefined Method
o User-defined Method
Predefined Method
54
In Java, predefined methods are the method that is already defined in the Java class libraries is
known as predefined methods. It is also known as the standard library method or built-in
method. We can directly use these methods just by calling them in the program at any point. Some
pre-defined methods are length(), equals(), compareTo(), sqrt(), etc. When we call any of the
predefined methods in our program, a series of codes related to the corresponding method runs in
the background that is already stored in the library.
Each and every predefined method is defined inside a class. Such as print() method is defined in
the java.io.PrintStream class. It prints the statement that we write inside the method. Forexample,
print("Java"), it prints Java on the console.
Demo.java
The method written by the user or programmer is known as a user-defined method. These methods
are modified according to the requirement.
Let's create a user defined method that checks the number is even or odd. First, we will define
the method.
55
2. public static void findEvenOdd(int num)
3. {
4. //method body
5. if(num%2==0)
6. System.out.println(num+" is even");
7. else
8. System.out.println(num+" is odd");
9. }
3.7.1. Encapsulation
Encapsulation in Java is a process of wrapping code and data together into a single unit, for
example, a capsule which is mixed of several medicines.
We can create a fully encapsulated class in Java by making all the data members of the class
private. Now we can use setter and getter methods to set and get the data in it.
By providing only a setter or getter method, you can make the class read-only or write-
only. In other words, you can skip the getter or setter methods.
It provides you the control over the data. Suppose you want to set the value of id which
should be greater than 100 only, you can write the logic inside the setter method. You can
write the logic not to store the negative numbers in the setter methods.
It is a way to achieve data hiding in Java because other class will not be able to access the
data through the private data members.
56
The encapsulate class is easy to test. So, it is better for unit testing.
The standard IDE's are providing the facility to generate the getters and setters. So, it
is easy and fast to create an encapsulated class in Java.
Let's see the simple example of encapsulation that has only one field with its setter and getter
methods.
File: Student.java
3. package com.javatpoint;
4. public class Student{
9. return name;
10. }
13. this.name=name
14. }
15. }
3.7.2. Inheritance
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors
of a parent object. It is an important part of OOPs (Object Oriented programming system).
57
The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent
class. Moreover, you can add new methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
Class: A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created.
Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived
class, extended class, or child class.
Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It
is also called a base class or a parent class.
Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the
fields and methods of the existing class when you create a new class. You can use the same fields
and methods already defined in the previous class.
The extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.
58
As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The
relationship between the two classes is Programmer IS-A Employee. It means that Programmer
is a type of Employee.
1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. System.out.println("Programmer salary is:"+p.salary);
9. System.out.println("Bonus of Programmer is:"+p.bonus);
10. }
11. }
Types of inheritance in java
59
On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only. We
will learn about interfaces later.
When one class inherits multiple classes, it is known as multiple inheritance. For
Example:
60
Single Inheritance Example
When a class inherits another class, it is known as a single inheritance. In the example given
below, Dog class inherits the Animal class, so there is the single inheritance.
File: TestInheritance.java
class Animal{
void eat(){System.out.println("eating...");}
void bark(){System.out.println("barking...");}
class TestInheritance{
d.bark();
61
d.eat();
}}
Output:
barking...
eating...
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the
example given below, BabyDog class inherits the Dog class which again inherits the Animal class,
so there is a multilevel inheritance.
File: TestInheritance2.java
class Animal{
void eat(){System.out.println("eating...");}
void bark(){System.out.println("barking...");}
void weep(){System.out.println("weeping...");}
class TestInheritance2{
d.weep();
62
d.bark();
d.eat();
}}
Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If
A and B classes have the same method and you call it from child class object, there will be
ambiguity to call the method of A or B class.
Since compile-time errors are better than runtime errors, Java renders compile-time error if you
inherit 2 classes. So whether you have same method or different, there will be compile time error.
Aggregation in Java
Consider a situation, Employee object contains many informations such as id, name, emailId etc.
It contains one more object named address, which contains its own informations such as city, state,
country, zipcode etc. as given below.
class Employee{
int id;
String name;
...
In such case, Employee has an entity reference address, so relationship is Employee HAS-A
address.
63
For Code Reusability.
Aggregation in Java
Consider a situation, Employee object contains many information’s such as id, name, email ID etc.
It contains one more object named address, which contains its own information’s such as city,
state, country, zip code etc. as given below.
Class Employee {
Int id;
String name;
...
In such case, Employee has an entity reference address, so relationship is Employee HAS-A
address.
64
Simple Example of Aggregation
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.
65
1) Method Overloading: changing no. of arguments
In this example, we have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers. we are creating static
methods so that we don't need to create instance for calling methods.
class Adder{
class TestOverloading1{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
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.
class Adder{
class TestOverloading2{
System.out.println(Adder.add(11,11));
66
System.out.println(Adder.add(12.3,12.6));
}}
One type is promoted to another implicitly if no matching datatype is found. Let's understand the
concept by the figure given below:
As displayed in the above diagram, byte can be promoted to short, int, long, float or double. The
short datatype can be promoted to int, long, float or double. The char datatype can be promoted
to int,long,float or double and so on.
class OverloadingCalculation1{
67
OverloadingCalculation1 obj=new OverloadingCalculation1();
obj.sum(20,20,20);
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.
Method overriding is used to provide the specific implementation of a method which is already
provided by its superclass.
68
3.8 Review question
1. Write a program to print the area of a rectangle by creating a class named 'Area' having two
methods. First method named as 'setDim' takes length and breadth of rectangle as parameters
and the second method named as 'getArea' returns the area of the rectangle. Length and
breadth of rectangle are entered through keyboard.
2. Create a class named 'Student' with String variable 'name' and integer variable 'roll_no'.
Assign the value of roll_no as '2' and that of name as "John" by creating an object of the class
Student.
3. Assign and print the roll number, phone number and address of two students having names
"Sam" and "John" respectively by creating two objects of class 'Student'.
4. Write a program to print the area and perimeter of a triangle having sides of 3, 4 and 5 units
by creating a class named 'Triangle' without any parameter in its constructor.
5. Write a program to print the area and perimeter of a triangle having sides of 3, 4 and 5 units
by creating a class named 'Triangle' with constructor having the three sides as its parameters.
6. Write a program to print the area of two rectangles having sides (4,5) and (5,8) respectively
by creating a class named 'Rectangle' with a method named 'Area' which returns the area and
length and breadth passed as parameters to its constructor.
7. Write a program to print the area of a rectangle by creating a class named 'Area' taking the
values of its length and breadth as parameters of its constructor and having a method named
'returnArea' which returns the area of the rectangle. Length and breadth of rectangle are
entered through keyboard.
69
9. Print the average of three numbers entered by user by creating a class named 'Average' having
a method to calculate and print the average.
10. Print the sum, difference and product of two complex numbers by creating a class named
'Complex' with separate methods for each operation whose real and imaginary parts are
entered by user.
11. Write a program that would print the information (name, year of joining, salary, address) of
three employees by creating a class named 'Employee'. The output should be as follows: Name
Year of joining AddressRobert 1994 64C-
WallsStreat
Sam 2000 68D- WallsStreat
John 1999 26B- WallsStreat
12. Add two distances in inch-feet by creating a class named 'AddDistance'.
70
Chapter 4:
4. Exception Handling
The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that the normal flow of the application can be maintained.
In Java, an exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.
Exception Handling is a mechanism to handle runtime errors such as Class Not Found
Exception, IO Exception, SQL Exception, Remote Exception, etc.
The core advantage of exception handling is to maintain the normal flow of the application. An
exception normally disrupts the normal flow of the application; that is why we need to handle
exceptions. Let's consider a scenario:
statement 1;
statement 2;
statement 3;
statement 4;
71
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two
subclasses: Exception and Error. The hierarchy of Java Exception classes is given below:
72
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. An error is considered as the
unchecked exception. However, according to Oracle, there are three types of exceptions namely:
Checked Exception
Unchecked Exception
Error
1) Checked Exception
The classes that directly inherit the Throwable class except Runtime Exception and Error are
known as checked exceptions. For example, IOException, SQLException, etc. Checked
exceptions are checked at compile-time.
2) Unchecked Exception
The classes that inherit the Runtime Exception are known as unchecked exceptions. For example,
Arithmetic Exception, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked
exceptions are not checked at compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable. Some example of errors is Out of Memory Error, Virtual Machine Error,
Assertion Error etc.
Java provides five keywords that are used to handle the exception. The following table describes
each.
73
Keyword Description
Try The "try" keyword is used to specify a block where we should place an exception code.
It means we can't use try block alone. The try block must be followed by eithercatch
or finally.
Catch The "catch" block is used to handle the exception. It must be preceded by try block
which means we can't use catch block alone. It can be followed by finally block later.
Finally The "finally" block is used to execute the necessary code of the program. It is
executed whether an exception is handled or not.
Throws The "throws" keyword is used to declare exceptions. It specifies that there may occur
an exception in the method. It doesn't throw an exception. It is always used with
method signature.
Let's see an example of Java Exception Handling in which we are using a try-catch statement to
handle the exception.
JavaExceptionExample.java
try{
74
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
There are given some scenarios where unchecked exceptions may occur. They are as follows:
int a=50/0;//ArithmeticException
If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may be
other reasons to occur ArrayIndexOutOfBoundsException. Consider the following statements.
75
a[10]=50; //ArrayIndexOutOfBoundsException
(1) An abnormal execution condition was synchronously detected by the Java virtual machine.
– When evaluation of an expression violates the normal semantics (Example: an integer divide
by zero)
– An error occurs in loading or linking part of the program
– When limitation on a resource is exceeded (Example: using too much memory)
If a method needs to be able to throw an exception, it has to declare the exception(s) thrown in
the method signature, and then include a throw-statement in the method. Here is an example:
throws BadNumberException{
if(numberToDivideBy == 0){
76
When an exception is thrown the method stops execution right after the "throw" statement. Any
statements following the "throw" statement are not executed. In the example above the "return
numberToDivide / numberToDivideBy;" statement is not executed if a BadNumberException is
thrown. The program resumes execution when the exception is caught somewhere by a "catch"
block. Catching exceptions is explained later.
You can throw any type of exception from your code, as long as your method signature declares
it. You can also make up your own exceptions. Exceptions are regular Java classes that extends
java.lang.Exception, or any of the other built-in exception classes. If a method declares that it
throws an exception A, then it is also legal to throw subclasses of A.
Catching Exceptions
If a method calls another method that throws checked exceptions, the calling method is forced to
either pass the exception on, or catch it. Catching the exception is done using a try-catch block.
Here is an example:
try {
System.out.println(result);
} catch (BadNumberException e) {
System.out.println(e.getMessage());
77
If no exeception is thrown by any of the methods called or statements executed inside the
try-block, the catch-block is simply ignored. It will not be executed.
If an exception is thrown inside the try-block, for instance from the divide method, the
program flow of the calling method, callDivide, is interrupted just like the program flow
inside divide. The program flow resumes at a catch-block in the call stack that can catch
the thrown exception. In the example above the "System.out.println(result);" statement will
not get executed if an exception is thrown fromt the divide method. Instead program
execution will resume inside the "catch
If an exception is thrown inside the catch-block and that exception is not caught, the catch-
block is interrupted just like the try-block would have been.
When the catch block is finished the program continues with any statements following
the catch block. In the example above the "System.out.println("Division attempt done");"
statement will always get executed.
Finally
You can attach a finally-clause to a try-catch block. The code inside the finally clause will
always be executed, even if an exception is thrown from within the try or catch block. If your code
has a return statement inside the try or catch block, the code inside the finally-block will get
executed before returning from the method. Here is how a finally clause looks:
try {
int i=0;
while(i != -1){
78
i = reader.read();
System.out.println((char) i );
} catch (IOException e) {
} finally {
if(reader != null){
try {
reader.close();
} catch (IOException e) {
No matter whether an exception is thrown or not inside the try or catch block the code inside the
finally-block is executed. The example above shows how the file reader is always closed,
regardless of the program flow inside the try or catch block.
Note: If an exception is thrown inside a finally block, and it is not caught, then that finally block
is interrupted just like the try-block and catch-block is. That is why the previous example had the
reader.close() method call in the finally block wrapped in a try-catch block:
} finally {
if(reader != null){
79
try {
reader.close();
} catch (IOException e) {
That way the System.out.println("--- File End ---"); method call will always be executed. If no
unchecked exceptions are thrown that is. More about checked and unchecked in a later chapter.
You don't need both a catch and a finally block. You can have one of them or both of them with
a try-block, but not none of them. This code doesn't catch the exception but lets it propagate up the
call stack. Due to the finally block the code still closes the filer reader even if an exception is
thrown.
Although java provides the Exception class, which covers almost all cases of exceptions
that could be raised during program execution, custom exceptions will bring the spotlight
onto exception handling.
Custom exceptions enable the flexibility of adding messages and methods that are not
part of the Exception class. They can be used to store case-specific messages like status
codes and error codes or override an existing method to present the exception as per the
use case.
80
Custom exceptions are helpful while writing exceptions for business logic. It helps the
application developers to better understand the exception, which is business-specific.
Now that we are aware of custom exceptions in java and their use cases, let's have a look at how
to create them.
Let's add our custom message to the exception class. This can be done in two ways :
1. Pass the Exception Message to Super Class Constructor and Retrieve It Using the
getMesssage() Method
//parameter constructor
SimpleCustomException(String msg) {
super(msg);
}
81
In the above code, we've made a call to the parent class constructor using the super keyword. Since
the custom class is extended by the Exception class, it is considered to be the parent class, and the
Exception class has a parameter constructor which expects a string. It will construct a new
exception with the specified message that can be retrieved later using the
getMessage() method.
2. Override the toString() Method and Customize It with Our Exception Message
String msg;
SimpleCustomException(String msg) {
this.msg=msg;
@Override
return msg;
In the above code, we've overridden the toString() method. Usually, when we print an object of a
java class, it prints the hashcode of that object (default implementation of the toString() method).
82
Overriding the toString() method provides the flexibility to customize the print statement when we
print an object. Now that we've overridden the method with our custom message, the user only
needs to print the exception object to know the exception message.
Chapter 5:
83
users can connect with an application. Swing and JavaFX are two commonly used applications
to create GUIs in Java.
Elements of GUI:
A GUI comprises an array of user interface elements. All these elements are displayed when a user
is interacting with an application and they are as follows:
1. Input commands such as buttons, check boxes, dropdown lists and text fields.
As mentioned above, to create a GUI in Java, Swing and JavaFX are the most commonly used
applications. Swing was designed with a flexible architecture to make the elementscustomizable
and easy to plug-and-play which is why it is the first choice for java developers while creating
GUIs.
As far as JavaFX is concerned, it consists of a totally different set of graphic components along
with new features and terminologies.
Creating a GUI
The process of creating a GUI in Swing starts with creating a class that represents the main
GUI. An article of this class acts as a container which holds all the other components to be
displayed.
In most of the projects, the main interface article is a frame, i.e., the JFrame class in
javax.swing package. A frame is basically a window which is displayed whenever a
user opens an application on his/her computer. It has a title bar and buttons such as
minimize, maximize and close along with other features.
The JFrame class consists of simple constructors such as JFrame() and JFrame(String). The
JFrame() leaves the frame’s title bar empty, whereas the JFrame(String) places the title bar
to a specified text.
84
Apart from the title, the size of the frame can also be customized. It can be established by
incorporating the setSize(int, int) method by inserting the width and height desired for
the frame. The size of a frame is always designated in pixels.
For example, calling setSize(550,350) would create a frame that would be 550 pixels wide and
350 pixels tall.
Usually, frames are invisible at the time of their creation. However, a user can make them
visible by using the frame’s setVisible(boolean) method by using the word ‘true’ as an argument.
STEP 2: Save and compile the code as mentioned above and then run it.
STEP 3: Adding buttons to the above frame. To create a component in Java, the user is
required to create an object of that component’s class. We have already understood the container
class JFrame.
One such component to implement is JButton. This class represents the clickable buttons.
In any application or program, buttons trigger user actions. Literally, every action begins
with a click; like to close an application, the user would click on the close button.
A swing can also be inserted, which can feature a text, a graphical icon or a combination
of both. A user can use the following constructors:
STEP 4: The above is to be executed. A big button will appear on the screen.
STEP 5: A user can add two buttons to the frame as well. Copy the code given below into an
editor.
85
STEP 6: Save, compile and run the above code.
STEP 7: Unpredicted output = ? It means that the buttons are getting overlapped.
STEP 8: A user can create chat frames as well. Below is an example of the same:
There are current three sets of Java APIs for graphics programming:
AWT API was introduced in JDK 1.0. Most of the AWT UI components have become
obsolete and should be replaced by newer Swing UI components.
Swing API, a much more comprehensive set of graphics libraries that enhances the AWT,
was introduced as part of Java Foundation Classes (JFC) after the release of JDK 1.1. JFC
consists of Swing, Java2D, Accessibility, Internationalization, and Pluggable Look- and-
Feel Support APIs. JFC has been integrated into core Java since JDK 1.2.
The latest JavaFX, which was integrated into JDK 8, was meant to replace Swing. JavaFX
was moved out from the JDK in JDK 11, but still available as a separate module.
Other than AWT/Swing/JavaFX graphics APIs provided in JDK, other
organizations/vendors have also provided graphics APIs that work with Java, such as
Eclipse's Standard Widget Toolkit (SWT) (used in Eclipse), Google Web Toolkit (GWT)
(used in Android), 3D Graphics API such as Java bindings for OpenGL (JOGL), Java3D,
and etc. Furthermore, developers have moved to use technologies such as HTML5 as the
basis of webapps.
86
o GUI Component classes, such as Button, TextField, and Label.
o GUI Container classes, such as Frame and Panel.
o Layout managers, such as Flow Layout, Border Layout and Grid Layout.
o Custom graphics classes, such as Graphics, Color and Font.
o The java.awt.event package supports event handling:
o Event classes, such as ActionEvent, MouseEvent, KeyEvent and WindowEvent,
o EventListenerInterfaces,suchas ActionListener, MouseListener, MouseMotionListener, K
eyListener and WindowListener,
o Event Listener Adapter classes, such as Mouse Adapter, KeyAdapter,
and WindowAdapter.
Component (Widget, Control): Components are elementary GUI entities, such as Button, Label,
and TextField. They are also called widgets, controls in other graphics systems.
Container: Containers, such as Frame and Panel, are used to hold components in a specificlayout
(such as FlowLayout or GridLayout). A container can also hold sub-containers.
In the above figure, there are three containers: a Frame and two Panels. A Frame is the top-level
container of an AWT program. A Frame has a title bar (containing an icon, a title, and the
minimize/maximize/close buttons), an optional menu bar and the content display area. A Panel is
a rectangular area used to group related GUI components in a certain layout. In the above
87
figure, the top-level Frame contains two Panels. There are five components: a Label (providing
description), a TextField (for users to enter text), and three Buttons (for user to trigger certain
programmed actions).
In a GUI program, a component must be kept (or added) in a container. You need to identify a
container to hold the components. Every container has a method called add(Component c).
A container (say aContainer) can invoke aContainer.add(aComponent) to add aComponent into
itself. For example,
GUI components are also called controls (e.g., Microsoft ActiveX Control), widgets (e.g., Eclipse's
Standard Widget Toolkit, Google Web Toolkit), which allow users to interact with (or control) the
application.
Each GUI program has a top-level container. The commonly-used top-level containers in AWT
are Frame, Dialog and Applet:
A Frame provides the "main window" for your GUI application. It has a title bar (containing an
icon, a title, the minimize, maximize/restore-down and close buttons), an optional menu bar, and
88
the content display area. To write a GUI program, we typically start with a subclass extending
from java.awt.Frame to inherit the main window as follows:
// This subclass inherits all properties from Frame, e.g., title, icon, buttons, content-pane
// private variables
......
new MyGUIProgram();
89
An AWT Dialog is a "pop-up window" used for interacting with the users. A Dialog has a title-
bar (containing an icon, a title and a close button) and a content display area, as illustrated.
An AWT Applet (in package java.applet) is the top-level container for an applet, which is a Java
program running inside a browser. Applet is no longer supported in most of the browsers.
Secondary containers are placed inside a top-level container or another secondary container.
AWT provides these secondary containers:
Panel: a rectangular box used to layout a set of related GUI components in pattern such as grid or
flow.
ScrollPane: provides automatic horizontal and/or vertical scrolling for a single child component.
others.
90
As illustrated, a Container has a Layout Manager to layout the components in a certain pattern,
e.g., flow, grid.
91
A java.awt.Label provides a descriptive text string. Take note that System.out.println() prints to
the system console, NOT to the graphics screen. You could use a Label to label another component
(such as text field) to provide a text description.
Constructors
public Label(String strLabel, int alignment); // Construct a Label with the given text String, of
the text alignment
public Label(String strLabel); // Construct a Label with the given text String
i. The first constructor constructs a Label object with the given text string in the given
alignment. Note that three static constants Label.LEFT, Label.RIGHT,and
Label.CENTER are defined in the class for you to specify the alignment (rather than
asking you to memorize arbitrary integer values).
ii. The second constructor constructs a Label object with the given text string in default of
left-aligned.
iii. The third constructor constructs a Label object with an initially empty string. You could
set the label text via the setText() method later.
92
These three constants are defined for specifying the alignment of the Label's text, as used in the
above constructor.
Public Methods
// Examples
The getText() and setText() methods can be used to read and modify the Label's text. Similarly,
the getAlignment() and setAlignment() methods can be used to retrieve and modify thealignment
of the text.
Construct the component by invoking an appropriate constructor via the new operator;
Identify the container (such as Frame or Panel) designed to hold this component. The container
can then add this component onto itself via aContainer.add(aComponent) method. Every container
has a add(Component) method. Take note that it is the container that actively and explicitly adds
a component onto itself, NOT the other way.
Swing
Swing is part of the so-called "Java Foundation Classes (JFC)" (have you heard of MFC?), which
was introduced in 1997 after the release of JDK 1.1. JFC was subsequently included as an integral
part of JDK since JDK 1.2. JFC consists of:
93
Java 2D API: for high quality 2D graphics and images.
Pluggable look and feel supports.
Drag-and-drop support between Java and native applications.
The goal of Java GUI programming is to allow the programmer to build GUI that looks good on
ALL platforms. JDK 1.0's AWT was awkward and non-object-oriented (using many
event.getSource()). JDK 1.1's AWT introduced event-delegation (event-driven) model, much
clearer and object-oriented. JDK 1.1 also introduced inner class and JavaBeans – a component
programming model for visual programming environment (similar to Visual Basic).
Swing appeared after JDK 1.1. It was introduced into JDK 1.1 as part of an add-on JFC (Java
Foundation Classes). Swing is a rich set of easy-to-use, easy-to-understand JavaBean GUI
components that can be dragged and dropped as "GUI builders" in visual programming
environment. Swing is now an integral part of Java since JDK 1.2.
Swing's Features
Swing is huge (consists of 18 packages of 737 classes as in JDK 1.8) and has great depth.
Compared with AWT, Swing provides a huge and comprehensive collection of reusable GUI
components, as shown in the Figure below (extracted form Swing Tutorial).
The main features of Swing are (extracted from the Swing website):
Swing is written in pure Java (except a few classes) and therefore is 100% portable.
Swing components are lightweight. The AWT components are heavyweight (in terms of system
resource utilization). Each AWT component has its own opaque native display, and always
displays on top of the lightweight components. AWT components rely heavily on the underlying
windowing subsystem of the native operating system. For example, an AWT button ties to an
actual button in the underlying native windowing subsystem, and relies on the native windowing
subsystem for their rendering and processing. Swing components (JComponents) are written in
Java. They are generally not "weight-down" by complex GUI considerations imposed by the
underlying windowing subsystem.
Swing components support pluggable look-and-feel. You can choose between Java look-and-
feel and the look-and-feel of the underlying OS (e.g., Windows, UNIX or macOS). If the later is
94
chosen, a Swing button runs on the Windows looks like a Windows' button and feels like a
Window's button. Similarly, a Swing button runs on the UNIX looks like a UNIX's button and
feels like a UNIX's button.
Swing supports mouse-less operation, i.e., it can operate entirely using keyboard.
Swing components are JavaBeans – a Component-based Model used in Visual Programming (like
Visual Basic). You can drag-and-drop a Swing component into a "design form" using a "GUI builder"
and double-click to attach an event handler.
1. Swing application uses AWT event-handling classes (in package java.awt.event). Swing
added some new classes in package javax.swing.event, but they are not frequently used.
2. Swing application uses AWT's layout manager (such as FlowLayout and BorderLayout in
package java.awt). It added new layout managers, such as Springs, Struts,and
BoxLayout (in package javax.swing).
95
3. Swing implements double-buffering and automatic repaint batching for smoother screen
repaint.
4. Swing introduces JLayeredPane and JInternalFrame for creating Multiple Document
Interface (MDI) applications.
5. Swing supports floating toolbars (in JToolBar), splitter control, "undo".
If you understood the AWT programming (in particular, container/component and event-
handling), switching over to Swing (or any other Graphics packages) is straight-forward.
Swing's Components
Compared with the AWT component classes (in package java.awt), Swing component classes (in
package javax.swing) begin with a prefix "J", e.g., JButton, JTextField, JLabel, JPanel, JFrame, or
JApplet.
The above figure shows the class hierarchy of the swing GUI classes. Similar to AWT, there are
two groups of classes: containers and components. A container is used to hold components. A
container can also hold containers because it is a (subclass of) component.
96
As a rule, do not mix heavyweight AWT components and lightweight Swing components in the
same program, as the heavyweight components will always be painted on top of the lightweight
components.
Swing's Top-Level and Secondary Containers
Just like AWT application, a Swing application requires a top-level container. There are three top-
level containers in Swing:
1. JFrame: used for the application's main window (with an icon, a title,
minimize/maximize/close buttons, an optional menu-bar, and a content-pane), asillustrated.
2. JDialog: used for secondary pop-up window (with a title, a close button, and a content-
pane).
3. JApplet: used for the applet's display-area (content-pane) inside a browser’s window.
Similarly to AWT, there are secondary containers (such as JPanel) which can be used to group
and layout relevant components.
The Content-Pane of Swing's Top-Level Container
However, unlike AWT, the JComponents shall not be added onto the top-level container (e.g.,
JFrame, JApplet) directly because they are lightweight components. The
JComponents must be added onto the so-called content-pane of the top-level container. Content-
pane is in fact a java.awt.Container that can be used to group and layout components.
97
You could:
1. get the content-pane via getContentPane() from a top-level container, and add components
onto it. For example,
14. set the content-pane to a JPanel (the main panel created in your application which holds all
your GUI components) via JFrame's setContentPane().
98
Notes: If a component is added directly into a JFrame, it is added into the content-pane
Event-Handling in Swing
Swing uses the AWT event-handling classes (in package java.awt.event). Swing introduces a few
new event-handling classes (in package javax.swing.event) but they are not frequently used.
A top-level container (typically JFrame) is needed. The JComponents should not be added directly
onto the top-level container. They shall be added onto the content-pane of the top-level container.
You can retrieve a reference to the content-pane by invoking method getContentPane() from the top-
level container.
Run the constructor in the Event Dispatcher Thread (instead of Main thread) for thread safety, as
shown in the following program template.
99
4
// ......
9
10
// Constructor to setup the GUI components and event handlers
11
public SwingTemplate() {
12
// Retrieve the top-level content-pane from JFrame
13
Container cp = getContentPane();
14
15
// Content-pane sets layout
16
cp.setLayout(new .... Layout());
17
18
// Allocate the GUI components
19
// .....
20
22 cp.add(. .. );
23
25 // .....
100
26
27 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
32 }
33
// The entry main() method
34
public static void main(String[] args) {
35
// Run GUI codes in Event-Dispatching thread for thread-safety
36
SwingUtilities.invokeLater(new Runnable() {
37
@Override
38
public void run() {
39
new SwingTemplate(); // Let the constructor do the job
40
}
41 });
42 }
43 }
44
45
Java Swing is a GUI toolkit and a part of JFC (Java Foundation Class) helpful in developing
window-based applications. Java Swing is lightweight and platform-independent that contains
101
various components and container classes. Furthermore, the Java swing library is built on the top
of the AWT(Abstract Window Toolkit), an API completely written in Java. In every application,
users can find an interactive and user-friendly interface that gives them the freedom to use the app.
A component is independent visual control, and Java Swing Framework contains a large set of
these components, providing rich functionalities and allowing high customization. They all are
derived from JComponent class. All these components are lightweight components. This class
offers some standard functionality like pluggable look and feel, support for accessibility, drag
and drop, layout, etc.
A container holds a group of components. It delivers a space where a component can bemanaged
and displayed. Containers are of two types:
Heavyweight.
It is a general-purpose container.
Example: JPanel
102
Below are the 21 top components of swing in java are:
JButton
We use JButton class to create a push button on the UI. The button can include some display text
or images. It yields an event when clicked and double-clicked. We can implement a JButton in the
application by calling one of its constructors.
Syntax:
JButton
We use JButton class to create a push button on the UI. The button can include some display text
or images. It yields an event when clicked and double-clicked. We can implement a JButton in
the application by calling one of its constructors.
Syntax:
103
Returns a button with the car icon and text as Car.
Display:
JLabel
We use JLabel class to render a read-only text label or images on the UI. It does not generate any
event.
Syntax:
JLabel()
JLabel(String s)
JLabel(Icon i)
Display:
JTextField
The JTextField renders an editable single-line text box. Users can input non-formatted text in the
box. We can initialize the text field by calling its constructor and passing an optional integer
parameter. This parameter sets the box width measured by the number of columns. Also, it does
not limit the number of characters that can be input into the box.
Syntax:
104
JTextField txtBox = new JTextField(50);
JTextField(int cols)
JTextField(String str)
Display:
JCheckBox
The JCheckBox renders a check-box with a label. The check-box has two states, i.e., on and off.
On selecting, the state is set to "on," and a small tick is displayed inside the box.
Syntax:
It returns a checkbox with the label Pepperoni pizza. Notice the second parameter in the
constructor. It is a boolean value that denotes the default state of the check-box. True means the
check-box defaults to the "on" state.
Display:
JRadioButton
A radio button is a group of related buttons from which we can select only one. We use
JRadioButton class to create a radio button in Frames and render a group of radio buttons in the
UI. Users can select one choice from the group.
Syntax:
Display:
105
JComboBox
Syntax:
Display:
JTextArea
In Java, the Swing toolkit contains a JTextArea Class. It is under package javax.swing.JTextArea
class. It is used for displaying multiple-line text.
Declaration:
Syntax:
JTextArea()
JTextArea(String s)
Display:
JPasswordField
106
Declaration:
Syntax:
JPasswordField()
JPasswordField(int columns)
JPasswordField(String text)
Display:
JTable
In Java, the Swing toolkit contains a JTable Class. It is under package javax.swing.JTable class.
It is used to draw a table to display data.
Syntax:
JTable()
Display:
JList
In Java, the Swing toolkit contains a JList Class. It is under package javax.swing.JList class. It is
used to represent a list of items together. We can select one or more than one items from the list.
107
Declaration:
Syntax:
list1.addElement("Apple");
list1.addElement("Orange");
list1.addElement("Banan");
list1.addElement("Grape");
JList()
JList(ary[] listData)
JList(ListModel<ary> dataModel)
Display:
JOptionPane
Declaration:
Syntax:
JOptionPane(Object message)
Display:
JScrollBar
In Java, the Swing toolkit contains a JScrollBar class. It is under package javax.swing.JScrollBar
class. It is used for adding horizontal and vertical scrollbars.
Declaration:
Syntax:
JScrollBar()
JScrollBar(int orientation)
Display:
In Java, the Swing toolkit contains a JMenuBar, JMenu, and JMenuItem class. It is underpackage
javax.swing.JMenuBar, javax.swing.JMenu and javax.swing.JMenuItem class. The JMenuBar
class is used for displaying menubar on the frame. The JMenu Object is used to pull down the
menu bar's components. The JMenuItem Object is used for adding the labeled menu item.
109
public class JMenu extends JMenuItem implements MenuElement, Accessible
Syntax:
menu.add(menuItem1);
menu.add(menuItem2);
menu.add(menuItem3);
Display:
JPopupMenu
Declaration:
Syntax:
JPopupMenu()
JPopupMenu(String label)
110
Display:
JCheckBoxMenuItem
Syntax:
JCheckBoxMenuItem()
JCheckBoxMenuItem(Action a)
JCheckBoxMenuItem(Icon icon)
JCheckBoxMenuItem(String text)
Display:
JSeparator
components.
Declaration:
Syntax:
111
jmenu_Item.addSeparator();
JSeparator()
JSeparator(int orientation)
Display:
JProgressBar
Declaration:
Syntax:
JProgressBar()
JProgressBar(int orient)
Display:
JTree
In Java, the Swing toolkit contains a JTree Class. It is under package javax.swing.JTreeclass. It is
used for creating tree-structured data. It is a very complex component.
Declaration:
112
public class JTree extends JComponent implements Scrollable, Accessible
Syntax:
JTree()
JTree(Object[] value)
JTree(TreeNode root)
Display:
JFileChooser
The JFileChooser class renders a file selection utility. This component lets a user select a file
from the local system.
Syntax:
fileBtn.AddEventListner(new ActionListner(){
fileChooser.showOpenDialog();
})
The above code creates a file chooser dialog and attaches it to the button. The button click would
open the file chooser dialog. The selected file is returned through the get file method chosen.
Display:
113
JTabbedPane
The JTabbedPane is another beneficial component that lets the user switch between tabs in an
application. It is a handy utility as it allows users to browse more content without navigating to
different pages.
Syntax:
The above code creates a two-tabbed panel with headings Tab_1 and Tab_2.
Display:
JSlider
The JSlider component displays a slider that the user can drag to change its value. The
constructor takes three arguments: minimum, maximum, and initial.
114
Syntax:
The above code makes a slider from 0 to 100 with an initial value set to 20. The value specified
by the user is returned by the getValue method.
Display:
AWT (Abstract Window Toolkit) and Swing are both Java GUI (Graphical User Interface) toolkits
that provide a set of classes and components to create desktop applications. The main differences
between AWT and Swing are listed below:
115
Event handling mechanism Less flexible More flexible
JDBC was initially conceived as a client-side API, enabling a Java client to interact with a data
source. That changed with JDBC 2.0, which included an optional package supporting server-side
JDBC connections. Every new JDBC release since then has featured updates to both the client-
side package (java.sql) and the server-side package (javax.sql). JDBC 4.3, the most current version
as of this writing, was released as part of Java SE 9 in September 2017 as JSR 221.
As a developer, you can use JDBC to interact with a database from within a Java program. JDBC
acts as a bridge from your code to the database, as shown in Figure 1.
IDG
JDBC vs ODBC
116
ways, JDBC takes its inspiration from ODBC. The difference is that JDBC is Java-specific,
offering a programming-level interface that handles the mechanics of Java applications
communicating with a database.
JDBC’s architecture
IDG
Figure 2. JDBC’s architecture consists of the JDBC API and JDBC drivers.
JDBC drivers
JDBC-ODBC bridge driver: A thin Java layer that uses an ODBC driver under the hood.
117
Native API driver: Provides an interface from Java to the native database client.
Middleware driver: A universal interface (“middleware”) between Java and the RDBMS’s vendor-
specific protocol.
Pure Java driver: A driver that implements the vendor-specific protocol directly in Java.
When you start thinking about architecture and performance, it will be beneficial to consider the
type of driver you are using.
One of the benefits of programming in the Java ecosystem is that you will likely find a stable JDBC
database connector for whatever database you choose. In this tutorial, we'll use SQLite to get to
know JDBC, mainly because it's so easy to use.
To find a driver for your chosen database, simply do a web search for your database and JDBC.
For instance, typing in "mysql jdbc driver" will turn up a driver for MySQL. I challenge you to find
an enterprise-grade database without a JDBC driver!
SQLite is a very compact database. It isn't intended for production use but is a great choice for
quickly trying things out. SQLite uses a file as its functional database, without requiring any
service or daemon installations.
118
To get started with this demonstration, first download the SQLite sample database. Unzip the
.db file and save it somewhere you won't forget. This file contains both a functional file-based
database and sample schema and data that we can use.
NoSQL is popular but relational databases remain the most used type of datastore. A relational
database is a structured repository consisting of tables with columns and rows and the relationships
between the tables. SQL, or structured query language, is the language data architects use to
perform CRUD (create, read, update, and delete) operations on records in a relational database.
JDBC is an adapter layer from Java to SQL: it gives Java developers a common interface for
connecting to a database, issuing queries and commands, and managing responses.
We could do our coding in an IDE, but coding directly in a text editor will better demonstrate
JDBC's simplicity. To begin, you will need to have a compatible JDK installation for your
operating system.
Assuming you have a JDK installed, we can start by creating a simple Java program. In your text
editor, paste in the code shown in Listing 1. Call this file WhatIsJdbc.java.
class WhatIsJdbc{
System.out.println("Hello InfoWorld");
Now, compile the code by entering the command: javac WhatIsJdbc.java. Compiling will output
the WhatIsJdbc.class file. Execute this file from the command line with the call: java WhatIsJdbc.
119
Once you have a basic Java program, you can include the JDBC libraries. Paste in the code from
Listing 2 at the head of your simple Java program.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Statement;
Each of these imports provides access to a class that facilitates the standard Java database
connection:
DriverManager obtains the connection to the database. (Another option is DataSource, used for
connection pooling.)
SQLException handles SQL errors between the Java application and the database.
ResultSet and Statement model the data result sets and SQL statements.
Next, you'll add the SQLite driver to your classpath. Remember, a JDBC driver is a class that
implements the JDBC API for a specific database.
Go to the GitHub page for SQLite driver and download the latest SQLite .jar. If you are using
Maven or Gradle, or something similar, you can add the driver via the Maven repository. Be sure
to get the most recent .jar file and store it somewhere you'll remember.
The next time you execute your Java program, you will pull in that .jar file via the classpath. There
are several ways to set the classpath. Listing 3 shows how to do it using a command-line switch.
120
Listing 3. Executing the SQLite driver on the Java classpath
Notice that we've set the classpath to point at the driver and the local directory; this way, Java
will still find our class file.
The classpath now has access to the driver. Next, change your simple Java application file to
look like the program in Listing 4.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Statement;
PreparedStatement ps = con.prepareStatement(sql)) {
ps.setInt(1, userId);
while(rs.next()) {
121
} catch (SQLException e) {
e.printStackTrace();
return users;
class WhatIsJdbc{
System.out.println("Got it!");
} catch (SQLException e) {
Compile and execute this code. Assuming all goes well, you will get an affirming message.
If you've received an error that looks like "No suitable driver found for jdbc:sqlite," then you need to
revisit the classpath and make sure it points to the driver you downloaded. Failed driver connection
is the most common stumbling block for beginners using JDBC. Don't sweat it; just fix it.
With the live connection object in hand, we can do something useful, like querying the database.
Listing 5 shows how to query SQLite using the JDBC Connection and Statement objects.
122
Listing 5. Querying the database with JDBC
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Statement;
class WhatIsJdbc{
try {
while (rs.next()) {
System.out.println(name);
} catch (SQLException e ) {
} catch (SQLException e) {
123
throw new Error("Problem", e);
In Listing 5 we use our Connection object to obtain a Statement object: conn.createStatement(). We then
use this object to execute an SQL query: stmt.executeQuery(query).
The executeQuery command returns a ResultSet object, which we then use to iterate over the data
with while (rs.next()). In this example, you should see the album titles we've queried on as output.
124
12. Explain in detail of JDBC DriverManager?
13. Write an example program to connect Java application without DSN?
14. Explain Connection Interface?
15. Write a program which perform CRUD [Create, Update, Delete] operation using
Statement Interface.
16. What are the types of ResultSet?
17. Explain with a program on how to get the object of ResultSetMetaData?
18. Explain the database warnings in JDBC and how can we handle the database warnings
in JDBC?
19. Write a Java JDBC program to store image in Oracle Database.
20. What is the role of Class.forName() while loading JDBC drivers?
21. What are the multiple ways to connect to the database using JDBC?
22. What are the new available features of JDBC 4.0?
23. Give a list of Packages used in JDBC?
24. What is Data Source in JDBC and explain its benefits?
25. What are DDL and DML statements?
Chapter 6:
The java.io package contains nearly every class you might ever need to perform input and output
(I/O) in Java. All these streams represent an input source and an output destination. The stream
in the java.io package supports many data such as primitives, object, localized characters, etc.
Stream
A stream can be defined as a sequence of data. There are two kinds of Streams −
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many
classes related to byte streams but the most frequently used classesare,
FileInputStream and FileOutputStream. Following is an example which makes use of these two
classes to copy an input file into an output file −
Example
import java.io.*;
FileInputStream in = null;
try {
in = new FileInputStream("input.txt");
int c;
126
while ((c = in.read()) != -1) {
out.write(c);
}finally {
if (in != null) {
in.close();
if (out != null) {
out.close();
As a next step, compile the above program and execute it, which will result in creating output.txt
file with the same content as we have in input.txt. So let's put the above code in CopyFile.java
file and do the following −
$javac CopyFile.java
$java CopyFile
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, whereasJava
Character streams are used to perform input and output for 16-bit unicode. Though there aremany
classes related to character streams but the most frequently used classes
127
are, FileReader and FileWriter. Though internally FileReader uses FileInputStream and FileWriter
uses FileOutputStream but here the major difference is that FileReader reads two bytes at a time
and FileWriter writes two bytes at a time.
We can re-write the above example, which makes the use of these two classes to copy an input file
(having unicode characters) into an output file −
Example
import java.io.*;
FileReader in = null;
try {
in = new FileReader("input.txt");
int c;
out.write(c);
}finally {
if (in != null) {
128
in.close();
if (out != null) {
out.close();
As a next step, compile the above program and execute it, which will result in creating output.txt
file with the same content as we have in input.txt. So let's put the above code in CopyFile.java
file and do the following −
$javac CopyFile.java
$java CopyFile
Standard Streams
All the programming languages provide support for standard I/O where the user's program can
take input from a keyboard and then produce an output on the computer screen. If you are aware
of C or C++ programming languages, then you must be aware of three standard devices STDIN,
STDOUT and STDERR. Similarly, Java provides the following three standard streams −
Standard Input − This is used to feed the data to user's program and usually a keyboard is used as
standard input stream and represented as System.in.
Standard Output − This is used to output the data produced by the user's program and usually a
computer screen is used for standard output stream and represented as System.out.
129
Standard Error − This is used to output the error data produced by the user's program and usually
a computer screen is used for standard error stream and represented as System.err.
Following is a simple program, which creates InputStreamReader to read standard input stream
until the user types a "q" −
Example
Live Demo
import java.io.*;
try {
char c;
do {
c = (char) cin.read();
System.out.print(c);
} while(c != 'q');
}finally {
if (cin != null) {
cin.close();
130
}
Let's keep the above code in ReadConsole.java file and try to compile and execute it as shown in
the following program. This program continues to read and output the same character until we
press 'q' −
$javac ReadConsole.java
$java ReadConsole
As described earlier, a stream can be defined as a sequence of data. The InputStream is used to
read data from a source and the OutputStream is used for writing data to a destination.
131
The two important streams are FileInputStream and FileOutputStream, which would be
discussed in this tutorial.
FileInputStream
This stream is used for reading data from the files. Objects can be created using the
keyword new and there are several types of constructors available.
Following constructor takes a file name as a string to create an input stream object to read the file
−
Following constructor takes a file object to create an input stream object to read the file. First we
create a file object using File() method as follows −
132
Once you have InputStream object in hand, then there is a list of helper methods which can be
used to read to stream or to do other operations on the stream.
This method closes the file output stream. Releases any system resources associated
with the file. Throws an IOException.
This method cleans up the connection to the file. Ensures that the close method of this
file output stream is called when there are no more references to this stream. Throws an
IOException.
This method reads the specified byte of data from the InputStream. Returns an int.
Returns the next byte of data and -1 will be returned if it's the end of the file.
This method reads r.length bytes from the input stream into an array. Returns the total
number of bytes read. If it is the end of the file, -1 will be returned.
Gives the number of bytes that can be read from this file input stream. Returns an int.
133
There are other important input streams available, for more detail you can refer to the following
links −
ByteArrayInputStream
DataInputStream
FileOutputStream
FileOutputStream is used to create a file and write data into it. The stream would create a file, if
it doesn't already exist, before opening it for output.
Here are two constructors which can be used to create a FileOutputStream object.
Following constructor takes a file name as a string to create an input stream object to write the
file −
Following constructor takes a file object to create an output stream object to write the file. First,
we create a file object using File() method as follows −
Once you have OutputStream object in hand, then there is a list of helper methods, which can be
used to write to stream or to do other operations on the stream.
This method closes the file output stream. Releases any system resources associated
with the file. Throws an IOException.
This method cleans up the connection to the file. Ensures that the close method of this
134
file output stream is called when there are no more references to this stream. Throws an
IOException.
Writes w.length bytes from the mentioned byte array to the OutputStream.
There are other important output streams available, for more detail you can refer to the following
links −
ByteArrayOutputStream
DataOutputStream
Example
import java.io.*;
try {
135
}
os.close();
is.close();
} catch (IOException e) {
System.out.print("Exception");
The above code would create file test.txt and would write given numbers in binary format. Same
would be the output on the stdout screen.
There are several other classes that we would be going through to get to know the basics of File
Navigation and I/O.
File Class
FileReader Class
FileWriter Class
136
Directories in Java
A directory is a File which can contain a list of other files and directories. You use File object to
create directories, to list down files available in a directory. For complete detail, check a list of all
the methods which you can call on File object and what are related to directories.
Creating Directories
There are two useful File utility methods, which can be used to create directories −
The mkdir( ) method creates a directory, returning true on success and false on failure. Failure
indicates that the path specified in the File object already exists, or that the directory cannot be
created because the entire path does not exist yet.
The mkdirs() method creates both a directory and all the parents of the directory.
Example
import java.io.File;
d.mkdirs();
137
Note − Java automatically takes care of path separators on UNIX and Windows as per conventions.
If you use a forward slash (/) on a Windows version of Java, the path will still resolve correctly.
Listing Directories
You can use list( ) method provided by File object to list down all the files and directories
available in a directory as follows −
Example
import java.io.File;
String[] paths;
try {
paths = file.list();
for(String path:paths) {
138
// prints filename and directory name
System.out.println(path);
} catch (Exception e) {
e.printStackTrace();
139
18. How do you copy a file in Java?
19. How do you check the permission of a file or directory in Java?
20. How do you change the permission of a file in Java?
21. Can you open a ZIP file in Java? How?
22. What is the difference between ZipFile and ZipInputStream?
23. When does java.io.FileNotFoundException: (Access is denied) comes? How do you fix that?
24. How do you append text into an existing file in Java?
25. How do you get the default character encoding in Java?
26. Can you delete a directory with files in Java? How?
27. What is a memory-mapped file in Java?
28. How do you read a file line by line in Java?
29. How do you check if a file is hidden in Java?
30. What is difference between getPath(), getCanonicalPath() and getAbsolutePath() in Java?
31. How do you convert an InputStream into String in Java?
32. Can we load a resource from ClassPath in Java?
33. How do you read an XML file in Java as String?
34. Can we read the Microsoft Excel (XLS and XLSX) file in Java? How?
35. How do you load a CSV file in Java?
36. How do you read the Properties file in Java?
37. How do you serialize an Object in Java?
38. What is the difference between FileInputStream and ObjectInputStream in Java?
39. How do you read/write a text file in Java?
40. How do you upload a file into a Web Server in Java?
41. How do you read a file line by line in Java 8?
42. What is RandomAccessFile? What is the benefit of using RandomAccessFile?
43. How do you convert an InputStream to Byte Array in Java
140
141