Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 136

Unit – 1

What is Java?

Java is a programming language and a platform. Java is a high level, robust, object- oriented and secure
programming language.

Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year 1995. James Gosling
is known as the father of Java. Before Java, its name was Oak. Since Oak was already a registered company, so
James Gosling and his team changed the name from Oak to Java.

Platform: Any hardware or software environment in which a program runs, is known as a platform. Since
Java has a runtime environment (JRE) and API, it is called a platform.

Java Example

Let's have a quick look at Java programming example. A detailed description of Hello Java example is
available in next page.

Simple.java

1. class Simple{
2. public static void main(String args[]){

3. System.out.println("Hello Java"); 4. }

5. }

Application
According to Sun, 3 billion devices run Java. There are many devices where Java is currently used. Some of
them are as follows:

1. Desktop Applications such as acrobat reader, media player, antivirus, etc.

2. Web Applications such as irctc.co.in, javatpoint.com, etc.

3. Enterprise Applications such as banking applications.

4. Mobile

5. Embedded System

6. Smart Card
7. Robotics

8. Games, etc.

Types of Java Applications

There are mainly 4 types of applications that can be created using Java programming:

1) Standalone Application
Standalone applications are also known as desktop applications or window-based applications. These are
traditional software that we need to install on every machine. Examples of standalone application are Media
player, antivirus, etc. AWT and Swing are used in Java for creating standalone applications.

2) Web Application
An application that runs on the server side and creates a dynamic page is called a web application.
Currently, Servlet

, J SP
, S truts
, S pring
, H ibernate
, J SF
, etc. technologies are used for creating web applications in Java.

3) Enterprise Application
An application that is distributed in nature, such as banking applications, etc. is called an
enterprise application. It has advantages like high-level security, load balancing, and clustering.
In Java, E JB is used for creating enterprise applications.

4) Mobile Application
An application which is created for mobile devices is called a mobile application. Currently, Android and Java
ME are used for creating mobile applications.

Java Platforms / Editions

There are 4 platforms or editions of Java:

1) Java SE (Java Standard Edition)


It is a Java programming platform. It includes Java programming APIs such as java.lang, java.io, java.net, java.util,
java.sql, java.math etc. It includes core topics like OOPs, String

, Regex, Exception, Inner classes, Multithreading, I/O Stream, Networking, AWT, Swing, Reflection,
Collection, etc.

2) Java EE (Java Enterprise Edition)


It is an enterprise platform that is mainly used to develop web and enterprise applications. It is built on top of the
Java SE platform. It includes topics like Servlet, JSP, Web Services, EJB, J PA, etc.
3) Java ME (Java Micro Edition)
It is a micro platform that is dedicated to mobile applications.

4) JavaFX
It is used to develop rich internet applications. It uses a lightweight user interface API.

History of Java

The history of Java is very interesting. Java was originally designed for interactive television, but it was too
advanced technology for the digital cable television industry at the time. The history of Java starts with the Green
Team. Java team members (also known as Green Team), initiated this project to develop a language for digital
devices such as set-top boxes, televisions, etc. However, it was best suited for internet programming. Later, Java
technology was incorporated by Netscape.The principles for creating Java programming were "Simple, Robust,
Portable, Platform-independent, Secured, High Performance, Mulltithreaded,Architecture Neutral, Object-Oriented,
Interpreted, and Dynamic". Java

was developed by James Gosling, who is known as the father of Java, in 1995. James Gosling and his team members
started the project in the early '90s.

Currently, Java is used in internet programming, mobile devices, games, e- business solutions, etc. Following are given
significant points that describe the history of Java.

J ames Gosling , Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991. The small team of sun
engineers called Green Team.Initially it was designed for small, embedded systems in electronic appliances like set-top boxes.
Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
After that, it was called Oak and was developed as a part of the Green project.
Why Java was named as "Oak"?

Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries like the U.S.A., France, Germany,
Romania, etc.

In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.

Why Java Programming named "Java"?


Why had they choose the name Java for Java language? The team gathered to choose a new name. The suggested words were
"dynamic", "revolutionary", "Silk", "jolt", "DNA", etc. They wanted something that reflected the essence of the technology:
revolutionary, dynamic, lively, cool, unique, and easy to spell, and fun to say.
According to James Gosling, "Java was one of the top choices along with Silk". Since Java was so unique, most of the
team members preferred Java than other names.

Java is an island in Indonesia where the first coffee was produced (called Java coffee). It is a kind of espresso bean. Java name
was chosen by James Gosling while having a cup of coffee nearby his office.
Initially developed by James Gosling at Sun Microsystems
(which is now a subsidiary of Oracle Corporation) and released in 1995.
In 1995, Time magazine called Java one of the Ten Best Products of 1995.

JDK 1.0 was released on January 23, 1996. After the first release of Java, there have been many additional features added to the
language. Now Java is being used in Windows applications, Web applications, enterprise applications, mobile applications,
cards, etc. Each new version adds new features in Java.

Features of Java
The primary objective of Java programming language creation was to make it portable, simple and secure programming
language. Apart from this, there are also some excellent features which play an important role in the popularity of this language.
The features of Java are also known as Java buzzwords.
A list of the most important features of the Java language is given below.
Simple
Object-Oriented
Portable
Platform independent
Secured
Robust
Architecture neutral
Interpreted
High Performance
Multithreaded
Distributed
Dynamic

Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to Sun Microsystem, Java language
is a simple programming language because:

Java syntax is based on C++ (so easier for programmers to learn it after C++).
Java has removed many complicated and rarely-used features, for example, explicit pointers, operator overloading, etc.
There is no need to remove unreferenced objects because there is an Automatic Garbage Collection in Java.

Object-oriented
Java is an object-oriented programming language. Everything in Java is an object. Object-oriented means we organize our
software as a combination of different types of objects that incorporate both data and behavior.

Object-oriented programming (OOPs) is a methodology that simplifies software development and maintenance by providing
some rules.

Basic concepts of OOPs are:

Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Platform Independent
Java is platform independent because it is different from other languages like C, C++, etc. which are compiled into platform
specific machines while Java is a write once, run anywhere language. A platform is the hardware or software environment in
which a program runs.

There are two types of platforms software-based and hardware-based. Java provides a software-based platform.

The Java platform differs from most other platforms in the sense that it is a software-based platform that runs on top of other
hardware-based platforms. It has two components:

Runtime Environment
API(Application Programming Interface)

Java code can be executed on multiple platforms, for example, Windows, Linux, Sun Solaris, Mac/OS, etc. Java code is
compiled by the compiler and converted into bytecode. This bytecode is a platform-independent code because it can be run on
multiple platforms, i.e., Write Once and Run Anywhere (WORA).
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is secured because:

No explicit pointer
Java Programs run inside a virtual machine sandbox

Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE) which is used to load Java classes into the
Java Virtual Machine dynamically. It adds security by separating the package for the classes of the local file system from those
that are imported from network sources.
Bytecode Verifier: It checks the code fragments for illegal code that can violate access rights to objects.
Security Manager: It determines what resources a class can access such as reading and writing to the local disk.
Java language provides these securities by default. Some security can also be provided by an application developer explicitly
through SSL, JAAS, Cryptography, etc.

Robust
The English mining of Robust is strong. Java is robust because:

It uses strong memory management.


There is a lack of pointers that avoids security problems.
Java provides automatic garbage collection which runs on the Java Virtual Machine to get rid of objects which are not being
used by a Java application anymore.
There are exception handling and the type checking mechanism in Java. All these points make Java robust.

Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for example, the size of primitive types is
fixed.

In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of memory for 64-bit
architecture. However, it occupies 4 bytes of memory for both 32 and 64-bit architectures in Java.

Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require any implementation.

High-performance
Java is faster than other traditional interpreted programming languages because Java bytecode is "close" to native code. It is still
a little bit slower than a compiled language (e.g., C++). Java is an interpreted language that is why it is slower than compiled
languages, e.g., C, C++, etc.

Distributed
Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB are used for creating
distributed applications. This feature of Java makes us able to access files by calling the methods from any machine on the
internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that deal with many tasks at once by
defining multiple threads. The main advantage of multi-threading is that it doesn't occupy memory for each thread. It shares a
common Memory area. Threads are important for multi-media, Web applications, etc.
Dynamic
Java is a dynamic language. It supports the dynamic loading of classes. It means classes are loaded on demand. It also supports
functions from its native languages, i.e., C and C++.
Difference between JDK, JRE, and JVM

JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it doesn't physically exist. It is a
specification that provides a runtime environment in which Java bytecode can be executed. It can also run those programs which
are written in other languages and compiled to Java bytecode.

JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are platform dependent because the
configuration of each OS

is different from each other. However, Java is platform independent. There are three notions of the JVM: specification,
implementation, and instance.
The JVM performs the following main tasks:

Loads code
Verifies code
Executes code
Provides runtime environment

JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java Runtime Environment is a set of
software tools which are used for developing Java applications. It is used to provide the runtime environment. It is the
implementation of JVM. It physically exists. It contains a set of libraries + other files that JVM uses at runtime.

The implementation of JVM is also actively released by other companies besides Sun Micro Systems.
JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software development environment
which is used to develop Java applications and applets

. It physically exists. It contains JRE + development tools.

JDK is an implementation of any one of the below given Java Platforms released by Oracle Corporation:

Standard Edition Java Platform


Enterprise Edition Java Platform
Micro Edition Java Platform

The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an interpreter/loader (java), a
compiler (javac), an archiver (jar), a documentation generator (Javadoc), etc. to complete the development of a Java
Application.
JVM (Java Virtual Machine) Architecture

1. J ava Virtual Machine


2. I nternal Architecture of JVM

JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which
java bytecode can be executed.

JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent).

What is JVM

It is:

1. A specification where working of Java Virtual Machine is specified. But implementation provider is
independent to choose the algorithm. Its implementation has been provided by Oracle and other companies.
2. An implementation Its implementation is known as JRE (Java Runtime Environment).
3. Runtime Instance Whenever you write java command on the command prompt to run the java class, an
instance of JVM is created.

What it does

The JVM performs following operation:

o Loads code
o Verifies code
o Executes code
o Provides runtime environment

JVM provides definitions for the:

o Memory area
o Class file format
o Register set
o Garbage-collected heap
o Fatal error reporting etc.

JVM Architecture
Let's understand the internal architecture of JVM. It contains classloader, memory area, execution engine etc.
Classloader
Classloader is a subsystem of JVM which is used to load class files. Whenever we run the java program, it is loaded
first by the classloader. There are three built-in classloaders in Java.

Bootstrap ClassLoader: This is the first classloader which is the super class of Extension classloader. It loads the
rt.jar file which contains all class files of Java Standard Edition like java.lang package classes, java.net package
classes, java.util Package classes, java.io package classes, java.sql package classes etc.
Extension ClassLoader: This is the child classloader of Bootstrap and parent classloader of System classloader. It
loades the jar files located inside $JAVA_HOME/jre/lib/ext directory.
System/Application ClassLoader: This is the child classloader of Extension classloader. It loads the classfiles from
classpath. By default, classpath is set to current directory. You can change the classpath using "-cp" or "-classpath"
switch. It is also known as Application classloader.

These are the internal classloaders provided by Java. If you want to create your own classloader, you need to extend
the ClassLoader class.

Class(Method) Area
Class(Method) Area stores per-class structures such as the runtime constant pool, field and method data, the code for
methods.
Heap
It is the runtime data area in which objects are allocated.
Stack
Java Stack stores frames. It holds local variables and partial results, and plays a part in method invocation and
return.Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes.
Program Counter Register
PC (program counter) register contains the address of the Java virtual machine instruction currently being executed.

Native Method Stack


It contains all the native methods used in the application.
Execution Engine
It contains:
A virtual processor
Interpreter: Read bytecode stream then execute the instructions.
Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts of the byte code that have
similar functionality at the same time, and hence reduces the amount of time needed for compilation. Here, the term
"compiler" refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a
specific CPU.

Java Native Interface


Java Native Interface (JNI) is a framework which provides an interface to communicate with another application
written in another language like C, C++, Assembly etc. Java uses JNI framework to send output to the Console or
interact with OS libraries.
A java archive file is a file format/ archiving tool which contains all the components of an executable Java
application. All the predefined libraries are available in this format.
To include any of these (other than rt.jar) in to your project you need to set the class path for this particular JAR file.
You can create a JAR file using the command line options or using any IDE’s.

Creating a Jar file


You can create a Jar file using the jar command as shown below.
jar cf jar-file input-file(s)
Let us consider an example, create a Sample Java program with name Sample.java

Sample.java

public class Sample {


public static void main(String args[]){
System.out.println("Hi welcome to Java");
}

}
If you compile this program using Javac command as shown below −
C:\Examples >javac Sample.java
This command compiles the given java file and generates a .class file (byte code)

Now, create a jar file for the generated class as −


C:\Sample>jar cvf sample.jar *.class added manifest
adding: Sample.class(in = 434) (out= 302)(deflated 30%)
This will generate a jar file for all the classes in the current directory (since we used * instead of name) with
specified name.

Sandbox Security Model


In computer security, a sandbox is a security mechanism for separating running programs, usually in order to
minimize system failures or software vulnerabilities from spreading. In general, a sandbox is an isolated computing
environment in which a program or file can be executed without affecting the application in which it runs.
Sandboxes are used by software developers to test new programming code.
A sandbox typically provides a tightly controlled set of resources for guest programs to run in, such as limited
space on disk and memory.
In a Java programming language, the sandbox is the program area and it has some set of rules that programmers
need to follow when creating Java code (like an applet) that is sent as part of a page.
Since a Java applet is sent automatically as part of the page and can be executed as soon as it arrives, the applet can
easily do harm, either accidentally or intentionally
The sandbox restrictions provide strict limitations on which system resources the applet can request or access.The
programmer must write code that “plays” only within the sandbox, such as children are allowed to play within the
confined limits of a place. The sandbox can be conceived as a small area within your computer where an applet’s
code can play freely – but it’s not allowed to play anywhere else.
Security in Java
The original security model provided by the Java platform is known as the sandbox model, which existed in order
to provide a very restricted environment in which to run untrusted code obtained from the open network.
The essence of the sandbox model is that local code is trusted to have full access to vital system resources (such as
the file system) while downloaded remote code (an applet) is not trusted and can access only the limited resources
provided inside the sandbox.

The sandbox model was deployed through the Java Development Kit (JDK), and was generally adopted by
applications built with JDK 1.0, including Java-enabled web browsers.
Overall security is provided through a number of mechanisms.The language is designed to be type-safe and easy to
use i.e the hope is that the burden on the programmer is such that the likelihood of making mistakes is less compare
to using other programming languages such as C or C++. Language features such as automatic memory
management, garbage collection, and range checking on strings and arrays are examples of how the language helps
the programmer to write safe code.
Second, compilers and a bytecode verifier ensure that only legitimate Java bytecodes are executed. The bytecode
verifier, together with the Java Virtual Machine, guarantees language safety at run time.
A Classloader defines a local name space, which can be used to ensure that an untrusted applet cannot interfere
with the running of other programs.
Finally, access to crucial system resources is mediated by the Java Virtual Machine and is checked in advance by a
SecurityManager class that restricts the actions of a piece of untrusted code to the bare minimum.(SandBoxing)
Usage
Sandboxing is frequently used to test unverified programs that may contain a virus
Data Types in Java

Data types specify the different sizes and values that can be stored in the variable. There are two types of data types in Java:

1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and double.

2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.

Java Primitive Data Types

In Java language, primitive data types are the building blocks of data manipulation. These are the most basic data types
available in Java language.

Java is a statically-typed programming language. It means, all variables must be declared before its use. That is why we need to
declare variable's type and name.

There are 8 types of primitive data types:

o boolean data type

o byte data type

o char data type

o short data type

o int data type

o long data type

o float data type


o double data type

Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte

Boolean Data Type

The Boolean data type is used to store only two possible values: true and false. This data type is used for simple flags that track
true/false conditions.

The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.

Example:

1. Boolean one = false

Byte Data Type

The byte data type is an example of primitive data type. It isan 8-bit signed two's complement integer. Its value-range lies
between -128 to 127 (inclusive). Its minimum value is -128 and maximum value is 127. Its default value is 0.
The byte data type is used to save memory in large arrays where the memory savings is most required. It saves space because a
byte is 4 times smaller than an integer. It can also be used in place of "int" data type.

Example:

1. byte a = 10, byte b = -20

Short Data Type

The short data type is a 16-bit signed two's complement integer. Its value-range lies between -32,768 to 32,767 (inclusive). Its
minimum value is -32,768 and maximum value is 32,767. Its default value is 0.

The short data type can also be used to save memory just like byte data type. A short data type is 2 times smaller than an
integer.

Example:

1. short s = 10000, short r = -5000

Int Data Type

The int data type is a 32-bit signed two's complement integer. Its value-range lies between - 2,147,483,648 (-2^31) to
2,147,483,647 (2^31 -1) (inclusive). Its minimum value is - 2,147,483,648and maximum value is 2,147,483,647. Its default
value is 0.

The int data type is generally used as a default data type for integral values unless if there is no problem about memory.

Example:

1. int a = 100000, int b = -200000

Long Data Type

The long data type is a 64-bit two's complement integer. Its value-range lies between -9,223,372,036,854,775,808(-2^63) to
9,223,372,036,854,775,807(2^63 -1)(inclusive). Its minimum value is - 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used when you need a range of values more than those
provided by int.

Example:

1. long a = 100000L, long b = -200000L

Float Data Type

The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range is unlimited. It is recommended to use a
float (instead of double) if you need to save memory in large arrays of floating point numbers. The float data type should never
be used for precise values, such as currency. Its default value is 0.0F.

Example:

1. float f1 = 234.5f

Double Data Type

The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is unlimited. The double data type is
generally used for decimal values just like float. The double data type also should never be used for precise values, such as
currency. Its default value is 0.0d.
Example:

1. double d1 = 12.3

Char Data Type

The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000' (or 0) to '\uffff' (or 65,535
inclusive).The char data type is used to store characters.

Example:

1. char letterA = 'A'

Why char uses 2 byte in java and what is \u0000 ?

It is because java uses Unicode system not ASCII code system. The \u0000 is the lowest range of Unicode system.

Scope of Variables in Java


In programming, scope of variable defines how a specific variable is accessible within the program or across
classes. In this section, we will discuss the scope of variables in Java.
Scope of a Variable
In programming, a variable can be declared and defined inside a class, method, or block. It defines the scope of the
variable i.e. the visibility or accessibility of a variable. Variable declared inside a block or method are not visible to
outside. If we try to do so, we will get a compilation error. Note that the scope of a variable can be nested.
We can declare variables anywhere in the program but it has limited scope.
A variable can be a parameter of a method or constructor.
A variable can be defined and declared inside the body of a method and constructor.
It can also be defined inside blocks and loops.
Variable declared inside main() function cannot be accessed outside the main() function

Demo.java
public class Demo
{
//instance variable
String name = "Andrew";
//class and static variable
static double height= 5.9;
public static void main(String args[])
{
//local variable
int marks = 72;
}
}
In Java, there are three types of variables based on their scope:
PlayNext
Unmute
Current Time 0:00
/
Duration 18:10
Loaded: 0.37%
Â
Fullscreen
Backward Skip 10sPlay VideoForward Skip 10s
Member Variables (Class Level Scope)
Local Variables (Method Level Scope)
Member Variables (Class Level Scope)
These are the variables that are declared inside the class but outside any function have class-level scope. We can
access these variables anywhere inside the class. Note that the access specifier of a member variable does not affect
the scope within the class. Java allows us to access member variables outside the class with the following rules:

Access Modifier Package Subclass Word

public Yes Yes Yes

protected Yes Yes No

private No No No

default Yes No No

Syntax:
public class DemoClass
{
//variables declared inside the class have class level scope
int age;
private String name;
void displayName()
{
//statements
}
int dispalyAge()
{
//statements
}
char c;
}
Let's see an example.
VariableScopeExample1.java
public class VariableScopeExample1
{
public static void main(String args[])
{
int x=10;
{
//y has limited scope to this block only
int y=20;
System.out.println("Sum of x+y = " + (x+y));
}
//here y is unknown
y=100;
//x is still known
x=50;
}
}
Output:

