0% found this document useful (0 votes)
13 views

12. OOP Module

this file explains about object oriented programming briefly

Uploaded by

abenezer865
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

12. OOP Module

this file explains about object oriented programming briefly

Uploaded by

abenezer865
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 145

Werabe University

Institute of Technology

Department of Information Systems

Course Module for


Object Oriented Programing

Prepared by: Amelework F.

May 23, 2023

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

Introduction to Object-Oriented Programming (OOP)


1.1 What is OOP?

Object-oriented programming (OOP) is a programming paradigm based on the conceptof


objects, which are data structures that contain data, in the form of fields (or attributes) and code,
in the form of procedures, (or methods). A distinguishing feature of objects is that an object's
procedures provide access to and modify its fields. In object-oriented programming, computer
programs are designed by making them out of objects that interact with one another. There is
significant diversity in object-oriented programming, but most popular languages are class-based,
meaning that objects are instances of classes, which typically also determines their type.

Object orientation is an outgrowth of procedural programming. Procedural programming is a


programming paradigm, derived from structured programming, based upon the concept of the
procedure call. Procedures, also known as routines, subroutines, or methods define the
computational steps to be carried out. Any given procedure might be called at any point during a
program's execution, including by other procedures or itself. Procedural programming is a list or
set of instructions telling a computer what to do step by step and how to perform from the first
code to the second code. Procedural programming languages include C, Fortran, Pascal, and
BASIC.

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.

Object-Oriented Programming (OOP) is a programming paradigm in computer science that


relies on the concept of classes and objects. It is used to structure a software program intosimple,
reusable pieces of code blueprints (usually called classes), which are used to create individual
instances of objects. There are many object-oriented programming languages, including
JavaScript, C++, Java, and Python.

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.

Benefits of OOP for software engineering

 OOP models’ complex things as reproducible, simple structures


 Reusable, OOP objects can be used across programs
 Polymorphism allows for class-specific behavior
 Easier to debug, classes often contain all applicable information to them
 Securely protects sensitive information through encapsulation

1.2 Basic Concepts of Object-Oriented Programming

It is necessary to understand some of the concepts used extensively in object-oriented


programming. These include:

• Objects

• Classes

• Data abstraction and encapsulation

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.

Here are the different components of a class –

1. Public - The class members can be accessed from everywhere.


2. Private - The class members can only be accessed by the defining class
3. Protected - the class members can only be accessed by parent and inherited classes

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 is a high-level and purely object-oriented programming language. It is platform


independent, robust, secure, and multithreaded programming language which makes it popular
among other OOP languages. It is widely used for software, web, mobile application development,
along with this it is also used in big data analytics and server-side technology.

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

Java is an Object-Oriented Programming Language, which means in Java everything is written in


terms of classes and objects. Now, what is an Object? Object is nothing but a real world entity that
can represent any person, place, or thing and can be distinguished from others. Every object near
us has some state and behavior associated with it. For example, my mobile phone, it is a realworld
entity and has states like color, model, brand, camera quality, etc, and these properties are

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:

1. Class and Object


2. Encapsulation
3. Abstraction
4. Inheritance
5. Polymorphism

 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.

How Java Programming Language Works?


 A Java Programmer writes a program in a human-readable language called Source Code.
Therefore, the CPU or Chips never understand the source code written in any
programming language.
 These computers or chips understand only one thing, which is called machine language or
code. These machine codes run at the CPU level. Therefore, it would be different machine
codes for other models of CPU.
 However, you need to worry about the machine code, as programming is all about the
source code. The machine understands this source code and translates them into machine
understandable code, which is an executable code.

All these functionalities happen inside the following 3 Java platform components:

 Java Development kit (JDK)

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):

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.

The important reasons of using JVM:

 JVM provides a platform-independent way of executing Java source code.


 It has numerous libraries, tools, and frameworks.
 Once you run a Java program, you can run on any platform and save lots of time.
 JVM comes with JIT (Just-in-Time) compiler that converts Java source code into low-
level machine language. Hence, it runs faster than a regular application.

Java Runtime Environment (JRE)

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.

The main reasons of using JRE:

 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.

Types of Java Platforms

There are four different types of Java programing language platforms:

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.

1.4. The JVM, Byte Code and Code Execution in Java

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.

What is Bytecode in Java?

Bytecode in Java is the reason java is platform-independent, as soon as a Java program


is compiled bytecode is generated. To be more precise a Java bytecode is the machine code in the
form of a .class file.

9
A bytecode in Java is the instruction set for Java Virtual Machine and acts similar to an
assembler.

How does Bytecode Work

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.

 Byte code vs Machine code

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

Following are a few advantages of Byte code:

 It helps in achieving platform-independence which is one of the reasons why James


Gosling started the formation of Java.
 The set of instructions for a JVM may differ from system to system but can all interpret
Bytecode.
 Bytecodes are non-runnable codes that rely on the availability of an interpreter, this is
where JVM comes into play.
 It is a machine-level language code that runs on the JVM.
 It adds portability to Java which resonates with the saying, “write once, read anywhere”.

1.5 Review question

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?

5. What is the main reasons for using JDK?

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:

2. Basics in Java Programming


2.1 Java syntax; Variable and identifiers, Data types and constants

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 −

 Access Modifiers − default, public , protected, private


 Non-access Modifiers − final, abstract, strictfp

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.

2.2. Output and Input statements in java

User Input: Scanner Class in Java

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;

The import statement needs to go just above the Class statement:

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.

2.3. Type Conversion/ Casting


The two terms type casting and the type conversion are used in a program to convert one data
type to another data type. The conversion of data type is possible only by the compiler when they
are compatible with each other. Let's discuss the difference between type casting and type
conversion in any programming language.

Type conversion in Java?

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.

Two types of casting are possible in Java are as follows:

1. Implicit type casting (also known as automatic type conversion)


2. Explicit type casting

2.4 Implicit Type Casting in Java


 Automatic conversion (casting) done by Java compiler internally is called implicit
conversion or implicit type casting in java.

 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.

2.5 Explicit Type casting (Narrowing conversion) in Java


As we know that automatic conversion is very helpful and safe, but it cannot fulfill all needs.

 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.

The general form of a cast is given below:

Syntax:
(type_name) expression;

Disadvantage of Explicit Type casting in Java

There are the following disadvantages of using type casting in Java.

 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.

2.6 If-else statement in Java?


If else statement is a condition statement that is used in the execution of a computer program in
pre-defined rules. The if-else statement helps you to run a specific block of a program if the
condition is true or else, it will check other conditions. It is used to control the flow or to determine
the rules in a program.

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:

