Java OOPS Notes
Java OOPS Notes
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:
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games, etc.
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.
, Regex, Exception, Inner classes, Multithreading, I/O Stream, Networking, AWT, Swing, Reflection,
Collection, etc.
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.
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.
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:
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
JDK is an implementation of any one of the below given Java Platforms released by Oracle Corporation:
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
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
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
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.
Sample.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)
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.
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.
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
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:
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:
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:
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:
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:
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
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
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:
It is because java uses Unicode system not ASCII code system. The \u0000 is the lowest range of Unicode system.
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:
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
additive +-
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
Ternary ternary ?:
}}
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
equality == !=
bitwise exclusive ^
OR
bitwise inclusive |
OR
logical OR ||
Ternary ternary ?:
}}
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.
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.
If you make any variable as final, you cannot change the value of final variable(It will be constant).
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
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...
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.
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
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. }
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 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.
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{}
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.
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:
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:
Output:
drawing rectangle...
drawing circle...
drawing triangle...
Output:
eating bread...
eating rat...
eating meat...
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.
Output:
90
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
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.
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.
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%).
Let's see a simple example where we are using interface and abstract class both.
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 −
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 */
You can execute the class file within the package and get the result as shown below.
Mammal eats
Mammal travels
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.
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.
1. Exception Handling
4. Types of Exception
5. Exception Example
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.
In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.
Exception Handling is a mechanism to handle runtime errors such as 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 are the 4 rules for using exception handling with method overriding?
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 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.
throws The "throws" keyword is used to declare exceptions. It specifies that there may occur an exception in the method. It
doesn't throw an exception. It is always used with method signature.
Let's see an example of Java Exception Handling in which we are using a try-catch statement to handle the exception.
JavaExceptionExample.java
Output:
In the above example, 100/0 raises an ArithmeticException which is handled by a try-catch block.
There are given some scenarios where unchecked exceptions may occur. They are as follows:
1. int a=50/0;//ArithmeticException
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
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
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
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.
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().
Starting a thread:
The start() method of Thread class is used to start a newly created thread. It performs the following tasks:
FileName: Multi.java
Output:
thread is running...
FileName: Multi3.java
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.
We can directly use the Thread class to spawn new threads using the constructors defined above.
FileName: MyThread1.java
Output:
My first thread
FileName: MyThread2.java
Output:
My new thread
Now the thread is running ...
UNIT IV
File Handling in Java (Java FileReader & FileWriter)
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 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.
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.
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.
We can write into a file using the byte stream class OutputStreamWriter or Character stream class FileWriter.
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.
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.
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.
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.
The FileReader is a class of the character stream, thus it reads 16 bits of data at a time. It is faster than InputStreamReader.
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.
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
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.*;
String driverClassName
= "sun.jdbc.odbc.JdbcOdbcDriver";
String query
// Obtain a connection
// Obtain a statement
Statement st = con.createStatement();
System.out.println(
+ count);
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 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.
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.
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.
We can write into a file using the byte stream class OutputStreamWriter or Character stream class FileWriter.
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.
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.
The FileReader is a class of the character stream, thus it reads 16 bits of data at a time. It is faster than InputStreamReader.
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.
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
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.*;
String driverClassName
= "sun.jdbc.odbc.JdbcOdbcDriver";
String query
Class.forName(driverClassName);
// Obtain a connection
// Obtain a statement
Statement st = con.createStatement();
System.out.println(
+ count);
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.
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
import java.io.*;
import javax.swing.*;
// Main class
class GFG {
JFrame frame
// JButton
button.setBounds(
Output:
Example 2: Write a program to create three buttons with caption OK , SUBMIT, CANCLE.
Java
import java.awt.*;
class button {
button() {
f.add(b1);
f.add(b2);
f.add(b3);
f.setSize(500, 500);
f.setLayout(null);
f.setVisible(true);
new button();
OUTPUT:
Example 3 :
Java
import java.awt.*;
class Lan {
Lan() {
f.add(l1);
f.add(c2);
f.add(c3);
f.add(c4);
f.setSize(500, 500);
f.setLayout(null);
f.setVisible(true);
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
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
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
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.
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.
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.
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
import java.applet.Applet;
import java.awt.Graphics;
{
// Overriding paint() method
@Override
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
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
import java.applet.Applet;
import java.awt.Graphics;
/*
</applet>
*/
@Override
}
With this approach, first compile HelloWorld.java file and then simply run the below command to run applet :
appletviewer HelloWorld
To prove paint() method is called again and again, here is the code:
Java
//and again
import java.awt.*;//Graphic
// 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.
Displaying documents
Playing animations
Due to security reasons, the following restrictions are imposed on Java applets:
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
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.
Java is called platform independent because of its byte codes which can run on any system irrespective of its underlying
operating system.
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.
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.
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.
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 does not define the increment size. Vector defines the increment size.
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.
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 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.
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?
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 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
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.
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
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 {
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
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
2 {
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{
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.
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.
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:
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
.
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
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.
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
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:
Compile time polymorphism is method overloading whereas Runtime time polymorphism is done using inheritance and
interface.
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:
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:
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
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:
A class which inherits the properties is known as Child Class whereas a class whose properties are inherited is known as Parent
class.
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.
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.
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.
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:
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.
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.
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.
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
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.
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.
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;
super(message);
this.errorCode=errorCode;
}
public String getErrorCode(){
return this.errorCode;
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.