We see that y=100 is unknown. If you want to compile and run the above program remove or comment the
statement y=100. After removing the statement, the above program runs successfully and shows the following
output.
Sum of x+y = 30
There is another variable named an instance variable. These are declared inside a class but outside any method,
constructor, or block. When an instance variable is declared using the keyword static is known as a static variable.
Their scope is class level but visible to the method, constructor, or block that is defined inside the class.
Let's see an example.
Product.java
public class Product
{
//variable visible to any child class
public String pName;
//variable visible to product class only
private double pPrice;
//creating a constructor and parsed product name as a parameter
public Product (String pname)
{
pName = pname;
}
//function sets the product price
public void setPrice(double pprice)
{
pPrice= pprice;
}
//method prints all product info
public void getInfo()
{
System.out.println("Product Name: " +pName );
System.out.println("Product Price: " +pPrice);
}
public static void main(String args[])
{
Product pro = new Product("Mac Book");
pro.setPrice(65000);
pro.getInfo();
}
}
Output:
Product Name: Mac Book
Product Price: 65000.0
Let's see another example.
StaticVariableScope.java
public class StaticVariableScope
{
//declaring a private static variable
private static double pivalue;
//declaring a constant variable
public static final String piconstant = "PI";
public static void main(String args[])
{
pivalue = 3.14159265359;
System.out.println("The value of " + piconstant + " is: " + pivalue);
}
}
Output:
The value of PI is: 3.14159265359
Local Variables (Method Level Scope)
These are the variables that are declared inside a method, constructor, or block have a method-level or block-
level scope and cannot be accessed outside in which it is defined. Variables declared inside a pair of curly
braces {} have block-level scope.
Declaring a Variable Inside a Method
public class DemoClass1
{
void show()
{
//variable declared inside a method has method level scope
int x=10;
System.out.println("The value of x is: "+x);
}
public static void main(String args[])
{
DemoClass1 dc = new DemoClass1();
dc.show();
}
}
Output:
The value of x is: 10
Let's see another example of method-level scope.
DemoClass2.java
public class DemoClass2
{
private int a;
public void setNumber(int a)
{
this.a = a;
System.out.println("The value of a is: "+a);
}
public static void main(String args[])
{
DemoClass2 dc = new DemoClass2();
dc.setNumber(3);
}
}
Output:
The value of a is: 3
In the above example, we have passed a variable as a parameter. We have used this keyword that differentiates the
class variable and local variable.
Declaring a Variable Inside a Constructor
VariableInsideConstructor.java
public class VariableInsideConstructor
{
//creating a default constructor
VariableInsideConstructor()
{
int age=24;
System.out.println("Age is: "+age);
}
//main() method
public static void main(String args[])
{
//calling a default constructor
VariableInsideConstructor vc=new VariableInsideConstructor();
}
}
Output:
Age is: 24
Declaring a Variable Inside a Block
VariableInsideBlock.java
public class VariableInsideBlock
{
public static void main(String args[])
{
int x=4;
{
//y has limited scope to this block only
int y=100;
System.out.println("Sum of x+y = " + (x+y));
y=10;
//gives error, already defined
int y=200;
}
//creates a new variable
int y;
}
}
Output:

We see that y=100 is unknown. If you want to compile and run the above program remove or comment the
statement y=100. After removing the statement, the above program runs successfully and shows the following
output.
Sum of x+y = 30
Let's see another example.
BlockScopeExample1.java
public class BlockScopeExample1
{
public static void main(String args[])
{
for (int x = 0; x < 10; x++)
{
System.out.println(x);
}
System.out.println(x);
}
}
Output:

When we run the above program, it shows an error at line 9, cannot find symbol because we have tried to print the
variable x that is declared inside the loop. To resolve this error, we need to declare the variable x just before the for
loop.
BlockScopeExample2.java
public class BlockScopeExample2
{
public static void main(String args[])
{
int x;
for (x = 0; x < 10; x++)
{
//prints 0 to 9
System.out.print(x+"\t");
}
//prints 10
System.out.println(x);
}
}
Output:
0 1 2 3 4 5 6 7 8 9
Operators in Java
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
Unary Operator,
Arithmetic Operator,
Shift Operator,
Relational Operator,
Bitwise Operator,
Logical Operator,
Ternary Operator and
Assignment Operator.
Java Operator Precedence

Operator Type Category Precedence

Unary postfix expr++ expr--

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

Arithmetic multiplicative */%

additive +-

Shift shift << >> >>>

Relational comparison < > <= >= instanceof

equality == !=

Bitwise bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

Logical logical AND &&

logical OR ||

Ternary ternary ?:

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


Java Unary Operator
The Java unary operators require only one operand. Unary operators are used to perform various operations i.e.:
PlayNext
Unmute
Current Time 0:00
/
Duration 18:10
Loaded: 0.37%
Â
Fullscreen
Backward Skip 10sPlay VideoForward Skip 10s
incrementing/decrementing a value by one
negating an expression
inverting the value of a boolean
Java Unary Operator Example: ++ and --
public class OperatorExample{
public static void main(String args[]){
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}}
Output:
10
12
12
10
Java Unary Operator Example 2: ++ and --
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=10;
System.out.println(a++ + ++a);//10+12=22
System.out.println(b++ + b++);//10+11=21

}}
Output:
22
21
Java Unary Operator Example: ~ and !
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(~a);//-11 (minus of total positive value which starts from 0)
System.out.println(~b);//9 (positive of total minus, positive starts from 0)
System.out.println(!c);//false (opposite of boolean value)
System.out.println(!d);//true
}}
Output:
-11
9
false
true
Java Arithmetic Operators
Java arithmetic operators are used to perform addition, subtraction, multiplication, and division. They act as basic
mathematical operations.
Java Arithmetic Operator Example
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
}}
Output:
15
5
50
2
0
Java Arithmetic Operator Example: Expression
public class OperatorExample{
public static void main(String args[]){
System.out.println(10*10/5+3-1*4/2);
}}
Output:
21
Java Left Shift Operator
The Java left shift operator << is used to shift all of the bits in a value to the left side of a specified number of times.
Java Left Shift Operator Example
public class OperatorExample{
public static void main(String args[]){
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(10<<3);//10*2^3=10*8=80
System.out.println(20<<2);//20*2^2=20*4=80
System.out.println(15<<4);//15*2^4=15*16=240
}}
Output:
40
80
80
240
Java Right Shift Operator
The Java right shift operator >> is used to move the value of the left operand to right by the number of bits
specified by the right operand.
Java Right Shift Operator Example
public OperatorExample{
public static void main(String args[]){
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}}
Output:
2
5
2
Java Shift Operator Example: >> vs >>>
public class OperatorExample{
public static void main(String args[]){
//For positive number, >> and >>> works same
System.out.println(20>>2);
System.out.println(20>>>2);
//For negative number, >>> changes parity bit (MSB) to 0
System.out.println(-20>>2);
System.out.println(-20>>>2);
}}
Output:
5
5
-5
1073741819
Java AND Operator Example: Logical && and Bitwise &
The logical && operator doesn't check the second condition if the first condition is false. It checks the second
condition only if the first one is true.
The bitwise & operator always checks both conditions whether first condition is true or false.
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a<c);//false && true = false
System.out.println(a<b&a<c);//false & true = false
}}
Output:
false
false
Java AND Operator Example: Logical && vs Bitwise &
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a++<c);//false && true = false
System.out.println(a);//10 because second condition is not checked
System.out.println(a<b&a++<c);//false && true = false
System.out.println(a);//11 because second condition is checked
}}
Output:
false
10
false
11
Java OR Operator Example: Logical || and Bitwise |
The logical || operator doesn't check the second condition if the first condition is true. It checks the second condition
only if the first one is false.
The bitwise | operator always checks both conditions whether first condition is true or false.
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a>b||a<c);//true || true = true
System.out.println(a>b|a<c);//true | true = true
//|| vs |
System.out.println(a>b||a++<c);//true || true = true
System.out.println(a);//10 because second condition is not checked
System.out.println(a>b|a++<c);//true | true = true
System.out.println(a);//11 because second condition is checked
}}
Output:
true
true
true
10
true
11
Java Ternary Operator
Java Ternary operator is used as one line replacement for if-then-else statement and used a lot in Java
programming. It is the only conditional operator which takes three operands.
Java Ternary Operator Example
public class OperatorExample{
public static void main(String args[]){
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}
Output:
2
Another Example:
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}
Output:
5
Java Assignment Operator
Java assignment operator is one of the most common operators. It is used to assign the value on its right to the
operand on its left.
Java Assignment Operator Example
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}}
Output:
14
16
Java Assignment Operator Example
public class OperatorExample{
public static void main(String[] args){
int a=10;
a+=3;//10+3
System.out.println(a);
a-=4;//13-4
System.out.println(a);
a*=2;//9*2
System.out.println(a);
a/=2;//18/2
System.out.println(a);
}}
Output:
13
9
18
9
Java Assignment Operator Example: Adding short
public class OperatorExample{
public static void main(String args[]){
short a=10;
short b=10;
//a+=b;//a=a+b internally so fine
a=a+b;//Compile time error because 10+10=20 now int
System.out.println(a);
}}
Output:
Compile time error
After type cast:
public class OperatorExample{
public static void main(String args[]){
short a=10;
short b=10;
a=(short)(a+b);//20 which is int now converted to short
System.out.println(a);
}}
Output:
20
Operators in Java
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
Unary Operator,
Arithmetic Operator,
Shift Operator,
Relational Operator,
Bitwise Operator,
Logical Operator,
Ternary Operator and
Assignment Operator.
Java Operator Precedence

Operator Category Precedence


Type

Unary postfix expr++ expr--

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

Arithmetic multiplicative */%


additive +-

Shift shift << >> >>>

Relational comparison < > <= >= instanceof

equality == !=

Bitwise bitwise AND &

bitwise exclusive ^
OR

bitwise inclusive |
OR

Logical logical AND &&

logical OR ||

Ternary ternary ?:

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


>>= >>>=

Java Unary Operator


The Java unary operators require only one operand. Unary operators are used to perform various operations i.e.:
PlayNext
Unmute
Current Time 0:00
/
Duration 18:10
Loaded: 0.37%
Â
Fullscreen
Backward Skip 10sPlay VideoForward Skip 10s
incrementing/decrementing a value by one
negating an expression
inverting the value of a boolean
Java Unary Operator Example: ++ and --
public class OperatorExample{
public static void main(String args[]){
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}}
Output:
10
12
12
10
Java Unary Operator Example 2: ++ and --
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=10;
System.out.println(a++ + ++a);//10+12=22
System.out.println(b++ + b++);//10+11=21

}}
Output:
22
21
Java Unary Operator Example: ~ and !
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(~a);//-11 (minus of total positive value which starts from 0)
System.out.println(~b);//9 (positive of total minus, positive starts from 0)
System.out.println(!c);//false (opposite of boolean value)
System.out.println(!d);//true
}}
Output:
-11
9
false
true
Java Arithmetic Operators
Java arithmetic operators are used to perform addition, subtraction, multiplication, and division. They act as basic
mathematical operations.
Java Arithmetic Operator Example
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
}}
Output:
15
5
50
2
0
Java Arithmetic Operator Example: Expression
public class OperatorExample{
public static void main(String args[]){
System.out.println(10*10/5+3-1*4/2);
}}
Output:
21
Java Left Shift Operator
The Java left shift operator << is used to shift all of the bits in a value to the left side of a specified number of times.
Java Left Shift Operator Example
public class OperatorExample{
public static void main(String args[]){
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(10<<3);//10*2^3=10*8=80
System.out.println(20<<2);//20*2^2=20*4=80
System.out.println(15<<4);//15*2^4=15*16=240
}}
Output:
40
80
80
240
Java Right Shift Operator
The Java right shift operator >> is used to move the value of the left operand to right by the number of bits
specified by the right operand.
Java Right Shift Operator Example
public OperatorExample{
public static void main(String args[]){
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}}
Output:
2
5
2
Java Shift Operator Example: >> vs >>>
public class OperatorExample{
public static void main(String args[]){
//For positive number, >> and >>> works same
System.out.println(20>>2);
System.out.println(20>>>2);
//For negative number, >>> changes parity bit (MSB) to 0
System.out.println(-20>>2);
System.out.println(-20>>>2);
}}
Output:
5
5
-5
1073741819
Java AND Operator Example: Logical && and Bitwise &
The logical && operator doesn't check the second condition if the first condition is false. It checks the second
condition only if the first one is true.
The bitwise & operator always checks both conditions whether first condition is true or false.
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a<c);//false && true = false
System.out.println(a<b&a<c);//false & true = false
}}
Output:
false
false
Java AND Operator Example: Logical && vs Bitwise &
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a++<c);//false && true = false
System.out.println(a);//10 because second condition is not checked
System.out.println(a<b&a++<c);//false && true = false
System.out.println(a);//11 because second condition is checked
}}
Output:
false
10
false
11
Java OR Operator Example: Logical || and Bitwise |
The logical || operator doesn't check the second condition if the first condition is true. It checks the second condition
only if the first one is false.
The bitwise | operator always checks both conditions whether first condition is true or false.
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a>b||a<c);//true || true = true
System.out.println(a>b|a<c);//true | true = true
//|| vs |
System.out.println(a>b||a++<c);//true || true = true
System.out.println(a);//10 because second condition is not checked
System.out.println(a>b|a++<c);//true | true = true
System.out.println(a);//11 because second condition is checked
}}
Output:
true
true
true
10
true
11
Java Ternary Operator
Java Ternary operator is used as one line replacement for if-then-else statement and used a lot in Java
programming. It is the only conditional operator which takes three operands.
Java Ternary Operator Example
public class OperatorExample{
public static void main(String args[]){
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}
Output:
2
Another Example:
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}
Output:
5
Java Assignment Operator
Java assignment operator is one of the most common operators. It is used to assign the value on its right to the
operand on its left.
Java Assignment Operator Example
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}}
Output:
14
16
Java Assignment Operator Example
public class OperatorExample{
public static void main(String[] args){
int a=10;
a+=3;//10+3
System.out.println(a);
a-=4;//13-4
System.out.println(a);
a*=2;//9*2
System.out.println(a);
a/=2;//18/2
System.out.println(a);
}}
Output:
13
9
18
9
Java Assignment Operator Example: Adding short
public class OperatorExample{
public static void main(String args[]){
short a=10;
short b=10;
//a+=b;//a=a+b internally so fine
a=a+b;//Compile time error because 10+10=20 now int
System.out.println(a);
}}
Output:
Compile time error
After type cast:
public class OperatorExample{
public static void main(String args[]){
short a=10;
short b=10;
a=(short)(a+b);//20 which is int now converted to short
System.out.println(a);
}}
Output:
20
Java Package
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined packages. Copts iAdvantage of Java
Package
1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
Simple example of java package
The package keyword is used to create a package in java.
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
How to compile java package
If you are not using any IDE, you need to follow the syntax given below:
1. javac -d directory javafilename
For example
1. javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can use any directory name like
/home (in case of Linux), d:/abc (in case of windows) etc. If you want to keep the package within the same
directory, you can use . (dot).
How to run java package program
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
To Compile: javac -d . Simple.java
To Run: java mypack.Simple
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The . represents the
current folder.
How to access package from another package?
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not subpackages.
The import keyword is used to make the classes and interface of another package accessible to the current
package.
Example of package that import the packagename.*
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10.}
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
Example of package by import package.classname
1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2. package mypack;
3. import pack.A;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10.}
Output:Hello
3) Using fully qualified name
If you use fully qualified name then only declared class of this package will be accessible. Now there is no need to
import. But you need to use fully qualified name every time when you are accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql packages contain Date
class.
Example of package by import fully qualified name
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. class B{
4. public static void main(String args[]){
5. pack.A obj = new pack.A();//using fully qualified name
6. obj.msg();
7. }
8. }
Output:Hello
Note: If you import a package, subpackages will not be imported.
If you import a package, all the classes and interface of that package will be imported excluding the classes and
interfaces of the subpackages. Hence, you need to import the subpackage as well.
Note: Sequence of the program must be package then import then class.
Subpackage in java
Package inside the package is called the subpackage. It should be created to categorize the package further.
Let's take an example, Sun Microsystem has definded a package named java that contains many classes like
System, String, Reader, Writer, Socket etc. These classes
represent a particular group e.g. Reader and Writer classes are for Input/Output operation, Socket and ServerSocket
classes are for networking etc and so on. So, Sun has subcategorized the java package into subpackages such as
lang, net, io etc. and put the Input/Output related classes in io package, Server and ServerSocket classes in net
packages and so on.
The standard of defining package is domain.company.package e.g. com.javatpoint.bean or org.sssit.dao.
Example of Subpackage
1. package com.javatpoint.core;
2. class Simple{
3. public static void main(String args[]){
4. System.out.println("Hello subpackage");
5. }
6. }
To Compile: javac -d . Simple.java
To Run: java com.javatpoint.core.Simple
Output:Hello subpackage
How to send the class file to another directory or drive?
There is a scenario, I want to put the class file of A.java source file in classes folder of c: drive. For example:
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
To Compile:
e:\sources> javac -d c:\classes Simple.java
To Run:
To run this program from e:\source directory, you need to set classpath of the directory where the clafile resides.
e:\sources> set classpath=c:\classes;.;
e:\sources> java mypack.Simple
Another way to run this program by -classpath switch of java: The -classpath switch can be used with javac and
java tool.
To run this program from e:\source directory, you can use -classpath switch of java that tells where to look for
class file. For example:
e:\sources> java -classpath c:\classes mypack.Simple Output:Welcome to package
Ways to load the class files or jar files
There are two ways to load the class files temporary and permanent. o Temporary
o By setting the classpath in the command prompt
o By -classpath switch
o Permanent
o By setting the classpath in the environment variables o By creating the jar file, that contains all the class files, and
copying the jar file in the jre/lib/ext folder.
Rule: There can be only one public class in a java source file and it must be saved by the public class name.
1. //save as C.java otherwise Compilte Time Error
2.
3. class A{}
4. class B{}
5. public class C{}
How to put two public classes in a package?
If you want to put two public classes in a package, have two java source files containing one pubclass, but keep the
package name same. For example:
1. //save as A.java
2.
3. package javatpoint;
4. public class A{}
1. //save as B.java
2.
3. package javatpoint;
4. public class B{}
Access Modifiers in Java
1.Private access modifier
2.Role of private constructor
3.Default access modifier
4.Protected access modifier
5.Public access modifier
6.Access Modifier with Method Overriding
There are two types of modifiers in Java: access modifiers and non-access modifiers.
ACCESS MODIFIERS
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We can
change the access level of fields, constructors, methods, and class by applying the access modifier on it.
There are four types of Java access modifiers:
1. Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the
class.
2. Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the
package. If you do not specify any access level, it will be the default.
3. Protected: The access level of a protected modifier is within the package and outside the package through child
class. If you do not make the child class, it cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the
class, within the package and outside the package.
There are many non-access modifiers, such as static, abstract, synchronized, native, volatile, transient, etc. Here,
we are going to learn the access modifiers only.
26.1M
616
OOPs Concepts in Java
Understanding Java Access Modifiers Let's understand the access modifiers in Java by a simple table.
Access
within
within
outside package by subclass
outside
Modifier
class
package
only
package

Private N N N
Y

Default Y N N
Y

Protected Y Y Y N

Public Y Y Y
Y