public static void main(String[] arg){

// here we declare variable

int age = 20; //integer data format

// here we check the age is greater than 18

if(age>18)

System.out.println("Age is greater than 18");// print output

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.

The example for the if string statement code is given below.

Code 2:

public static void main(String[] arg){

// here we declare variable

String location = "paris"; //String(Collection of Character) data format

// here we check the the location is paris

if(location.equals("paris")) // here we use equals method its inbuilt method

System.out.println("Location is Same");// print output

22
Output:
Location is the same.

Java if-else statement:

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){

// code if condition is true

}else{

//code if condition is false

Code 4:

public static void main(String[] arg){

// here we declare variable

int checkingNumber=13;

23
//Check if the number is divisible by 2 or not

if(checkingNumber%2==0){

System.out.println(checkingNumber+" is even number");

}else{

System.out.println(checkingNumber+" is odd number");

Output:
13 is an odd number.

Java if-else-if Ladder Statement:

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){

//code to be executed if condition1 is true

}else if(condition2){

//code to be executed if condition2 is true

24
}

Else if(condition3){

//code to be executed if condition3 is true

Else{

//code to be executed if all the condition is false

Code 5:

public static void main(String[] arg){

//here we declare a variable

int internalMarks=65;

// here we checking the mark with if and else if condition

// if we want check more than one condition we will use this if and else if

if(internalMarks<50) // checks if condition is true

System.out.println("fail");

25
else if(internalMarks>=50 && internalMarks<60) //checks if previous condition is false

System.out.println("C grade");

else if(internalMarks>=60 && internalMarks<70) //checks if previous condition is false

System.out.println("B grade");

else //checks if all the condition is false

System.out.println("A grade");

Output:
B grade.

2.7 Java Ternary Operator if-else Statement:


The ternary operator is a condition that has three arguments,the first is to determine the
comparison, the second one is to determine the result on true comparison & the third is vice

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.

For example, variable=Expression? Expression1: expression2

How does it work in the ternary operator?

 If the expression is true, the expression is assigned to the variable

 If the expression is false, the expression is assigned to the variable

Code 6:

public static void main(String[] arg){

//here we declare a variable

int checkingNumber=13;

//Using ternary operator

String output=(checkingNumber%2==0)?"even number":"odd number";//like single line if and


else statement

System.out.println(output);

// ternary operator ?: if the condition is true it will take before colon values

// if condition is false it will take after the 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.

Java Nested if Statement:

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:

public static void main(String[] arg) {

// Creating two variables for age and weight

int personage = 25;

int personweight = 48;

28
// applying condition on age and weight

if (personage >= 18)

if (personweight > 50) //here we check the person weight is greater than 50

System.out.println("You are eligible to donate blood");

else

System.out.println("You are not eligible to donate blood");

else

System.out.println("Age must be greater than 18");// if age is less than 18 this condition will
execute

29
}

Output:

You are not eligible to donate blood.

Java switch Statement

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.

There are three types of for loops in Java.

30
o Simple for Loop
o For-each or Enhanced for Loop
o Labeled for Loop

Java Simple 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.

Syntax: for(initialization; condition; increment/decrement){


//statement or code to be executed
}
Java Nested for Loop

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.

Java for Loop vs while Loop vs do-while Loop

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?

11. How do you create thread-safe Singleton in Java?


12. When to use the volatile variable in Java?
13. When to use a transient variable in Java?
14. Difference between the transient and volatile variable in Java?
15. Difference between Serializable and Externalizable in Java?
16. Can we override the private method in Java?
17. Difference between Hashtable and HashMap in Java?
18. Difference between Listand Set in Java?
19. Difference between ArrayList and Vector in Java
20. Difference between Hashtable and ConcurrentHashMap in Java?
21. How does ConcurrentHashMap achieve scalability?
22. Which two methods you will override for an Object to be used as Key in HashMap?
23. Difference between wait and sleep in Java?
24. Difference between notify and notifyAll in Java?
25. Why you override hashcode, along with equals() in Java?
26. What is the load factor of HashMap means?
27. Difference between ArrayList and LinkedList in Java?
28. Difference between CountDownLatch and CyclicBarrier in Java?
29. When do you use Runnable vs Thread in Java?
30. What is the meaning of Enum being type-safe in Java?

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:

3. Class and Objects


In object-oriented programming technique, we design a program using objects and classes. An
object in Java is the physical as well as a logical entity, whereas, a class in Java is a logical entity
only.

3.1 What is an object in Java

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.

An object has three characteristics:

o State: represents the data (value) of an object.


o Behavior: represents the behavior (functionality) of an object such as deposit, withdraw,
etc.
o Identity: An object identity is typically implemented via a unique ID. The value of the ID
is not visible to the external user. However, it is used internally by the JVM to identifyeach
object uniquely.

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:

o An object is a real-world entity.


o An object is a runtime entity.
o The object is an entity which has state and behavior.
o The object is an instance of a class.

What is a class in Java

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.

A class in Java can contain:

o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface

Instance variable in Java

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

3 Ways to initialize object

There are 3 ways to initialize object in Java.

1. By reference variable
2. By method
3. By constructor

1) Object and Class Example: Initialization through reference

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.

2) Object and Class Example: Initialization through method

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.

3) Object and Class Example: Initialization through a constructor

What are the different ways to create an object in Java?

There are many ways to create an object in java. They are:

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.

3.2. Instantiating and using objects


What is instantiation in Java?

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.

Instantiation is an immense word to define a universal and straightforward concept in Java


programming, creating new instances of objects to be used in a program. In this section, we will
discuss what is instantiation in Java, how to instantiate a class, and what are the ways to
create instances or objects of the class? In Java, instantiation mean to call the constructor of a
class that creates an instance or object of the type of that class. In other words, creating an object
of the class is called instantiation. It occupies the initial memory for the object and returns a
reference. An object instantiation in Java provides the blueprint for the class.

What is an object?

 It is a runtime entity.
 It contains the blueprint of the class.

 We can create any number of objects of a class.


 It may represent user-defined data like Vector, Lists, etc.

Syntax for Instantiation

ClassName objName = new ClassName();

Or

1. ClassName cn;

2. cn= new ClassName;

What is an object?
39
 It is a runtime entity.

 It contains the blueprint of the class.


 We can create any number of objects of a class.

 It may represent user-defined data like Vector, Lists, etc.

Syntax for Instantiation

ClassName objName = new ClassName();

Or

ClassName cn;

cn= new ClassName;

3.3. Contractor, types of constructor and constructor overloading


 a constructor is a block of codes similar to the method. It is called when an instance of
the class is created. At the time of calling constructor, memory for the object is allocated
in the memory.

It is a special type of method which is used to initialize the object.

 Every time an object is created using the new() keyword, at least one constructor is
called.
 It calls a default constructor if there is no constructor available in the class. In such case,
Java compiler provides a default constructor by default.
 There are two types of constructors in Java: no-arg constructor, and parameterized
constructor.

Note: It is called constructor because it constructs the values at the time of object creation. It is
not necessary to write a constructor for a class. It is because java compiler creates a default
constructor if your class doesn't have any.

Rules for creating Java constructor

 There are two rules defined for the constructor.


 Constructor name must be the same as its class name
40
 A Constructor must have no explicit return type
 A Java constructor cannot be abstract, static, final, and synchronized

Types of Java constructors

There are two types of constructors in Java:

 Default constructor (no-arg constructor)


 Parameterized constructor

Java Default Constructor

A constructor is called "Default Constructor" when it doesn't have any parameter.

Syntax of default constructor:<class_name>(){}

Java Parameterized Constructor

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

 Why use the parameterized constructor?

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

Constructor Overloading in Java

In Java, a constructor is just like a method but without return type. It can also be overloaded like
Java methods.

Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a different
task. They are differentiated by the compiler by the number of parameters in the list and their types.

Example of Constructor Overloading

//Java program to overload constructors

class Student5{

int id;

41
String name;

int age;

//creating two arg constructor

Student5(int i,String n){

id = i;

name = n;

//creating three arg constructor

Student5(int i,String n,int a){

id = i;

name = n;

age=a;

void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){

Student5 s1 = new Student5(111,"Karan");

Student5 s2 = new Student5(222,"Aryan",25);

s1.display();

s2.display();

Difference between constructor and method in Java

42
There are many differences between constructors and methods. They are given below.

Java Constructor Java Method

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 constructor is invoked implicitly. The method is invoked explicitly.

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

the class name. the class name.

Java Copy Constructor

There is no copy constructor in Java. However, we can copy the values from one object to
another like copy constructor in C++.

There are many ways to copy the values of one object into another in Java. They are:

 By constructor
 By assigning the values of one object into another
 By clone() method of Object class

Copying values without constructor

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.

3.4. Member methods and their components


A java method can be defined as a set of logical java statements written to perform a specific task.
They provide a way to reuse code without writing the code again. In Java, any method should be
part of a different class from Python, C, and C++. The existence of methods is not possible without
a java class. Here is the list of components involved while creating javamethods:

Components for Creating Java Methods

Here is the list of components involved while creating java methods:

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:

Here is a basic syntax of methods:

//declare Enclosing class

public class Myclass{

//declare java method

public String concat(String s1, String s2){

// combine two strings with space

String s3= s1 + " " + s2 ;

//return resulting string

return s3;

Types of Methods in Java

Methods can be categorized into the following two types:

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.

User-defined Methods: A developer in java classes explicitly defines these methods.

Calling a Java Method

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;

public class MethodDemo{

public static int getMaximum(int a , int b){

if(a>b){

return a;

}else {

return b;

public static void main (String args[]){

int maxvalue1 = getMaximum(10,23);

46
System.out.println("Out of 10 and 23, " + maxvalue1 + " is greater" );

int maxvalue2= getMaximum(40,20);

System.out.println("Out of 40 and 20, " + maxvalue2 + " is greater" );

3.5. Members of class


A member class is a class that is declared as a non-static member of a containing class. If a static
member class is analogous to a class field or class method, a member class is analogous to an
instance field or instance method. Example shows how a member class can be defined and used.
This example extends the previous Linked Stack example to allow enumeration of the elements on
the stack by defining an enumerate() method that returns an implementation of the
java.util.Enumeration interface. The implementation of this interface is defined as a member class.

An Enumeration Implemented as a Member Class

public class LinkedStack {

// Our static member interface; body omitted here...

public static interface Linkable { ... }

// The head of the list private Linkable head;

// Method bodies omitted here public void push(Linkable node) { ... }

public Linkable pop() { ... }

// This method returns an Enumeration object for this LinkedStack

public java.util.Enumeration enumerate() { return new Enumerator(); }

// Here is the implementation of the Enumeration interface,

// defined as a member class.

protected class Enumerator implements java.util.Enumeration {

Linkable current;

47
// The constructor uses the private head field of the containing class

public Enumerator() { current = head; }

public boolean hasMoreElements() { return (current != null); }

public Object nextElement() {

if (current == null) throw new java.util.NoSuchElementException();

Object value = current;

current = current.getNext();

return value;

Features of Member Classes

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;

Restrictions on Member Classes

There are three important restrictions on member classes:

 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.

3.5.1. Static members (variables, methods)


Is variable which belongs to the class and initialized only once at the start of the execution. It is a
variable which belongs to the class and not to object(instance ). Static variables are initialized only
once, at the start of the execution. These variables will be initialized first, before the initialization
of any instance variables.

 A single copy to be shared by all instances of the class


 A static variable can be accessed directly by the class name and doesn’t need any object

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>

3.5.2. Instance members (variables, methods)

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}

And if you create two STUDENT objects like,

Then two instances of the class Student will be created.

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.

Features of an instance variable?

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.

How do you implement an instance variable in Java?

Implementation of Instance variables in Java is quite easy. I have written a simple code that will
help you to grasp the technical usage.

Difference between an instance variable and a class variable

To clarify the differences, I have jotted down a few points that will help you to discard any
ambiguity between the two.

Instance Variable Class Variable

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.

What is a method in Java?

A method is a block of code or collection of statements or a set of code grouped together to


perform a certain task or operation. It is used to achieve the reusability of code. We write a method
once and use it many times. We do not require to write code again and again. It also provides the
easy modification and readability of code, just by adding or removing a chunk of code. The
method is executed only when we call or invoke it.

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:

Single-word method name: sum(), area()

Multi-word method name: areaOfCircle(), stringComparision()

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

There are two types of methods in Java:

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.

Let's see an example of the predefined method.

Demo.java

1. public class Demo


2. {
3. public static void main(String[] args)
4. {
5. // using the max() method of Math class
6. System.out.print("The maximum number is: " + Math.max(9,7));
7. }
8. }
User-defined Method

The method written by the user or programmer is known as a user-defined method. These methods
are modified according to the requirement.

How to Create a User-defined Method

Let's create a user defined method that checks the number is even or odd. First, we will define
the method.

1. //user defined 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. Object-Oriented Concept

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.

The Java Bean class is the example of a fully encapsulated class.

Advantage of Encapsulation in Java

 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

1. //A Java class which is a fully encapsulated class.


2. //It has a private data member and getter and setter methods.

3. package com.javatpoint;
4. public class Student{

5. //private data member


6. private String name;

7. //getter method for name


8. public String getName(){

9. return name;
10. }

11. //setter method for name


12. public void setName(String name){

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.

Why use inheritance in java

For Method Overriding (so runtime polymorphism can be achieved).

For Code Reusability.

Terms used in Inheritance

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 syntax of Java Inheritance

class Subclass-name extends Superclass-name

//methods and fields

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.

Java Inheritance Example

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.

Note: Multiple inheritance is not supported in Java through class.

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...");}

class Dog extends Animal{

void bark(){System.out.println("barking...");}

class TestInheritance{

public static void main(String args[]){

Dog d=new Dog();

d.bark();

61
d.eat();

}}

Output:

barking...

eating...

Multilevel Inheritance Example

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...");}

class Dog extends Animal{

void bark(){System.out.println("barking...");}

class BabyDog extends Dog{

void weep(){System.out.println("weeping...");}

class TestInheritance2{

public static void main(String args[]){

BabyDog d=new BabyDog();

d.weep();

62
d.bark();

d.eat();

}}

Why multiple inheritance is not supported in java?

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

If a class have an entity reference, it is known as Aggregation. Aggregation represents HAS-A


relationship.

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;

Address address;//Address is a class

...

In such case, Employee has an entity reference address, so relationship is Employee HAS-A
address.

Why use Aggregation?

63
For Code Reusability.

Simple Example of Aggregation

Aggregation in Java

If a class have an entity reference, it is known as Aggregation. Aggregation represents HAS-A


relationship.

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;

Address address;//Address is a class

...

In such case, Employee has an entity reference address, so relationship is Employee HAS-A
address.

Why use Aggregation?

For Code Reusability.

64
Simple Example of Aggregation

3.7.3. Polymorphism, Method overloading and overriding

Method Overloading in Java

If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.

If we have to perform only one operation, having same name of the methods increases the
readability of the program.

Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three
parameters then it may be difficult for you as well as other programmers to understand the behavior
of the method because its name differs.

So, we perform method overloading to figure out the program quickly.

Advantage of method overloading

Method overloading increases the readability of the program.

 Different ways to overload the method


 There are two ways to overload the method in java
 By changing number of arguments
 By changing the data type

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{

static int add(int a,int b){return a+b;}

static int add(int a,int b,int c){return a+b+c;}

class TestOverloading1{

public static void main(String[] args){

System.out.println(Adder.add(11,11));

System.out.println(Adder.add(11,11,11));

}}

2) Method Overloading: changing data type of arguments

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

class Adder{

static int add(int a, int b){return a+b;}

static double add(double a, double b){return a+b;}

class TestOverloading2{

public static void main(String[] args){

System.out.println(Adder.add(11,11));

66
System.out.println(Adder.add(12.3,12.6));

}}

Method Overloading and Type Promotion

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.

Example of Method Overloading with Type Promotion

class OverloadingCalculation1{

void sum(int a,long b){System.out.println(a+b);}

void sum(int a,int b,int c){System.out.println(a+b+c);}

public static void main(String args[]){

67
OverloadingCalculation1 obj=new OverloadingCalculation1();

obj.sum(20,20);//now second int literal will be promoted to long

obj.sum(20,20,20);

Method Overriding in Java

If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.

In other words, If a subclass provides the specific implementation of the method that has been
declared by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding

Method overriding is used to provide the specific implementation of a method which is already
provided by its superclass.

Method overriding is used for runtime polymorphism

 Rules for Java Method Overriding


 The method must have the same name as in the parent class
 The method must have the same parameter as in the parent class.
 There must be an IS-A relationship (inheritance).
 A real example of Java Method Overriding
 Consider a scenario where Bank is a class that provides functionality to get the rate of
interest. However, the rate of interest varies according to banks. For example, SBI, ICICI
and AXIS banks could provide 8%, 7%, and 9% rate of interest.

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.

4.1. What is Exception in Java?


Dictionary Meaning: Exception is an abnormal condition.

In Java, an exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.

What is Exception Handling?

Exception Handling is a mechanism to handle runtime errors such as Class Not Found
Exception, IO Exception, SQL Exception, Remote Exception, etc.

Advantage of Exception Handling

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;

statement 5;//exception occurs

71
statement 6;

statement 7;

statement 8;

statement 9;

statement 10;

Hierarchy of Java Exception classes

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 Exception Keywords

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.

Throw The "throw" keyword is used to throw an exception.

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.

Java Exception Handling Example

Let's see an example of Java Exception Handling in which we are using a try-catch statement to
handle the exception.

JavaExceptionExample.java

public class JavaExceptionExample{

public static void main(String args[]){

try{

//code that may raise exception

74
int data=100/0;

}catch(ArithmeticException e){System.out.println(e);}

//rest code of the program

System.out.println("rest of the code...");

Common Scenarios of Java Exceptions

There are given some scenarios where unchecked exceptions may occur. They are as follows:

1) A scenario where Arithmetic Exception occurs

If we divide any number by zero, there occurs an ArithmeticException.

int a=50/0;//ArithmeticException

2) A scenario where Null Pointer Exception occurs

If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.

3) A scenario where Number Format Exception occurs

If the formatting of any variable or number is mismatched, it may result into


NumberFormatException. Suppose we have a string variable that has characters; converting this
variable into digit will cause NumberFormatException.

String s="abc";

int i=Integer.parseInt(s);//NumberFormatException

4) A scenario where ArrayIndexOutOfBoundsException occurs

When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may be
other reasons to occur ArrayIndexOutOfBoundsException. Consider the following statements.

int a[]=new int[5];

75
a[10]=50; //ArrayIndexOutOfBoundsException

4.2. The causes of exceptions


What are the causes of exceptions in java?

A java exception can be thrown only in the following three scenarios:

(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)

(2) A throw statement was executed.

(3) An asynchronous exception occurred.


– The stop method (deprecated) of class Thread was invoked
– An internal error has occurred in the java virtual machine

4.3. The throw statement and the finally clause


Throwing Exceptions

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:

public int divide(int numberToDivide, int numberToDivideBy)

throws BadNumberException{

if(numberToDivideBy == 0){

throw new BadNumberException("Cannot divide by 0");

return numberToDivide / numberToDivideBy;

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:

public void callDivide(){

try {

int result = divide(2,1);

System.out.println(result);

} catch (BadNumberException e) {

//do something clever with the exception

System.out.println(e.getMessage());

System.out.println("Division attempt done");

 The BadNumberException parameter e inside the catch-clause points to the exception


thrown from the divide method, if an exception is thrown.

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

(BadNumberException e) { }" block.

 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:

public void openFile(){

FileReader reader = null;

try {

reader = new FileReader("someFile");

int i=0;

while(i != -1){

78
i = reader.read();

System.out.println((char) i );

} catch (IOException e) {

//do something clever with the exception

} finally {

if(reader != null){

try {

reader.close();

} catch (IOException e) {

//do something clever with the exception

System.out.println("--- File End ---");

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) {

//do something clever with the exception

System.out.println("--- File End ---");

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.

4.4. User defined exceptions


User-defined exceptions are also referred to as custom exceptions. The exceptions created per
our use case and thrown using the throw keyword are user-defined exceptions, and such
exceptions are derived classes of the Exception class from the java.lang package.

Why Use Custom Exceptions?

 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.

How to Create User-Defined Exceptions in Java?

 To create a custom exception in java, we have to create a class by extending it with an


Exception class from the java.lang package.
 It's always a good practice to add comments and follow naming conventions to easily
identify and recognize the benefit of our exception class.
 Below is the template to be followed for creating a user-defined exception in java.

//user-defined exception in java

public class SimpleCustomException extends Exception{

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

Here's the code to demonstrate that in java

//simple custom exception in java

public class SimpleCustomException extends Exception {

//parameter constructor

SimpleCustomException(String msg) {

//passing the parameter to the super class constructor

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

Here's the code to demonstrate that in Java

//simple custom exception in java

public class SimpleCustomException extends Exception{

//member variable to store our custom message

String msg;

SimpleCustomException(String msg) {

this.msg=msg;

//overriding with our custom message

@Override

public String toString() {

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.

4.5 Review question

1. What is an Exception in Java?


2. What are the Exception Handling Keywords in Java?
3. Explain Java Exception Hierarchy?
4. What are the important methods of Java Exception Class?
5. Explain Java 7 ARM Feature and multi-catch block?
6. What is the difference between Checked and Unchecked Exceptions in Java?
7. What is the difference between the throw and throws keyword in Java?
8. How to write custom exceptions in Java?
9. What is OutOfMemoryError in Java?
10. What are different scenarios causing “Exception in thread main”?
11. What is the difference between final, finally, and finalize in Java?
12. What happens when an exception is thrown by the main method?
13. Can we have an empty catch block?
14. Provide some Java Exception Handling Best Practices?
15. What is the problem with the below programs and how do we fix it?

Chapter 5:

5. Graphic User Interface (GUI) and JDBC


5.1. Overview of GUI
GUI, which stands for Graphical User Interface, is a user-friendly visual experience builder for
Java applications. It comprises graphical units like buttons, labels, windows, etc. via which

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.

2. Informational components like banners, icons, labels or notification dialogs.

3. Navigational units like menus, sidebars and breadcrumbs.

GUI in JAVA: Swing and JavaFX

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.

The following are the steps to create GUI in Java

STEP 1: The following code is to be copied into an editor

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:

· JButton(String): This button is labelled with a specified text.

· JButton(Icon): This button is labelled with a graphical icon.

· JButton(String,Icon): This button is labelled with a combination of text and icon.

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:

5.2. Elements of GUI: Component and container


OOP, including composition, inheritance, polymorphism, abstract class and interface; otherwise,
read the earlier articles. I will describe another important OO concept called nested class
(or inner class) in this article.

There are current three sets of Java APIs for graphics programming:

AWT (Abstract Windowing Toolkit), Swing and JavaFX.

 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.

5.3. Concepts of GUI


AWT is huge! It consists of 12 packages of 370 classes (Swing is even bigger, with 18 packages
of 737 classes as of JDK 8). Fortunately, only 2 packages - java.awt and java.awt.event - are
commonly-used.

The java.awt package contains the core AWT graphics classes:

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.

AWT provides a platform-independent and device-independent interface to develop graphic


programs that runs on all platforms, including Windows, macOS, and Unixes.

AWT Containers and Components

There are two groups of GUI elements:

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,

Panel pnl = new Panel(); // Panel is a container Button

btn = new Button("Press"); // Button is a component

pnl.add(btn); // The Panel container adds a Button component

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.

2.3 AWT Container Classes


Top-Level Containers: Frame, Dialog and Applet

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:

import java.awt.Frame; // Using Frame class in package java.awt

// A GUI program is written as a subclass of Frame - the top-level container

// This subclass inherits all properties from Frame, e.g., title, icon, buttons, content-pane

public class MyGUIProgram extends Frame {

// private variables

......

// Constructor to setup the GUI components and event handlers

public MyGUIProgram() {....... }

// The entry main() method

public static void main(String[] args) {

// Invoke the constructor (to setup the GUI) by allocating an instance

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: Panel and ScrollPane

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.

Hierarchy of the AWT Container Classes

The hierarchy of the AWT Container classes is as follows:

90
As illustrated, a Container has a Layout Manager to layout the components in a certain pattern,
e.g., flow, grid.

2.4 AWT Component Classes


AWT provides many ready-made and reusable GUI components in package java.awt. The
frequently-used are: Button, TextField, Label, Checkbox, CheckboxGroup (radio buttons), List,
and Choice, as illustrated below.

AWT GUI Component: java.awt.Label

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.

Check the JDK API specification for java.awt.Label.

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

public Label(); // Construct an initially empty Label

The Label class has three constructors:

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.

Constants (final static fields)

public static final LEFT; // Label.LEFT

public static final RIGHT; // Label.RIGHT

public static final CENTER; // Label.CENTER

92
These three constants are defined for specifying the alignment of the Label's text, as used in the
above constructor.

Public Methods

// Examples

public String getText();

public void setText(String strLabel);

public int getAlignment();

public void setAlignment(int alignment); // Label.LEFT, Label.RIGHT, Label.CENTER

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.

Constructing a Component and Adding the Component into a Container

Three steps are necessary to create and place a GUI component:

Declare the component with an identifier (name);

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:

 Swing API: for advanced graphical programming.


 Accessibility API: provides assistive technology for the disabled.

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 support "tool-tips".

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".

6. Others - check the Swing website.

Using Swing API

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,

2. public class SwingDemo extends JFrame {


3. // Constructor
4. public SwingDemo() {
5. // Get the content-pane of this JFrame, which is a java.awt.Container
6. // All operations, such as setLayout() and add() operate on the content-
pane
7. Container cp = getContentPane();
8. cp.setLayout(new FlowLayout());
9. cp.add(new JLabel("Hello, world!"));
10. cp.add(new JButton("Button"));
11. ......
12. }
13. .......

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().

15. public class SwingDemo extends JFrame {


16. // Constructor
17. public SwingDemo() {
18. // The "main" JPanel holds all the GUI components
19. JPanel mainPanel = new JPanel(new FlowLayout());
20. mainPanel.add(new JLabel("Hello, world!"));
21. mainPanel.add(new JButton("Button"));
22.
23. // Set the content-pane of this JFrame to the main JPanel
24. setContentPane(mainPanel);
25. ......
26. }
27. .......

98
Notes: If a component is added directly into a JFrame, it is added into the content-pane

of JFrame instead, i.e.,

// Suppose that "this" is a JFrame


add(new JLabel("add to JFrame directly"));
// is executed as
getContentPane().add(new JLabel("add to JFrame directly"));

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.

Writing Swing Applications

In summary, to write a Swing application, you have:

Use the Swing components with prefix "J" in package javax.swing,


e.g., JFrame, JButton, JTextField, JLabel, etc.

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.

Swing applications uses AWT event-handling classes,


e.g., ActionEvent/ActionListener, MouseEvent/MouseListener, etc.

Run the constructor in the Event Dispatcher Thread (instead of Main thread) for thread safety, as
shown in the following program template.

Swing Program Template

1 import java.awt.*; // Using AWT layouts

2 import java.awt.event.*; // Using AWT event classes and listener interfaces

3 import javax.swing.*; // Using Swing components and containers

99
4

5 // A Swing GUI application inherits from top-level container javax.swing.JFrame

6 public class SwingTemplate extends JFrame {

8 // Private instance variables

// ......
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

21 // Content-pane adds components

22 cp.add(. .. );

23

24 // Source object adds listener

25 // .....

100
26

27 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

28 // Exit the program when the close-window button clicked

29 setTitle("......"); // "super" JFrame sets title

30 setSize(300, 150); // "super" JFrame sets initial size

31 setVisible(true); // "super" JFrame shows

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.

What are Swing Components in Java?

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:

Top-level Containers It inherits the Component and Container of AWT.

We cannot contain it within other containers.

Heavyweight.

Example: JFrame, JDialog, JApplet

Lightweight Containers It inherits JComponent class.

It is a general-purpose container.

We can use it to organize related components together.

Example: JPanel

Top 21 Components of Swing in Java

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 okBtn = new JButton(“Click”);

This constructor returns a button with the text Click on it.

JButton homeBtn = new JButton(carIcon);

Returns a button with a car Icon on it.

JButton homeBtn2 = new JButton(carIcon, “Car”);

Returns a button with the car icon and text as Car.

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 okBtn = new JButton(“Click”);

This constructor returns a button with the text Click on it.

JButton homeBtn = new JButton(carIcon);

Returns a button with a car Icon on it.

JButton homeBtn2 = new JButton(carIcon, “Car”);

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 textLabel = new JLabel(“This is 1st L...”);

This constructor returns a label with specified text.

JLabel imgLabel = new JLabel(carIcon);

It returns a label with a car icon.

The JLabel Contains four constructors. They are as follows:

JLabel()

JLabel(String s)

JLabel(Icon i)

JLabel(String s, Icon i, int horizontalAlignment)

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);

It is the most widely used text component. It has three constructors:

JTextField(int cols)

JTextField(String str, int cols)

JTextField(String str)

Note: cols represent the number of columns in the text field.

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:

CheckBox chkBox = new JCheckBox(“Java Swing”, true);

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:

JRadioButton jrb = new JRadioButton("Easy");

Display:

105
JComboBox

The combo box is a combination of text fields and a drop-down list. We


use JComboBox component to create a combo box in Swing.

Syntax:

JComboBox jcb = new JComboBox(name);

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:

public class JTextArea extends JTextComponent

Syntax:

JTextArea textArea_area=new JTextArea("Ninja! please write something in the text area.");

The JTextArea Contains four constructors. They are as follows:

JTextArea()

JTextArea(String s)

JTextArea(int row, int column)

JTextArea(String s, int row, int column)

Display:

JPasswordField

In Java, the Swing toolkit contains a JPasswordField Class. It is under package


javax.swing.JPasswordField class. It is specifically used for the password, and we can edit them.

106
Declaration:

public class JPasswordField extends JTextField

Syntax:

JPasswordField password = new JPasswordField();

The JPasswordFieldContains 4 constructors. They are as follows:

JPasswordField()

JPasswordField(int columns)

JPasswordField(String text)

JPasswordField(String text, int columns)

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 table = new JTable(table_data, table_column);

The JTable contains two constructors. They are as follows:

JTable()

JTable(Object[][] rows, Object[] columns)

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:

public class JList extends JComponent implements Scrollable, Accessible

Syntax:

DefaultListModel<String> list1 = new DefaultListModel<>();

list1.addElement("Apple");

list1.addElement("Orange");

list1.addElement("Banan");

list1.addElement("Grape");

JList<String> list_1 = new JList<>(list1);

The JListContains 3 constructors. They are as follows:

JList()

JList(ary[] listData)

JList(ListModel<ary> dataModel)

Display:

JOptionPane

In Java, the Swing toolkit contains a JOptionPane Class. It is under package


javax.swing.JOptionPane class. It is used for creating dialog boxes for displaying a message,
confirm box, or input dialog box.

Declaration:

public class JOptionPane extends JComponent implements Accessible

Syntax:

JOptionPane.showMessageDialog(jframe_obj, "Good Morning, Evening & Night.");

The JOptionPaneContains 3 constructors. They are as following:


108
JOptionPane()

JOptionPane(Object message)

JOptionPane(Object message, intmessageType)

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:

public class JScrollBar extends JComponent implements Adjustable, Accessible

Syntax:

JScrollBar scrollBar = new JScrollBar();

The JScrollBarContains 3 constructors. They are as following:

JScrollBar()

JScrollBar(int orientation)

JScrollBar(int orientation, int value, int extent, int min_, intmax_)

Display:

JMenuBar, JMenu and JMenuItem

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.

JMenuBar, JMenu and JMenuItem Declarations:

public class JMenuBar extends JComponent implements MenuElement, Accessible

109
public class JMenu extends JMenuItem implements MenuElement, Accessible

public class JMenuItem extends AbstractButton implements Accessible, MenuElement

Syntax:

JMenuBar menu_bar = new JMenuBar();

JMenu menu = new JMenu("Menu");

menuItem1 = new JMenuItem("Never");

menuItem2 = new JMenuItem("Stop");

menuItem3 = new JMenuItem("Learing");

menu.add(menuItem1);

menu.add(menuItem2);

menu.add(menuItem3);

Display:

JPopupMenu

In Java, the Swing toolkit contains a JPopupMenu Class. It is under package


javax.swing.JPopupMenu class. It is used for creating popups dynamically on a specified position.

Declaration:

public class JPopupMenu extends JComponent implements Accessible, MenuElement

Syntax:

final JPopupMenu popupmenu1 = new JPopupMenu("Edit");

The JPopupMenuContains 2 constructors. They are as follows:

JPopupMenu()

JPopupMenu(String label)

110
Display:

JCheckBoxMenuItem

In Java, the Swing toolkit contains a JCheckBoxMenuItem Class. It is under package


javax.swing.JCheckBoxMenuItem class. It is used to create a checkbox on a menu.

Syntax:

JCheckBoxMenuItem item = new JCheckBoxMenuItem("Option_1");

The JCheckBoxMenuItemContains 2 constructors. They are as following:

JCheckBoxMenuItem()

JCheckBoxMenuItem(Action a)

JCheckBoxMenuItem(Icon icon)

JCheckBoxMenuItem(String text)

JCheckBoxMenuItem(String text, boolean b)

JCheckBoxMenuItem(String text, Icon icon)

JCheckBoxMenuItem(String text, Icon icon, boolean b)

Display:

JSeparator

In Java, the Swing toolkit contains a JSeparator Class. It is under package


javax.swing.JSeparator class. It is used for creating a separator line between two

components.

Declaration:

public class JSeparator extends JComponent implements SwingConstants, Accessible

Syntax:

111
jmenu_Item.addSeparator();

The JSeparatorContains 2 constructors. They are as following:

JSeparator()

JSeparator(int orientation)

Display:

JProgressBar

In Java, the Swing toolkit contains a JProgressBar Class. It is under package


javax.swing.JProgressBarclass. It is used for creating a progress bar of a task.

Declaration:

public class JProgressBar extends JComponent implements SwingConstants, Accessible

Syntax:

JProgressBar progressBar = new JProgressBar(0,2000);

The JProgressBarContains 4 constructors. They are as following:

JProgressBar()

JProgressBar(int min, int max)

JProgressBar(int orient)

JProgressBar(int orient, int min, int max)

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 tree = new JTree(tree_style);

The JTreeContains 3 constructors. They are as follows:

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:

JFileChooser fileChooser = new JFileChooser();

JButton fileBtn = new JButton(“Select File”);

fileBtn.AddEventListner(new ActionListner(){

fileChooser.showOpenDialog();

})

var selectedFile = fileChooser.getSelectedFile();

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:

JTabbedPane jtabbedPane = new JTabbedPane();

jtabbedPane.addTab(“Tab_1”, new JPanel());

jtabbedPane.addTab(“Tab_2”, new JPanel());

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:

JSlider volumeSlider = new JSlider(0, 100, 20);

var volumeLevel = volumeSlider.getValue();

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:

Difference between AWT and Swing

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:

Feature AWT Swing

Look and feel Native Cross-platform (customizable)

Performance Faster (lightweight) Slower (heavier)

Accessibility Limited More accessible

Component set Limited More comprehensive

Layout Managers Limited More comprehensive

Consistency across OS Less consistent More consistent

Support for advanced GUI Limited More advanced

2D graphics rendering No Yes

115
Event handling mechanism Less flexible More flexible

5.4. Java Database Connectivity (JDBC)


JDBC (Java Database Connectivity) is the Java API that manages connecting to a database, issuing
queries and commands, and handling result sets obtained from the database. Released as part of
JDK 1.1 in 1997, JDBC was one of the earliest libraries developed for the Java language.

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.

How JDBC works

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

Figure 1. JDBC connects Java programs to databases.

JDBC vs ODBC

Before JDBC, developers used Open Database Connectivity (ODBC), a language-agnostic


standard approach to accessing a relational database management system, or RDBMS. In some

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

 The JDBC interface consists of two layers:


 The JDBC API supports communication between the Java application and the JDBC
manager.
 The JDBC driver supports communication between the JDBC manager and the database
driver.
 The JDBC API and JDBC driver have been refined extensively over the years, resulting
in a feature-rich, performant, and reliable library.
 JDBC is the common API that your application code interacts with. Beneath that is the
JDBC-compliant driver for the database you are using.

Figure 2 illustrates the JDBC architecture.

IDG

Figure 2. JDBC’s architecture consists of the JDBC API and JDBC drivers.

JDBC drivers

As an application programmer, you don’t need to immediately be concerned with the


implementation of the driver you use, so long as it is secure and official. However, it is useful to
be aware that there are four JDBC driver types:

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.

Simple database connections and queries

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.

The steps for connecting to a database with JDBC are as follows:

i. Install or locate the database you want to access.


ii. Include the JDBC library.
iii. Ensure the JDBC driver you need is on your classpath.
iv. Use the JDBC library to obtain a connection to the database.
v. Use the connection to issue SQL commands.
vi. Close the connection when you are finished.

We'll go through these steps together.

Finding a JDBC driver

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!

Step 1. Download and install SQLite

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.

SQL and JDBC

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.

Step 2. Import JDBC into your Java application

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.

Listing 1. A simple Java program

class WhatIsJdbc{

public static void main(String args[]){

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.

Listing 2. JDBC imports

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:

Connection represents the connection to the database.

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.

You'll see each of these in action shortly.

Step 3. Add the JDBC driver to your classpath

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

java.exe -classpath /path-to-driver/sqlite-jdbc-3.23.1.jar:. WhatIsJdbc

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.

Step 4. Obtain a database connection

The classpath now has access to the driver. Next, change your simple Java application file to
look like the program in Listing 4.

Listing 4. Using the JDBC Connection class to connect to SQLite

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.ResultSet;

import java.sql.Statement;

String sql = "SELECT id, username FROM users WHERE id = ?";

List users = new ArrayList<>();

try (Connection con = DriverManager.getConnection(myConnectionURL);

PreparedStatement ps = con.prepareStatement(sql)) {

ps.setInt(1, userId);

try (ResultSet rs = ps.executeQuery()) {

while(rs.next()) {

users.add(new User(rs.getInt("id"), rs.getString("name")));

121
} catch (SQLException e) {

e.printStackTrace();

return users;

class WhatIsJdbc{

public static void main(String[] args) {

String url = "jdbc:sqlite:path-to-db/chinook/chinook.db";

try (Connection conn = DriverManager.getConnection(url){

System.out.println("Got it!");

} catch (SQLException e) {

throw new Error("Problem", e);

Compile and execute this code. Assuming all goes well, you will get an affirming message.

No suitable driver found

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.

Now, we're ready for some SQL commands.

Step 5. Query the database

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{

public static void main(String[] args) {

String sql = "SELECT id, username FROM users WHERE id = ?";

String url = "jdbc:sqlite:path-to-db-file/chinook/chinook.db";

try (Connection conn = DriverManager.getConnection(url);

Statement stmt = conn.createStatement()) {

try {

ResultSet rs = stmt.executeQuery("select * from albums";);

while (rs.next()) {

String name = rs.getString("title");

System.out.println(name);

} catch (SQLException e ) {

throw new Error("Problem", 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.

Notice that we also closed the connection, via a call to conn.close().

Network connections with JDBC

The database connection string in Listing 5 is for a local connection: jdbc:sqlite:path-to-db-


file/chinook/chinook.db. To access the database via a network, the connection string would need to
include the network URL and (usually) credentials for accessing it.

5.5 Review question


1. What is JDBC?
2. What is JDBC Driver?
3. Write a program to Connect MySQL or Oracle to Java?
4. Describe the concepts of JDBC API components?
5. Explain the JDBC Statements?
6. What is the difference between Statement and PreparedStatement?
7. What are the major advantages of using PreparedStatement over Statement in Java?
8. Differentiate between JDBC and ODBC drivers?
9. Write a sample code to execute StoredProcedure?
10. Is it possible to connect to more than one database? Also, using a single statement can
we update or extract data from two or three or many databases?
11. What is ResultSet?

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:

6. Files and Streams


6.1 Files and Streams

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 −

InPutStream − The InputStream is used to read data from a source.

OutPutStream − The OutputStream is used for writing data to a destination.


125
Java provides strong but flexible support for I/O related to files and networks but this tutorial
covers very basic functionality related to streams and I/O. We will see the most commonly used
examples one by one −

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.*;

public class CopyFile {

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

FileInputStream in = null;

FileOutputStream out = null;

try {

in = new FileInputStream("input.txt");

out = new FileOutputStream("output.txt");

int c;

126
while ((c = in.read()) != -1) {

out.write(c);

}finally {

if (in != null) {

in.close();

if (out != null) {

out.close();

Now let's have a file input.txt with the following content −

This is test for copy file.

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.*;

public class CopyFile {

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

FileReader in = null;

FileWriter out = null;

try {

in = new FileReader("input.txt");

out = new FileWriter("output.txt");

int c;

while ((c = in.read()) != -1) {

out.write(c);

}finally {

if (in != null) {

128
in.close();

if (out != null) {

out.close();

Now let's have a file input.txt with the following content −

This is test for copy file.

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.*;

public class ReadConsole {

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

InputStreamReader cin = null;

try {

cin = new InputStreamReader(System.in);

System.out.println("Enter characters, 'q' to quit.");

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

Enter characters, 'q' to quit.

Reading and Writing Files

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.

Here is a hierarchy of classes to deal with Input and Output streams.

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

InputStream f = new FileInputStream("C:/java/hello");

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 −

File f = new File("C:/java/hello");

InputStream f = new FileInputStream(f);

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.

Sr.No. Method & Description

1 public void close() throws IOException{}

This method closes the file output stream. Releases any system resources associated
with the file. Throws an IOException.

2 protected void finalize()throws 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.

3 public int read(int r)throws 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.

4 public int read(byte[] r) throws IOException{}

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.

5 public int available() throws IOException{}

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 −

OutputStream f = new FileOutputStream("C:/java/hello")

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 −

File f = new File("C:/java/hello");

OutputStream f = new FileOutputStream(f);

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.

Sr.No. Method & Description

1 public void close() throws IOException{}

This method closes the file output stream. Releases any system resources associated
with the file. Throws an IOException.

2 protected void finalize()throws 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.

3 public void write(int w)throws IOException{}

This methods writes the specified byte to the output stream.

4 public void write(byte[] w)

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

Following is the example to demonstrate InputStream and OutputStream −

import java.io.*;

public class fileStreamTest {

public static void main(String args[]) {

try {

byte bWrite [] = {11,21,3,40,5};

OutputStream os = new FileOutputStream("test.txt");

for(int x = 0; x < bWrite.length ; x++) {

os.write( bWrite[x] ); // writes the bytes

135
}

os.close();

InputStream is = new FileInputStream("test.txt");

int size = is.available();

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

System.out.print((char)is.read() + " ");

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.

File Navigation and I/O

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.

Following example creates "/tmp/user/java/bin" directory −

Example

import java.io.File;

public class CreateDir {

public static void main(String args[]) {

String dirname = "/tmp/user/java/bin";

File d = new File(dirname);

// Create directory now.

d.mkdirs();

Compile and execute the above code to create "/tmp/user/java/bin".

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;

public class ReadDir {

public static void main(String[] args) {

File file = null;

String[] paths;

try {

// create new file object

file = new File("/tmp");

// array of files and directory

paths = file.list();

// for each name in the path array

for(String path:paths) {

138
// prints filename and directory name

System.out.println(path);

} catch (Exception e) {

// if any error occurs

e.printStackTrace();

6.2. Review question


1. Which class is used to create a directory in Java?
2. How do you create a file and directory in Java?
3. What is the difference between InputStream and OutputStream in Java?
4. Can you create a symbolic link from Java Program on supported platforms like UNIX?
5. What is the difference between FileInputStream and FileReader in Java IO?
6. What is the difference between BufferedReader and FileReader in Java?
7. What is the difference between BufferedReader and Scanner in Java?
8. What is the difference between Scanner and FileReader in Java?
9. What is the use of the PrintStream class in Java IO?
10. What is the right way to close the streams in Java
11. Why you need to close the streams in finally block?
12. Why do you need a separate try-catch block inside finally to close the input and output
streams?
13. What is the file descriptor?
14. Can we monitor a directory for adding new files in Java?
15. How do you process a large file in Java?
16. What is the try-with-resource statement in Java?
17. How do you convert a file into String in Java?

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

You might also like