1) Private
The private access modifier is accessible only within the class.
Simple example of private access modifier
In this example, we have created two classes A and Simple. A class contains private data member and private
method. We are accessing these private members from outside the class, so there is a compile-time error.
1. class A{
2. private int data=40;
3. private void msg(){System.out.println("Hello java");}
4. }
5.
6. public class Simple{
7. public static void main(String args[]){
8. A obj=new A();
9. System.out.println(obj.data);//Compile Time Error
10. obj.msg();//Compile Time Error
11. }
12.}
Role of Private Constructor
If you make any class constructor private, you cannot create the instance of that class from outside the class. For
example:
1. class A{
2. private A(){}//private constructor
3. void msg(){System.out.println("Hello java");}
4. }
5. public class Simple{
6. public static void main(String args[]){
7. A obj=new A();//Compile Time Error
8. }
9. }
Note: A class cannot be private or protected except nested class.
2) Default
If you don't use any modifier, it is treated as default by default. The default modifier is accessible only within
package. It cannot be accessed from outside the package. It provides more accessibility than private. But, it is more
restrictive than protected, and public.
Example of default access modifier
In this example, we have created two packages pack and mypack. We are accessing the A class from outside its
package, since A class is not public, so it cannot be accessed from outside the package.
1. //save by A.java
2. package pack;
3. class A{
4. void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4. class B{
5. public static void main(String args[]){
6. A obj = new A();//Compile Time Error
7. obj.msg();//Compile Time Error
8. }
9. }
In the above example, the scope of class A and its method msg() is default so it cannot be accessed from outside
the package.
3) Protected
The protected access modifier is accessible within package and outside the package but through inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It can't be applied on
the class.
It provides more accessibility than the default modifer.
Example of protected access modifier
In this example, we have created the two packages pack and mypack. The A class of pack package is public, so can
be accessed from outside the package. But msg method of this package is declared as protected, so it can be
accessed from outside the class only through inheritance.
1. //save by A.java
2. package pack;
3. public class A{
4. protected void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B extends A{
6. public static void main(String args[]){
7. B obj = new B();
8. obj.msg();
9. }
10.}
Output:Hello
4) Public
The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.
Example of public access modifier
1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2.
3. package mypack;
4. import pack.*;
5.
6. class B{
7. public static void main(String args[]){
8. A obj = new A();
9. obj.msg(); 10. }
11.}
Output:Hello

Unit – II
Inheritance in Java
Inheritance
Types of Inheritance
Why multiple inheritance is not possible in Java in case of class?
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).
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.
Inheritance in Java
Inheritance
Types of Inheritance
Why multiple inheritance is not possible in Java in case of class?
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).
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.
In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is called
child or subclass.

Java Inheritance Example


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.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Test it Now
Programmer salary is:40000.0
Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class as well as of Employee class i.e. code
reusability.

Types of inheritance in java


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:

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();
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();
d.bark();
d.eat();
}}
Output:
weeping...
barking...
eating...
Hierarchical Inheritance Example
When two or more classes inherits a single class, it is known as hierarchical inheritance. In the example given
below, Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance.
File: TestInheritance3.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing...
eating...

Q) Why multiple inheritance is not supported in java?


To reduce the complexity and simplify the language, 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.
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were

public static void main(String args[]){


C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
Test it Now
Compile Time Error
/
s
In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is called
child or subclass.

Java Inheritance Example


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.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Test it Now
Programmer salary is:40000.0
Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class as well as of Employee class i.e. code
reusability.

Types of inheritance in java


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:

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();
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();
d.bark();
d.eat();
}}
Output:
weeping...
barking...
eating...
Hierarchical Inheritance Example
When two or more classes inherits a single class, it is known as hierarchical inheritance. In the example given
below, Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance.
File: TestInheritance3.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing...
eating...

Q) Why multiple inheritance is not supported in java?


To reduce the complexity and simplify the language, 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.
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were

public static void main(String args[]){


C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
Test it Now
Compile Time Error
Final Keyword In Java
1. Final variable
2. Final method
3. Final class
4. Is final method inherited ?
5. Blank final variable
6. Static blank final variable
7. Final parameter
8. Can you declare a final constructor

The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be:

1. variable
2. method
3. class

The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or
uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be
initialized in the static block only. We will have detailed learning of these. Let's first learn the basics of final keyword.

1) Java final variable

If you make any variable as final, you cannot change the value of final variable(It will be constant).

Example of final variable

There is a final variable speedlimit, we are going to change the value of this variable, but It can't be changed because final
variable once assigned a value can never be changed.

1. class Bike9{
2. final int speedlimit=90;//final variable
3. void run(){
4. speedlimit=400;
5. }
6. public static void main(String args[]){
7. Bike9 obj=new Bike9();
8. obj.run();
9. }
10. }//end of class
Test it Now
Output:Compile Time Error

2) Java final method

If you make any method as final, you cannot override it.

Example of final method


1. class Bike{
2. final void run(){System.out.println("running");}
3. }
4.
5. class Honda extends Bike{
6. void run(){System.out.println("running safely with 100kmph");}
7.
8. public static void main(String args[]){
9. Honda honda= new Honda();
10. honda.run();
11. }
12. }
Test it Now
Output:Compile Time Error

3) Java final class

If you make any class as final, you cannot extend it.

Example of final class


1. final class Bike{}
2.
3. class Honda1 extends Bike{
4. void run(){System.out.println("running safely with 100kmph");}
5.
6. public static void main(String args[]){
7. Honda1 honda= new Honda1();
8. honda.run();
9. }
10. }
Test it Now
Output:Compile Time Error

Q) Is final method inherited?

Ans) Yes, final method is inherited but you cannot override it. For Example:

1. class Bike{
2. final void run(){System.out.println("running...");}
3. }
4. class Honda2 extends Bike{
5. public static void main(String args[]){
6. new Honda2().run();
7. }
8. }
Test it Now
Output:running...

Q) What is blank or uninitialized final variable?

A final variable that is not initialized at the time of declaration is known as blank final variable.

If you want to create a variable that is initialized at the time of creating object and once initialized may not be changed, it is
useful. For example PAN CARD number of an employee.

It can be initialized only in constructor.

Example of blank final variable


1. class Student{
2. int id;
3. String name;
4. final String PAN_CARD_NUMBER;
5. ...
6. }

Que) Can we initialize blank final variable?

Yes, but only in constructor. For example:

1. class Bike10{
2. final int speedlimit;//blank final variable
3.
4. Bike10(){
5. speedlimit=70;
6. System.out.println(speedlimit);
7. }
8.
9. public static void main(String args[]){
10. new Bike10();
11. }
12. }
Test it Now
Output: 70

static blank final variable

A static final variable that is not initialized at the time of declaration is known as static blank final variable. It can be initialized
only in static block.
Example of static blank final variable
1. class A{
2. static final int data;//static blank final variable
3. static{ data=50;}
4. public static void main(String args[]){
5. System.out.println(A.data);
6. }
7. }

Q) What is final parameter?

If you declare any parameter as final, you cannot change the value of it.

1. class Bike11{
2. int cube(final int n){
3. n=n+2;//can't be changed as n is final
4. n*n*n;
5. }
6. public static void main(String args[]){
7. Bike11 b=new Bike11();
8. b.cube(5);
9. }
10. }
Test it Now
Output: Compile Time Error

Polymorphism in Java

Polymorphism in Java is a concept by which we can perform a single action in different ways. Polymorphism is derived from
2 Greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means many
forms.

There are two types of polymorphism in Java: compile-time polymorphism and runtime polymorphism. We can perform
polymorphism in java by method overloading and method overriding.

If you overload a static method in Java, it is the example of compile time polymorphism. Here, we will focus on runtime
polymorphism in java.

Runtime Polymorphism in Java

Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved at
runtime rather than compile-time.

In this process, an overridden method is called through the reference variable of a superclass. The determination of the method
to be called is based on the object being referred to by the reference variable.

Let's first understand the upcasting before Runtime Polymorphism.

Upcasting

If the reference variable of Parent class refers to the object of Child class, it is known as upcasting. For example:
1. class A{}
2. class B extends A{}
1. A a=new B();//upcasting

For upcasting, we can use the reference variable of class type or an interface type. For Example:

1. interface I{}
2. class A{}
3. class B extends A implements I{}

Here, the relationship of B class would be:

B IS-A A
B IS-A I
B IS-A Object

Since Object is the root class of all classes in Java, so we can write B IS-A Object.

Example of Java Runtime Polymorphism

In this example, we are creating two classes Bike and Splendor. Splendor class extends Bike class and overrides its run()
method. We are calling the run method by the reference variable of Parent class. Since it refers to the subclass object and
subclass method overrides the Parent class method, the subclass method is invoked at runtime.

Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism.

1. class Bike{
2. void run(){System.out.println("running");}
3. }
4. class Splendor extends Bike{
5. void run(){System.out.println("running safely with 60km");}
6.
7. public static void main(String args[]){
8. Bike b = new Splendor();//upcasting
9. b.run();
10. }
11. }
Test it Now

Output:

running safely with 60km.


Java Runtime Polymorphism Example: Bank

Consider a scenario where Bank is a class that provides a method to get the rate of interest. However, the rate of interest may
differ according to banks. For example, SBI, ICICI, and AXIS banks are providing 8.4%, 7.3%, and 9.7% rate of interest.

Note: This example is also given in method overriding but there was no upcasting.
1. class Bank{
2. float getRateOfInterest(){return 0;}
3. }
4. class SBI extends Bank{
5. float getRateOfInterest(){return 8.4f;}
6. }
7. class ICICI extends Bank{
8. float getRateOfInterest(){return 7.3f;}
9. }
10. class AXIS extends Bank{
11. float getRateOfInterest(){return 9.7f;}
12. }
13. class TestPolymorphism{
14. public static void main(String args[]){
15. Bank b;
16. b=new SBI();
17. System.out.println("SBI Rate of Interest: "+b.getRateOfInterest());
18. b=new ICICI();
19. System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest());
20. b=new AXIS();
21. System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest());
22. }
23. }
Test it Now

Output:

SBI Rate of Interest: 8.4


ICICI Rate of Interest: 7.3
AXIS Rate of Interest: 9.7

Java Runtime Polymorphism Example: Shape


1. class Shape{
2. void draw(){System.out.println("drawing...");}
3. }
4. class Rectangle extends Shape{
5. void draw(){System.out.println("drawing rectangle...");}
6. }
7. class Circle extends Shape{
8. void draw(){System.out.println("drawing circle...");}
9. }
10. class Triangle extends Shape{
11. void draw(){System.out.println("drawing triangle...");}
12. }
13. class TestPolymorphism2{
14. public static void main(String args[]){
15. Shape s;
16. s=new Rectangle();
17. s.draw();
18. s=new Circle();
19. s.draw();
20. s=new Triangle();
21. s.draw();
22. }
23. }
Test it Now

Output:

drawing rectangle...
drawing circle...
drawing triangle...

Java Runtime Polymorphism Example: Animal


1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void eat(){System.out.println("eating bread...");}
6. }
7. class Cat extends Animal{
8. void eat(){System.out.println("eating rat...");}
9. }
10. class Lion extends Animal{
11. void eat(){System.out.println("eating meat...");}
12. }
13. class TestPolymorphism3{
14. public static void main(String[] args){
15. Animal a;
16. a=new Dog();
17. a.eat();
18. a=new Cat();
19. a.eat();
20. a=new Lion();
21. a.eat();
22. }}
Test it Now

Output:

eating bread...
eating rat...
eating meat...

Java Runtime Polymorphism with Data Member

A method is overridden, not the data members, so runtime polymorphism can't be achieved by data members.

In the example given below, both the classes have a data member speedlimit. We are accessing the data member by the
reference variable of Parent class which refers to the subclass object. Since we are accessing the data member which is not
overridden, hence it will access the data member of the Parent class always.

Rule: Runtime polymorphism can't be achieved by data members.


1. class Bike{
2. int speedlimit=90;
3. }
4. class Honda3 extends Bike{
5. int speedlimit=150;
6.
7. public static void main(String args[]){
8. Bike obj=new Honda3();
9. System.out.println(obj.speedlimit);//90
10. }
Test it Now

Output:

90

Java Runtime Polymorphism with Multilevel Inheritance

Let's see the simple example of Runtime Polymorphism with multilevel inheritance.

1. class Animal{
2. void eat(){System.out.println("eating");}
3. }
4. class Dog extends Animal{
5. void eat(){System.out.println("eating fruits");}
6. }
7. class BabyDog extends Dog{
8. void eat(){System.out.println("drinking milk");}
9. public static void main(String args[]){
10. Animal a1,a2,a3;
11. a1=new Animal();
12. a2=new Dog();
13. a3=new BabyDog();
14. a1.eat();
15. a2.eat();
16. a3.eat();
17. }
18. }
Test it Now

Output:

eating
eating fruits
drinking Milk

Try for Output


1. class Animal{
2. void eat(){System.out.println("animal is eating...");}
3. }
4. class Dog extends Animal{
5. void eat(){System.out.println("dog is eating...");}
6. }
7. class BabyDog1 extends Dog{
8. public static void main(String args[]){
9. Animal a=new BabyDog1();
10. a.eat();
11. }}
Test it Now

Output:

Dog is eating
Difference between abstract class and interface

Abstract class and interface both are used to achieve abstraction where we can declare the abstract methods. Abstract class and
interface both can't be instantiated.

But there are many differences between abstract class and interface that are given below.

Abstract class Interface

1) Abstract class can have abstract and non- Interface can have only abstract methods. Since Java 8,
abstract methods. it can have default and static methods also.

2) Abstract class doesn't support multiple Interface supports multiple inheritance.


inheritance.

3) Abstract class can have final, non-final, static Interface has only static and final variables.
and non-static variables.

4) Abstract class can provide the implementation Interface can't provide the implementation of
of interface. abstract class.

5) The abstract keyword is used to declare The interface keyword is used to declare interface.
abstract class.

6) An abstract class can extend another Java class An interface can extend another Java interface only.
and implement multiple Java interfaces.

7) An abstract class can be extended using An interface can be implemented using keyword
keyword "extends". "implements".
8) A Java abstract class can have class members Members of a Java interface are public by default.
like private, protected, etc.

9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully abstraction (100%).

Example of abstract class and interface in Java

Let's see a simple example where we are using interface and abstract class both.

1. //Creating interface that has 4 methods


2. interface A{
3. void a();//bydefault, public and abstract
4. void b();
5. void c();
6. void d();
7. }
8.
9. //Creating abstract class that provides the implementation of one method of A interface
10. abstract class B implements A{
11. public void c(){System.out.println("I am C");}
12. }
13.
14. //Creating subclass of abstract class, now we need to provide the implementation of rest of the methods
15. class M extends B{
16. public void a(){System.out.println("I am a");}
17. public void b(){System.out.println("I am b");}
18. public void d(){System.out.println("I am d");}
19. }
20.
21. //Creating a test class that calls the methods of A interface
22. class Test5{
23. public static void main(String args[]){
24. A a=new M();
25. a.a();
26. a.b();
27. a.c();
28. a.d();
29. }}
Test it Now

Output:

I am a
I am b
I am c
I am d
Packages
Packages are used in Java in order to prevent naming conflicts, to control access, to make searching/locating and usage of
classes, interfaces, enumerations and annotations easier, etc.
A Package can be defined as a grouping of related types (classes, interfaces, enumerations and annotations ) providing access
protection and namespace management.
Some of the existing packages in Java are −
 java.lang − bundles the fundamental classes
 java.io − classes for input , output functions are bundled in this package
Programmers can define their own packages to bundle group of classes/interfaces, etc. It is a good practice to group related
classes implemented by you so that a programmer can easily determine that the classes, interfaces, enumerations, and
annotations are related.
Since the package creates a new namespace there won't be any name conflicts with names in other packages. Using packages, it
is easier to provide access control and it is also easier to locate the related classes.

Creating a Package
While creating a package, you should choose a name for the package and include a package statement along with that name at
the top of every source file that contains the classes, interfaces, enumerations, and annotation types that you want to include in
the package.
The package statement should be the first line in the source file. There can be only one package statement in each source file,
and it applies to all types in the file.
If a package statement is not used then the class, interfaces, enumerations, and annotation types will be placed in the current
default package.
To compile the Java programs with package statements, you have to use -d option as shown below.
javac -d Destination_folder file_name.java
Then a folder with the given package name is created in the specified destination, and the compiled class files will be placed in
that folder.
Example
Let us look at an example that creates a package called animals. It is a good practice to use names of packages with lower case
letters to avoid any conflicts with the names of classes and interfaces.
Following package example contains interface named animals −

/* File name : Animal.java */


package animals;

interface Animal {
public void eat();
public void travel();
}
Now, let us implement the above interface in the same package animals −

package animals;
/* File name : MammalInt.java */

public class MammalInt implements Animal {

public void eat() {


System.out.println("Mammal eats");
}

public void travel() {


System.out.println("Mammal travels");
}

public int noOfLegs() {


return 0;
}
public static void main(String args[]) {
MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}
Now compile the java files as shown below −
$ javac -d . Animal.java
$ javac -d . MammalInt.java
Now a package/folder with the name animals will be created in the current directory and these class files will be placed in it as
shown below.

You can execute the class file within the package and get the result as shown below.
Mammal eats
Mammal travels

The import Keyword


If a class wants to use another class in the same package, the package name need not be used. Classes in the same package find
each other without any special syntax.
Example
Here, a class named Boss is added to the payroll package that already contains Employee. The Boss can then refer to the
Employee class without using the payroll prefix, as demonstrated by the following Boss class.

package payroll;
public class Boss {
public void payEmployee(Employee e) {
e.mailCheck();
}
}
What happens if the Employee class is not in the payroll package? The Boss class must then use one of the following
techniques for referring to a class in a different package.

 The fully qualified name of the class can be used. For example −
payroll.Employee
 The package can be imported using the import keyword and the wild card (*). For example −
import payroll.*;
 The class itself can be imported using the import keyword. For example −
import payroll.Employee;
Note − A class file can contain any number of import statements. The import statements must appear after the package
statement and before the class declaration.

The Directory Structure of Packages


Two major results occur when a class is placed in a package −
 The name of the package becomes a part of the name of the class, as we just discussed in the previous section.
 The name of the package must match the directory structure where the corresponding bytecode resides.
Here is simple way of managing your files in Java −
Put the source code for a class, interface, enumeration, or annotation type in a text file whose name is the simple name of the
type and whose extension is .java.
For example −

// File Name : Car.java


package vehicle;

public class Car {


// Class implementation.
}
Now, put the source file in a directory whose name reflects the name of the package to which the class belongs −
....\vehicle\Car.java
Now, the qualified class name and pathname would be as follows −

 Class name → vehicle.Car


 Path name → vehicle\Car.java (in windows)
In general, a company uses its reversed Internet domain name for its package names.
Example − A company's Internet domain name is apple.com, then all its package names would start with com.apple. Each
component of the package name corresponds to a subdirectory.
Example − The company had a com.apple.computers package that contained a Dell.java source file, it would be contained in a
series of subdirectories like this −
....\com\apple\computers\Dell.java
At the time of compilation, the compiler creates a different output file for each class, interface and enumeration defined in it.
The base name of the output file is the name of the type, and its extension is .class.
For example −

// File Name: Dell.java


package com.apple.computers;

public class Dell {


}

class Ups {
}
Now, compile this file as follows using -d option −
$javac -d . Dell.java
The files will be compiled as follows −
.\com\apple\computers\Dell.class
.\com\apple\computers\Ups.class
You can import all the classes or interfaces defined in \com\apple\computers\ as follows −
import com.apple.computers.*;
Like the .java source files, the compiled .class files should be in a series of directories that reflect the package name. However,
the path to the .class files does not have to be the same as the path to the .java source files. You can arrange your source and
class directories separately, as −
<path-one>\sources\com\apple\computers\Dell.java

<path-two>\classes\com\apple\computers\Dell.class
By doing this, it is possible to give access to the classes directory to other programmers without revealing your sources. You
also need to manage source and class files in this manner so that the compiler and the Java Virtual Machine (JVM) can find all
the types your program uses.
The full path to the classes directory, <path-two>\classes, is called the class path, and is set with the CLASSPATH system
variable. Both the compiler and the JVM construct the path to your .class files by adding the package name to the class path.
Say <path-two>\classes is the class path, and the package name is com.apple.computers, then the compiler and JVM will look
for .class files in <path-two>\classes\com\apple\computers.
A class path may include several paths. Multiple paths should be separated by a semicolon (Windows) or colon (Unix). By
default, the compiler and the JVM search the current directory and the JAR file containing the Java platform classes so that
these directories are automatically in the class path.

Set CLASSPATH System Variable


To display the current CLASSPATH variable, use the following commands in Windows and UNIX (Bourne shell) −

 In Windows → C:\> set CLASSPATH


 In UNIX → % echo $CLASSPATH
To delete the current contents of the CLASSPATH variable, use −

 In Windows → C:\> set CLASSPATH =


 In UNIX → % unset CLASSPATH; export CLASSPATH
To set the CLASSPATH variable −

 In Windows → set CLASSPATH = C:\users\jack\java\classes


 In UNIX → % CLASSPATH = /home/jack/java/classes; export CLASSPATH
Exception Handling in Java

1. Exception Handling

2. Advantage of Exception Handling

3. Hierarchy of Exception classes

4. Types of Exception

5. Exception Example

6. Scenarios where an exception may occur

Exception Handling in Java

The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that the normal flow of the
application can be maintained.

In this tutorial, we will learn about Java exceptions, it's types, and the difference between checked and unchecked exceptions.

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 ClassNotFoundException, IOException, SQLException,
RemoteException, 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:

1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;

Suppose there are 10 statements in a Java program and an exception occurs at statement 5; the rest of the code will not be
executed, i.e., statements 6 to 10 will not be executed. However, when we perform exception handling, the rest of the
statements will be executed. That is why we use exception handling in Java.

Do You Know?

o What is the difference between checked and unchecked exceptions?

o What happens behind the code int data=50/0;?

o Why use multiple catch block?

o Is there any possibility when the finally block is not executed?

o What is exception propagation?

o What is the difference between the throw and throws keyword?

o What are the 4 rules for using exception handling with method overriding?

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

1. Checked Exception

2. Unchecked Exception

3. Error
Difference between Checked and Unchecked Exceptions

1) Checked Exception

The classes that directly inherit the Throwable class except RuntimeException 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 RuntimeException are known as unchecked exceptions. For example, ArithmeticException,
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 are OutOfMemoryError, VirtualMachineError, AssertionError etc.

Java Exception Keywords

Java provides five keywords that are used to handle the exception. The following table describes each.

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 either catch 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

1. public class JavaExceptionExample{


2. public static void main(String args[]){
3. try{
4. //code that may raise exception
5. int data=100/0;
6. }catch(ArithmeticException e){System.out.println(e);}
7. //rest code of the program
8. System.out.println("rest of the code...");
9. }
10. }
Test it Now

Output:

Exception in thread main java.lang.ArithmeticException:/ by zero


rest of the code...

In the above example, 100/0 raises an ArithmeticException which is handled by a try-catch block.

Common Scenarios of Java Exceptions

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

1) A scenario where ArithmeticException occurs

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

1. int a=50/0;//ArithmeticException

2) A scenario where NullPointerException occurs

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

1. String s=null;
2. System.out.println(s.length());//NullPointerException

3) A scenario where NumberFormatException 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.

1. String s="abc";
2. 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.
1. int a[]=new int[5];
2. a[10]=50; //ArrayIndexOutOfBoundsException
Java Threads | How to create a thread in Java

There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.

Thread class:

Thread class provide constructors and methods to create and perform operations on a thread.Thread class extends Object class
and implements Runnable interface.

Commonly used Constructors of Thread class:


o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)

Commonly used methods of Thread class:


1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the thread.JVM calls the run() method on the thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease execution) for
the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing thread.
11. public int getId(): returns the id of the thread.
12. public Thread.State getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object to temporarily pause and allow other threads to
execute.
15. public void suspend(): is used to suspend the thread(depricated).
16. public void resume(): is used to resume the suspended thread(depricated).
17. public void stop(): is used to stop the thread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemon thread.
19. public void setDaemon(boolean b): marks the thread as daemon or user thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been interrupted.

Runnable interface:

The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. Runnable
interface have only one method named run().

1. public void run(): is used to perform action for a thread.

Starting a thread:

The start() method of Thread class is used to start a newly created thread. It performs the following tasks:

o A new thread starts(with new callstack).


o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will run.

1) Java Thread Example by extending Thread class

FileName: Multi.java

1. class Multi extends Thread{


2. public void run(){
3. System.out.println("thread is running...");
4. }
5. public static void main(String args[]){
6. Multi t1=new Multi();
7. t1.start();
8. }
9. }

Output:

thread is running...

2) Java Thread Example by implementing Runnable interface

FileName: Multi3.java

1. class Multi3 implements Runnable{


2. public void run(){
3. System.out.println("thread is running...");
4. }
5.
6. public static void main(String args[]){
7. Multi3 m1=new Multi3();
8. Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
9. t1.start();
10. }
11. }
Output:

thread is running...

If you are not extending the Thread class, your class object would not be treated as a thread object. So you need to explicitly
create the Thread class object. We are passing the object of your class that implements Runnable so that your class run()
method may execute.

3) Using the Thread Class: Thread(String Name)

We can directly use the Thread class to spawn new threads using the constructors defined above.

FileName: MyThread1.java

1. public class MyThread1


2. {
3. // Main method
4. public static void main(String argvs[])
5. {
6. // creating an object of the Thread class using the constructor Thread(String name)
7. Thread t= new Thread("My first thread");
8.
9. // the start() method moves the thread to the active state
10. t.start();
11. // getting the thread name by invoking the getName() method
12. String str = t.getName();
13. System.out.println(str);
14. }
15. }

Output:

My first thread

4) Using the Thread Class: Thread(Runnable r, String name)

Observe the following program.

FileName: MyThread2.java

1. public class MyThread2 implements Runnable


2. {
3. public void run()
4. {
5. System.out.println("Now the thread is running ...");
6. }
7.
8. // main method
9. public static void main(String argvs[])
10. {
11. // creating an object of the class MyThread2
12. Runnable r1 = new MyThread2();
13.
14. // creating an object of the class Thread using Thread(Runnable r, String name)
15. Thread th1 = new Thread(r1, "My new thread");
16.
17. // the start() method moves the thread to the active state
18. th1.start();
19.
20. // getting the thread name by invoking the getName() method
21. String str = th1.getName();
22. System.out.println(str);
23. }
24. }

Output:

My new thread
Now the thread is running ...
UNIT IV
File Handling in Java (Java FileReader & FileWriter)

Java File Handling:

Java provides us with library classes and various methods to perform file handling easily. All these methods are present in the
File Class of the java.io package.
So, first of all, before starting these programs, we need to import this package and the file class.

import java.io.File;
Java uses stream to perform file-related operations. Let us understand the concept of stream first.

Stream in Java:

Stream is a concept of java that pipelines a sequence of objects to obtain the desired result. A stream can not be called to be a
data structure, rather it just takes input from the collection of I/O.

A stream can be classified into two types: Byte Stream and Character Stream.

Byte Stream:

The byte stream deals with mainly byte data. We know that one byte is equal to eight-bit. Thus, this stream mainly deals with
8bit of data. This stream performs an Input-output operation per 8bit of data.

The byte stream contains two stream classes, Input Stream classes and Output Stream Classes.

1. Input Stream Classes: This stream helps take input(Read Data) from the collection in I/O File.
2. Output Stream Classes: This stream helps to give output(Write Data) into the collection in I/O File.
The most commonly used Input and Output Stream Classes are FileInputStream and FileOutputStream.
We will see how to use them later while discussing the various file operations.

Character Stream:

There is also Character Stream which allows I/O operation on 16bit of Unicode data at a time. Character Stream takes 2 bytes
of data at a time. It is faster as it can take double the intake as compared to a byte stream. Character streams usually use Byte
Stream classes to implement operations.

The two main classes used in Character Stream are FileReader and FileWriter.

We will see how to use them later while discussing the various file operations.

The methods present in File class(java.io.File):

The file class contains various methods that perform various important tasks. Let us discuss them through this easy to
comprehend table.

SL. Return
Method Description
No. Type
1. canRead() Boolean This method checks whether the file is readable or not.
This method creates a new file in the desired path. The file
2. createNewFile() Boolean
created is generally empty.
This method checks whether the file is writable or not,i.e, not a
3. canWrite() Boolean
read-only file.
This method verifies if the file asked for is present or not in the
4. exists() Boolean
directory.
5. delete() Boolean This method is used to delete a file from the directory.
This method helps us find the name of a particular file from
6. getName() String
the directory.
getAbsolutePath(
7. String This method returns the absolute path of the given file.
)
8. length() Long This method returns the size of a file in bytes.
This method returns an array, listing all the files present in the
9. list() String[]
present working directory(PWD).
This Method stands for make directory. This method helps us
10. mkdir() Boolean
create a new directory(Not a file).

Now we will discuss the different operations for File Handling in Java using both byte stream and character stream.

Java File Operation:

1. Creating a File in Java:

We can use the createNewFile() method to create a new file using Java. If the method returns true, the file has been created
successfully, else the file creation was unsuccessful.

Code to explain the working of createNewFile():


package com.DataFlair.FileHandling;
import java.io.File;
import java.io.IOException;
public class CreatingNewFile
{
public static void main(String args[])
{
try {
File fcreate = new File("G:\\Internship\\File Handling\\NewFile.txt");
if (fcreate.createNewFile()) {
System.out.println("File " + fcreate.getName() + " is created successfully.");
}
else {
System.out.println("File is already exist in the directory.");
}
} catch (IOException exception) {
System.out.println("An unexpected error is occurred.");
exception.printStackTrace();
}
}
}
The output of the above code:
File NewFile.txt is created successfully.
The File named NewFile.txt was created in the given path. The Try-Catch block is used to handle errors if there is already a file
with the same name.

2. Java Get File Information:

Through the various methods given in File class, we are able to get all sorts of information about a file. These methods can give
information like name, length, path, read-only, write-only, etc.

Code to Explain Methods to get various file information:


package com.DataFlair.FileHandling;
import java.io.File;
public class FileInformation
{
public static void main(String[] args) {
File finfo = new File("G:\\Internship\\File Handling\\NewFile.txt");
if (finfo.exists()) {
System.out.println("The name of the file is: " + finfo.getName());
System.out.println("The absolute path of the file is: " + finfo.getAbsolutePath());
System.out.println("Is file writeable: " + finfo.canWrite());
System.out.println("Is file readable: " + finfo.canRead());
System.out.println("The size of the file is: " + finfo.length());
} else {
System.out.println("The file does not exist.");
}
}
}
The output of the above code:
The name of the file is: NewFile.txt
The absolute path of the file is: G:\Internship\File Handling\NewFile.txt
Is file writeable: true
Is file readable: true
The size of the file is: 0
The above class uses methods like getName(), getAbsolutePath(), canWrite(),canRead(),length(), to get various information
about the file NewFile.txt.
We use the try-catch block to check if the file exists or not.

3. Write into a Java File:

We can write into a file using the byte stream class OutputStreamWriter or Character stream class FileWriter.

Let us discuss them individually.

Using OutputStreamWriter:

We can use the OutputStreamWriter class of the byte stream to write into a file. This class writes 8 bits of data at a time.
We should always remember to close the stream or else it might create dump memory.

Code to Write into a File using OutputStreamWriter:


package com.DataFlair.FileHandling;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
public class ByteStreamWrite
{
public static void main(String[] args) {
try {
OutputStream fwrite = new FileOutputStream("G:\\Internship\\File Handling\\NewFile.txt");
Writer fwriteWriter = new OutputStreamWriter(fwrite);
fwriteWriter.write("Writing Using OutputStreamWriter!!!");
fwriteWriter.close();
} catch (Exception e) {
e.getMessage();
}
}
}
Using java FileWriter:

The character stream contains the FileWriter class, which can write 16-bits of data at a time into a file. This is a much quicker
technique compared to OutputStreamWriter as 16 bits of data is written at a time.

Code to Write into a file using FileWriter:


package com.DataFlair.FileHandling;
import java.io.FileWriter;
import java.io.IOException;
public class CharacterStreamWrite
{
public static void main(String[] args) {
try {
FileWriter fwrite = new FileWriter("G:\\Internship\\File Handling\\NewFile.txt");
fwrite.write("Written using FileWriter!!!");
fwrite.close();
} catch (IOException e) {
System.out.println("Error While Writing!!!");
e.printStackTrace();
}
}
}
4. Read from a Java File:

Similarly like write, we can read a file using byte stream and character stream. In the byte-stream we use InputStreamreader
and in the character stream, we have FileReader to read the contents of a file.

Using Java InputStreamReader:

The InputStreamReader class is part of the java byte stream, it can read 8 bits of data at a time. After reading the data the file
object should always be closed.

Code to understand reading using InputStreamReader:


package com.DataFlair.FileHandling;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.Reader;
import java.io.InputStreamReader;
public class ByteStreamRead
{
public static void main(String[] args) {
try {
InputStream fread = new FileInputStream("G:\\Internship\\File Handling\\NewFile.txt");
Reader freader = new InputStreamReader(fread);
int data = freader.read();
while (data != -1) {
System.out.print((char) data);
data = freader.read();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
The output of the above code:
Written using FileWriter!!!
This was the content of the file after executing the previous code, so the printed output gives the content of the file properly.

Using java FileReader:

The FileReader is a class of the character stream, thus it reads 16 bits of data at a time. It is faster than InputStreamReader.

Code to understand reading file using FileReader:


package com.DataFlair.FileHandling;
import java.io.FileReader;
public class CharacterStreamRead
{
public static void main(String args[])throws Exception
{
FileReader fr=new FileReader("G:\\Internship\\File Handling\\NewFile.txt");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
}
The output of the above code:
Written using FileWriter!!!
We can see that the code is much shorter, simpler and faster. This is the reason why programmers prefer to use the character
stream instead of the byte stream.

5. Deleting a File in Java:

A file can be deleted using java through the method delete(). We do not need to close the file as we do not use any reader or
writer classes.

Code to Delete File using delete():


package com.DataFlair.FileHandling;
import java.io.File;
public class DeleteFile
{
public static void main(String[] args)
{
File fdel = new File("G:\\Internship\\File Handling\\NewFile.txt");
if (fdel.delete())
{
System.out.println(fdel.getName()+ " is deleted successfully.");
}
else
{
System.out.println("Could Not Delete File");
}
}
}
The output of the above code:
NewFile.txt is deleted successfully.

Introduction to JDBC (Java Database Connectivity)

JDBC or Java Database Connectivity is a Java API to connect and execute the query with the database. It is a specification
from Sun microsystems that provides a standard abstraction(API or Protocol) for java applications to communicate with
various databases. It provides the language with java database connectivity standards. It is used to write programs required to
access databases. JDBC, along with the database driver, can access databases and spreadsheets. The enterprise data stored in a
relational database(RDB) can be accessed with the help of JDBC APIs.
Definition of JDBC(Java Database Connectivity)
JDBC is an API(Application programming interface) used in java programming to interact with
databases. The classes and interfaces of JDBC allow the application to send requests made by users to the specified database.
Purpose of JDBC
Enterprise applications created using the JAVA EE technology need to interact with databases to store application-specific
information. So, interacting with a database requires efficient database connectivity, which can be achieved by using
the ODBC(Open database connectivity) driver. This driver is used with JDBC to interact or communicate with various kinds of
databases such as Oracle, MS Access, Mysql, and SQL server database.
Components of JDBC
There are generally four main components of JDBC through which it can interact with a database. They are as mentioned
below:
1. JDBC API: It provides various methods and interfaces for easy communication with the database. It provides two packages
as follows, which contain the java SE and Java EE platforms to exhibit WORA(write once run anywhere) capabilities.
java.sql.*;
It also provides a standard to connect a database to a client application.
2. JDBC Driver manager: It loads a database-specific driver in an application to establish a connection with a database. It is
used to make a database-specific call to the database to process the user request.
3. JDBC Test suite: It is used to test the operation(such as insertion, deletion, updation) being performed by JDBC Drivers.
4. JDBC-ODBC Bridge Drivers: It connects database drivers to the database. This bridge translates the JDBC method call to
the ODBC function call. It makes use of the sun.jdbc.odbc package which includes a native library to access ODBC
characteristics.

Architecture of JDBC
Architecture of JDBC

Description:
1. Application: It is a java applet or a servlet that communicates with a data source.
2. The JDBC API: The JDBC API allows Java programs to execute SQL statements and retrieve results. Some of the
important classes and interfaces defined in JDBC API are as follows:
3. DriverManager: It plays an important role in the JDBC architecture. It uses some database-specific drivers to effectively
connect enterprise applications to databases.
4. JDBC drivers: To communicate with a data source through JDBC, you need a JDBC driver that intelligently
communicates with the respective data source.
JDBC Drivers
JDBC drivers are client-side adapters (installed on the client machine, not on the server) that convert requests from Java
programs to a protocol that the DBMS can understand. There are 4 types of JDBC drivers:
1. Type-1 driver or JDBC-ODBC bridge driver
2. Type-2 driver or Native-API driver
3. Type-3 driver or Network Protocol driver
4. Type-4 driver or Thin driver

Types of JDBC Architecture(2-tier and 3-tier)

The JDBC architecture consists of two-tier and three-tier processing models to access a database. They are as described
below:
1. Two-tier model: A java application communicates directly to the data source. The JDBC driver enables the
communication between the application and the data source. When a user sends a query to the data source, the answers for
those queries are sent back to the user in the form of results.
The data source can be located on a different machine on a network to which a user is connected. This is known as
a client/server configuration, where the user’s machine acts as a client, and the machine has the data source running acts
as the server.

2. Three-tier model: In this, the user’s queries are sent to middle-tier services, from which the commands are again sent to
the data source. The results are sent back to the middle tier, and from there to the user.
This type of model is found very useful by management information system directors.
Interfaces of JDBC API
A list of popular interfaces of JDBC API is given below:
 Driver interface
 Connection interface
 Statement interface
 PreparedStatement interface
 CallableStatement interface
 ResultSet interface
 ResultSetMetaData interface
 DatabaseMetaData interface
 RowSet interface
Classes of JDBC API
A list of popular classes of JDBC API is given below:
 DriverManager class
 Blob class
 Clob class
 Types class
Working of JDBC
Java application that needs to communicate with the database has to be programmed using JDBC API. JDBC Driver supporting
data sources such as Oracle and SQL server has to be added in java application for JDBC support which can be done
dynamically at run time. This JDBC driver intelligently communicates the respective data source.
Creating a simple JDBC application
 Java

package com.vinayak.jdbc;

import java.sql.*;

public class JDBCDemo {

public static void main(String args[])

throws SQLException, ClassNotFoundException

String driverClassName

= "sun.jdbc.odbc.JdbcOdbcDriver";

String url = "jdbc:odbc:XE";

String username = "scott";

String password = "tiger";

String query

= "insert into students values(109, 'bhatt')";

// Load driver class


Class.forName(driverClassName);

// Obtain a connection

Connection con = DriverManager.getConnection(

url, username, password);

// Obtain a statement

Statement st = con.createStatement();

// Execute the query

int count = st.executeUpdate(query);

System.out.println(

"number of rows affected by this query= "

+ count);

// Closing the connection as per the

// requirement with connection is completed

con.close();

} // class

The above example demonstrates the basic steps to access a database using JDBC. The application uses the JDBC-ODBC
bridge driver to connect to the database. You must import java.sql package to provide basic SQL functionality and use the
classes of the package.
UNIT IV
File Handling in Java (Java FileReader & FileWriter)

.
Java File Handling:

Java provides us with library classes and various methods to perform file handling easily. All these methods are present in the
File Class of the java.io package.
So, first of all, before starting these programs, we need to import this package and the file class.

import java.io.File;
Java uses stream to perform file-related operations. Let us understand the concept of stream first.

Stream in Java:

Stream is a concept of java that pipelines a sequence of objects to obtain the desired result. A stream can not be called to be a
data structure, rather it just takes input from the collection of I/O.

A stream can be classified into two types: Byte Stream and Character Stream.

Byte Stream:

The byte stream deals with mainly byte data. We know that one byte is equal to eight-bit. Thus, this stream mainly deals with
8bit of data. This stream performs an Input-output operation per 8bit of data.

The byte stream contains two stream classes, Input Stream classes and Output Stream Classes.

1. Input Stream Classes: This stream helps take input(Read Data) from the collection in I/O File.
2. Output Stream Classes: This stream helps to give output(Write Data) into the collection in I/O File.
The most commonly used Input and Output Stream Classes are FileInputStream and FileOutputStream.

We will see how to use them later while discussing the various file operations.

Character Stream:

There is also Character Stream which allows I/O operation on 16bit of Unicode data at a time. Character Stream takes 2 bytes
of data at a time. It is faster as it can take double the intake as compared to a byte stream. Character streams usually use Byte
Stream classes to implement operations.

The two main classes used in Character Stream are FileReader and FileWriter.

We will see how to use them later while discussing the various file operations.

The methods present in File class(java.io.File):

The file class contains various methods that perform various important tasks. Let us discuss them through this easy to
comprehend table.

SL. Return
Method Description
No. Type
1. canRead() Boolean This method checks whether the file is readable or not.
2. createNewFile() Boolean This method creates a new file in the desired path. The file
created is generally empty.
This method checks whether the file is writable or not,i.e, not a
3. canWrite() Boolean
read-only file.
This method verifies if the file asked for is present or not in the
4. exists() Boolean
directory.
5. delete() Boolean This method is used to delete a file from the directory.
This method helps us find the name of a particular file from
6. getName() String
the directory.
getAbsolutePath(
7. String This method returns the absolute path of the given file.
)
8. length() Long This method returns the size of a file in bytes.
This method returns an array, listing all the files present in the
9. list() String[]
present working directory(PWD).
This Method stands for make directory. This method helps us
10. mkdir() Boolean
create a new directory(Not a file).

Now we will discuss the different operations for File Handling in Java using both byte stream and character stream.

Java File Operation:

1. Creating a File in Java:

We can use the createNewFile() method to create a new file using Java. If the method returns true, the file has been created
successfully, else the file creation was unsuccessful.

Code to explain the working of createNewFile():


package com.DataFlair.FileHandling;
import java.io.File;
import java.io.IOException;
public class CreatingNewFile
{
public static void main(String args[])
{
try {
File fcreate = new File("G:\\Internship\\File Handling\\NewFile.txt");
if (fcreate.createNewFile()) {
System.out.println("File " + fcreate.getName() + " is created successfully.");
}
else {
System.out.println("File is already exist in the directory.");
}
} catch (IOException exception) {
System.out.println("An unexpected error is occurred.");
exception.printStackTrace();
}
}
}
The output of the above code:
File NewFile.txt is created successfully.
The File named NewFile.txt was created in the given path. The Try-Catch block is used to handle errors if there is already a file
with the same name.

2. Java Get File Information:

Through the various methods given in File class, we are able to get all sorts of information about a file. These methods can give
information like name, length, path, read-only, write-only, etc.

Code to Explain Methods to get various file information:


package com.DataFlair.FileHandling;
import java.io.File;
public class FileInformation
{
public static void main(String[] args) {
File finfo = new File("G:\\Internship\\File Handling\\NewFile.txt");
if (finfo.exists()) {
System.out.println("The name of the file is: " + finfo.getName());
System.out.println("The absolute path of the file is: " + finfo.getAbsolutePath());
System.out.println("Is file writeable: " + finfo.canWrite());
System.out.println("Is file readable: " + finfo.canRead());
System.out.println("The size of the file is: " + finfo.length());
} else {
System.out.println("The file does not exist.");
}
}
}
The output of the above code:
The name of the file is: NewFile.txt
The absolute path of the file is: G:\Internship\File Handling\NewFile.txt
Is file writeable: true
Is file readable: true
The size of the file is: 0
The above class uses methods like getName(), getAbsolutePath(), canWrite(),canRead(),length(), to get various information
about the file NewFile.txt.
We use the try-catch block to check if the file exists or not.

3. Write into a Java File:

We can write into a file using the byte stream class OutputStreamWriter or Character stream class FileWriter.

Let us discuss them individually.

Using OutputStreamWriter:

We can use the OutputStreamWriter class of the byte stream to write into a file. This class writes 8 bits of data at a time.
We should always remember to close the stream or else it might create dump memory.
Code to Write into a File using OutputStreamWriter:
package com.DataFlair.FileHandling;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
public class ByteStreamWrite
{
public static void main(String[] args) {
try {
OutputStream fwrite = new FileOutputStream("G:\\Internship\\File Handling\\NewFile.txt");
Writer fwriteWriter = new OutputStreamWriter(fwrite);
fwriteWriter.write("Writing Using OutputStreamWriter!!!");
fwriteWriter.close();
} catch (Exception e) {
e.getMessage();
}
}
}
Using java FileWriter:

The character stream contains the FileWriter class, which can write 16-bits of data at a time into a file. This is a much quicker
technique compared to OutputStreamWriter as 16 bits of data is written at a time.

Code to Write into a file using FileWriter:


package com.DataFlair.FileHandling;
import java.io.FileWriter;
import java.io.IOException;
public class CharacterStreamWrite
{
public static void main(String[] args) {
try {
FileWriter fwrite = new FileWriter("G:\\Internship\\File Handling\\NewFile.txt");
fwrite.write("Written using FileWriter!!!");
fwrite.close();
} catch (IOException e) {
System.out.println("Error While Writing!!!");
e.printStackTrace();
}
}
}
4. Read from a Java File:

Similarly like write, we can read a file using byte stream and character stream. In the byte-stream we use InputStreamreader
and in the character stream, we have FileReader to read the contents of a file.
Using Java InputStreamReader:

The InputStreamReader class is part of the java byte stream, it can read 8 bits of data at a time. After reading the data the file
object should always be closed.

Code to understand reading using InputStreamReader:


package com.DataFlair.FileHandling;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.Reader;
import java.io.InputStreamReader;
public class ByteStreamRead
{
public static void main(String[] args) {
try {
InputStream fread = new FileInputStream("G:\\Internship\\File Handling\\NewFile.txt");
Reader freader = new InputStreamReader(fread);
int data = freader.read();
while (data != -1) {
System.out.print((char) data);
data = freader.read();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
The output of the above code:
Written using FileWriter!!!
This was the content of the file after executing the previous code, so the printed output gives the content of the file properly.

Using java FileReader:

The FileReader is a class of the character stream, thus it reads 16 bits of data at a time. It is faster than InputStreamReader.

Code to understand reading file using FileReader:


package com.DataFlair.FileHandling;
import java.io.FileReader;
public class CharacterStreamRead
{
public static void main(String args[])throws Exception
{
FileReader fr=new FileReader("G:\\Internship\\File Handling\\NewFile.txt");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
}
The output of the above code:
Written using FileWriter!!!
We can see that the code is much shorter, simpler and faster. This is the reason why programmers prefer to use the character
stream instead of the byte stream.

5. Deleting a File in Java:

A file can be deleted using java through the method delete(). We do not need to close the file as we do not use any reader or
writer classes.

Code to Delete File using delete():


package com.DataFlair.FileHandling;
import java.io.File;
public class DeleteFile
{
public static void main(String[] args)
{
File fdel = new File("G:\\Internship\\File Handling\\NewFile.txt");
if (fdel.delete())
{
System.out.println(fdel.getName()+ " is deleted successfully.");
}
else
{
System.out.println("Could Not Delete File");
}
}
}
The output of the above code:
NewFile.txt is deleted successfully.

Introduction to JDBC (Java Database Connectivity)

JDBC or Java Database Connectivity is a Java API to connect and execute the query with the database. It is a specification
from Sun microsystems that provides a standard abstraction(API or Protocol) for java applications to communicate with
various databases. It provides the language with java database connectivity standards. It is used to write programs required to
access databases. JDBC, along with the database driver, can access databases and spreadsheets. The enterprise data stored in a
relational database(RDB) can be accessed with the help of JDBC APIs.
Definition of JDBC(Java Database Connectivity)
JDBC is an API(Application programming interface) used in java programming to interact with
databases. The classes and interfaces of JDBC allow the application to send requests made by users to the specified database.
Purpose of JDBC
Enterprise applications created using the JAVA EE technology need to interact with databases to store application-specific
information. So, interacting with a database requires efficient database connectivity, which can be achieved by using
the ODBC(Open database connectivity) driver. This driver is used with JDBC to interact or communicate with various kinds of
databases such as Oracle, MS Access, Mysql, and SQL server database.
Components of JDBC
There are generally four main components of JDBC through which it can interact with a database. They are as mentioned
below:
1. JDBC API: It provides various methods and interfaces for easy communication with the database. It provides two packages
as follows, which contain the java SE and Java EE platforms to exhibit WORA(write once run anywhere) capabilities.
java.sql.*;
It also provides a standard to connect a database to a client application.
2. JDBC Driver manager: It loads a database-specific driver in an application to establish a connection with a database. It is
used to make a database-specific call to the database to process the user request.
3. JDBC Test suite: It is used to test the operation(such as insertion, deletion, updation) being performed by JDBC Drivers.
4. JDBC-ODBC Bridge Drivers: It connects database drivers to the database. This bridge translates the JDBC method call to
the ODBC function call. It makes use of the sun.jdbc.odbc package which includes a native library to access ODBC
characteristics.

Architecture of JDBC

Architecture of JDBC

Description:
5. Application: It is a java applet or a servlet that communicates with a data source.
6. The JDBC API: The JDBC API allows Java programs to execute SQL statements and retrieve results. Some of the
important classes and interfaces defined in JDBC API are as follows:
7. DriverManager: It plays an important role in the JDBC architecture. It uses some database-specific drivers to effectively
connect enterprise applications to databases.
8. JDBC drivers: To communicate with a data source through JDBC, you need a JDBC driver that intelligently
communicates with the respective data source.
JDBC Drivers
JDBC drivers are client-side adapters (installed on the client machine, not on the server) that convert requests from Java
programs to a protocol that the DBMS can understand. There are 4 types of JDBC drivers:
5. Type-1 driver or JDBC-ODBC bridge driver
6. Type-2 driver or Native-API driver
7. Type-3 driver or Network Protocol driver
8. Type-4 driver or Thin driver

Types of JDBC Architecture(2-tier and 3-tier)


The JDBC architecture consists of two-tier and three-tier processing models to access a database. They are as described
below:
3. Two-tier model: A java application communicates directly to the data source. The JDBC driver enables the
communication between the application and the data source. When a user sends a query to the data source, the answers for
those queries are sent back to the user in the form of results.
The data source can be located on a different machine on a network to which a user is connected. This is known as
a client/server configuration, where the user’s machine acts as a client, and the machine has the data source running acts
as the server.

4. Three-tier model: In this, the user’s queries are sent to middle-tier services, from which the commands are again sent to
the data source. The results are sent back to the middle tier, and from there to the user.
This type of model is found very useful by management information system directors.
Interfaces of JDBC API
A list of popular interfaces of JDBC API is given below:
 Driver interface
 Connection interface
 Statement interface
 PreparedStatement interface
 CallableStatement interface
 ResultSet interface
 ResultSetMetaData interface
 DatabaseMetaData interface
 RowSet interface
Classes of JDBC API
A list of popular classes of JDBC API is given below:
 DriverManager class
 Blob class
 Clob class
 Types class
Working of JDBC
Java application that needs to communicate with the database has to be programmed using JDBC API. JDBC Driver supporting
data sources such as Oracle and SQL server has to be added in java application for JDBC support which can be done
dynamically at run time. This JDBC driver intelligently communicates the respective data source.
Creating a simple JDBC application
 Java

package com.vinayak.jdbc;

import java.sql.*;

public class JDBCDemo {

public static void main(String args[])

throws SQLException, ClassNotFoundException

String driverClassName
= "sun.jdbc.odbc.JdbcOdbcDriver";

String url = "jdbc:odbc:XE";

String username = "scott";

String password = "tiger";

String query

= "insert into students values(109, 'bhatt')";

// Load driver class

Class.forName(driverClassName);

// Obtain a connection

Connection con = DriverManager.getConnection(

url, username, password);

// Obtain a statement

Statement st = con.createStatement();

// Execute the query

int count = st.executeUpdate(query);

System.out.println(

"number of rows affected by this query= "

+ count);

// Closing the connection as per the

// requirement with connection is completed

con.close();
}

} // class

The above example demonstrates the basic steps to access a database using JDBC. The application uses the JDBC-ODBC
bridge driver to connect to the database. You must import java.sql package to provide basic SQL functionality and use the
classes of the package.
UNIT IV
Introduction to Java Swing
Swing is a Java Foundation Classes [JFC] library and an extension of the Abstract Window Toolkit [AWT]. Swing offers
much-improved functionality over AWT, new components, expanded components features, and excellent event handling with
drag-and-drop support.

Introduction of Java Swing

Swing has about four times the number of User Interface [UI] components as AWT and is part of the standard Java
distribution. By today’s application GUI requirements, AWT is a limited implementation, not quite capable of providing the
components required for developing complex GUI’s required in modern commercial applications. The AWT component set
has quite a few bugs and really does take up a lot of system resources when compared to equivalent Swing resources. Netscape
introduced its Internet Foundation Classes [IFC] library for use with Java. Its Classes became very popular with programmers
creating GUI’s for commercial applications.
 Swing is a Set Of API ( API- Set Of Classes and Interfaces )
 Swing is Provided to Design Graphical User Interfaces
 Swing is an Extension library to the AWT (Abstract Window Toolkit)
 Includes New and improved Components that have been enhancing the looks and Functionality of GUIs’
 Swing can be used to build(Develop) The Standalone swing GUI Apps Also as Servlets And Applets
 It Employs model/view design architecture
 Swing is more portable and more flexible than AWT, The Swing is built on top of the AWT
 Swing is Entirely written in Java
 Java Swing Components are Platform-independent And The Swing Components are lightweight
 Swing Supports a Pluggable look and feels And Swing provides more powerful components
 such as tables, lists, Scrollpanes, Colourchooser, tabbedpane, etc
 Further Swing Follows MVC.
Many programmers think that JFC and Swing are one and the same thing, but that is not so.
JFC contains Swing [A UI component package] and quite a number of other items:
 Cut and paste: Clipboard support
 Accessibility features: Aimed at developing GUI’s for users with disabilities
 The Desktop Colors Features Has been Firstly introduced in Java 1.1
 Java 2D: it has Improved colors, images, and also texts support
Features Of Swing Class
 Pluggable look and feel
 Uses MVC architecture
 Lightweight Components
 Platform Independent
 Advanced features such as JTable, JTabbedPane, JScollPane, etc.
 Java is a platform-independent language and runs on any client machine, the GUI look and feel, owned and delivered by a
platform-specific O/S, simply does not affect an application’s GUI constructed using Swing components
 Lightweight Components: Starting with the JDK 1.1, its AWT-supported lightweight component development. For a
component to qualify as lightweight, it must not depend on any non-Java [O/s based) system classes. Swing components
have their own view supported by Java’s look and feel classes.
 Pluggable Look and Feel: This feature enables the user to switch the look and feel of Swing components without
restarting an application. The Swing library supports components’ look and feels that remain the same across all platforms
wherever the program runs. The Swing library provides an API that gives real flexibility in determining the look and feel of
the GUI of an application
 Highly customizable – Swing controls can be customized in a very easy way as visual appearance is independent of
internal representation.
 Rich controls– Swing provides a rich set of advanced controls like Tree TabbedPane, slider, colorpicker, and table
controls.
Swing Classes Hierarchy

The MVC Connection

 In general, a visual component is a composite of three distinct aspects:


1. The way that the component looks when rendered on the screen
2. The way such that the component reacts to the user
3. The state information associated With the component
 Over the years, one component architecture has proven itself to be exceptionally effective:- Model-View-
Controller or MVC for short.
 In MVC terminology, the model corresponds to the state information associated with the Component
 The view determines how the component is displayed on the screen, including any aspects of the view that are affected by
the current state of the model.
 The controller determines how the component reacts to the user
The simplest Swing components have capabilities far beyond AWT components as follows:
 Swing buttons and labels can be displaying images instead of or in addition to text
 The borders around most Swing components can be changed easily. For example, it is easy to put a 1 pixel border around
the outside of a Swing label
 Swing components do not have to be rectangular. Buttons, for example, can be round
 Now The Latest Assertive technologies such as screen readers can easily get information from Swing components. For
example: A screen reader tool can easily capture the text that is displayed on a Swing button or label
Example 1: Develop a program using label (swing) to display message “GFG WEB Site Click”;
 Java

import java.io.*;

import javax.swing.*;

// Main class

class GFG {

// Main driver method

public static void main(String[] args)


{

JFrame frame

= new JFrame(); // creating instance of JFrame

JButton button = new JButton(

" GFG WebSite Click"); // creating instance of

// JButton

button.setBounds(

150, 200, 220,

50); // x axis, y axis, width, height

frame.add(button); // adding button in JFrame

frame.setSize(500, 600); // 400 width and 500 height

frame.setLayout(null); // using no layout managers

frame.setVisible(true); // making the frame visible

Output:
Example 2: Write a program to create three buttons with caption OK , SUBMIT, CANCLE.
 Java

import java.awt.*;

class button {

button() {

Frame f = new Frame();

Button b1 = new Button("OK");

b1.setBounds(100, 50, 50, 50);

f.add(b1);

Button b2 = new Button("SUBMIT");

b2.setBounds(100, 101, 50, 50);

f.add(b2);

Button b3 = new Button("CANCLE");

b3.setBounds(100, 150, 80, 50);

f.add(b3);

f.setSize(500, 500);
f.setLayout(null);

f.setVisible(true);

public static void main(String a[]) {

new button();

OUTPUT:

Example 3 :
 Java

import java.awt.*;

class Lan {

Lan() {

Frame f = new Frame();

Label l1 = new Label("Select known Languages");


l1.setBounds(100, 50, 120, 80);

f.add(l1);

Checkbox c2 = new Checkbox("Hindi");

c2.setBounds(100, 150, 50, 50);

f.add(c2);

Checkbox c3 = new Checkbox("English");

c3.setBounds(100, 200, 80, 50);

f.add(c3);

Checkbox c4 = new Checkbox("marathi");

c4.setBounds(100, 250, 80, 50);

f.add(c4);

f.setSize(500, 500);

f.setLayout(null);

f.setVisible(true);

public static void main(String ar[]) {

new Lan();

output:
Components of Swing Classthe task’s percentage

Class Description

A Component is the Abstract base class for about the non menu user-interface controls of SWING.
Component
Components are represents an object with a graphical representation

Container A Container is a component that can container SWING Components

A JComponent is a base class for all swing UI Components In order to use a swing component that
JComponent inherits from JComponent, component must be in a containment hierarchy whose root is a top-level
Swing container

JLabel A JLabel is an object component for placing text in a container

JButton This class creates a labeled button

A JColorChooser provides a pane of controls designed to allow the user to manipulate and select a
JColorChooser
color

JCheckBox A JCheckBox is a graphical(GUI) component that can be in either an on-(true) or off-(false) state
Class Description

The JRadioButton class is a graphical(GUI) component that can be in either an on-(true) or off-(false)
JRadioButton
state. in the group

JList A JList component represents the user with the scrolling list of text items

JComboBox A JComboBox component is Presents the User with a show up Menu of choices

JTextField A JTextField object is a text component that will allow for the editing of a single line of text

JPasswordField A JPasswordField object it is a text component specialized for password entry

JTextArea A JTextArea object is a text component that allows for the editing of multiple lines of text

Imagelcon A ImageIcon control is an implementation of the Icon interface that paints Icons from Images

A JScrollbar control represents a scroll bar component in order to enable users to Select from range
JScrollbar
values

JOptionPane JOptionPane provides set of standard dialog boxes that prompt users for a value or Something

JFileChooser A JFileChooser it Controls represents a dialog window from which the user can select a file.

As the task progresses towards completion, the progress bar displays the tasks percentage on its
JProgressBar
completion

A JSlider this class is lets the user graphically(GUI) select by using a value by sliding a knob within a
JSlider
bounded interval.

A JSpinner this class is a single line input where the field that lets the user select by using a number or
JSpinner
an object value from an ordered sequence

AWT Controls

Previous Page
Next Page
Every user interface considers the following three main aspects:
 UI elements : Thes are the core visual elements the user eventually sees and interacts with. GWT provides a huge list of
widely used and common elements varying from basic to complex which we will cover in this tutorial.
 Layouts: They define how UI elements should be organized on the screen and provide a final look and feel to the GUI
(Graphical User Interface). This part will be covered in Layout chapter.
 Behavior: These are events which occur when the user interacts with UI elements. This part will be covered in Event
Handling chapter.
Every AWT controls inherits properties from Component class.

Sr. Control & Description


No.

1
Component
A Component is an abstract super class for GUI controls and it represents an object
with graphical representation.

AWT UI Elements:
Following is the list of commonly used controls while designed GUI using AWT.

Sr. Control & Description


No.

1
Label
A Label object is a component for placing text in a container.

2
Button
This class creates a labeled button.

3
Check Box
A check box is a graphical component that can be in either an on (true) or off (false)
state.

4
Check Box Group
The CheckboxGroup class is used to group the set of checkbox.

5
List
The List component presents the user with a scrolling list of text items.

6
Text Field
A TextField object is a text component that allows for the editing of a single line of
text.

7
Text Area
A TextArea object is a text component that allows for the editing of a multiple lines of
text.

8
Choice
A Choice control is used to show pop up menu of choices. Selected choice is shown on
the top of the menu.

9
Canvas
A Canvas control represents a rectangular area where application can draw something
or can receive inputs created by user.

10
Image
An Image control is superclass for all image classes representing graphical images.

11
Scroll Bar
A Scrollbar control represents a scroll bar component in order to enable user to select
from range of values.

12
Dialog
A Dialog control represents a top-level window with a title and a border used to take
some form of input from the user.

13
File Dialog
A FileDialog control represents a dialog window from which the user can select a file.

Java Applet Basics


 Read
 Discuss
 Courses
 Practice
 Video
Note:
java.applet package package has been deprecated in Java 9 and later versions,as applets are no longer widely used on the
web.
Let’s understand first how many Package does GUI support:
1. AWT(Abstract Window Toolkit)
2. Swing
Throwback of making GUI application:
Java was launched on 23-Jan-1996(JDK 1.0) and at that time it only supported CUI(Character User Interface) application. But
in 1996 VB(Visual Basic) of Microsoft was preferred for GUI programming. So the Java developers in hurry(i.e within 7 days)
have given the support for GUI from Operating System(OS). Now, the components like button, etc. were platform-
dependent(i.e in each platform there will be different size, shape button). But they did the intersection of such components
from all platforms and gave a small library which contains these intersections and it is available in AWT(Abstract Window
Toolkit) technology but it doesn’t have advanced features like dialogue box, etc.
Now to run Applet, java needs a browser and at that time only “Internet Explorer” was there of Microsoft but Microsoft
believes in monopoly. So “SUN Micro-System”(the company which developed Java) contracted with other company known as
“Netscape”(which developed Java Script) and now the “Netscape” company is also known as “Mozilla Firefox” which we all
know is a browser. Now, these two companies have developed a technology called “SWING” and the benefit is that the
SWING components are produced by Java itself. Therefore now it is platform-independent as well as some additional features
have also been added which were not in AWT technology. So we can say that SWING is much more advanced as compared to
AWT technology.
What is Applet?
An applet is a Java program that can be embedded into a web page. It runs inside the web browser and works at client side. An
applet is embedded in an HTML page using the APPLET or OBJECT tag and hosted on a web server.
Applets are used to make the website more dynamic and entertaining.
Important points :
1. All applets are sub-classes (either directly or indirectly) of java.applet.Applet class.
2. Applets are not stand-alone programs. Instead, they run within either a web browser or an applet viewer. JDK provides a
standard applet viewer tool called applet viewer.
3. In general, execution of an applet does not begin at main() method.
4. Output of an applet window is not performed by System.out.println(). Rather it is handled with various AWT methods, such
as drawString().
Life cycle of an applet :

It is important to understand the order in which the various methods shown in the above image are called. When an applet
begins, the following methods are called, in this sequence:
1. init( )
2. start( )
3. paint( )
When an applet is terminated, the following sequence of method calls takes place:
1. stop( )
2. destroy( )
Let’s look more closely at these methods.
1. init( ) : The init( ) method is the first method to be called. This is where you should initialize variables. This method is
called only once during the run time of your applet.
2. start( ) : The start( ) method is called after init( ). It is also called to restart an applet after it has been stopped. Note
that init( ) is called once i.e. when the first time an applet is loaded whereas start( ) is called each time an applet’s HTML
document is displayed onscreen. So, if a user leaves a web page and comes back, the applet resumes execution at start( ).
3. paint( ) : The paint( ) method is called each time an AWT-based applet’s output must be redrawn. This situation can occur
for several reasons. For example, the window in which the applet is running may be overwritten by another window and then
uncovered. Or the applet window may be minimized and then restored.
paint( ) is also called when the applet begins execution. Whatever the cause, whenever the applet must redraw its
output, paint( ) is called.
The paint( ) method has one parameter of type Graphics. This parameter will contain the graphics context, which describes the
graphics environment in which the applet is running. This context is used whenever output to the applet is required.
Note: This is the only method among all the method mention above, which is parameterized. It’s prototype is
public void paint(Graphics g)
where g is an object reference of class Graphic.
Now the Question Arises:
Q. In the prototype of paint() method, we have created an object reference without creating its object. But how is it possible to
create object reference without creating its object?
Ans. Whenever we pass object reference in arguments then the object will be provided by its caller itself. In this case the caller
of paint() method is browser, so it will provide an object. The same thing happens when we create a very basic program in
normal Java programs. For Example:
public static void main(String []args){}
Here we have created an object reference without creating its object but it still runs because it’s caller,i.e JVM will provide it
with an object.
4. stop( ) : The stop( ) method is called when a web browser leaves the HTML document containing the applet—when it goes
to another page, for example. When stop( ) is called, the applet is probably running. You should use stop( ) to suspend threads
that don’t need to run when the applet is not visible. You can restart them when start( ) is called if the user returns to the page.
5. destroy( ) : The destroy( ) method is called when the environment determines that your applet needs to be removed
completely from memory. At this point, you should free up any resources the applet may be using. The stop( ) method is
always called before destroy( ).
Creating Hello World applet :
Let’s begin with the HelloWorld applet :
 Java

// A Hello World Applet

// Save file as HelloWorld.java

import java.applet.Applet;

import java.awt.Graphics;

// HelloWorld class extends Applet

public class HelloWorld extends Applet

{
// Overriding paint() method

@Override

public void paint(Graphics g)

g.drawString("Hello World", 20, 20);

Explanation:
1. The above java program begins with two import statements. The first import statement imports the Applet class from applet
package. Every AWT-based(Abstract Window Toolkit) applet that you create must be a subclass (either directly or
indirectly) of Applet class. The second statement import the Graphics class from AWT package.
2. The next line in the program declares the class HelloWorld. This class must be declared as public because it will be
accessed by code that is outside the program. Inside HelloWorld, paint( ) is declared. This method is defined by the AWT
and must be overridden by the applet.
3. Inside paint( ) is a call to drawString( ), which is a member of the Graphics class. This method outputs a string beginning
at the specified X,Y location. It has the following general form:
void drawString(String message, int x, int y)
Here, message is the string to be output beginning at x,y. In a Java window, the upper-left corner is location 0,0. The call
to drawString( ) in the applet causes the message “Hello World” to be displayed beginning at location 20,20.
Notice that the applet does not have a main( ) method. Unlike Java programs, applets do not begin execution at main( ). In
fact, most applets don’t even have a main( ) method. Instead, an applet begins execution when the name of its class is passed to
an applet viewer or to a network browser.
Running the HelloWorld Applet :
After you enter the source code for HelloWorld.java, compile in the same way that you have been compiling java
programs(using javac command). However, running HelloWorld with the java command will generate an error because it is
not an application.
java HelloWorld

Error: Main method not found in class HelloWorld,


please define the main method as:
public static void main(String[] args)
There are two standard ways in which you can run an applet :
1. Executing the applet within a Java-compatible web browser.
2. Using an applet viewer, such as the standard tool, applet-viewer. An applet viewer executes your applet in a window. This
is generally the fastest and easiest way to test your applet.
Each of these methods is described next.
1. Using java enabled web browser : To execute an applet in a web browser we have to write a short HTML text file that
contains a tag that loads the applet. We can use APPLET or OBJECT tag for this purpose. Using APPLET, here is the HTML
file that executes HelloWorld :
<applet code="HelloWorld" width=200 height=60>
</applet>
The width and height statements specify the dimensions of the display area used by the applet. The APPLET tag contains
several other options. After you create this html file, you can use it to execute the applet.
NOTE : Chrome and Firefox no longer supports NPAPI (technology required for Java applets). Refer here
2. Using appletviewer : This is the easiest way to run an applet. To execute HelloWorld with an applet viewer, you may also
execute the HTML file shown earlier. For example, if the preceding HTML file is saved with
RunHelloWorld.html, then the following command line will run HelloWorld :
appletviewer RunHelloWorld.html

3. appletviewer with java source file : If you include a comment at the head of your Java source code file that contains the
APPLET tag then your code is documented with a prototype of the necessary HTML statements, and you can run your
compiled applet merely by starting the applet viewer with your Java source code file. If you use this method, the HelloWorld
source file looks like this :
 Java

// A Hello World Applet

// Save file as HelloWorld.java

import java.applet.Applet;

import java.awt.Graphics;

/*

<applet code="HelloWorld" width=200 height=60>

</applet>

*/

// HelloWorld class extends Applet

public class HelloWorld extends Applet

// Overriding paint() method

@Override

public void paint(Graphics g)


{

g.drawString("Hello World", 20, 20);

}
With this approach, first compile HelloWorld.java file and then simply run the below command to run applet :

appletviewer HelloWorld

To prove above mentioned point,i.e paint is called again and again.

To prove this, let’s first study what is “Status Bar” in Applet:


“Status Bar” is available in the left bottom window of an applet. To use the status bar and write something in it, we use method
showStatus() whose prototype is
public void showStatus(String)
By default status bar shows “Applet Started”
By default background color is white.

To prove paint() method is called again and again, here is the code:

Note: This code is with respect to Netbeans IDE.

Java

//code to illustrate paint

//method gets called again

//and again

import java.applet.*;// used

//to access showStatus()

import java.awt.*;//Graphic

//class is available in this package

import java.util.Date;// used

//to access Date object

public class GFG extends Applet

public void paint(Graphics g)


{

Date dt = new Date();

super.showStatus("Today is" + dt);

//in this line, super keyword is

// avoidable too.

}
Note:- Here we can see that if the screen is maximized or minimized we will get an updated time. This shows that paint() is
called again and again.

Features of Applets over HTML

Displaying dynamic web pages of a web application.

Playing sound files.

Displaying documents

Playing animations

Restrictions imposed on Java applets

Due to security reasons, the following restrictions are imposed on Java applets:

An applet cannot load libraries or define native methods.

An applet cannot ordinarily read or write files on the execution host.

An applet cannot read certain system properties.

An applet cannot make network connections except to the host that it came from.

An applet cannot start any program on the host that’s executing it.

NIKKI Q&A

UNIT I (Question With Answer)

Q1. Explain JDK, JRE and JVM?

JDK vs JRE vs JVM

JDK JRE JVM

It stands for Java Runtime


It stands for Java Development Kit. It stands for Java Virtual Machine.
Environment.
It is the tool necessary to compile, JRE refers to a runtime environment It is an abstract machine. It is a specification
document and package Java in which Java bytecode can be that provides a run-time environment in which
programs. executed. Java bytecode can be executed.

JVM follows three notations:


It’s an implementation of the JVM
It contains JRE + development tools. Specification, Implementation, and Runtime
which physically exists.
Instance.
Q2. Explain public static void main(String args[]) in Java.

main() in Java is the entry point for any Java program. It is always written as public static void main(String[] args).

public: Public is an access modifier, which is used to specify who can access this method. Public means that this Method will
be accessible by any Class.

static: It is a keyword in java which identifies it is class-based. main() is made static in Java so that it can be accessed without
creating the instance of a Class. In case, main is not made static then the compiler will throw an error as main() is called by the
JVM before any objects are made and only static methods can be directly invoked via the class.

void: It is the return type of the method. Void defines the method which will not return any value.

main: It is the name of the method which is searched by JVM as a starting point for an application with a particular signature
only. It is the method where the main execution occurs.

String args[]: It is the parameter passed to the main method.

Q3. Why Java is platform independent?

Java is called platform independent because of its byte codes which can run on any system irrespective of its underlying
operating system.

Q4. Why Java is not 100% Object-oriented?

Java is not 100% Object-oriented because it makes use of eight primitive data types such as boolean, byte, char, int, float,
double, long, short which are not objects.

Q5. What are wrapper classes in Java?

Wrapper classes convert the Java primitives into the reference types (objects). Every primitive data type has a class dedicated
to it. These are known as wrapper classes because they “wrap” the primitive data type into an object of that class. Refer to the
below image which displays different primitive type, wrapper class and constructor argument.

Q6. What are constructors in Java?

In Java, constructor refers to a block of code which is used to initialize an object. It must have the same name as that of the
class. Also, it has no return type and it is automatically called when an object is created.

There are two types of constructors:

Default Constructor: In Java, a default constructor is the one which does not take any inputs. In other words, default
constructors are the no argument constructors which will be created by default in case you no other constructor is defined by
the user. Its main purpose is to initialize the instance variables with the default values. Also, it is majorly used for object
creation.

Parameterized Constructor: The parameterized constructor in Java, is the constructor which is capable of initializing the
instance variables with the provided values. In other words, the constructors which take the arguments are called parameterized
constructors.

Q7. What is the difference between Array list and vector in Java?
ArrayList Vector

Array List is not synchronized. Vector is synchronized.


Array List is fast as it’s non-synchronized. Vector is slow as it is thread safe.

If an element is inserted into the Array List, it increases


Vector defaults to doubling size of its array.
its Array size by 50%.

Array List does not define the increment size. Vector defines the increment size.

Array List can only use Iterator for traversing an Array


Vector can use both Enumeration and Iterator for traversing.
List.
Q8. What is the difference between equals() and == in Java?

Equals() method is defined in Object class in Java and used for checking equality of two objects defined by business logic.

“==” or equality operator in Java is a binary operator provided by Java programming language and used to compare primitives
and objects. public boolean equals(Object o) is the method provided by the Object class. The default implementation uses ==
operator to compare two objects. For example: method can be overridden like String class. equals() method is used to compare
the values of two objects.

Q9. When can you use the super keyword?

In Java, the super keyword is a reference variable that refers to an immediate parent class object.When you create a subclass
instance, you’re also creating an instance of the parent class, which is referenced to by the super reference variable.

The uses of the Java super Keyword are-

To refer to an immediate parent class instance variable, use super.

The keyword super can be used to call the method of an immediate parent class.

Super() can be used to call the constructor of the immediate parent class.

Q10. Can you call a constructor of a class inside another constructor?

Yes, we can call a constructor of a class inside another constructor. This is also called as constructor chaining. Constructor
chaining can be done in 2 ways-

Within the same class: For constructors in the same class, the this() keyword can be used.

From the base class: The super() keyword is used to call the constructor from the base class.
The constructor chaining follows the process of inheritance. The constructor of the sub class first calls the constructor of the
super class. Due to this, the creation of sub class’s object starts with the initialization of the data members of the super class.
The constructor chaining works similarly with any number of classes. Every constructor keeps calling the chain till the top of
the chain.

Q11. Contiguous memory locations are usually used for storing actual values in an array but not in ArrayList. Explain.

An array generally contains elements of the primitive data types such as int, float, etc. In such cases, the array directly stores
these elements at contiguous memory locations. While an ArrayList does not contain primitive data types. An arrayList
contains the reference of the objects at different memory locations instead of the object itself. That is why the objects are not
stored at contiguous memory locations.
Q12. How is the creation of a String using new() different from that of a literal?
When we create a string using new(), a new object is created. Whereas, if we create a string using the string literal syntax, it
may return an already existing object with the same name.

Q13. Why is it said that the length() method of String class doesn’t return accurate results?

The length() method of String class doesn’t return accurate results because
it simply takes into account the number of characters within in the String. In other words, code points outside of the BMP
(Basic Multilingual Plane), that is, code points having a value of U+10000 or above, will be ignored.

The reason for this is historical. One of Java’s original goals was to consider all text as Unicode; yet, Unicode did not define
code points outside of the BMP at the time. It was too late to modify char by the time Unicode specified such code points.

Q14. What are the differences between Heap and Stack Memory in Java?

The major difference between Heap and Stack memory are:

Features Stack Heap

Stack memory is used only by one thread of


Memory Heap memory is used by all the parts of the application.
execution.
Stack memory can’t be accessed by other
Access Objects stored in the heap are globally accessible.
threads.

Memory Memory management is based on the generation


Follows LIFO manner to free memory.
Management associated with each object.

Heap memory lives from the start till the end of


Lifetime Exists until the end of execution of the thread.
application execution.

Stack memory only contains local primitive and Whenever an object is created, it’s always stored in the
Usage
reference variables to objects in heap space. Heap space.
Q15. What is a package in Java? List down various advantages of packages.

Packages in Java, are the collection of related classes and interfaces which are bundled together. By using packages, developers
can easily modularize the code and optimize its reuse. Also, the code within the packages can be imported by other classes and
reused. Below I have listed down a few of its advantages:

Packages help in avoiding name clashes

They provide easier access control on the code

Packages can also contain hidden classes which are not visible to the outer classes and only used within the package

Creates a proper hierarchical structure which makes it easier to locate the related classes

Q16. Why pointers are not used in Java?

Java doesn’t use pointers because they are unsafe and increases the complexity of the program. Since, Java is known for its
simplicity of code, adding the concept of pointers will be contradicting. Moreover, since JVM is responsible for implicit
memory allocation, thus in order to avoid direct access to memory by the user, pointers are discouraged in Java.

Q17. What is JIT compiler in Java?


JIT stands for Just-In-Time compiler in Java. It is a program that helps in converting the Java bytecode into instructions that are
sent directly to the processor. By default, the JIT compiler is enabled in Java and is activated whenever a Java method is
invoked. The JIT compiler then compiles the bytecode of the invoked method into native machine code, compiling it “just in
time” to execute. Once the method has been compiled, the JVM summons the compiled code of that method directly rather
than interpreting it. This is why it is often responsible for the performance optimization of Java applications at the run time.

Q18. What are access modifiers in Java?

In Java, access modifiers are special keywords which are used to restrict the access of a class, constructor, data member and
method in another class. Java supports four types of access modifiers:

Default

Private

Protected

Public

Modifier Default Private Protected Public

Same class YES YES YES YES

Same Package subclass YES NO YES YES

Same Package non-subclass YES NO YES YES

Different package subclass NO NO YES YES

Different package non-subclass NO NO NO YES


Q19. Define a Java Class.

A class in Java is a blueprint which includes all your data. A class contains fields (variables) and methods to describe the
behavior of an object. Let’s have a look at the syntax of a class.

1 class Abc {

2 member variables // class body

3 methods}
Q20. What is an object in Java and how is it created?

An object is a real-world entity that has a state and behavior. An object has three characteristics:

State

Behavior

Identity

An object is created using the ‘new’ keyword. For example:

ClassName obj = new ClassName();

Q21. What is Object Oriented Programming?

Object-oriented programming or popularly known as OOPs is a programming model or approach where the programs are
organized around objects rather than logic and functions. In other words, OOP mainly focuses on the objects that are required
to be manipulated instead of logic. This approach is ideal for the programs large and complex codes and needs to be actively
updated or maintained.
Q22. What are the main concepts of OOPs in Java?

Object-Oriented Programming or OOPs is a programming style that is associated with concepts like:

Inheritance: Inheritance is a process where one class acquires the properties of another.

Encapsulation: Encapsulation in Java is a mechanism of wrapping up the data and code together as a single unit.

Abstraction: Abstraction is the methodology of hiding the implementation details from the user and only providing the
functionality to the users.

Polymorphism: Polymorphism is the ability of a variable, function or object to take multiple forms.

Q23. What is the difference between a local variable and an instance variable?

In Java, a local variable is typically used inside a method, constructor, or a block and has only local scope. Thus, this variable
can be used only within the scope of a block. The best benefit of having a local variable is that other methods in the class won’t
be even aware of that variable.

Example

1 if(x > 100)

2 {

3 String test = "Edureka";

4 }
Whereas, an instance variable in Java, is a variable which is bounded to its object itself. These variables are declared within
a class, but outside a method. Every object of that class will create it’s own copy of the variable while using it. Thus, any
changes made to the variable won’t reflect in any other instances of that class and will be bound to that particular instance only.

1 class Test{

2 public String EmpName;

3 public int empAge;

4 }
Q24. Differentiate between the constructors and methods in Java?

Methods Constructors
1. Used to represent the behavior of an object 1. Used to initialize the state of an object
2. Must have a return type 2. Do not have any return type
3. Needs to be invoked explicitly 3. Is invoked implicitly
4. A default constructor is provided by the compiler if the class has
4. No default method is provided by the compiler
none
5. Method name may or may not be same as class
5. Constructor name must always be the same as the class name
name
In case you are facing any challenges with these Java interview questions, please comment on your problems in the section
below.

Q25. What is final keyword in Java?

final is a special keyword in Java that is used as a non-access modifier. A final variable can be used in different contexts such
as:
final variable

When the final keyword is used with a variable then its value can’t be changed once assigned. In case the no value has been
assigned to the final variable then using only the class constructor a value can be assigned to it.

final method

When a method is declared final then it can’t be overridden by the inheriting class.

final class

When a class is declared as final in Java, it can’t be extended by any subclass class but it can extend other class.

Q26. What is the difference between break and continue statements?

break continue
1. Can be used in switch and loop (for, while, do while)
1. Can be only used with loop statements
statements

2. It causes the switch or loop statements to terminate the 2. It doesn’t terminate the loop but causes the loop to jump to
moment it is executed the next iteration

3. It terminates the innermost enclosing loop or switch 3. A continue within a loop nested with a switch will cause the
immediately next loop iteration to execute
Example break:

1
for (int i = 0; i < 5; i++)</div>
2 <div>
3 <pre>{
4 if (i == 3)
5 {
6 break;
}
7 System.out.println(i);
8 }
9
Example continue:
1 for (int i = 0; i < 5; i++)
2 {
3 if(i == 2)
4 {
5 continue;
6 }
7 System.out.println(i);
8 }
Q27. What is an infinite loop in Java? Explain with an example.

An infinite loop is an instruction sequence in Java that loops endlessly when a functional exit isn’t met. This type of loop can
be the result of a programming error or may also be a deliberate action based on the application behavior. An infinite loop will
terminate automatically once the application exits.

For example:

1 public class InfiniteForLoopDemo


2 {
3 public static void main(String[] arg) {
4 for(;;)
5 System.out.println("Welcome to Edureka!");
6 // To terminate this program press ctrl + c in the console.
7 }
8 }

Q28. What is the difference between this() and super() in Java?

In Java, super() and this(), both are special keywords that are used to call the constructor.

this() super()
1. this() represents the current instance of a class 1. super() represents the current instance of a parent/base class
2. Used to call the default constructor of the same class 2. Used to call the default constructor of the parent/base class
3. Used to access methods of the current class 3. Used to access methods of the base class
4. Used for pointing the current class instance 4. Used for pointing the superclass instance
5. Must be the first line of a block 5. Must be the first line of a block
.

Q29. Differentiate between static and non-static methods in Java.

Static Method Non-Static Method


1. No need to use the static keyword before the method
1. The static keyword must be used before the method name
name
2. It is called using the class (className.methodName) 2. It is can be called like any general method
3. They can’t access any non-static instance variables or 3. It can access any static method and any static variable
methods without creating an instance of the class
Q30. Difference between String, StringBuilder, and StringBuffer.

Factor String StringBuilder StringBuffer


Storage Area Constant String Pool Heap Area Heap Area
Mutability Immutable Mutable Mutable
Thread Safety Yes No Yes
Performance Fast More efficient Less efficient
If you think this article on Java Interview Questions is helpful, you can check out Edureka’s Java Training in Chennai as well.
Q31. What is a classloader in Java?

The Java ClassLoader is a subset of JVM (Java Virtual Machine) that is responsible for loading the class files. Whenever a
Java program is executed it is first loaded by the classloader. Java provides three built-in classloaders:

1. Bootstrap ClassLoader
2. Extension ClassLoader
3. System/Application ClassLoader

Q32. Why Java Strings are immutable in nature?

In Java, string objects are immutable in nature which simply means once the String object is created its state cannot be
modified. Whenever you try to update the value of that object instead of updating the values of that particular object, Java
creates a new string object. Java String objects are immutable as String objects are generally cached in the String pool. Since
String literals are usually shared between multiple clients, action from one client might affect the rest. It enhances security,
caching, synchronization, and performance of the application.

Q33. What is the difference between an array and an array list?

Array ArrayList

Cannot contain values of different data types Can contain values of different data types.
Size must be defined at the time of declaration Size can be dynamically changed
Need to specify the index in order to add data No need to specify the index

Arrays are not type parameterized Arraylists are type

Arraylists can contain only objects, no primitive data types are


Arrays can contain primitive data types as well as objects
allowed
.

UNIT II (Question with Answers)

1. What is Polymorphism?

Polymorphism is briefly described as “one interface, many implementations”. Polymorphism is a characteristic of being able to
assign a different meaning or usage to something in different contexts – specifically, to allow an entity such as a variable, a
function, or an object to have more than one form. There are two types of polymorphism:

1. Compile time polymorphism


2. Run time polymorphism

Compile time polymorphism is method overloading whereas Runtime time polymorphism is done using inheritance and
interface.

2. What is runtime polymorphism or dynamic method dispatch?

In Java, runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at
runtime rather than at compile-time. In this process, an overridden method is called through the reference variable of a
superclass. Let’s take a look at the example below to understand it better.

1 class Car {
2 void run()
3 {
4 System.out.println(“car is running”);
5 }
6 }
7 class Audi extends Car {
8 void run()
9 {
10 System.out.prinltn(“Audi is running safely with 100km”);
11 }
12 public static void main(String args[])
13 {
14 Car b= new Audi(); //upcasting
15 b.run();
16 }
17 }
2. What is abstraction in Java?

Abstraction refers to the quality of dealing with ideas rather than events. It basically deals with hiding the details and showing
the essential things to the user. Thus you can say that abstraction in Java is the process of hiding the implementation details
from the user and revealing only the functionality to them. Abstraction can be achieved in two ways:

1. Abstract Classes (0-100% of abstraction can be achieved)


2. Interfaces (100% of abstraction can be achieved)

4. What do you mean by an interface in Java?

An interface in Java is a blueprint of a class or you can say it is a collection of abstract methods and static constants. In an
interface, each method is public and abstract but it does not contain any constructor. Thus, interface basically is a group of
related methods with empty bodies. Example:

public interface Animal {


public void eat();
public void sleep();
public void run();
}
5. What is the difference between abstract classes and interfaces?

Abstract Class Interfaces

An abstract class can provide complete, default code and/or


An interface cannot provide any code at all, just the signature
just the details that have to be overridden
In the case of an abstract class, a class may extend only one
A Class may implement several interfaces
abstract class
An abstract class can have non-abstract methods All methods of an Interface are abstract

An abstract class can have instance variables An Interface cannot have instance variables
An abstract class can have any visibility: public, private,
An Interface visibility must be public (or) none
protected
If we add a new method to an abstract class then we have the If we add a new method to an Interface then we have to track
option of providing default implementation and therefore all down all the implementations of the interface and define
the existing code might work properly implementation for the new method

An abstract class can contain constructors An Interface cannot contain constructors

Interfaces are slow as it requires extra indirection to find the


Abstract classes are fast
corresponding method in the actual class
Q6. What is inheritance in Java?

Inheritance in Java is the concept where the properties of one class can be inherited by the other. It helps to reuse the code and
establish a relationship between different classes. Inheritance is performed between two types of classes:

1. Parent class (Super or Base class)


2. Child class (Subclass or Derived class)

A class which inherits the properties is known as Child Class whereas a class whose properties are inherited is known as Parent
class.

7.What are the different types of inheritance in Java?

Java supports four types of inheritance which are:

1. Single Inheritance: In single inheritance, one class inherits the properties of another i.e there will be only one parent as
well as one child class.
2. Multilevel Inheritance: When a class is derived from a class which is also derived from another class, i.e. a class
having more than one parent class but at different levels, such type of inheritance is called Multilevel Inheritance.
3. Hierarchical Inheritance: When a class has more than one child classes (subclasses) or in other words, more than one
child classes have the same parent class, then such kind of inheritance is known as hierarchical.
4. Hybrid Inheritance: Hybrid inheritance is a combination of two or more types of inheritance.
8. What is method overloading and method overriding?

Method Overloading :

 In Method Overloading, Methods of the same class shares the same name but each method must have a different
number of parameters or parameters having different types and order.
 Method Overloading is to “add” or “extend” more to the method’s behavior.
 It is a compile-time polymorphism.
 The methods must have a different signature.
 It may or may not need inheritance in Method Overloading.

Let’s take a look at the example below to understand it better.

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

 In Method Overriding, the subclass has the same method with the same name and exactly the same number and type
of parameters and same return type as a superclass.
 Method Overriding is to “Change” existing behavior of the method.
 It is a run time polymorphism.
 The methods must have the same signature.
 It always requires inheritance in Method Overriding.

Let’s take a look at the example below to understand it better.

1 class Car {
2 void run(){
3 System.out.println(“car is running”);
4 }
5 Class Audi extends Car{
6 void run()
7 {
8 System.out.prinltn("Audi is running safely with 100km");
9 }
10 public static void main( String args[])
11 {
12 Car b=new Audi();
13 b.run();
14 }
15 }
9. Can you override a private or static method in Java?

You cannot override a private or static method in Java. If you create a similar method with the same return type and same
method arguments in child class then it will hide the superclass method; this is known as method hiding. Similarly, you cannot
override a private method in subclass because it’s not accessible there. What you can do is create another private method with
the same name in the child class. Let’s take a look at the example below to understand it better.

1 class Base {
2 private static void display() {
3 System.out.println("Static or class method from Base");
4 }
5 public void print() {
6 System.out.println("Non-static or instance method from Base");
7 }
8 class Derived extends Base {
9 private static void display() {
10 System.out.println("Static or class method from Derived");
11 }
12 public void print() {
13 System.out.println("Non-static or instance method from Derived");
14 }
15 public class test {
16 public static void main(String args[])
17 {
18 Base obj= new Derived();
19 obj1.display();
20 obj1.print();
21 }
22 }
10. What is multiple inheritance? Is it supported by Java?

If a child class inherits the property from multiple classes is known as multiple inheritance. Java
does not allow to extend multiple classes.

The problem with multiple inheritance is that if multiple parent classes have the same method name, then at runtime it becomes
difficult for the compiler to decide which method to execute from the child class.

Therefore, Java doesn’t support multiple inheritance. The problem is commonly referred to as Diamond Problem.

In case you are facing any challenges with these java interview questions, please comment on your problems in the section
below.

11. What is encapsulation in Java?

Encapsulation is a mechanism where you bind your data(variables) and code(methods) together as a single unit. Here, the data
is hidden from the outer world and can be accessed only via current class methods. This helps in protecting the data from any
unnecessary modification. We can achieve encapsulation in Java by:

 Declaring the variables of a class as private.


 Providing public setter and getter methods to modify and view the values of the variables.

12. What is an association?

Association is a relationship where all object have their own lifecycle and there is no owner. Let’s take the example of Teacher
and Student. Multiple students can associate with a single teacher and a single student can associate with multiple teachers but
there is no ownership between the objects and both have their own lifecycle. These relationships can be one to one, one to
many, many to one and many to many.

UNIT III(Question with Answers)


1. What is an Exception in Java?

An exception is an error event that can happen during the execution of a program and disrupts its normal flow. The exception
can arise from different kinds of situations such as wrong data entered by the user, hardware failure, network connection
failure, etc. Whenever any error occurs while executing a java statement, an exception object is created, and then JRE tries to
find an exception handler to handle the exception. If a suitable exception handler is found then the exception object is passed to
the handler code to process the exception, known as catching the exception. If no handler is found then the application throws
the exception to the runtime environment and JRE terminates the program. Java Exception handling framework is used to
handle runtime errors only, compile-time errors are not handled by exception handling framework.

2. What are the Exception Handling Keywords in Java?

There are four keywords used in java exception handling.

1. throw: Sometimes we explicitly want to create an exception object and then throw it to halt the normal processing of the
program. The throw keyword is used to throw exceptions to the runtime to handle it.
2. throws: When we are throwing any checked exception in a method and not handling it, then we need to use the throws
keyword in the method signature to let the caller program know the exceptions that might be thrown by the method. The caller
method might handle these exceptions or propagate them to its caller method using the throws keyword. We can provide
multiple exceptions in the throws clause and it can be used with the main() method also.
3. try-catch: We use try-catch block for exception handling in our code. try is the start of the block and catch is at the end of the
try block to handle the exceptions. We can have multiple catch blocks with a try and try-catch blocks can be nested also. catch
block requires a parameter that should be of type Exception.
4. finally: The finally block is optional and can be used only with a try-catch block. Since exception halts the process of
execution, we might have some resources open that will not get closed, so we can use the finally block. The finally block gets
executed always, whether an exception occurs or not.

3. Explain Java Exception Hierarchy?

Java Exceptions are hierarchical and inheritance is used to categorize different types of exceptions. Throwable is the parent
class of Java Exceptions Hierarchy and it has two child objects – Error and Exception. Exceptions are further divided into
checked exceptions and runtime exceptions. Errors are exceptional scenarios that are out of the scope of application and it’s
not possible to anticipate and recover from them, for example, hardware failure, JVM crash, or out-of-memory error. Checked
Exceptions are exceptional scenarios that we can anticipate in a program and try to recover from it, for example,
FileNotFoundException. We should catch this exception and provide a useful message to the user and log it properly for
debugging purposes. Exception is the parent class of all Checked Exceptions. Runtime Exceptions are caused by bad
programming, for example, trying to retrieve an element from the Array. We should check the length of the array first before
trying to retrieve the element otherwise it might throw ArrayIndexOutOfBoundException at runtime. RuntimeException is the

parent class of all runtime exceptions.

4. What are the important methods of Java Exception Class?

Exception and all of its subclasses don’t provide any specific methods and all of the methods are defined in the base class
Throwable.

1. String getMessage() - This method returns the message String of Throwable and the message can be provided while creating
the exception through its constructor.
2. String getLocalizedMessage() - This method is provided so that subclasses can override it to provide the locale-specific
messages to the calling program. Throwable class implementation of this method simply use getMessage() method to return the
exception message.
3. synchronized Throwable getCause() - This method returns the cause of the exception or null if the cause is unknown.
4. String toString() - This method returns the information about Throwable in String format, the returned String contains the
name of Throwable class and localized message.
5. void printStackTrace() - This method prints the stack trace information to the standard error stream, this method is
overloaded and we can pass PrintStream or PrintWriter as an argument to write the stack trace information to the file or stream.

5. What is the difference between Checked and Unchecked Exceptions in Java?

1. Checked Exceptions should be handled in the code using try-catch block or else the method should use the throws keyword to
let the caller know about the checked exceptions that might be thrown from the method. Unchecked Exceptions are not
required to be handled in the program or to mention them in the throws clause of the method.
2. Exception is the superclass of all checked exceptions whereas RuntimeException is the superclass of all unchecked exceptions.
Note that RuntimeException is the child class of Exception.
3. Checked exceptions are error scenarios that require to be handled in the code, or else you will get compile time error. For
example, if you use FileReader to read a file, it throws FileNotFoundException and we must catch it in the try-catch block or
throw it again to the caller method. Unchecked exceptions are mostly caused by poor programming, for example,
NullPointerException when invoking a method on an object reference without making sure that it’s not null. For example, I can
write a method to remove all the vowels from the string. It’s the caller’s responsibility to make sure not to pass a null string. I
might change the method to handle these scenarios but ideally, the caller should take care of this.

6. What is the difference between the throw and throws keyword in Java?

throws keyword is used with method signature to declare the exceptions that the method might throw whereas throw keyword
is used to disrupt the flow of the program and handing over the exception object to runtime to handle it.

7. How to write custom exceptions in Java?

We can extend Exception class or any of its subclasses to create our custom exception class. The custom exception class can
have its own variables and methods that we can use to pass error codes or other exception-related information to the exception
handler. A simple example of a custom exception is shown below.

package com.journaldev.exceptions;

import java.io.IOException;

public class MyException extends IOException {

private static final long serialVersionUID = 4664456874499611218L;

private String errorCode="Unknown_Exception";

public MyException(String message, String errorCode){

super(message);

this.errorCode=errorCode;

}
public String getErrorCode(){

return this.errorCode;

8. What is OutOfMemoryError in Java?

OutOfMemoryError in Java is a subclass of java.lang.VirtualMachineError and it’s thrown by JVM when it ran out of heap
memory. We can fix this error by providing more memory to run the java application through java options. $>java MyProgram
-Xms1024m -Xmx1024m -XX:PermSize=64M -XX:MaxPermSize=256m

9. What are different scenarios causing “Exception in thread main”?

Some of the common main thread exception scenarios are:

 Exception in thread main java.lang.UnsupportedClassVersionError: This exception comes when your java class is
compiled from another JDK version and you are trying to run it from another java version.
 Exception in thread main java.lang.NoClassDefFoundError: There are two variants of this exception. The first one is
where you provide the class full name with .class extension. The second scenario is when Class is not found.
 Exception in thread main java.lang.NoSuchMethodError: main: This exception comes when you are trying to run a class
that doesn’t have the main method.
 Exception in thread “main” java.lang.ArithmeticException: Whenever an exception is thrown from the main method, it
prints the exception in the console. The first part explains that an exception is thrown from the main method, the second part
prints the exception class name and then after a colon, it prints the exception message..

10. What is the difference between final, finally, and finalize in Java?

final and finally are keywords in java whereas finalize is a method. final keyword can be used with class variables so that they
can’t be reassigned, with the class to avoid extending by classes and with methods to avoid overriding by subclasses, finally
keyword is used with try-catch block to provide statements that will always get executed even if some exception arises, usually
finally is used to close resources. finalize() method is executed by Garbage Collector before the object is destroyed, it’s a great
way to make sure all the global resources are closed. Out of the three, only finally is related to java exception handling.

11. What happens when an exception is thrown by the main method?

When an exception is thrown by a main() method, Java Runtime terminates the program and prints the exception message and
stack trace in the system console.

12. Can we have an empty catch block?

We can have an empty catch block but it’s an example of bad programming. We should never have an empty catch block
because if the exception is caught by that block, we will have no information about the exception and it wil be a nightmare to
debug it. There should be at least a logging statement to log the exception details in console or log files.

13. What is multitasking?


A multitasking operating system is an operating system that gives you the perception of 2 or more tasks/jobs/processes running
at the same time. It does this by dividing system resources amongst these tasks/jobs/processes and switching between the
tasks/jobs/processes while they are executing over and over again. Usually, the CPU processes only one task at a time but the
switching is so fast that it looks like the CPU is executing multiple processes at a time. They can support either preemptive
multitasking, where the OS provides time to applications (virtually all modern OS), or cooperative multitasking, where the OS
waits for the program to give back control (Windows 3.x, Mac OS 9, and earlier), leading to hangs and crashes. Also known as
Timesharing, multitasking is a logical extension of multiprogramming.
Multitasking programming is of two types which are as follows:
1. Process-based Multitasking
2. Thread-based Multitasking

Note: Performing multiple tasks at one time is referred to as multithreading in java which is of two types namely Process-based
multithreading and Thread based multithreading.
14.How can you identify the process?
Any program which is in a working state is referred to as a process. These processes do have threads that are single
dispatchable units.
15 How do you see a thread?
In order to see threads status let us take windows as an operating system, it illustrates then we’d have ProcessExplorer where
you can see GUI shown below for windows operating systems.
This PC > OS > Users > GeeksforGeeks > Downloads > ProcessExplorer
ProcessExplorer is illustrated below in the windows operating systems

Note: All of them as listed in the above media are the processes as shown above where at a time many are running in parallel to
each other henceforth illustrating multiprocessing in the Jwindows operating system.
As we have seen threads do reside in a single process so we have to deep dive into a specific process to see them in order to
show users how multithreading is going on in the computers at the backend. For example: let us pick a random process from
the above media consisting of various processes say it be ‘chrome’. Now we need to right-click over the process and click the
properties’ menu.
From the above media, it is clearly perceived that chrome is a process and after proceeding with the steps to figure out threads
running inside the chrome process we go to properties of the process ‘chrome’ below pictorial output will be generated
representing threads running in the process chrome.
Note: If we look scroll way from up to down then it will be seeing some colors against a few of those threads. Here green color
threads are associated as the newly created threads and red colors associated threads are representing the closed threads.

Note: So for chrome to increase the performance by reducing the response time that is referred to as Thread based
multitasking.
16. What is Multithreading and How it is Different from Multitasking?
Multithreading is a specialized form of multitasking. Process-based multitasking refers to executing several tasks
simultaneously where each task is a separate independent process is Process-based multitasking.
Example: Running Java IDE and running TextEdit at the same time. Process-based multitasking is represented by the below
pictorial which is as follows:

Thread-based multitasking refers to executing several tasks simultaneously where each task is a separate independent part of
the same program known as a thread. For example, JUnits uses threads to run test cases in parallel. Henceforth, process-based
multitasking is a bigger scenario handling process where threads handle the details. It is already discussed to deeper depth
already with visual aids.
For more details, please refer to Process-based and Thread-based multitasking in Java
17. Which Kind of Multitasking is Better and Why?
Thread-based multitasking is better as multitasking of threads requires less overhead as compared to process multitasking
because processes are heavyweight in turn requiring their own separate address space in memory while threads being very
light-weight processes and share the same address space as cooperatively shared by heavyweight processes.
Switching is a secondary reason as inter-process communication is expensive and limited. Context switching from one process
to another is cost hefty whereas inter-thread communication is inexpensive and context switching from one thread to another is
lower in cost.
Note: However java programs make use of process-based multitasking environments, but this feature is not directly under
Java’s direct control while multithreading is complete.
18. What is a thread?
Threads are lightweight processes within processes as seen. In java, there are two ways of creating threads namely via Thread
class and via Runnable interface.
To read more about this, please refer Thread class in Java, Runnable interface in Java
19. What are the different states of a thread, or what is thread lifecycle?
A thread in Java at any point of time exists in any one of the following states. A thread lies only in one of the shown states at
any instant:
1. New
2. Runnable
3. Blocked
4. Waiting
5. Timed Waiting
6. Terminated

To read more about this, please refer Lifecycle and States of a Thread in Java
20. What is the task of the main thread?
All Java programs have at least one thread, known as the main thread which is created by JVM at the program start when the
main() method is invoked with the main thread as depicted from the output perceived from pseudo-code illustration.
Illustration:
System.out.println(“Mayank Solanki”);
Output: Mayank Solanki
System.out.println(Thread.getname().currentthread());
Output: main
Q-9 What are Different Types of threads in Java?
There are two types of threads in java as follows:
 User thread
 Daemon thread
User threads are created by java developers for example Main thread. All threads are created inside the main() method are by
default non-daemon thread because the ‘main’ thread is non-daemon. Daemon thread is a low-priority thread that runs in the
background to perform tasks such as garbage collection, etc. They do not prevent daemon threads from exiting when all user
threads finish their execution. JVM terminates itself when all non-daemon threads finish their execution. JVM does not care
whether a thread is running or not, if JVM finds a running daemon thread it terminates the thread and after that shutdown itself.
21. How to Create a User thread?
As discussed earlier when the JVM starts it creates a main thread over which the program is run unless an additional thread is
not created by the user. The first thing “Main” thread looks for ‘public static void main(String [] args)’ method to invoke it as it
acts as an entry point to the program. All other threads created in main acts as child threads of the “Main” thread.
User thread can be implemented in two ways listed below:
1. Using Thread class by extending java.lang.Thread class.
2. Using Runnable Interface by implementing it.
22. How to set the name of the thread?
We can name a thread by using a method been already up there known as setName() replacing default naming which was
‘Thread-0’, ‘Thread-1’, and so on.
thread_class_object.setName("Name_thread_here");
23.What is thread priority?
Priorities in threads is a concept where each thread is having a priority which in layman’s language one can say every object
is having priority here which is represented by numbers ranging from 1 to 10.
 The default priority is set to 5 as excepted.
 Minimum priority is set to 0.
 Maximum priority is set to 10.
Here 3 constants are defined in it namely as follows:
1. public static int NORM_PRIORITY
2. public static int MIN_PRIORITY
3. public static int MAX_PRIORITY
To read more about this, please refer Thread Priority in Multithreading in Java
24. How deadlock plays a important role in multithreading?
If we do incorporate threads in operating systems one can perceive that the process scheduling algorithms in operating systems
are strongly deep-down working on the same concept incorporating thread in Gantt charts. A few of the most popular are
listed below which wraps up all of them and are used practically in software development.

 First In First Out


 Last In First Out
 Round Robin Scheduling
Now one Imagine the concept of Deadlock in operating systems with threads by now how the switching is getting computed
over internally if one only has an overview of them.

25. Why output is not ordered?


Scheduling of threads involves two boundary scheduling,
 Scheduling of user-level threads (ULT) to kernel-level threads (KLT) via lightweight process (LWP) by the application
developer.
 Scheduling of kernel-level threads by the system scheduler to perform different unique os functions.
If multiple threads are waiting to execute then thread execution is decided by “ThreadScheduler” which is a part of JVM hence
its vendor dependent resulting in unexpected execution of output order.
Note:
 In multithreading, the guarantee of order is very less where we can predict possible outputs but not exactly one.
 Also, note that synchronization when incorporated with multithreading does affect our desired output simply by using the
keyword ‘synchronized’.
It is as illustrated in the below illustration which is as follows:
26. What is Daemon Thread in Java and explain their properties?
Daemon thread is a low-priority thread that runs in the background to perform tasks such as garbage collection. It does possess
certain specific properties as listed below:
 They can not prevent the JVM from exiting when all the user threads finish their execution.
 JVM terminates itself when all user threads finish their execution
 If JVM finds a running daemon thread, it terminates the thread and after that shutdown itself. JVM does not care whether
the Daemon thread is running or not.
 It is an utmost low priority thread
Note: The main difference between user thread and daemon thread is that JVM does not wait for daemon thread before exiting
while it do waits for the user thread.
To read more about this, please refer to Daemon Thread in Java
27. How to Make User Thread to Daemon Thread?
It is carried out with the help of two methods listed in ‘Thread class’ known as setDaemon() and isDaemon(). First, the
setDaemon() method converts user thread to daemon thread and vice-versa. This method can only be called before starting the
thread using start() method else is called after starting the thread with will throw IllegalThreadStateException After this,
isDaemon() method is used which returns a boolean true if the thread is daemon else returns false if it is a non-daemon thread.
28. What are the tasks of the start() method?
The primary task of the start() method is to register the thread with the thread scheduler, so one can tell what child thread
should perform, when, and how it will be scheduled that is handled by the thread scheduler. The secondary task is to call the
corresponding run() method got the threads.
29. What is the difference between the start() and run() method?
First, both methods are operated in general over the thread. So if we do use threadT1.start() then this method will look for
the run() method to create a new thread. While in case of theadT1.run() method will be executed just likely the normal method
by the “Main” thread without the creation of any new thread.
Note: If we do replace start() method with run() method then the entire program is carried by ‘main’ thread.
30. Can we Overload run() method? What if we do not override the run() method?

Yes, it is possible to overload run() by passing parameters to it and also keeping a check over to comment down @override
from the run() method.
It should be as good as a thread wherein thread we do not have any arguments, so practice to overload is to comment on the
call out for overloaded run() method. Now, so we need to acknowledge the same whether the output is the same or not if we
have not overloaded it.
If we have overloaded the run() method, then we will observe that output is always the main method as can be perceived from
the stack call from the above image. It is because if we debug the code as provided in the link below we see as soon as the
start() method is called again, run() is called because we have not overridden the run() method.
For more refer to the Implementation part of how the run() method is overloaded
Conclusion: We can overload the run() method but start() method will call no argument run() only. Hence, it will be of no help
to us and is considered as bad practice.
The compiler will simply execute the run() method of the Thread class, keeping a check that the run() method of the Thread
class must have an empty implementation. Hence, it results out in no output corresponding to the thread. As we have discussed
above already, if we try to do so, then the Thread class run() method will be called and we will never get our desired output.
Even if we override the start() method in the custom class then no initializations will be carried on by the Thread class for us.
The run() method is also not called and even a new thread is also not created.

UNIT IV(Question with Answers)

1. What is the difference between InputStream and OutputStream in Java?


(InputStream is used to read data from sources like File, Socket, or Console, while OutputStream is used to write data into a
destination like a File, Socket, or Console.

2. What is the difference between BufferedReader and FileReader in Java?


BufferedReader is a Decorator that provides buffering for faster IO, while FileReader is used to read data from File.
BufferedWriter and BufferedReader provide better buffering in addition to basic file writing and reading operations. For
example, instead of reading the entire file, we can read a file line by line. Let’s write an example to write and read from a file
using FileReader and FileWriter.
BufferedWriter class helps writing to a class with better buffering than FileWriter. BufferedWriter Constructors only accept
another Writer as argument.
FileWriter fileWriter3 = new FileWriter("BufferedFileName.txt");
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter3);
bufferedWriter.write("How are you doing Buddy?");
bufferedWriter.newLine();
bufferedWriter.write("I'm Doing Fine");
//Always flush before close. Writing to file uses Buffering.
bufferedWriter.flush();
bufferedWriter.close();
fileWriter3.close();
BufferedReader helps to read the file line by line. BufferedReader Constructors only accept another Reader as argument.
FileReader fileReader3 = new FileReader("BufferedFileName.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader3);

String line;
//readLine returns null when reading the file is completed.
while((line=bufferedReader.readLine()) != null){
System.out.println(line);
}
3. What is the use of the PrintStream class in Java IO? (answer)
PrintStream is used to write data on Console, for example, System.out.println(), here out is an object of PrintStream class and
we are calling println() method from that class.

4. Explain what is JDBC?


This is one of the first and most frequently asked questions in most of the interviews. JDBC stands for Java Database
Connectivity. As its name implies, it is a Java API used for interacting with relational databases to access, modify and process
data using SQL. It utilizes JDBC drivers for interacting with the database. By using JDBC, one can access tabular data from
different types of relational databases such as MySQL, Oracle, MS Access, and so on.

5. What is a JDBC driver?


A JDBC driver is a software component having multiple interfaces and classes that enables a Java application to communicate
with a database. To establish a link with individual databases, JDBC needs specific drivers for each database. These drivers are
available with the database vendor along with the database.

A JDBC driver establishes a connection to the database. It also executes the protocol for sending the query and result between
the database and the client.
6.. Explain the different drivers of JDBC.
There are four different drivers in JDBC. They are:
JDBC-ODBC Bridge: JDBC-ODBC bridge acts as an interface between the DB server and the client.
Native API: Half Java Driver: This driver almost behaves as a JDBC-ODBC driver. However, instead of an ODBC driver, you
4se native APIs and a client-side database.
Network Protocol: This driver works like a 3-tier approach for accessing the database. An intermediate server connects to the
database. The JDBC method calls send data to a transitional server and then the server communicates with the database.
Thin Driver: It is completely written in Java. This driver explicitly changes JDBC method calls to the vendor-specific database
protocol.

7. Are there any advantages of using a Prepared Statement in Java?


A Prepared Statement executes certain SQL statements repetitively. This statement is compiled only once even though it is
executed “n” number of times.
8. Explain the term connection pooling.
This is another one of the popular JDBC interview questions. Connection pooling is the technique by which we reuse the
resource-like connection objects that are required to establish a connection with the database. It is a technique of managing and
creating a pool of connections that can be used by any thread that requires them. Each time an application tries to access a
backend store (such as a database), it needs resources to develop, maintain, and release a connection to that datastore. Thus,
connection pooling can greatly increase the performance of a Java application while reducing the overall resource usage.
9. Explain the types of JDBC Architecture?
There are two kinds of architecture models to access the database while using JDBC.
They are:
Two-tier Architecture: In this model, Java programs exclusively connect with the database and there is no requirement of any
mediator like applications servers to connect with the database. This model is also known as the client-server architecture.
Three-tier Architecture: This model is the complete opposite of two-tier architecture. An application server is used as a
mediator between the Java program or JDBC driver and the database. The Java program sends a request to the application
server. The server then forwards this request to the database and waits for a response from the database.

What are the main components of JDBC?


Following are the four major components available in JDBC:
JDBC Driver Manager
JDBC API
JDBC Test Suite
JDBC-ODBC Bridge

10. What are the steps to connect with JDBC?


Following are the 6 basic steps to connect with the database in Java.
Import the JDBC packages.
Load and register the JDBC driver.
Open and establish a connection to the database.
Creation a statement object to perform a query.
Execute the statement object and return a query ResultSet(). Then process the ResultSet().
Close the ResultSet() and statement objects.
Close the connection.
11. Explain the meaning of hot backup and cold backup.
While this question is not related to JDBC directly, it may still be asked in an interview. The cold back is the backup process in
which the backup of files is taken before restarting the database. In the hot back, backup process the backup of tables and files
is taken at the time when the database is running.
12. What are the steps to connect with JDBC?
There are 2 types of locking available in JDBC by which we can manage various user issues. If two users are trying to access
the same record then there is no issue but the problem arises when multiple users are trying to update the same record
simultaneously. To address this issue, there are two locking modes available in JDBC. They are:
Optimistic Locking: Locks the record only when an update is taking place. This kind of locking does not use exclusive locks
while reading.
Pessimistic Locking: In this system, the records are locked as the row to update is selected.
13. Explain if the JDBC-ODBC Bridge supports different concurrent open statements per connection?
No, when using the JDBC-ODBC Bridge, you can open only one Statement object.
14. What are database warnings in JDBC and explain how we can manage database warnings in JDBC?
The database warning or SQL warning is nothing but the subclass of the SQLException class. You can manage or handle this
warning by using the getWarnings() method on a statement, connection, and ResultSet.
15. Explain the difference between executeQuery, executing, and executeUpdate in JDBC?
executeQuery(): The executeQuery() can be used for select query.
execute(): The execute() can be used for any type of SQL Query.
executeUpdate(): The executeUpdate() can be used to modify/update tables.
16. Explain what you mean by Metadata and also explain why we use it.
Metadata means information about other data. You use metadata to get the database product version, driver name, the total
number of views and tables.

17. What is an applet in Java?


An applet is a small Java program that can be embedded in a web page. Applets are used to make web pages more interactive
and can perform tasks such as animating images, calculating formulas, or checking usernames and passwords.
2. Can you explain the lifecycle of a java applet?
The lifecycle of a java applet is as follows:
1. The applet is loaded into memory and initialized.
2. The applet’s start() method is called.
3. The applet’s paint() method is called.
4. The applet’s stop() method is called.
5. The applet’s destroy() method is called.
6. The applet is unloaded from memory.
3. What are the differences between an application and an applet?
The main difference between an application and an applet is that an applet is designed to be run within a web browser, while an
application is not. Applets also have some restrictions placed on them in terms of what they are allowed to do, for security
reasons.

18.How do you use threading with Applets to make them more efficient?
Threading can be used with Applets to make them more efficient by allowing multiple tasks to be performed simultaneously.
For example, if you have an Applet that is responsible for both drawing images and playing sound, you can use threading to
have the Applet perform both tasks at the same time. This can help to improve the overall performance of the Applet.
19. What’s the difference between the Applet class and the Panel class?
The Applet class is a subclass of the Panel class, meaning that it inherits all of the Panel class’s methods and variables. The
Applet class also adds a few methods of its own, specifically related to loading and running the applet within a web browser.
20. Can you give me some examples of real-world applications that use Applets?
There are a few examples of real-world applications that use Applets. One example is an online banking application that uses
an Applet to provide a secure connection for customers to log in and access their accounts. Another example is an online
shopping application that uses an Applet to provide a secure connection for customers to enter their credit card information.
21. What is the best way to create multiple threads for an Applet?
The best way to create multiple threads for an Applet is to use the Thread class.

22. What is the significance of init() method in Applet?


The init() method is called when an Applet is first loaded. This is where you should initialize any variables that will be used by
the Applet.
23. Why isn’t it a good idea to override paint() or update() methods directly?
Overriding the paint() or update() methods directly can lead to problems because they are both called automatically by the
system. If you override them, then you can end up with a situation where your code is executed at unexpected times, which can
lead to errors. It is better to instead use a method like paintComponent() that is only called when you explicitly request it.
24. When should we stop using Applets in our web applications?
While applets can provide a richer user experience than traditional web applications, they require the user to have a Java
runtime installed on their machine. With the rise of HTML5 and other web technologies, there are now other ways to provide a
similar user experience without the need for a Java runtime. As such, it is generally recommended that developers stop using
applets in their web applications.
25. Is it possible to communicate between two different Applets running on the same page? If yes, then how?
Yes, it is possible to communicate between two different Applets running on the same page. One way to do this is to use the
getAppletContext() method, which returns an AppletContext object. This object can be used to call the other Applet’s methods.

26. Is it possible to load one Applet from another Applet? If yes, then how?
Yes, it is possible to load one Applet from another Applet. This can be done using the getAppletContext().showDocument()
method. This method takes as input an Applet URL, which specifies the Applet to be loaded.
27. How can you pass parameters to Applets?
You can pass parameters to an Applet in two ways:
1. By using the tag inside the HTML code that embeds the Applet.
2. By using the AppletContext.showDocument() method.

28.What is difference between Swing and AWT in Java?


Answer : One of the most frequently asked AWT and Swing Interview question. One answer of this question is that, Swing is a
considered as light weight and AWT is considered as heavy weight. Another difference between AWT and Swing is that,
Swing offers uniform look and feel across platform while look and feel of AWT GUI application are platform dependent
because AWT mostly use native components e.g. a AWT windows will look different in DOS and Windows operating system.

29.What is difference between paint and repaint in Java Swing?


Answer : This can be a tough Java question if you are not familiar with Swing API. Well, this is similar
to start() and run() method of thread class. As calling start() method will eventually calls run() method of Runnable interface,
Calling repaint() will call paint() method in Swing. Since painting can only be done in EDT thread, repaint() just put a paint
request in EDT Queue, later EDT thread may combine several repaint request to one and can perform repainting. repaint() is a
not a blocking method in Java and returns quickly.

30.: What is difference between BorderLayout and GridLayout ?


Answer : This is one of interesting Swing interview question. BorderLayout and GridLayout are two widely
used LayoutManager from Swing API, former arranges components in predefined position e.g. NORTH, SOUTH,
EAST and WEST while later arranges components one after other until there is space and wraps them afterwards. This Swing
question becomes more difficult when Interviewer asked to write code to implement a layout e.g. drawing a layout and ask you
to implement as discussed in Top 10 Swing interview questions in Java.

31. How to change a button from enable to disable after click ?


Answer : When button is clicked an action event is fired which can be captured by implementing ActionListener interface
and actionPerformed(ActionEvent ae) method. You can then call button.setEnable(false) to disable this button.

32: Why Swing is called light weight ?


Answer : Most of Swing component are inherited form JComponent and doesn't required a native peer and that's why they are
referred as light weight component. light weight component implement look and feel in Java rather than using look and feel of
native component and that's why Swing's look and feel remains same across platform.
S
33: Is Swing Thread safe in Java ?
Answer : This is one of the tricky question in Java Swing and AWT. No, Swing is not thread-safe in Java. Swing components
are not thread-safe they can not be modified from multiple threads. All swing components are designed to be updated by using
Event dispatcher thread or EDT thread. See How to write thread-safe code in Java to know more about thread-safety. By the
way you can use invokeAndWait and invokeLater to safely update swing components as discussed in previous Swing interview
question.

34: Which method of Swing are thread-safe?


Answer : This AWT and Swing question is asked as follow-up of previous Swing interview question. Only couple of methods
like repaint() and revalidate() are thread-safe in Swing, i.e. they can be called from multiple threads without
additional synchronization in Java.

35: What is difference between Container and Component ?


Answer : Main difference between Container and Component is that former can hold other components e.g. JFrame which is
used as container to hold other components e.g. JButton. This is rather a simple Swing question and mostly asked in telephonic
or upto 2 years experienced programmers.

That's on this list of Swing Interview questions and answers in Java. Despite reducing popularity and losing competition
with C#, Swing is a great GUI technology and one of the most preferred technology for implementing thick clients in Java.
Especially in finance and insurance domain, where client application need to work with high volume of data, Java Swing is the
solution. Good Swing developers are hard to find and that's why well paid in this industry.

You might also like