0% found this document useful (0 votes)
8 views214 pages

II-i-oops-lecture Notes Java (3)

This document provides an introduction to Object Oriented Programming (OOP) and the Java programming language, covering its history, principles, editions, and key features. It explains core OOP concepts such as classes, objects, inheritance, polymorphism, abstraction, and encapsulation, as well as Java's unique characteristics like platform independence, security, and robustness. Additionally, it includes a simple Java program example and outlines the steps for writing and executing Java code.

Uploaded by

kaminiganesan13
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
8 views214 pages

II-i-oops-lecture Notes Java (3)

This document provides an introduction to Object Oriented Programming (OOP) and the Java programming language, covering its history, principles, editions, and key features. It explains core OOP concepts such as classes, objects, inheritance, polymorphism, abstraction, and encapsulation, as well as Java's unique characteristics like platform independence, security, and robustness. Additionally, it includes a simple Java program example and outlines the steps for writing and executing Java code.

Uploaded by

kaminiganesan13
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 214

Unit-1

Introduction: Introduction to Object Oriented Programming, The History and Evolution of Java,
Introduction to Classes, Objects, Methods, Constructors, this keyword, Garbage Collection, Data Types,
Variables, Type Conversion and Casting, Arrays, Operators, Control Statements, Method Overloading,
Constructor Overloading, Parameter Passing, Recursion, String Class and String handling methods.

History of Java:-
Java is a popular object-oriented programming language, developed by sun micro systems of USA in
1991(which has since been acquired by oracle). Originally it was called as oak. The developers of java
are James Gosling and his team (Patrick naughton, Chris warth, ed frank, and mike Sheridan).
This language was renamed as “java” in 1995. Java was publicly announced in 1995 and now more than
3 billion devices run java

The primary motivation of java was need for a platform independent language which can be used to
create software to be embedded in different consumer electronic devices like remote controls,
microwave ovens etc.

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.

Principles
There were five primary goals in the creation of the Java language:

1. It must be simple, object-oriented, and familiar.


2. It must be robust and secure.
3. It must be architecture-neutral and portable.
4. It must execute with high performance.
5. It must be interpreted, threaded, and dynamic.

Editions:
 Java Standard Edition: - Java Standard Edition, also known as J2SE / JSE is the
java platform (Any hardware or software environment in which a program runs is known as a
platform.) for developing client-side application which runs on desktop, and applets which run on
web browser.
Core Java + JDBC is the part of Java Standard Edition (J2SE / JSE).

 Java Enterprise Edition : - Java Enterprise Edition, also known as J2EE / JEE is the java platform
built on the top of Java SE , which is used to develop enterprise- oriented server applications.(Server
side applications include servlets, which are java programs that are similar to applets but run on a
server rather than a client.)
Servlets + JSPs are the part of Java Enterprise Edition.
Java Micro Edition: - Java Micro Edition, also known as J2ME / JME is the java platform
which is also built on Java SE. It is mainly used to develop mobile applications.

Java FX: - Java FX, also known as Java Flex is used to develop rich internet applications. It
uses light-weight user interface API.

Introduction to Object Oriented Programming:-

Object-oriented programming (OOP) is a programming paradigm based on the concept of objects,


which are data structures that contain data, in the form of fields (or attributes) and code, in the form of
procedures, (or methods).

Characteristics of OOP:

 Emphasis on data.
 Programs are divided into what are known as methods.
 Data structures are designed such that they characterize the objects.
 Methods that operate on the data of an object are tied together.
 Data is hidden.
 Objects can communicate with each other through methods.
 Reusability.
 Follows bottom-up approach in program design

OOP concepts:

Object-Oriented Programming is a methodology or paradigm to design a program using classes and


objects. It simplifies software development and maintenance by providing some concepts:

o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation

Object:

Any entity that has state and behavior is known as


an object. For example, a chair, pen, table,
keyboard, bike, etc. It can be physical or logical.

An Object can be defined as an instance of a class.


An object contains an address and takes up some
space in memory. Objects can communicate without knowing the details of each other's data or code. The
only necessary thing is the type of message accepted and the type of response returned by the objects.
Example: A dog is an object because it has states like color, name, breed, etc. as well as behaviors like
wagging the tail, barking, eating, etc.

Class:

Collection of objects is called class. It is a logical entity.

A class can also be defined as a blueprint from which we can create an individual object. Class doesn't
consume any space.

Inheritance

When one object acquires all the properties and behaviors of a parent object, it is known as inheritance. It
provides code reusability. It is used to achieve runtime polymorphism.

Polymorphism:

Polymorphism means taking many forms, where ‘poly’ means many and ‘morph’ means forms. It is the
ability of a variable, function or object to take on multiple forms. In other words, polymorphism allows us
to define one interface or method and have multiple implementations.

For eg, Bank is a base class that provides a method rate of interest. But, rate of interest may differ
according to banks. For example, SBI, ICICI and AXIS are the child classes that provide different rates of
interest.

Polymorphism in Java is of two types:

 Run time polymorphism


 Compile time polymorphism

Abstraction:
Abstraction is a process of hiding the implementation details and showing only functionality to the user.

Another way, it shows only essential things to the user and hides the internal details, for example, sending
SMS where you type the text and send the message. You don't know the internal processing about the
message delivery.

Abstraction means simple things like objects, classes, and variables represent more complex underlying
code and data. It avoids repeating the same work multiple times. In java, we use abstract class and interface
to achieve abstraction.

Abstract class:

Abstract class in Java contains the ‘abstract’ keyword. If a class is declared abstract, it cannot be
instantiated. So we cannot create an object of an abstract class. Also, an abstract class can contain abstract
as well as concrete methods. To use an abstract class, we have to inherit it from another class where we
have to provide implementations for the abstract methods there itself, else it will also become an abstract
class.
Interface:

Interface in Java 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. Along with abstraction, interface also helps to
achieve multiple inheritances in Java. So an interface is a group of related methods with empty bodies.

Encapsulation:

Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps both safe
from outside interference and misuse.
 In Java, the basis of encapsulation is the class. There are mechanisms for hiding the complexity of
the implementation inside the class.
 Each method or variable in a class may be marked private or public.
 The public interface of a class represents everything that external users of the class need to know, or
may know.
 The private methods and data can only be accessed by code that is a member of the class.
 Therefore, any other code that is not a member of the class cannot access a private method or
variable.
 Since the private members of a class may only be accessed by other parts of program through the
class’ public methods, we can ensure that no improper actions take place.

Features of java:
The features of Java are also known as Java buzzwords. A list of most important features of java language
is given below

1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic

Simple:
Its coding style is very clean and easy to
understand.

 Java syntax is base on c++.


 Java has removed many complicated and rarely used features, for example
 Concept of Explicit Pointers
 Storage classes
 Preprocessors and header files
 Multiple Inheritance
 Operator Overloading
 Goto Statements
 There is no need to remove unreferenced objects because there is an automatic garbage collection
in java.
Object-Oriented:

Java is an object-oriented programming language. Everything in Java is an object. Object-oriented means we


organize our software as a combination of different types of objects that incorporate both data and
behavior.
Object-oriented programming (OOPs) is a methodology that simplifies software development and
maintenance by providing some rules.
Basic concepts of OOPs are:

1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

Portable:
Java is portable because it facilitates us to carry the Java byte code to any platform. It doesn't require any
implementation. Moreover, any changes and updates made in Operating Systems, Processors and System
resources will not enforce any changes in Java programs.

Platform Independent
Being platform-independent means a program compiled on one machine can be executed on any machine in
the world without any change. Java achieves platform independence by using the concept of the BYTE
code.
There are two types of platforms software-based and hardware based. Java provides a software
based platform.
Java has two components:
1. Runtime environment
2. API(Application programming language)
Java code can run on multiple platforms, for example Windows, Linux, Solaris, Mac Os, etc. Java
converts the source code into an intermediate code called the bytecode. This byte code is further translated
to machine-dependent code by another layer of software called JVM (Java Virtual Machine).
Java is a “Write Once, run anywhere” (WORA) which means that we can develop applications on one
environment (OS) and run on any other environment without doing any modification in the code.
Below diagram explains the platform independence feature of Java-Portable
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.

 Class loader: Class loader in java is part of Java Runtime Environment (JRE) which is used to load
java classes into Java Virtual Machine dynamically. It adds security by separating the package for the
classes of local file system from those that are imported from network sources.
 Byte code Verifier: It checks the code fragments for illegal code that can violate access right to
objects.
 Security Manager: It determines what resources a class can access such as reading and writing to the
local disk.

Robust:

Robust simply means strong. Java is robust beacuase:


 Java has a strong memory management system. It helps in eliminating errors as it checks the code
during both compile and runtime.
 There is a lack of pointers that avoid security problems.
 Java is garbage-collected language – JVM automatically deallocates the memory blocks and
programmers do not have to worry about deleting the memory manually as in case of C/C++.
 Java also provides the concept of exception handling which identifies runtime errors and eliminates
them.

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.

Interpreted:
Java is both compiled and interpreted language since java programs are compiled first using java
compiler (javac) then at runtime the compiled code (bytecode) is interpreted by java interpreter in order to
execute the program.
Java is a highly interpreted language. At runtime java bytecode is interpreted(converted) into
machine code using java interpreter(part of JVM) in order to run the program. Java has the feature of just-
in-time(JIT) compilation (happens at runtime) which reduces the interpretation time.
The diagram below shows the above process:
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.
Java provides high performance with the use of “JIT – Just In Time compiler”, in which the
compiler compiles the code on-demand basis, that is, it compiles only that method which is being called.
This saves time and makes it more efficient.

Multithreaded:
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 code of java is divided into smaller parts and Java executes them in a sequential and timely manner.
 The main advantage of multithreading is that the maximum utilization of resources is possible.
 It doesn’t occupy memory for each thread. It shares a common memory area.
 There is no need to wait for the application to finish one task before beginning another one.
 There is a decreased cost of maintenance. Also, It is time-saving. It improves the performance of
complex applications.

Distributed:
Java is distributed because it encourages users to create distributed applications.

RMI (Remote Method Invocation) and EJB (Enterprise JavaBeans) 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.
It also enables multiple programmers at many locations to work together on a single project.

Dynamic and Extensible:


Java is a dynamic language. It supports the dynamic loading of classes. It means classes are loaded on
demand. It also supports functions from its native languages, i.e., C and C++.
Java supports dynamic compilation and automatic memory management (garbage collection).

Java is dynamic and extensible means with the help of OOPs, we can add classes and add new methods to
classes, creating new classes through subclasses. This makes it easier for us to expand our own classes and
even modify them.
Java even supports functions written in other languages such as C and C++ to be written in Java programs.
These functions are called “native methods”. These methods are dynamically linked at runtime.

WRITING SIMPLE JAVA PROGRAM:

A java program may contain many classes, of which only one class should contains main() method.
Documentation section Suggested
Package statements Optional
Import statements Optional
Interface statements Optional
Class Definations Optional
Main Method Class
{ Essential
Main Method Definations
}

Documentation section:

It consists of comment lines( program name, author, date,…….),


// - for single line comment.
/*----*/ - multiple line comments.
/**---*/ - known as documentation comment, which generated documentation automatically.

Package statement:
This is the first statement in java file. This statement declares a package name and informs the compiler
that the class defined here belongs to this package.
Ex: - package student

Import statements:
This is the statement after the package statement. It is similar to # include in c/c++.
Ex: import java.lang.String
The above statement instructs the interpreter to load the String class from the lang package. Note:
• Import statement should be before the class definitions.
• A java file can contain N number of import statements.

Interface statements:
An interface is like a class but includes a group of method declarations.
Note: Methods in interfaces are not defined just declared.

Class definitions:
Java is a true oop, so classes are primary and essential elements of java program. A program can have
multiple class definitions.

Main method class:


Every stand-alone program required a main method as its starting point. As it is true oop the main method
is kept in a class definition. Every stand-alone small java program should contain at least one class with
main method definition.
A Simple Java Program:
In this section, we will learn how to write the simple program of Java. We can write a simple hello Java
program easily after installing the JDK.

To create a simple Java program, we need to create a class that contains the main method. Let's understand
the requirement first.
Requirements:
For executing any Java program, the following software or application must be properly installed.

o Install the JDK if you don't have installed it, download the JDK and install it.
o Set path of the jdk/bin directory. http://www.javatpoint.com/how-to-set-path-in-java
o Create the Java program
o Compile and run the Java program

Creating Hello World Example:

Let's create the hello java program:

class Simple{
public static void main(String args[])
{ System.out.println("Hello Java");
}
}
Save the above file as Simple.java.
To compile: javac Simple.java
To execute: java Simple

Output:

Hello Java

Compilation Flow:
When we compile Java program using javac tool, the Java compiler converts the source code into byte
code.

Parameters used in First Java Program:

Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().
o class keyword is used to declare a class in Java.
o public keyword is an access modifier that represents visibility. It means it is visible to all.
o static is a keyword. If we declare any method as static, it is known as the static method. The core
advantage of the static method is that there is no need to create an object to invoke the static
method. The main() method is executed by the JVM, so it doesn't require creating an object to
invoke the main() method. So, it saves memory.
o void is the return type of the method. It means it doesn't return any value.
o main represents the starting point of the program.
o String[] args or String args[] is used for command line argument.
o System.out.println() is used to print statement. Here, System is a class, out is an object of the
PrintStream class, println() is a method of the PrintStream class.

Rules for writing JAVA programs:


 Every statement ends with a semicolon
 Source file name and class name must be the same.
 It is a case-sensitive language.
 Everything must be placed inside a class, this feature makes JAVA a true object oriented
programming language.

Rules for file names:


 A source code file can have only one public class, and the file name must match the public class
name.
 A file can have more than one non-public class.
 Files with no public classes have no naming restriction

Java Comments:
The java comments are statements that are not executed by the compiler and interpreter. The comments
can be used to provide information or explanation about the variable, method, class or any statement. It can
also be used to hide program code for specific time. Types of Java Comments
There are 3 types of comments in java.
1. Single Line Comment
2. Multi Line Comment
3. Documentation Comment

Java Single Line Comment:


The single line comment is used to comment only one line.

Syntax:
//This is single line comment
Example:
public class CommentExample1
{
public static void main(String[] args)
{
int i=10;//Here, i is a variable System.out.println(i);
}}
Output: 10

Java Multi Line Comment:


The multi line comment is used to comment multiple lines of code.
Syntax:
/*
This is
multi
line
comment
*/
Example:
public class CommentExample2
{
public static void main(String[] args)
{
/* Let's declare and
print variable in java.*/
int i=10;
System.out.println(i);
}}
Output: 10

Java Documentation Comment:


The documentation comment is used to create documentation API. To create documentation API, you
need to use javadoc tool.
Syntax:
/**
This is
documentation
comment
*/
Example:
/** The Calculator class provides methods to get addition and subtraction of given 2 numbers.*/
public class Calculator
{
/** The add() method returns addition of given numbers.*/
public static int add(int a, int b)
{
return a+b;
}
/** The sub() method returns subtraction of given numbers.*/
public static int sub(int a, int b)
{
return a-b;
}}
Compile it by javac tool:
javac Calculator.java
Create Documentation API by javadoc tool:
javadoc Calculator.java
Now, there will be HTML files created for our Calculator class in the current directory. Open the HTML
files and see the explanation of Calculator class provided through documentation comment.

Data type:
Java is a statically typed and also a strongly typed language. In Java, each type of data (such as integer,
character, hexadecimal, etc. ) is predefined as part of the programming language and all constants or
variables defined within a given program must be described with one of the data types.
Data types represent the different values to be stored in the variable. In java, there are two categories of
data types:
 Primitive data types
 Non-primitive data types

Figure: Data types in java


Literals:
A literal represents a value that is stored into a variable directly in the program
For example:
boolean=false;
char gender=’F’;
short s=1000;
int i=-1256;
In the preceding statements, the right hand side values are called literals because these values are being
stored into the variables shown at the left hand side. As the data type of the variable changes, the type of
the literals also changes. So we have different types of literals. There are as follows:
 Integer literals
 Float literals
 Character literals
 String literals
 Boolean literals

Variable:
A variable is the name of a reserved area allocated in memory. In other words, it is a name of the memory
location. It is a combination of "vary + able" which means its value can be changed.
Types of Variable
There are three types of variables in java:
 Local variable
 Instance variable
 Static variable
Local variable:
 A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware that the
variable exists.
 Local variables are declared inside the methods, constructors, or blocks.
 Local variables are created when the method, constructor or block is entered.
 Local variable will be destroyed once it exits the method, constructor, or block.
 Local variables are visible only within the declared method, constructor, or block.
 Local variables are implemented at stack level internally.

There is no default value for local variables, so local variables should be declared and an initial value
should be assigned before the first use.

 Access specifiers cannot be used for local variables.


 A local variable cannot be defined with "static" keyword.

Instance variable:
 A variable declared inside the class but outside the method, is called instance variable.
 Instance variables are declared in a class, but outside a method, constructor or any block.
 A slot for each instance variable value is created when a space is allocated for an object in the
heap.
 Instance variables are created when an object is created with the use of the keyword ‘new’ and
destroyed when the object is destroyed.
 Instance variables hold values that must be referenced by more than one method, constructor or
block, or essential parts of an object’s state that must be present throughout the class.
 Access modifiers can be given for instance variables.
 The instance variables are visible for all methods, constructors and block in the class. It is
recommended to make these variables as private. However, visibility for subclasses can be given
for these variables with the use of access modifiers.
 Instance variables have default values.
 numbers, the default value is 0,
 Booleans it is false,
 Object references it is null.
 Values can be assigned during the declaration or within the constructor.
 Instance variables cannot be declared as static.
 Instance variables can be accessed directly by calling the variable name inside the class. However,
within static methods (when instance variables are given accessibility), they should be called using
the fully qualified name: ObjectReference.VariableName.
Static Variable:
 Class variables also known as static variables are declared with the static keyword in a class, but
outside a method, constructor or a block.
 Only one copy of each class variable per class is created, regardless of how many objects are
created from it.
 Static variables are rarely used other than being declared as constants. Constants are variables that
are declared as public/private, final, and static. Constant variables never change from their initial
value
 Static variables are stored in the static memory. It is rare to use static variables other than declared
final and used as either public or private constants.
 Static variables are created when the program starts and destroyed when the program stops.
 Visibility is same as instance variables. However, most static variables are declared public since
they must be available for users of the class.
 Default values are same as instance variables.
 Values can be assigned during the declaration or within the constructor. Additionally, values can be
assigned in special static initialize blocks.
 Static variables cannot be local.
 Static variables can be accessed by calling with the class name like ClassName.VariableName.
 When declaring class variables as public static final, then variable names (constants) are all in
upper case. If the static variables are not public and final, the naming syntax is the same as instance
and local variables.
Example:

class VaribleDemo
{
int a=10; //instance variable
static int b=20; //static variable or class variable
VaribleDemo()
{
int c =30; //Local
variables
System.out.println("c="+c);
}
void setData()
{
int d=40; //Local varibles
System.out.println("d="+d);
}
public static void main(String args[])
{
VaribleDemo v=new VaribleDemo();
System.out.println("a="+v.a);
System.out.println("b="+b);
v.setData();
}
}

Output:
ELEMENTS OR TOKENS IN JAVA PROGRAM:

A token is the smallest element of a program that is meaningful to the compiler. Tokens can be classified as
follows:

 Keywords
 Identifiers
 Constants
 Special Symbols
 Operators

Keyword:

Keywords are pre-defined or reserved words in a programming language. Each keyword is meant to
perform a specific function in a program. Since keywords are referred names for a compiler, they can’t be
used as variable names because by doing so, we are trying to assign a new meaning to the keyword which
is not allowed. Java language supports following keywords:
abstract assert boolean break byte
case catch char class const
continue default do double else
enum exports extends final finally
float for goto if implements
import instanceof int interface long
module native new open opens
package private protected provides public
requires return short static strictfp
super switch synchronized this throw
throws to transient transitive try
uses void volatile while with

Identifiers:
Identifiers used for naming classes, methods, variables, objects, labels and interfaces in a program.
Java identifiers follow the following rules:
1. Identifier must start with a letter, a currency character ($), or a connecting character such as
underscore (_).
2. Identifier cannot start with a number.
3. Uppercase and lowercase letters are distinct.
4. Total, TOTAL and total are different.
5. They can be of any length.
6. It should not be a keyword.
7. Spaces are not allowed.
Examples of legal and illegal identifiers follow,

first some legal identifiers:


 int _a;
 int $c;
 int 2_w;
 int _$;
 int this_is_a_very_detailed_name_for_an_identifier;

The following are illegal (Recognize why):


1. int :b;
2. int -d;
3. int e#;
4. int .f;

Conventions for identifier names:


1. Names of all public methods and instance variables start with lowercase, for more than one word
second word’s first character shold be capital.
Ex:- total(), display(), totalMarks, netSalary(), getData()
2. All classes and interfaces should start with capital letter, for more then one word the second word’s
first character should be capital.
Ex:- Student, HelloJava
3. Constant variables should be in capital letters and for more than one word underscore is used. Ex:-
MAX, TOTAL_VALUE
4. Package name should be in lowercase
only. Ex:- mypack

Constants in Java:

A constant is a variable which cannot have its value changed after declaration. It uses the 'final' keyword.

Syntax:
Modifier final dataType variableName = value; //variable constant
Modifier static final dataType variableName = value; //constant variable

Special Symbols:
The following special symbols are used in Java having some special meaning and thus, cannot be used for
some other purpose.
[] () {}, ; * =
1. Brackets[]: Opening and closing brackets are used as array element reference. These indicate
single and multidimensional subscripts.
2. Parentheses(): These special symbols are used to indicate function calls and function parameters.
3. Braces{}: These opening and ending curly braces marks the start and end of a block of code
containing more than one executable statement.
4. Comma (, ): It is used to separate more than one statements like for separating parameters in
function calls.
5. Semicolon: It is an operator that essentially invokes something called an initialization list.
6. Assignment operator: It is used to assign values
Operators:

Operator in java is a symbol that is used to perform operations. Java provides a rich set of operators to
manipulate variables. For example: +, -, *, / etc. All the Java operators can be divided into the following
groups
• Arithmetic Operators:
 Multiplicative : * / %
 Additive : + -

• Relational Operators
 Comparison : < > <= >=
 instanceof
 Equality : == !=
• Bitwise Operators
 bitwise AND : &
 bitwise exclusive OR : ^

 bitwise inclusive OR : |
 Shift operator: << >> >>>
• Logical Operators
 logical AND : &&
 logical OR : ||
 logical NOT : ~ !

• Assignment Operators: =
• Ternary operator: ? :
• Unary operator
 Postfix : expr++ exp--
 Prefix : ++expr --expr +expr -expr

Type Casting/type conversion:


Converting one primitive datatype into another is known as type casting (type conversion) in Java. We can cast
the primitive datatypes in two ways namely, Widening and, Narrowing.
Widening − Converting a lower datatype to a higher datatype is known as widening. In this case the
casting/conversion is done automatically therefore, it is known as implicit type casting. In this case both
datatypes should be compatible with each other.
Example
public class WideningExample {
public static void main(String args[]){
char ch = 'C';
int i = ch;
System.out.println(i);

Output
Integer value of the given character: 67

Narrowing − Converting a higher datatype to a lower datatype is known as narrowing. In this case the
casting/conversion is not done automatically, We need to convert explicitly using the cast operator “( )”
explicitly. Therefore, it is known as explicit type casting. In this case both datatypes need not be
compatible with each other.

Example
import java.util.Scanner;
public class NarrowingExample {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter an integer value: ");
int i = sc.nextInt();
char ch = (char) i;
System.out.println("Character value of the given integer: "+ch);
}
}

Output
Enter an integer value:
67
Character value of the given integer: C
Java Enum:
Enum in java is a data type that contains fixed set of constants.
It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
FRIDAY and SATURDAY) , directions (NORTH, SOUTH, EAST and WEST) etc. The java enum
constants are static and final implicitly. It is available from JDK 1.5.
Java Enums can be thought of as classes that have fixed set of constants.
Simple example of java enum
class EnumExample1
{
public enum Season { WINTER, SPRING, SUMMER, RAINY };
public static void main(String[] args)
{
for (Season s : Season.values())
System.out.println(s);
}
}
Output:
WINTER
SPRING
SUMMER
RAINY
Control flow Statements:
In java, the default execution flow of a program is a sequential order. But the sequential order of
execution flow may not be suitable for all situations. Sometimes, we may want to jump from line to
another line, we may want to skip a part of the program, or sometimes we may want to execute a part of the
program again and again. To solve this problem, java provides control statements.

Types of Control Statements


In java, the control statements are classified as follows.
 Selection Control Statements ( Decision Making Statements )
 Iterative Control Statements ( Looping Statements )
 Jump Statements

Let's look at each type of control statements in java.

Selection Control Statements


In java, the selection statements are also known as decision making statements or branching statements.
The selection statements are used to select a part of the program to be executed based on a condition. Java
provides the following selection statements.

 if statement
 if-else statement
 if-else if statement
 nested if statement
 switch

statement Example:

import java.util.Scanner;
public class IfElseDemo
{
public static void main(String[] args)
{
Scanner read = new Scanner(System.in);
System.out.print("Enter any number: ");
int num = read.nextInt();
if((num % 2) == 0) {
System.out.println("Given number is EVEN number!!");
}
else {

System.out.println("Given number is ODD number!!");


}
}
}
Iterative Control Statements
In java, the iterative statements are also known as looping statements or repetitive statements. The iterative
statements are used to execute a part of the program repeatedly as long as the given condition is True.
Using iterative statements reduces the size of the code, reduces the code complexity, makes it more
efficient, and increases the execution speed. Java provides the following iterative statements.

 while statement
 do-while statement
 for statement
 for-each statement
Example:

public class ForEachTest {


public static void main(String[] args) { int[]
arrayList = {10, 20, 30, 40, 50}; for(int i :
arrayList) { System.out.println("i = " + i);
}
System.out.println("Statement after for-each!");
}}
Jump Statements
In java, the jump statements are used to terminate a block or take the execution control to the next iteration.
Java provides the following jump statements.

 break
 continue
 return

break:

Continue:
Introduction of classes:

A class is a group of objects which have common properties. It is a template or blueprint from which
objects are created. It is a logical entity. It can't be physical.
A class in Java can contain:
o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface

General form of class:


A class is declared by use of the class keyword. The general form of a class definition is shown here:
class ClassName
{
VariableDeclaration-1;
VariableDeclaration-2;
VariableDeclaration-3;

VariableDeclaration-n;

returnType methodname-1([parameters list])


{
body of the method…
}
returnType methodname-2([parameters list])
{
body of the method…
}

returnType methodname-3([parameters list])


{
body of the method…
}
}// end of class

The data, or variables, defined within a class are called instance variables. The code is contained within
methods. Collectively, the methods and variables defined within a class are called members of the class. In
most classes, the instance variables are acted upon and accessed by the methods defined for that class.
Thus, it is the methods that determine how a class’ data can be used.
Example:
class Demo
{
int x=5;
void display()
{
System.out.println(“x value is: ”+x);
}}

Creating Objects:
An object in Java is essentially a block of memory that contains space to store all the instance variables.
Creating an object also known as instantiating an object. Objects in Java are created using the new
operator. The new operator creates an object of the specified class and returns a reference to that object.
Syntax for object creation:
classname objectname; //declares a variable to hold the object reference
objectname = new classname( ); // Assigns the object reference to the variable

Accessing class Members:


To access members (fields and the methods) of an object use the dot (.) operator together with the reference
to an object.
The general syntax is as follows:
objectname.variablename;
objectname.methodname(parameter-list);
Example:

class Demo
{
int x;
int display()
{
System.out.println("X value is: "+x);
return 0;
}
public static void main(String args[])
{
Demo D1=new Demo();
D1.x=10;
D1.display();
}
}
Output:
X value is: 10

Assigning Object Reference Variables


When you assign one object reference variable to another object reference variable, we are not creating a
copy of the object; we are only making a copy of the reference
Student s1=new Student();
Student s2=s1;

s1 Name: null
Student Objects
s2 Idno: 0

class Student
{
String name;
int idno;
public static void main(String args[])
{
Student s1=new Student();//create and initialize object

//Assigning Object Reference Variables


Student s2=s1;

System.out.println("Name: "+s2.name);
System.out.println("Idno: "+s2.idno);
}
}
Output:

Name: null
Idno: 0

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

Method Declaration

The method declaration provides information about method attributes, such as visibility, return-type, name,
and arguments. It has six components that are known as method header, as we have shown in the
following figure.
Method Signature: Every method has a method signature. It is a part of the method declaration. It
includes the method name and parameter list.

Access Specifier: Access specifier or modifier is the access type of the method. It specifies the visibility of
the method. Java provides four types of access specifier:

o Public: The method is accessible by all classes when we use public specifier in our application.
o Private: When we use a private access specifier, the method is accessible only in the classes in
which it is defined.
o Protected: When we use protected access specifier, the method is accessible within the same
package or subclasses in a different package.
o Default: When we do not use any access specifier in the method declaration, Java uses default
access specifier by default. It is visible only from the same package only.

Return Type: Return type is a data type that the method returns. It may have a primitive data type, object,
collection, void, etc. If the method does not return anything, we use void keyword.

Method Name: It is a unique name that is used to define the name of a method. It must be corresponding
to the functionality of the method. Suppose, if we are creating a method for subtraction of two numbers, the
method name must be subtraction(). A method is invoked by its name.

Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of parentheses.
It contains the data type and variable name. If the method has no parameter, left the parentheses blank.

Method Body: It is a part of the method declaration. It contains all the actions to be performed. It is
enclosed within the pair of curly braces.

Types of Method
There are two types of methods in Java:
o Predefined Method
o User-defined Method

Predefined Method

In Java, predefined methods are the method that is already defined in the Java class libraries is known as
predefined methods. It is also known as the standard library method or built-in method. We can directly
use these methods just by calling them in the program at any point. Some pre-defined methods
are length(), equals(), compareTo(), sqrt(), etc. When we call any of the predefined methods in our
program, a series of codes related to the corresponding method runs in the background that is already
stored in the library.
Each and every predefined method is defined inside a class. Such as print() method is defined in
the java.io.PrintStream class. It prints the statement that we write inside the method. For
example, print("Java"), it prints Java on the console.

Example:

public class Demo


{
public static void main(String[] args)
{
// using the max() method of Math class
System.out.print("The maximum number is: " + Math.max(9,7));
}
}
Output:
The maximum number is: 9is

In the above example, we have used three predefined methods main(), print(), and max(). We have used
these methods directly without declaration because they are predefined. The print() method is a method
of PrintStream class that prints the result on the console. The max() method is a method of the Math class
that returns the greater of two numbers.

User-defined Method

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

How to Create a User-defined Method

Let's create a user defined method that checks the number is even or odd. First, we will define the method.
import java.util.Scanner;
public class EvenOdd
{
public static void main (String args[])
{
//creating Scanner class object
Scanner scan=new Scanner(System.in);
System.out.print("Enter the number: ");
//reading value from user
int num=scan.nextInt();
//method calling
findEvenOdd(num);
}
//user defined method
public static void findEvenOdd(int num)
{
//method body
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}
}
Output:
Enter the number: 45
num is odd

Constructor:
A class contains constructors that are invoked to create objects from the class blueprint. Constructor
declarations look like method declarations—except that they use the name of the class and have no return
type. A constructor initializes an object immediately upon creation.
Rules with Constructors
 Constructor name must be the same as its class name
 A Constructor must have no explicit return type
 A Java constructor cannot be abstract, static, final, and synchronized
 Constructors should be public.
 Constructors cannot be inherited.
 They can be overloaded. Many constructors with the same name can be defined.
Types of Constructors:
o Default constructor: is the type of constructor with out any argument.
o Parameterized Constructor: is a constructor with one or more argument.
Default Constructor:
A constructor that have no parameter is known as default constructor.
Syntax of default constructor:
classname(){}
Example of default constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of
object creation.
Class Bike1
{
Bike1(){
System.out.println("Bike is created");
}
public static void main(String args[])
{
Bike1 b=new Bike1();
}}
Output:Bike is created

Parameterized constructor:
A parameterized constructor is a constructor that accepts some parameters. Any number of parameters can
be specified. Parameterized constructors are mostly used to initialize the instance fields of a class.
Example:
class Demo
{
int num;
String name;
Demo()
{
System.out.print("default constructor");
}
Demo(int n,String name1)
{
num=n;
name=name1;
}
void display()
{
System.out.println(" "+num+" "+name);
}
}
class ConstructorDemo
{
public static void main(String args[])
{
Demo d=new Demo ();
Demo d1=new Demo(1001,"shyam");
d.display();
d1.display();
}
}
Output:
default constructor
0 null
1001 shyam

Static Keyword
The static keyword in Java is used for memory management mainly. We can apply static keyword
with variables, methods, blocks and nested classes. The static keyword belongs to the class than an
instance of the class.
The static can be:
o Variable (also known as a class variable)
o Method (also known as a class method)
o Block

Static variable
If you declare any variable as static, it is known as a static variable.
 The static variable can be used to refer to the common property of all objects (which is not unique
for each object), for example, the company name of employees, college name of students, etc.
 The static variable gets memory only once in the class area at the time of class loading.
Advantages of static variable
It makes your program memory efficient (i.e., it saves memory).

Understanding the problem without static variable


class
Student{ int
rollno;
String name;
String college="SVREC";
}
Suppose there are 500 students in our college, now all instance data members will get memory each time
when the object is created. All students have its unique rollno and name, so instance data member is good
in such case. Here, "college" refers to the common property of all objects. If we make it static, this field
will get the memory only once.

Example of static variable


class Student{
int rollno;//instance variable
String name;
static String college ="SVREC";//static variable
//constructor
Student(int r, String n)
{ rollno = r;
name = n;
}
//method to display the values
void display (){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to show the values of objects
public class TestStaticVariable1{
public static void main(String args[])
{ Student s1 = new Student(101,"Shyam");
Student s2 = new Student(102,"vinod");
//we can change the college of all objects by the single line of code
//Student.college="SVREC";
s1.display();
s2.display();
}
}

Output:
101 Shyam SVREC
102 vinod SVREC
Program of the counter without static variable and with static variable:

//Java Program to demonstrate the use of an insta//Java Program to illustrate the use of static variab
nce variable which get memory each time when le which is shared with all objects.
we create an object of the class. class Counter{
class Counter{ static int count=0;//will get memory only once an
int count=0;//will get memory each time when the d retain its value
instance is created
Counter(){ count+ Counter(){
+;//incrementing value count++;//incrementing the value of static variable
System.out.println(count);
} System.out.println(count);
}
public static void main(String args[]){ public static void main(String args[]){
//Creating objects //creating objects
Counter c1=new Counter(); Counter c1=new Counter();
Counter c2=new Counter(); Counter c2=new Counter();
Counter c3=new Counter(); Counter c3=new Counter();
} }
} }
Output: Output:
1 1
1 2
1 3

Static method

If you apply static keyword with any method, it is known as static method.
 A static method belongs to the class rather than the object of a class.
 A static method can be invoked without the need for creating an instance of a class.
 A static method can access static data member and can change the value of it.

Example of static method


//Java Program to demonstrate the use of a static method.
class Student{
int rollno;
String name;
static String college = "SVR Engg College";
//static method to change the value of static variable
static void change(){
college = "SVREC";
}
//constructor to initialize the variable
Student(int r, String n){
rollno = r;
name = n;
}
//method to display values
void display(){
System.out.println(rollno+" "+name+" "+college);
}
}
//Test class to create and display the values of object
public class TestStaticMethod{
public static void main(String args[]){
Student.change();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method
s1.display();
s2.display();
s3.display();
}
}
Output:
111 Karan SVREC
222 Aryan SVREC
333 Sonoo SVREC

Restrictions for the static method


There are two main restrictions for the static method. They are:
 The static method cannot use non static data member or call non-static method directly.
 this and super cannot be used in static
context. class A{
int a=40;//non static

public static void main(String args[]){


System.out.println(a);
}
}
Output:
Compile Time Error

Q) Why is the Java main method static?


Ans) Because the object is not required to call a static method. If it were a non-static method, JVM creates
an object first then call main() method that will lead the problem of extra memory allocation.

static block
o Is used to initialize the static data member.
o It is executed before the main method at the time of classloading.

Example of static block


class A2{
static{System.out.println("static block is invoked");}
public static void main(String args[])
{ System.out.println("Hello main");
}
}
Output:
static block is invoked
Hello main

this Keyword
There can be a lot of usage of Java this keyword. In Java, this is a reference variable that refers to the
current object.

Usage of Java this keyword: Here is given the 6 usage of java this keyword.

1. this can be used to refer current class instance variable.


2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.
1. this can be used to refer current class instance variable.
The this keyword can be used to refer current class instance variable. If there is ambiguity between the
instance variables and parameters, this keyword resolves the problem of ambiguity.
Understanding the problem without this keyword
Let's understand the problem if we don't use this keyword by the example given below:
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new
Student(112,"sumit",6000f); s1.display();
s2.display();
}}

Output:
0 null 0.0
0 null 0.0
In the above example, parameters (formal arguments) and instance variables are same. So, we are using
this keyword to distinguish local variable and instance variable.

Solution of the above problem by this keyword

class Student{
int rollno;
String name;
float fee;
Student(int rollno,Stringname,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Output:
111 ankit 5000.0
112 sumit 6000.0
Note:If local variables (formal arguments) and instance variables are different, there is no need to use this
keyword.
2. this: to invoke current class method
You may invoke the method of the current class by using the this keyword. If you don't use the this
keyword, compiler automatically adds this keyword while invoking the method. Let's see the example
class A{
void m(){System.out.println("hello m");}
void n(){
System.out.println("hello n");
//m();//same as this.m()
this.m();
}
}
class TestThis4{
public static void main(String args[])
{ A a=new A();
a.n();
}}
Output:
hello n
hello m

3. this() can be used to invoked current class constructor.

The this() constructor call can be used to invoke the current class constructor (constructor chaining). This
approach is better if you have many constructors in the class and want to reuse that constructor.

class Student{
int id;
String name;
String city;
Student(int id,String name)
{ this.id = id;
this.name = name;
}
Student(int id,String name,String city){
this(id,name);//now no need to initialize id and name
this.city=city;
}
void display(){System.out.println(id+" "+name+" "+city);}
public static void main(String args[]){
Student e1=new Student(111,"karan");
Student e2 =new Student(222,"Aryan","delhi");
e1.display();
e2.display();
}}
Output:
111 Karan null
222 Aryan delhi
Rule: Call to this() must be the first statement in constructor.

Arrays:

Normally, an array is a collection of similar type of elements which has contiguous memory location.

Java array is an object which contains elements of a similar data type. Additionally, the elements of an
array are stored in a contiguous memory location. It is a data structure where we store similar elements. We
can store only a fixed set of elements in a Java array.

Array in Java is index-based, the first element of the array is stored at the 0th index, and 2nd element is
stored on 1st index and so on.

Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need to use the
sizeof operator.

In Java, array is an object of a dynamically generated class. Java array inherits the Object class, and
implements the Serializable as well as Cloneable interfaces. We can store primitive values or objects in an
array in Java. Like C/C++, we can also create single dimentional or multidimentional arrays in Java.

Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.

Advantages

o Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
o Random access: We can get any data located at an index position.

Disadvantages

o Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework is used in Java which grows automatically.
Types of Array in java There
are two types of array.
o Single Dimensional Array
o Multidimensional Array

Single Dimensional Array in


Java

Syntax to Declare an Array in Java

1. dataType[] arr; (or)


2. dataType []arr; (or)
3. dataType arr[];

Instantiation of an Array in

Java arrayRefVar=new

datatype[size];

Example of Java Array


Let's see the simple example of java array, where we are going to declare, instantiate, initialize and traverse an
array.
//Java Program to illustrate how to declare, instantiate, initialize
//and traverse the Java array.
class Testarray{
public static void main(String args[]){
int a[]; //declaration
a=new int[5]; //instantiation
a[0]=10; //initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
int b[]={33,3,4,5,6};//declaration, instantiation and initialization
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]+” “+b[i]);
}}
Output:
10 33
20
70
40
50

Multidimensional Array in Java:


In such case, data is stored in row and column based index (also known as matrix form).

Syntax to Declare Multidimensional Array in Java:


dataType[][] arrayRefVar; (or) dataType
[][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in Java


int[][] arr=new int[3][3];//3 row and 3 column

Example of Multidimensional Java Array


Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.
//Java Program to illustrate the use of multidimensional array
class Testarray1{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}
Output:
1 2 3
2 4 5
4 4 5

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

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

Advantage of method overloading


Method overloading increases the readability of the program.

Different ways to overload the method


There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type
Note: In Java, Method Overloading is not possible by changing the return type of the method only.

1) Method Overloading: changing no. of arguments

In this example, we have created two methods, first add() method performs addition of two numbers and
second add method performs addition of three numbers.
class Adder{
int add(int a,int b){return a+b;}
int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args)
{ Adder ob=new Adder();
System.out.println(ob.add(11,11));
System.out.println(ob.add(11,11,11));
}}
Output:
22
33

2) Method Overloading: changing data type of arguments

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

class Adder{
int add(int a, int b){return a+b;}
double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args)
{ Adder ob=new Adder();
System.out.println(ob.add(11,11));
System.out.println(ob.add(12.3,12.6));
}}
Output:
22
24.9

Constructor Overloading:
Constructor overloading is a technique in Java in which a class can have any number of constructors that
differ in parameter lists. The compiler differentiates these constructors by taking into account the number
of parameters in the list and their type.

Example:

class Box
{
double width, height, depth;
// constructor used when all dimensions specified
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box()
{
width = height = depth = 0;
}
// constructor used when cube is created
Box(double len)
{
width = height = depth = len;
}
// compute and return volume
double volume()
{
return width * height * depth;
}
}

// Driver code
public class Test
{
public static void main(String args[])
{
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println(" Volume of mybox1 is " + vol);

// get volume of second box


vol = mybox2.volume();
System.out.println(" Volume of mybox2 is " + vol);

// get volume of cube


vol = mycube.volume();
System.out.println(" Volume of mycube is " + vol);
}
}

Output:

Volume of mybox1 is 3000.0


Volume of mybox2 is 0.0
Volume of mycube is 343.0
Difference between constructor and method in Java

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

Java Constructor Java Method

A constructor is used to initialize the state of an A method is used to expose the behavior of an
object. object.

A constructor must not have a return type. A method must have a return type.

The constructor is invoked implicitly. The method is invoked explicitly.

The Java compiler provides a default constructor The method is not provided by the compiler in
if you don't have any constructor in a class. any case.

The constructor name must be same as the class The method name may or may not be same as the
name. class name.

Parameter passing:

Passing primitive datatypes t methods:


Primitive data types represent single values.
There are passed to methods by value. This means when we pass primitive data types to methods, a copy of
those will be passed to methods. Therefore, any changes made to the inside the method will not affect them
outside the method. This is called Call by value.

Example of call by value in java:


class CallByValue {
int a, b;

CallByValue(int x, int y) {
a = x;
b = y;
}
void swap(int a, int b) {
int temp;
temp = a;
a = b;
b = temp;
}
public static void main(String args[]) {

CallByValue p = new CallByValue(10, 20);


System.out.println("Before swap:a= " + p.a + "b= " + p.b);
p.swap(p.a, p.b);
System.out.println("After swap:a= " + p.a + "b= " + p.b);
}
}
Passing object to method:
Pass by reference is not valid in java.
In Java one possible solution is to use only object by value to a method and it takes two variables a, b, and
interchange their values in the object.
class Reference
{ int a, b;

Reference(int x, int y) {
a = x;
b = y;
}

void swap(Reference ref)


{ int temp;
temp = ref.a;
ref.a = ref.b;
ref.b = temp;
}

public static void main(String args[]) {

Reference r = new Reference(10, 20);


System.out.println("Before swap: a= " + r.a + " b= " + r.b);
r.swap(r);
System.out.println("After swap: a= " + r.a + " b= " + r.b);
}
}
Key Points:
1. Java passes the arguments both primitives and the copy of object reference by value.
2. Java never passes the object itself.
3. In real-time project, we pass class objects as parameters to method call in Java.
4. Call by value uses copies of data, while call by reference uses memory addresses or references to
the actual data.

Garbage Collection

In java, garbage means unreferenced objects.

Garbage collection in Java is the process by which Java programs perform automatic memory
management. Java programs compile to bytecode that can be run on a Java Virtual Machine, or JVM.
When Java programs run on the JVM, objects are created on the heap, which is a portion of memory
dedicated to the program. Eventually, some objects will no longer be needed. The garbage collector finds
these unused objects and deletes them to free up memory.
To do so, we were using free() function in C language and delete() in C++. But, in java it is performed
automatically. So, java provides better memory management.

Advantage of Garbage Collection


o It makes java memory efficient because garbage collector removes the unreferenced objects from
heap memory.
o It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra
efforts.
How can an object be unreferenced?
There are many ways:
o By null the reference
o By assigning a reference to another
o By anonymous object etc.
1) By nulling a reference:
Employee e=new Employee();
e=null;
2) By assigning a reference to another:
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for garbage collection
3) By anonymous object:
new Employee();

finalize() method:

The finalize() method is invoked each time before the object is garbage collected. This method can be used to
perform cleanup processing. This method is defined in Object class as:
protected void finalize(){}
Note: The Garbage collector of JVM collects only those objects that are created by new keyword. So if you
have created any object without new, you can use finalize method to perform cleanup processing
(destroying remaining objects).

gc() method:

The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is found in
System and Runtime classes.
public static void gc(){}
Note: Garbage collection is performed by a daemon thread called Garbage Collector(GC). This
thread calls the finalize() method before object is garbage collected.
Simple Example of garbage collection in java
public class
TestGarbage1{ int a,b;
TestGarbage1()
{ a=10;
b=20;
}
public void finalize(){System.out.println("object is garbage collected");}
public static void main(String args[])
{ TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=s1;
new TestGarbage1();
System.gc();
} }
Output:
object is garbage collected
object is garbage collected
object is garbage collected

Note: Neither finalization nor garbage collection is

guaranteed. Recursion:
Recursion in java is a process in which a method calls itself continuously. A method in java that calls itself
is called recursive method.
It makes the code compact but complex to understand.
Syntax:
returntype methodname()
{
//code to be executed methodname();//calling same method
}

Example:

// A simple example of recursion(factorial).

class Factorial
{
// this is a recursive function
int fact(int n)
{ int result;
if(n==1)
return 1;
result = fact(n-1) * n;
return result;
}}
class Recursion
{
public static void main(String args[])
{
Factorial f = new Factorial();
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}}
The output from this program is shown here:
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120
String class:
String is a sequence of characters. But in Java, a string is an object that represents a sequence of
characters. The java.lang.String class is used to create string object.
String is final class in java.
public final class String extends Object implements Serializable, Comparable<String>, CharSequence.

There are two ways to create a String object:


1. By string literal: Java String literal is created by using double
quotes. For Example: String s=“Welcome”;
2. By new keyword: Java String is created by using a keyword
“new”. For example: String s=new String (“Welcome”);
It creates two objects (in String pool and in heap) and one reference variable where the variable‘s’ will
refer to the object in the heap.

Java String Pool:


Java String pool refers to collection of Strings which are stored in heap memory. In this, whenever
a new object is created,
1) String pool first checks whether the object is already present in the pool or not.
2) If it is present, then same reference is returned to the variable.
3) Else new object will be created in the String pool and the respective reference will be returned.
Immutable String in Java:
In java, string objects are immutable. Immutable simply means un-modifiable or unchangeable.
 Once string object is created its data or state can't be changed but a new string object is created.
 Let's try to understand the immutability concept by the example given
below: class Simple
{
public static void main(String args[])
{ String s="Sachin";
s.concat(" Tendulkar"); //concat() method appends the string at the end
System.out.println(s); //will print Sachin because strings are immutable objects
}}

Methods of String class in Java:


java.lang.String class provides a lot of methods to work on string. By the help of these methods, we can
perform operations on string such as trimming, concatenating, converting strings etc.
s.no Method Description
1 public boolean equals(Object anObject) Compares this string to the specified object.
2 public boolean equalsIgnoreCase(String another) Compares this String to another String, ignoring case.
3 public String concat(String str) Concatenates the specified string to the end of this string.
4 public int compareTo(String str) Compares two strings and returns int
5 public int compareToIgnoreCase(String str) Compares two strings, ignoring case differences.
6 public String substring(int beginIndex) Returns a new string that is a substring of this string.
7 public String substring(int beginIndex,int Returns a new string that is a substring of this string.
endIndex)
8 public String toLowerCase() Converts all of the characters in this String to lower case.
9 public String toUpperCase() Converts all of the characters in this String to upper case.
10 public String trim() Returns a copy of the string, with leading and trailing
whitespace omitted.
11 public boolean startsWith(String prefix) Tests if this string starts with the specified prefix.
12 public boolean endsWith(String suffix) Tests if this string ends with the specified suffix.
13 public char charAt(int index) Returns the char value at the specified index.
14 public int length() Returns the length of this string.
15 public String intern() Returns a canonical representation for the string object.
16 public byte[] getBytes() Converts string into byte array.
Unit2: Inheritance, Packages, Interfaces

Inheritance: Basics, Using Super, Creating Multilevel hierarchy, Method overriding, Dynamic Method
Dispatch, Using Abstract classes, Using final with inheritance, Object class
Packages: Basics, Finding packages and CLASSPATH, Access Protection, Importing packages.
Interfaces: Definition, Implementing Interfaces, Extending Interfaces, Nested Interfaces, Applying Interfaces,
Variables in Interfaces.

Inheritance

Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent
object. It is an important part of OOPs (Object Oriented programming system).

The idea behind inheritance in Java is that we can create new classes that are built upon existing classes. When
we inherit from an existing class, we can reuse methods and fields of the parent class. Moreover, we can add new
methods and fields in your current class also.

Why use inheritance in java


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

Terms used in Inheritance


o Class: A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created.
o 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.
o 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.
o Reusability: As the name specifies, reusability is a mechanism which facilitates us to reuse the fields and
methods of the existing class when we create a new class. We can use the same fields and methods
already defined in the previous class.

General format for Inheritance


class superclass
{
// superclass data variables
// superclass member functions
}
class subclass extends superclass
{
// subclass data variables
// subclass member functions
}
Inheritance uses the “extends” keyword to create a derived class by reusing the base class code.

Extends keyword in JavaThe extended keyword extends a class and is an indicator that a class is being
inherited by another class. When we say class B extends a class A, it means that class B is inheriting the
properties(methods, attributes) from class A. Here, class A is the superclass or parent class and class B is the
subclass or child class.
Types of inheritance:

The different 5 types of Inheritance in java are:


 Single inheritance.
 Multi-level inheritance.
 Multiple inheritance.
 Hierarchical Inheritance.
 Hybrid Inheritance.

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

Single Inheritance:

When a class inherits another class, it is known as a single inheritance. It means that the properties of the base
class are acquired by the derived class.

Example:
class A
{
int a, b;
void display()
{
System.out.println(“Inside class A values =”+a+” ”+b);
}
}
class B extends A
{
int c;

void show()
{
System.out.println(“Inside Class B values=”+a+” “+b+” “+c);
}
}
class SingleInheritance
{
public static void main(String args[])
{
B obj = new B(); //derived class object
obj.a=10; Output:
obj.b=20; Inside class A values =10 20
obj.c=30; Inside Class B values=10 20 30
obj.display();
obj.show();
}
}
Note:
Even though a subclass includes all of the members of its super class, it cannot access those members who are
declared as Private in super class.

Super Keyword:

The super keyword in Java is a reference variable which is used to refer immediate parent class object.
Whenever we create the instance of subclass, an instance of parent class is created implicitly which is referred by
super reference variable.

Usage of Java super Keyword


1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

1) super can be used to refer immediate parent class instance variable.


We can use super keyword to access the data member or field of parent class. It is used if parent class and child
class have same fields.
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
Output:
black
white
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();

d.printColor();
}}
In the above example, Animal and Dog both classes have a common property color. If we print color
property, it will print the color of current class by default. To access the parent property, we need to use super
keyword.

2) super can be used to invoke parent class method


The super keyword can also be used to invoke parent class method. It should be used if subclass contains the
same method as parent class. In other words, it is used if method is overridden

// Java code to show use of super keyword with variables


// Base class vehicle
class Vehicle {
int maxSpeed = 120;

void display() {
// print maxSpeed of base class (vehicle)
System.out.println("vehicle class display");
}
Output:
}
vehicle class display
// sub class Car extending vehicle
car class display
class Car extends Vehicle {
Maximum Speed: 120
int maxSpeed = 180;

void display() {
// print maxSpeed of base class (vehicle)
super.display();
System.out.println("car class display");
System.out.println("Maximum Speed: " + super.maxSpeed);
}
}
// Driver Program
class Test {
public static void main(String[] args) {
Car small = new Car();
small.display();
}
}

3) super is used to invoke parent class constructor.

The super keyword can also be used to invoke the parent class constructor.

class A
{
int a;
A(int a)
{
this.a=a;
System.out.println("a="+a);
}
}
class B extends A
{
int b;
B(int a,int b)
{
super(a);
System.out.println("b="+b);
}
}

class TestSuper
{
public static void main(String args[])
{
B obj=new B(4,5);
}
}
Output:
a=4
b=5

Multilevel Inheritance:

In simple inheritance a subclass or derived class derives the properties from its parent class, but in multilevel
inheritance a subclass is derived from a derived class. One class inherits only single class. Therefore, in
multilevel inheritance, every time ladder increases by one. The lower most class will have the properties of all
the super classes’
It is common that a class is derived from another derived class. The class student serves as a base class for the
derived class marks, which in turn serves as a base class for the derived class percentage. The class marks is
known as intermediates base class since it provides a link for the inheritance between student and percentage.
The chain is known as inheritance path. When this type of situation occurs, each subclass inherits all of the
features found in all of its super classes. In this case, percentage inherits all aspects of marks and student.

Example:

class student {
int rollno;

String name;

student(int r, String n)

{
rollno = r;
name = n;
}
void dispdatas() {
System.out.println("Rollno = " + rollno);
System.out.println("Name = " + name);
}
}
class marks extends student {
int total;

marks(int r, String n, int t) {


super(r, n); // call super class (student) constructor
total = t;
}
void dispdatam() {
dispdatas(); // call dispdatap of student class
System.out.println("Total = " + total);
}
}

class percentage extends marks {


int per;

percentage(int r, String n, int t, int p) {


super(r, n, t); // call super class(marks) constructor
per = p;
}
void dispdatap() {
dispdatam(); // call dispdatap of marks class
System.out.println("Percentage = " + per);
}
}
class Multi_Inhe {
public static void main(String args[]) {
percentage stu = new percentage(102689, "RATHEESH", 350, 70); // call constructor percentage
stu.dispdatap(); // call dispdatap of percentage class
}
} Output:
B class object
Output: method of Class A
Rollno = 102689 method of Class B
Name = RATHEESH C class object
Total = 350 method of Class A
Percentage = 70 method of Class C
D class object
Hierarchical Inheritance: method of Class A
method of Class D
In Hierarchical Inheritance, one class serves as a superclass (base A class object class) for
more than one sub class. In other words the process of deriving method of Class A multiple
subclasses from the same superclass is known as Hierarchical inheritance.
Example:

class A {
public void methodA() {
System.out.println("method of Class A");
}
}
class B extends A {
public void methodB() {
System.out.println("method of Class B");
}
}
class C extends A {
public void methodC()
{
System.out.println("method of Class C");
}
}
class D extends A {
public void methodD() {
System.out.println("method of Class D");

}
}
class JavaExample {
public static void main(String args[]) {
B obj1 = new B();
C obj2 = new C();
D obj3 = new D();
System.out.println("B class object");
obj1.methodA();
obj1.methodB();
System.out.println("C class object");
obj2.methodA();
obj2.methodC();
System.out.println("D class object");
obj3.methodA();
obj3.methodD();
System.out.println("A class object");
A obj4 = new A();
obj4.methodA();
}
}

Multiple Inheritance:
Multiple Inheritance” refers to the concept of one class extending (Or inherits) more than one base class. The
inheritance we learnt earlier had the concept of one base class or parent. The problem with “multiple inheritance”
is that the derived class will have to manage the dependency on two base classes.

Note:
*To reduce the complexity and simplify the language, multiple inheritance is not supported in java.
*Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B
classes have the same method and you call it from child class object, there will be ambiguity to call the method
of A or B class.
*Since compile-time errors are better than runtime errors, Java renders compile-time error if we inherit 2 classes.
So whether we have same method or different, there will be compile time error.

Hybrid inheritance

A hybrid inheritance is a combination of more than one types of inheritance. For example when class A and B
extends class C & another class D extends class A then this is a hybrid inheritance, because it is a combination of
single and hierarchical inheritance.
Polymorphism:

Ability of an object to take many forms.


An object in java that passes IS-A test polymorphic and since all objects extends Object class hence all
objects are polymorphic.
Polymorphism is two types:
1. Compile time polymorphism (static polymorphism)
2. Run time polymorphism (dynamic polymorphism / dynamic method dispatch / virtual method invocation)

add(a,b) add(int a,int b)


add(a,b,c) add(double a,double b)

Note:
Overloading is not possible by changing the return type only. It gives compile time error due to ambiguity.

Type promotion:
Smaller data type is promoted to bigger once if no matching data type is found
Eg: add(int a,long b)
Call>add(4,5) the 5 is promoted to long data type.

Method Overriding:

In a class hierarchy, when a method in a subclass has the same name and type signature as a method in its
superclass, then the method in the subclass is said to override the method in the superclass.

 When an overridden method is called from within its subclass, it will always refer to the version of
that method defined by the subclass. The version of the method defined by the superclass will be
hidden.
 Method overriding is used for runtime polymorphism.
 Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at
run time, rather than compile time.

Rules for Method Overriding:

1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance)

Dynamic method dispatch:

Dynamic method dispatch is also known as run time polymorphism.


It is the process through which a call to an overridden method is resolved at runtime.
This technique is used to resolve a call to an overridden method at runtime rather than compile time.
To properly understand Dynamic method dispatch in Java, it is important to understand the concept of upcasting
because dynamic method dispatch is based on upcasting.

upcasting : It is a technique in which a superclass reference variable


refers to the object of the subclass

example:

class Animal{}
class Dog extends Animal{}
Animal a=new
Dog();//upcasting
In the above example, we've created two classes, named
Animal(superclass) & Dog(subclass).
While creating the object 'a', we've taken the reference variable of the parent class(Animal), and the object
created is of child class(Dog).

Example to demonstrate the use of Dynamic method dispatch :


 In the below code, we've created two classes: Phone & SmartPhone .
 The Phoneis the parent class and the SmartPhoneis the child class.
 The method on() of the parent class is overridden inside the child class.
 Inside the main() method, we've created an of the class by taking the reference
object obj Smartphone()
of the Phone() class.
 When obj.on() will be executed, it will call on() method of the SmartPhone()
class because the
the SmartPhone() .
reference variable obj is pointing towards the object of class Program:

class Phone {
public void showTime() {
System.out.println("Time is 8 am");
}
public void on() {
System.out.println("Turning on Phone...");
}
}

class SmartPhone extends Phone {


public void music() {
System.out.println("Playing music...");
}
public void on() {
System.out.println("Turning on SmartPhone...");
}
}

public class CWH {


public static void main(String[] args) {

Phone obj = new SmartPhone(); // upcasting


// SmartPhone obj2 = new Phone(); // Not allowed

obj.showTime();
obj.on();
// obj.music(); Not
Allowed obj = new
Phone(); obj.on();
}
}
Output:

Time is 8 am
Turning on SmartPhone...
Turning on Phone...

Why can we not override static method?


It is because the static method is bound with class whereas instance method is bound with an object. Static
belongs to the class area, and an instance belongs to the heap area.

Abstraction in Java

Abstraction is a process of hiding the implementation details and showing only functionality to the user.

Another way, it shows only essential things to the user and hides the internal details, for example, sending SMS
where we type the text and send the message. We don't know the internal processing about the message delivery.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java


1. Abstract class (0 to 100%)
2. Interface (100%)

Concrete class:
 A concrete class is one which contains fully defined methods. Defined methods are also known as
implemented or concrete methods. With respect to concrete class, we can create an object of that
class directly.

Abstract class:
 A class that is declared using “abstract” keyword is known as abstract class. It can have abstract
methods (methods without body) as well as concrete methods (regular methods with body). A
normal class(non-abstract class) cannot have abstract methods.
 An abstract class is one which contains some defined methods and some undefined methods. Undefined
methods are also known as unimplemented or abstract methods. Abstract method is one which does not
contain any definition. To make the method as abstract we have to use a keyword called “abstract” before
the function declaration.
In java, the following some important observations about abstract classes are as follows:
 An instance (object) of an abstract class cannot be created.
 Constructors are allowed.
 We can have an abstract class without any abstract method.
 There can be a final method in abstract class but any abstract method in class(abstract class) cannot be
declared as final or in simpler terms final method cannot be abstract itself as it will yield an error:
“Illegal combination of modifiers: abstract and final”
 We can define static methods in an abstract class
 We can use the abstract keyword for declaring top-level classes (Outer class) as well as inner
classes as abstract
 If a class contains at least one abstract method then compulsory should declare a class as abstract
 If the Child class is unable to provide implementation to all abstract methods of the Parent class then
we should declare that Child class as abstract so that the next level Child class should provide
implementation to the remaining abstract method.

Syntax for abstract method:


abstract return_type method_name (parameters list);

Example 1:
abstract class A
{
abstract void callme();
// concrete methods are still allowed in abstract classes
void callmetoo()
{
System.out.println("This is a concrete method.");
}
}
class B extends A
{ Output:
B's implementation of callme.
void callme()
This is a concrete method.
{
System.out.println("B's implementation of callme.");
}
}
class AbstractDemo
{
public static void main(String args[])
{
A b = new B();
b.callme();

b.callmetoo();
}}

Notice that no objects of class A are declared in the program. As mentioned, it is not possible to instantiate an abstract
class.
One other point: class A implements a concrete method called callmetoo()

Example 2:
abstract class Bike
{
static int speed=70;
Bike() //constructor
{
System.out.println("Bike is created");
}
abstract void run(); //abstrct method
static void runSpeed() //static method
{
System.out.println("Speed:"+speed);
}
final void changGear() //final method
{
System.out.println("Gear changed");
}
}
class Honda extends Bike{
void run()
{
System.out.println("Running safely");
}
}
abstract class Abstract{
Output:
public static void main(String[] args) {
Bike is created
Bike b=new Honda(); Running safely
b.run(); Speed:70
Bike.runSpeed(); Gear changed
b.changGear();
}
}

final key word:

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

final Variable – Once a variable is declared as final, it can be initialized during declaration or in the constructor.
And can never be changed during the course of the program. Hence static final variables are also called
constants.
If we make any variable as final, we cannot change the value of final variable(It will be constant).

Example:

public class Audi {


public final String EngineNumber;
public Audi(String EngineNumber){
this.EngineNumber = EngineNumber;
}
public static void main(String[] args) {
Audi audi = new Audi("ABCD1234");
audi.EngineNumber = "CDEF4568";
System.out.println("Engine Number : "+audi.EngineNumber);
}
}
Java Compiler throws an Error
The final field Audi.EngineNumber cannot be assigned.

final Method – Once a method is declared as final, it can never be overridden by any sub class that is inheriting
the method’s class.

Example:

public class Car {


public void brake(){
System.out.println("break in Car");
}
public final void accelerate()
{ System.out.println("accelerate in Car");
}
}
public class Audi extends Car {
public static void main(String[] args)
{
Audi audi = new Audi();
audi.accelerate();
audi.brake();
}

public void accelerate()


{ System.out.println("accelerate in Audi");
}
}
Java Compilation Error occurs
Cannot override the final method from Car

final Class – Once a class is declared as final, it can never be inherited.

Example:

final class Bike{}

class Honda1 extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda1 honda= new Honda1();
honda.run();
}
}
Java Compiler throws an Error

Cannot inherited the final class Bike

Object class:
Object class is present in java.lang package. Every class in Java is directly or indirectly derived from
the Object class. If a class does not extend any other class then it is a direct child class of Object and if
extends another class then it is indirectly derived. Therefore the Object class methods are available to all Java
classes. Hence Object class acts as a root of the inheritance hierarchy in any Java Program.

Method Description

public final Class getClass() returns the Class class object of this object. The Class class
can further be used to get the metadata of this class.

public int hashCode() returns the hashcode number for this object.

public boolean equals(Object obj) compares the given object to this object.
protected Object clone() throws creates and returns the exact copy (clone) of this object.
CloneNotSupportedException
public String toString() returns the string representation of this object.
public final void notify() wakes up single thread, waiting on this object's monitor.

public final void notifyAll() wakes up all the threads, waiting on this object's monitor.
public final void wait(long timeout)throws causes the current thread to wait for the specified
InterruptedException milliseconds, until another thread notifies (invokes notify() or
notifyAll() method).
public final void wait(long timeout,int causes the current thread to wait for the specified milliseconds
nanos)throws InterruptedException and nanoseconds, until another thread notifies (invokes
notify() or notifyAll() method).
public final void wait()throws causes the current thread to wait, until another thread notifies
InterruptedException (invokes notify() or notifyAll() method).

protected void finalize()throws Throwable is invoked by the garbage collector before object is being
garbage collected.

1. toString() method
The toString() provides a String representation of an object and is used to convert an object to a String.
The default toString() method for class Object returns a string consisting of the name of the class of which the
object is an instance, the at-sign character `@’, and the unsigned hexadecimal representation of the hash code
of the object. In other words, it is defined as:
// Default behavior of toString() is to print class name, then
// @, then unsigned hexadecimal representation of the hash code
// of the object
public String toString()
{
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
It is always recommended to override the toString() method to get our own String representation of Object.
Note: Whenever we try to print any Object reference, then internally toString() method is called.

Student s = new Student();


// Below two statements are equivalent
System.out.println(s);
System.out.println(s.toString());
2. hashcode():
It returns a hash value that is used to search objects in a collection. JVM(Java Virtual Machine) uses the
hashcode method while saving objects into hashing-related data structures like HashSet, HashMap, Hashtable,
etc. The main advantage of saving objects based on hash code is that searching becomes easy.
Note: Override of hashCode() method needs to be done such that for every object we generate a unique
number. For example, for a Student class, we can return the roll no. of a student from the hashCode() method
as it is unique.
Example:
// Java program to demonstrate working of
// hashCode() and toString()

public class Student {


static int last_roll =
100; int roll_no;

// Constructor
Student()
{
roll_no = last_roll;
last_roll++;
}
Output:
Student@64
// Overriding hashCode() Student@64
public int hashCode() { return roll_no; }

// Driver code
public static void main(String args[])
{
Student s = new Student();

// Below two statements are equivalent


System.out.println(s);
System.out.println(s.toString());
}
}

3. equals():
This method compares two objects and returns whether they are equal or not. It is used to compare the value of
the object on which the method is called and the object value which is passed as the parameter.

4. getClass():
It is used to return the class object of this object. Also, it fetches the actual runtime class of the object on
which the method is called. This is also a native method. It can be used to get the metadata of the this class.
Metadata of a class includes the class name, fields name, methods, constructor, etc.
Example:
public class MainClass {
public static void main(String[] args) {
Object s = new String("Hi");
Output:
Object i = new Integer(19); Class of Object s is : java.lang.String
Class c = s.getClass(); Class of Object i is : java.lang.Integer
Class d = i.getClass();
// for the String
System.out.println("Class of Object s is : " + c.getName());
// for the integer
System.out.println("Class of Object i is : " + d.getName());
}
}
5. clone():
The clone() method is used to create an exact copy of this object. It creates a new object and copies all the
data of the this object to the new object.
Example:
import java.util.*;

class MainClass implements Cloneable {

// declare variables
String name;
int age;

public static void main(String[] args) {

// create an object of Main class


MainClass obj1 = new MainClass();

// initialize name and age using obj1


obj1.name = "xyz";
obj1.age = 19;

// print variable
System.out.print(obj1.name); // xyz
System.out.println(" " + obj1.age); // 19

try {
Output:
xyz 19
// create clone of obj1
xyz 19
MainClass obj2 = (MainClass) obj1.clone();

// print the variables using obj2


System.out.print(obj2.name); // xyz
System.out.println(" " + obj2.age); // 19
} catch (Exception e) {
System.out.println(e);
}

}
}
JAVA - PACKAGES

What is package:
Packages are used in Java, in-order to avoid name conflicts and to control access of class, interface
and enumeration etc. A package can be defined as a group of similartypes of classes, interface,
enumeration or sub-package.
Using package it becomes easier to locate the related classes and it also provides a good structure for
projects with hundreds of classes and other files.
*Packages are those classes which contains methods without the main method in them.
*Packages are mainly used to reuse the classes which are already created/used in other program.
*We can define many numbers of classes in the same package.
Benefits of using package in java:
 Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
 Java package provides access protection.
 Java package removes naming collision.
 This package can be providing reusability of code.
 We can create our own package or extend already available package.

Java Packages: Types:

Built-in Package: Existing Java package forexample java.lang, java.util, java.io etc.

User-defined-package: Java package created by user to categorize their project's classes and
interface.

 Built Packages are provided for the programme in-order to reduce the burden.Some of the frequently used
built in packages are:

 These built in packages are placed in the package “java”.


 In order to use these packages/classes present in the package we need to import them in the current
program.
 The syntax for importing packages is: import java.util.*;
 The above statement tells the compiler that you need to import all the classes present in the “util”
package,which in turn present in the “java” package.
 The asterisk symbol tells the compiler to import all the classes in present in the util package.If you want
to import specific class then we need to mention the name of the class instead of the asterisk.
 For eg: import java.util.Scanner;

1. java.lang: language supports classes. These are classes that java compiler itself uses and therefore
automatically imported. They include classes for primitive types, strings, math, threads and exceptions.
2. java.util: language utility classes such as vectors, hash tables, random numbers, date etc.
3. java.io: input/output support classes. They provide the facility for input/output of data.
4. java.awt: set of classes for implementing graphical user interface. They include classes for windows,
buttons, lists
5. java.net: Classes for networking. They include classes for communicating with local computers as well
as with internal servers.
Access Protection:
Classes and packages are both means of encapsulating and containing the name space and scope of variables and
methods. Packages act as containers for classes and other subordinate packages. Classes act as containers for data
and code. The class is Java‘s smallest unit of abstraction.

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.

Access within within outside package by outside


Modifier class package subclass only package

Private

Default

Protected

Public
How to Create a package:
Creating a package in java is quite easy. Simply include a package command followed by name of the
package as the first statement in java source file.
Example:
package mypackage;
public class student
{
Statement;
}
The above statement will create a package name mypackage in the projectdirectory.
Java uses file system directories to store packages. For example the .java file for any class you define to be
part of mypackage package must be stored in a directory called mypackage. Additional points about
package:
 A package is always defined as a separate folder having the same name as the package name.
 Store all the classes in that package folder.
 All classes of the package which we wish to access outside the package mustbe declared public.
 All classes within the package must have the package statement as its firstline.
 All classes of the package must be compiled before use (So that they areerror free)

Example of Java packages:


Package mypack;
public class Simple
{

public static void main(String args[])


{
System.out.println("Welcome to package");
}
}
How to compile Java packages:
This is just like compiling a normal java program. If you are not using any IDE, you need to follow
the steps given below to successfully compile your packages:
1. java -d directory javafilename
example
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:


we 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.*:
//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello java");
}
}

//save by B.java
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new
A(); obj.msg();
}
}
Output: Hello java
2) Using packagename.classname:

If you import package.classname then only declared class of this package will beaccessible.

Example of package by import package.classname:


//save by A.java
package pack;

public class A

{
public void msg()
{
System.out.println("Hello");
}
}

//save by B.java package mypack;


import pack.A;
class B
{
public static void main(String args[])
{
A obj = new
A(); obj.msg();
}
}

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:


//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
//save by B.java
class B
{
public static void main(String args[])
{
pack.A obj = new pack.A(); //using fully qualified name
obj.msg();
}}
Output: Hello

Note: If we 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, we need to import the subpackage as well.

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.

package com.javatpoint.core;

class Simple{

public static void main(String args[])


{
System.out.println("Hello subpackage");
}
}
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, we want to put the class file of A.java source file in classes folderof c: drive.

For example:
//save as Simple.java
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}}

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 class file
resides.
e:\sources> set classpath=c:\classes;.;

e:\sources> java mypack.Simple

The -d switch specifies the destination where to put the generated class file. We can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If we want to keep
the package within the same directory, we can use . (dot).

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


INTERFACES IN JAVA

Introduction

An interface in java is a blueprint of a class.


It has static constants and abstract methods.
The interface in java is a mechanism to achieve abstraction.
There can be only abstract methods in the java interface not method body. It is used to achieve abstraction
and multiple inheritances in Java.
 Using the keyword interface, you can fully abstract a class’ interface from its implementation.
 That is, using interface, we can specify what a class must do, but not how it does it.
 Interfaces are syntactically similar to classes, but they lack instance variables, and their methods
are declared without any body.
 Interface do not have constructor.
 Variables can be declared inside of interface declarations.
 They are implicitly final and static, meaning they cannot be changed by the implementing class.
 They must also be initialized. All methods and variables are implicitly public.

Why do we use an Interface?

 It is used to achieve total abstraction.


 Since java does not support multiple inheritances in the case of class, by using an interface it can
achieve multiple inheritances.
 Any class can extend only 1 class but can any class implement infinite number of interface.
 It is also used to achieve loose coupling.
 Interfaces are used to implement abstraction. So the question arises why use interfaces when we have
abstract classes?
 The reason is, abstract classes may contain non-final variables, whereas variables in the interface are
final, public and static.
Declaring an Interface
An interface is defined much like a class.
This is the general form of an interface:
access interface name
{
return-type method-name1(parameter-
list); return-type method-name2(parameter-
list); type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-
list); type final-varnameN = value;
}

Since Java 8, interface can have default and static methods .


Internal addition by the compiler

The Java compiler adds public and abstract keywords before the interface method. Moreover, it adds public,
static and final keywords before data members.

In other words, Interface fields are public, static and final by default, and the methods are public and abstract.

The relationship between classes and interfaces

As shown in the figure given below, a class extends another class, an interface extends another interface, but
a class implements an interface.

Implementing Interfaces:

Once an interface has been defined, one or more classes can implement that interface. To implement an
interface, include the implements clause in a class definition, and then create the methods defined by the
interface. The general form of a class that includes the implements clause looks like this:
class classname [extends superclass] [implements interface [,interface...]]
{ // class-body }
If a class implements more than one interface, the interfaces are separated with a comma.

interface printable{
void print();
}
class A6 implements printable{ Output:
public void print(){System.out.println("Hello");} Hello

public static void main(String args[])


{ A6 obj = new A6();
obj.print();
}
}

Multiple inheritance in Java by interface

If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as multiple
inheritance.

interface Printable{
void print();
}
interface Showable{
void show();
} Output:
class A7 implements Printable,Showable{ Hello
public void print(){System.out.println("Hello");} Welcome
public void show(){System.out.println("Welcome");}

public static void main(String args[])


{ A7 obj = new A7();
obj.print();
obj.show();
}
}

Java 8 Default Method in Interface

Since Java 8, we can have method body in interface. But we need to make it default method. Let's see an
example:

File: TestInterfaceDefault.java

interface Drawable{
void draw();
default void msg(){System.out.println("default method");}
Output:
}
drawing rectangle
class Rectangle implements Drawable{
default method
public void draw(){System.out.println("drawing rectangle");}
}
class TestInterfaceDefault{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
d.msg();
}}

Nested Interfaces:
An interface i.e. declared within another interface or class is known as nested interface. The nested interfaces
are used to group related interfaces so that they can be easy to maintain. The nested interface must be referred
by the outer interface or class. It can't be accessed directly. There are given some points that should be
remembered by the java programmer.
 Nested interface must be public if it is declared inside the interface but it can have any access
modifier if declared within the class.
 Nested interfaces are declared static implicitly.
Syntax of nested interface which is declared within the interface
interface interface_name{
...
interface nested_interface_name{
...
}
}
Syntax of nested interface which is declared within the class
class class_name{
...
interface nested_interface_name{
...
}
}

Example:
interface Showable
{
void show();
interface Message
{
void msg();
}
}
class TestNestedInterface1 implements Showable.Message
{
public void msg()
{
System.out.println("Hello nested interface");
}
public static void main(String args[])
{
Showable.Message message=new TestNestedInterface1();//upcasting here
message.msg();
}
}

Output:
Hello nested interface

As we can see in the above example, we are acessing the Message interface by its outer interface Showable
because it cannot be accessed directly. It is just like almirah inside the room, we cannot access the almirah
directly because we must enter the room first.

Example of nested interface which is declared within the class


Let's see how we can define an interface inside the class and how we can access it.
TestNestedInterface2.java
class A{
interface Message{
void msg();
}
}
class TestNestedInterface2 implements A.Message{
public void msg(){System.out.println("Hello nested interface");}

public static void main(String args[]){


A.Message message=new TestNestedInterface2();//upcasting here
message.msg();
}
}

Output:
Hello nested interface

Difference between Abstract class and Interface:

Abstract class Interface

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

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


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

4) Abstract class can provide the Interface can't provide the implementation of
implementation 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 An interface can extend another Java interface only.
class 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();
} }

Difference Between Class and Interface

The major differences between a class and an interface are:


Class Interface
In class, we can instantiate variables and create In an interface, we can’t instantiate variables and
an object. create an object

Class can contain concrete(with implementation) The interface cannot contain concrete(with
methods implementation) methods
The access specifiers used with classes are In Interface only one specifier is used- Public.
private, protected, and public.
UNIT - III Exception handling, Stream based I/O (java.io)
Exception handling - Fundamentals, Exception types, Uncaught exceptions, using try and
catch, multiple catch clauses, nested try statements, throw, throws and finally, built-in
exceptions, creating own exception subclasses.
Stream based I/O (java.io) – The Stream classes-Byte streams and Character streams, Reading
console Input and Writing Console Output, File class, Reading and Writing Files, Random
access file operations, The Console class, Serialization, Enumerations, Autoboxing, Generics.

Exception handling:

An exception is an unexpected event that occurs during program execution. It affects the flow
of the program instructions which can cause the program to terminate abnormally.
An exception can occur for many reasons. Some of them are:
 Invalid user input
 Device failure
 Loss of network connection
 Physical limitations (out of disk memory)
 Code errors
 Opening an unavailable file
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.
Hierarchy of Java Exception classes

The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two
subclasses: Exception and Error. The hierarchy of Java Exception classes is given below:

Errors
Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out of
memory, memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc.
Errors are usually beyond the control of the programmer and we should not try to handle
errors.
Exceptions
Exceptions can be caught and handled by the program.
When an exception occurs within a method, it creates an object. This object is called the
exception object.
It contains information about the exception such as the name and description of the exception
and state of the program when the exception occurred.
RuntimeException
A runtime exception happens due to a programming error. They are also known
as unchecked exceptions.
These exceptions are not checked at compile-time but run-time. Some of the common runtime
exceptions are:
 Improper use of an API - IllegalArgumentException
 Null pointer access (missing the initialization of a variable) - NullPointerException
 Out-of-bounds array access - ArrayIndexOutOfBoundsException
 Dividing a number by 0 - ArithmeticException
 We can think about it in this way. “If it is a runtime exception, it is your fault”.
The NullPointerException would not have occurred if we had checked whether the variable
was initialized or not before using it.
An ArrayIndexOutOfBoundsException would not have occurred if we tested the array index
against the array bounds.
IOException
An IOException is also known as a checked exception. They are checked by the compiler
at the compile-time and the programmer is prompted to handle these exceptions.
Some of the examples of checked exceptions are:
 Trying to open a file that doesn’t exist results in FileNotFoundException
 Trying to read past the end of a file
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

1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and Error are
known as checked exceptions. For example, IOException, SQLException, etc. Checked
exceptions are checked at compile-time.
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions. For
example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException,
etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.

3) Error
Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError,
AssertionError etc.

Java Exception Keywords


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

Keyword Description
Try The "try" keyword is used to specify a block where we should place an exception
code. It means we can't use try block alone. The try block must be followed by
either catch or finally.
Catch The "catch" block is used to handle the exception. It must be preceded by try block
which means we can't use catch block alone. It can be followed by finally block
later.
Finally The "finally" block is used to execute the necessary code of the program. It is
executed whether an exception is handled or not.

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


Throws The "throws" keyword is used to declare exceptions. It specifies that there may
occur an exception in the method. It doesn't throw an exception. It is always used
with method signature.

Common Scenarios of Java Exceptions


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

1) A scenario where ArithmeticException occurs


If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0;//ArithmeticException

2) A scenario where NullPointerException occurs


If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.
String s=null;
System.out.println(s.length());//NullPointerException
3) A scenario where NumberFormatException occurs
If the formatting of any variable or number is mismatched, it may result into
NumberFormatException. Suppose we have a string variable that has characters; converting
this variable into digit will cause NumberFormatException.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException

4) A scenario where ArrayIndexOutOfBoundsException occurs


When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may
be other reasons to occur ArrayIndexOutOfBoundsException. Consider the following
statements.
int a[]=new int[5];
a[10]=50;

//ArrayIndexOutOfBoundsException without try

catch blocks:

public class JavaExceptionExample {


public static void main(String args[]) {

// code that may raise exception


int data = 100 / 0;

// rest code of the program


System.out.println("rest of the code...");
}
}
Output:
E:\>javac JavaExceptionExample.java

E:\>java JavaExceptionExample
Exception in thread "main" java.lang.ArithmeticException: / by zero
at JavaExceptionExample.main(JavaExceptionExample.java:5)

Methods to print the Exception information:

1. printStackTrace()– This method prints exception information in the format of Name


of the exception: description of the exception, stack trace.
Example:
int a=5,b=0;
try{
System.out.println(a/b);
}
catch(ArithmeticException e)
{ e.printStackTrace(); }
Output:
java.lang.ArithmeticException: / by zero
at GFG.main(File.java:10)

2. toString() – This method prints exception information in the format of Name of the
exception: description of the exception.
Example:
try{
System.out.println(a/b);
}
catch(ArithmeticException e){
System.out.println(e.toString());
}

Output:
java.lang.ArithmeticException: / by zero

3. getMessage() -This method prints only the description of the exception

try{
System.out.println(a/b);
}
catch(ArithmeticException e){
System.out.println(e.getMessage());
}
Output:
/ by zero

Using try and catch:

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:
E:\>javac JavaExceptionExample.java
public class JavaExceptionExample{
public static void main(String args[]){ E:\>java JavaExceptionExample
try{ java.lang.ArithmeticException: / by zero
//code that may raise exception rest of the code...
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}
Multiple catch clauses:

A try block can be followed by one or more catch blocks. Each catch block must contain a
different exception handler. So, if we have to perform different tasks at the occurrence of
different exceptions, use java multi-catch block.

Points to remember
o At a time only one exception occurs and at a time only one catch block is executed.
o All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.

public class MultipleCatchBlock1 {

public static void main(String[] args) { Output:


E:\>javac MultipleCatchBlock1.java E:\
>java MultipleCatchBlock1 Arithmetic
try { Exception occurs
int a[] = new int[5]; rest of the code
int b = 30 / 0;
a[5] = 10;
} catch (ArithmeticException e) {
System.out.println("Arithmetic Exception occurs");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBounds Exception occurs");
} catch (Exception e) {
System.out.println("Parent Exception
occurs");
}
System.out.println("rest of the code");
}
}
Nested try statements:

In Java, using a try block inside another try block is permitted. It is called as nested try block.
Every statement that we enter a statement in try block, context of that exception is pushed
onto the stack.

For example, the inner try block can be used to


handle ArrayIndexOutOfBoundsException while the outer try block can handle
the ArithemeticException (division by zero).

Why use nested try block

Sometimes a situation may arise where a part of a block may cause one error and the entire
block itself may cause another error. In such cases, exception handlers have to be nested.

public class NestedTryBlock {


public static void main(String args[]) {
// outer try
block try {
// inner try block 1
try {
System.out.println("going to divide by 0");
int b = 39 / 0;
}
// catch block of inner try block 1
catch (ArithmeticException e) {
System.out.println(e);
}

// inner try block 2


try {
int a[] = new int[5];
// assigning the value out of array bounds
a[5] = 4;
}
// catch block of inner try block 2
catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e);
}

System.out.println("other statement");
}
// catch block of outer try block
catch (Exception e) {
System.out.println("handled the exception (outer catch)");
}

System.out.println("normal flow..");
}
}
Output:
E:\>javac NestedTryBlock.java
E:\>java NestedTryBlock
going to divide by 0
java.lang.ArithmeticException: / by zero
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
other statement
normal flow..

Throw statement:

The Java throw keyword is used to throw an exception explicitly.


We can throw either checked or unchecked exceptions in Java by throw keyword. It is
mainly used to throw a custom exception.
Syntax:
throw throwableObject;
Example:
throw new ArithmeticException("/ by zero");

program:
//user defined exception
class Eligible extends Exception {
String str;

Eligible(String s) {
str = s;
}
public String toString() {
return ("user defined Exception is " + str);
}
public static void main(String[] args)throws Eligible {
int age = 15;
try {
if (age < 18) {
throw new Eligible("not eligible for vote");
} else {
System.out.println("eligible for vote");
}
} catch (Eligible e) {
Output:
System.out.println(e); E:\>javac Eligible.java E:\
} >java Eligible
finally user defined Exception is not eligible for
{ vote
System.out.println("Finally block"); Finally block
}
System.out.println("rest of code");
}
}

throws and finally:

throws is a keyword in Java which is used in the signature of method to indicate that this
method might throw one of the listed type exceptions. The caller to these methods has to
handle the exception using a try-catch block.

Syntax:
accessModifier returnType methodName() throws ExceptionType1, ExceptionType2 …
{
// code
}
exception_list is a comma separated list of all the
exceptions which a method might throw.
Example:
public static void findFile() throws NullPointerException, IOException,
InvalidClassException {

// code that may produce NullPointerException


………

// code that may produce IOException


………
// code that may produce InvalidClassException
………
}
Example:

class DemoExcep implements Cloneable {


void method() {
System.out.println("simple method");
}
public static void main(String args[]) throws CloneNotSupportedException {
DemoExcep d = new DemoExcep();
DemoExcep d1 = (DemoExcep) d.clone(); Output:
System.out.println(d1); E:\>javac DemoExcep.java
d1.method(); E:\>java DemoExcep
} DemoExcep@36baf30c
} simple method

Finally block:

Java finally block is a block used to execute important code such as closing the connection,
etc.

Java finally block is always executed whether an exception is handled or not. Therefore, it
contains all the necessary statements that need to be printed regardless of the exception occurs
or not.
Example:
public class TestFinallyBlock1{
public static void main(String args[]){

try {

System.out.println("Inside the try block");

//below code throws divide by zero exception


int data=25/0;
System.out.println(data);
}
//cannot handle Arithmetic type exception
//can only accept Null Pointer type exception
catch(NullPointerException e){
System.out.println(e);
}

//executes regardless of exception occured or not


finally {
System.out.println("finally block is always executed");
}

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


}
}

E:\>javac TestFinallyBlock.java
E:\>java TestFinallyBlock
Inside the try block
finally block is always executed
Exception in thread "main" java.lang.ArithmeticException: / by zero
at TestFinallyBlock.main(TestFinallyBlock.java:9)
List of checked exceptions in Java
The following table shows the list of several checked exceptions.
S.
No. Exception Class with Description

1 ClassNotFoundException
It is thrown when the Java Virtual Machine (JVM) tries to load a particular class and
the specified class cannot be found in the classpath.

2 CloneNotSupportedException
Used to indicate that the clone method in class Object has been called to clone an
object, but that the object's class does not implement the Cloneable interface.

3 IllegalAccessException
It is thrown when one attempts to access a method or member that visibility qualifiers
do not allow.

4 InstantiationException
It is thrown when an application tries to create an instance of a class using the
newInstance method in class Class , but the specified class object cannot be
instantiated because it is an interface or is an abstract class.

5 InterruptedException
It is thrown when a thread that is sleeping, waiting, or is occupied is interrupted.

6 NoSuchFieldException
It indicates that the class doesn't have a field of a specified name.

7 NoSuchMethodException
It is thrown when some JAR file has a different version at runtime that it had at
compile time, a NoSuchMethodException occurs during reflection when we try to
access a method that does not exist.

List of unchecked exceptions in Java


The following table shows the list of several unchecked exceptions.
S.
No. Exception Class with Description

1 ArithmeticException
It handles the arithmetic exceptions like dividion by zero
S.
No. Exception Class with Description

2 ArrayIndexOutOfBoundsException
It handles the situations like an array has been accessed with an illegal index. The
index is either negative or greater than or equal to the size of the array.

3 ArrayStoreException
It handles the situations like when an attempt has been made to store the wrong type
of object into an array of objects

4 AssertionError
It is used to indicate that an assertion has failed

5 ClassCastException
It handles the situation when we try to improperly cast a class from one type to
another.

6 IllegalArgumentException
This exception is thrown in order to indicate that a method has been passed an illegal
or inappropriate argument.

7 IllegalMonitorStateException
This indicates that the calling thread has attempted to wait on an object's monitor, or
has attempted to notify other threads that wait on an object's monitor, without
owning the specified monitor.

8 IllegalStateException
It signals that a method has been invoked at an illegal or inappropriate time.

9 IllegalThreadStateException
It is thrown by the Java runtime environment, when the programmer is trying to
modify the state of the thread when it is illegal.

10 IndexOutOfBoundsException
It is thrown when attempting to access an invalid index within a collection, such as
an array , vector , string , and so forth.

11 NegativeArraySizeException
It is thrown if an applet tries to create an array with negative size.

12 NullPointerException
it is thrown when program attempts to use an object reference that has the null value.
S.
No. Exception Class with Description

13 NumberFormatException
It is thrown when we try to convert a string into a numeric value such as float or
integer, but the format of the input string is not appropriate or illegal.

14 SecurityException
It is thrown by the Java Card Virtual Machine to indicate a security violation.

15 StringIndexOutOfBounds
It is thrown by the methods of the String class, in order to indicate that an index is
either negative, or greater than the size of the string itself.

16 UnsupportedOperationException
It is thrown to indicate that the requested operation is not supported.

creating own exception subclasses

Sometimes it is required to develop meaningful exceptions based on the application


requirements. We can create our own exceptions by extending Exception class in Java

class MyException extends Exception


{
String str1;
MyException(String str2)
{
str1=str2;
}
public String toString(){
return ("Output String = "+str1) ;
}
}
class CustomException
{
public static void main(String args[])
{
try
{
throw new MyException("Custom");
// I'm throwing user defined custom exception above
}
catch(MyException exp)
{
System.out.println("Hi this is my catch block") ;
System.out.println(exp) ;
}
}
}
Output:
D:\java\jpgms\labpgms>javac CustomException.java
D:\java\jpgms\labpgms>java CustomException
Hi this is my catch block
Output String = Custom

Differences between throw and throw keywords:

Sr. Key throw Throws


No.
Definition Throw is a keyword which Throws is a keyword used in the
is used to throw an method signature used to declare
1 exception explicitly in the an exception which might get
program inside a function or thrown by the function while
inside a block of code. executing the code.
Internal Internally throw is On other hand we can declare
implementation implemented as it is allowed multiple exceptions with throws
to throw only single keyword that could get thrown by
2 exception at a time i.e we the function where throws
cannot throw multiple keyword is used.
exception with throw
keyword.
Type of With throw keyword we can On other hand with throws
exception propagate only unchecked keyword both checked and
exception i.e checked unchecked exceptions can be
3 exception cannot be declared and for the propagation
propagated using throw. checked exception must use
throws keyword followed by
specific exception class name.
Syntax Syntax wise throw keyword On other hand syntax wise throws
4
is followed by the instance keyword is followed by exception
Sr. Key throw Throws
No.
variable. class names.

Declaration In order to use throw On other hand throws keyword is


keyword we should know used with the method signature.
5
that throw keyword is used
within the method.
Stream based I/O

The Stream:

A stream is a sequence of data. Streams facilitate translating data from one place to another.
Different streams are needed to send and receive data through different sources, such as to
receive data from keyboard, we need a stream and to send data to a file, we need another
stream. Without streams it is not possible to move data in java.

Java Standard Streams


As we know, all Java programs automatically import the java.lang package. This package
defines a class called System, which encapsulates several aspects of the run-time
environment.
 System class also contains three predefined stream variables, in, out, and err. These
fields are declared as public and static within System.
 System.out refers to the standard output stream. By default, this is the console.
 System.in refers to standard input, which is the keyboard by default.
 System.err refers to the standard error stream, which also is the console by default.
 System.in is an object of type InputStream;
 System.out and System.err are objects of type PrintStream.

 Standard Input: Accessed through in which is used to read input from the keyboard.
 Standard Output: Accessed through out which is used to write output to the display
(console).
 Standard Error: Accessed through err which is used to write error output to the
display (console).
There are two brands of Stream in Java Programming Language:

1. Input Stream:
The Input Stream provides the functionality of taking the Input from a Source. The Input
Stream provides the set of Objects and pipelines together to provide us the functionality of
Input the collection in I/O File.
2. Output Stream:
The Output Stream provides the functionality of writing the data to the Destination. The
Output Stream provides the set of Objects and pipelines together to provide us the
functionality of Output to the collection in I/O File.
Fig: Flow of data in standard Input-Output streams and file streams

The Java Input/Output (I/O) is a part of java.io package. This package contains a relatively
large number of classes that support input and output operations. These classes may be
categorized into groups based on the data type on which they operate.

1. Byte Stream Classes that provide support for handling I/O operations on bytes.
2. Character Stream Classes that provide support for managing I/O operations
on characters.
These two groups may further be classified based on their purpose. Figure below shows how
stream classes are grouped based on their functions. Byte stream and Character stream classes
contain specialized input and output stream classes to deal with input and output operations
independently on various types of streams.

1. Byte Stream Classes


 Java byte streams are used to perform input and output of 8-bit bytes.
 Byte streams are defined by using two class hierarchies.
 At the top there are two abstract
classes: java.io.InputStream and java.io.OutputStream.
 Each of these abstract classes has several concrete subclasses of each of these.
 The abstract classes InputStream and OutputStream define several key methods that the
other stream classes implement.
 Two of the most important are read() and write(), which, respectively, read and write
bytes of data.
 Both methods are declared as abstract inside InputStream and OutputStream.
 They are overridden by derived stream classes.
InputStream Classes
The InputStream class is used for reading the data such as a byte and array of bytes from an
input source. An input source can be a file, a string, or memory that may contain the data. It is
an abstract class that defines the programming interface for all input streams that are inherited
from it. An input stream is automatically opened when we create it. We cans explicitly close a
stream with the close() method, or let it be closed implicitly when the object is found as a
garbage.

The subclasses inherited from the InputStream class can be seen in a hierarchy manner shown
below:

Methods of InputStream
The InputStream class provides different methods that are implemented by its subclasses.
Here are some of the commonly used methods:
 read() - reads one byte of data from the input stream
 read(byte[] array) - reads bytes from the stream and stores in the specified array
 available() - returns the number of bytes available in the input stream
 mark() - marks the position in the input stream up to which data has been read
 reset() - returns the control to the point in the stream where the mark was set
 markSupported() - checks if the mark() and reset() method is supported in the stream
 skips() - skips and discards the specified number of bytes from the input stream
 close() - closes the input stream

OutputStream Classes
The OutputStream class is a sibling to InputStream that is used for writing byte and array of
bytes to an output source. Similar to input sources, an output source can be anything such as a
file, a string, or memory containing the data. Like an input stream, an output stream is
automatically opened when we create it. We can explicitly close an output stream with
the close() method, or let it be closed implicitly when the object is garbage collected.
The classes inherited from the OutputStream class can be seen in a hierarchy structure shown
below:

Methods of OutputStream
The OutputStream class provides different methods that are implemented by its subclasses.
Here are some of the methods:
 write() - writes the specified byte to the output stream
 write(byte[] array) - writes the bytes from the specified array to the output stream
 flush() - forces to write all data present in output stream to the destination
 close() - closes the output stream

2. Character Stream Classes


Java offers another type of streams called Character Streams, which are used to read from the
input device and write to the output device in units of 16-bit (Unicode) characters. In some
cases, character streams are more efficient than byte streams. The oldest version of Java (Java
1.0) did not include character streams and, thus, all I/O was byte-oriented. Character streams
were added by Java 1.1, and certain byte-oriented classes and methods were deprecated.
Character streams are defined by using two class hierarchies. At the top there are two abstract
classes, Reader and Writer. These abstract classes handle Unicode character (16-bit)
streams. Java has several concrete subclasses of each of these. The abstract
classes Reader and Writer define several key methods that the other stream classes implement.
Two of the most important methods are read() and write(), which read and write characters of
data, respectively. These methods are overridden by derived stream classes.

2.1 Reader Stream Classes


The Reader class contains methods that are identical to those available in
the InputStream class, except Reader is designed to handle characters. Therefore, Reader
classes can perform all the functions implemented by the InputStream classes. The hierarchy
of Reader character stream classes is shown below:

Modifier and Method Description


Type

abstract void close() It closes the stream and releases any system resources
associated with it.

void mark(int readAheadLimit) It marks the present position in the stream.

Boolean markSupported() It tells whether this stream supports the mark() operation.
int read() It reads a single character.

int read(char[] cbuf) It reads characters into an array.

abstract int read(char[] cbuf, int off, int It reads characters into a portion of an array.
len)

int read(CharBuffer target) It attempts to read characters into the specified character
buffer.

Boolean ready() It tells whether this stream is ready to be read.

void reset() It resets the stream.

2.2 Writer Stream Classes


The Writer class contains methods that are identical to those available in
the OutputStream class, except Writer is designed to handle characters. Therefore, Writer
classes can perform all the functions implemented by the OutputStream classes. The hierarchy
of Writer character stream classes is shown below
Methods
Modifier and Method Description
Type

Writer append(char c) It appends the specified character to this writer.

Writer append(CharSequence csq) It appends the specified character sequence to this


writer

Writer append(CharSequence csq, int start, It appends a subsequence of the specified character
int end) sequence to this writer.

abstract void close() It closes the stream, flushing it first.

abstract void flush() It flushes the stream.

void write(char[] cbuf) It writes an array of characters.

abstract void write(char[] cbuf, int off, int len) It writes a portion of an array of characters.

void write(int c) It writes a single character.

void write(String str) It writes a string.

void write(String str, int off, int len) It writes a portion of a string.

Reading console Input:

Java provides different ways to take input and provide output on the console.

There are three ways to take input from console in Java


1. Using Java BufferedReader class
2. Through Java Scanner class
3. Using Java Console class
1. Using BufferedReader class:
Using BufferedReader class is the classical method of taking input from the console. Java has
introduced this technique since Java 1. The BufferedClass reads data line by line through the
readLine() method. This class wraps the System.in with an InputStreamReader.

We use the object of Bufferedredaer class to take input from the keyboard

To use these classes, we need to use the java.io package. Let’s see an example to understand
this method of reading input from the console.

Example:

import java.io.BufferedReader;
import java.io.IOException;
import
java.io.InputStreamReader; public
class BufferedReaderDemo
{
public static void main(String[] args) throws IOException
{
InputStreamReader input = new InputStreamReader(System.in);
//Taking the input data using the BufferedReader class
BufferedReader br= new BufferedReader(input);

// Reading data using readLine


System.out.println("Please enter the input:");
String name = br.readLine();

System.out.println("Please enter the integer input:");


int num=Integer.parseInt(br.readLine());

// Printing the read line Output:


System.out.println("You entered: "); E:\pgms>javac BufferedReaderDemo.java
System.out.println(name); E:\pgms>java BufferedReaderDemo
Please enter the input:
System.out.println(num); shyam
} Please enter the integer input:
} 1000
You entered:
shyam
1000
Note: The method readLine() is used to take the String input from the user. If you want to read
the other types, we can use the methods like

 Integer.parseInt(): to read int values


 Double.parseDouble(): to read double values
 Float.parseFloat(): to read float values
To read multiple values, we use the split() method.

2.Using Scanner class


It is probably the best choice of taking console input from the user. This class reads the input
from the user in the console or the command line.

The other use of Scanner class is to parse the strings and primitive types with the help of java
regular expressions.

The Scanner class is present in the java.util package. This class obtains the input from
System.in (standard input stream).

Syntax of using Scanner class:

Scanner sc = new Scanner(System.in);

Advantages
 The Scanner class provides useful methods like nextInt(), nextDouble(), nextFloat(), etc,
for parsing primitive data types.
 The Scanner class uses regular expressions and we can use these regular expressions to
find tokens.
Drawback
 The methods of Scanner class for reading values are not synchronized

Methods:
To read the values of various data types, the Scanner class provides several methods. The
following table shows these methods:
Method Description

nextBoolean() This method reads a boolean value from the user

nextByte() This method reads a byte value from the user


nextDouble() This method reads a double value from the user

nextFloat() This method reads a float value from the user

nextInt() This method reads an int value from the user

nextLine() This method reads a String value from the user

nextLong() This method reads a long value from the user

nextShort() This method reads a short value from the user

Example:
import java.util.Scanner;
public class ScannerClassDemo
{
// Java program to understand the use of Scanner in Java
public static void main(String args[]) Output:
{ E:\pgms>javac
// Using Scanner for Getting Input from User ScannerClassDemo.java E:\pgms>java
Scanner sc = new Scanner(System.in); ScannerClassDemo Enter a string
ram
System.out.println("Enter a string"); You entered string: ram
Enter a number
String string = sc.nextLine(); 1001
System.out.println("You entered string: " +string); You entered integer: 1001
Enter a float number
System.out.println("Enter a number"); 78.9076
int num = sc.nextInt(); You entered float: 78.9076
System.out.println("You entered integer: " +num);

System.out.println("Enter a float number");


float fnum = sc.nextFloat();
System.out.println("You entered float: " +fnum);
}
}
3.Using the Java Console class
The Java Console class is the third technique to take input from the user through the console.
The Console class was introduced since Java 1.5. This class is present in the java.io package.

we use the Console class, the JVM associated system console isn't available if we run the code
within an IDE such as Eclipse or IntelliJ IDEA.
There are several methods in Console class that help in reading input texts and passwords
from the console, without displaying it on the screen.

Methods of Java Console class


Method Description

String readLine() This method reads a single line of text from the console.

char[] readPassword() It is used to read a password that is visible on the console screen.
Advantages
 Reading password without displaying the characters of the password on the console.
 Reading methods of the console class are synchronized.
 We can also use the format string syntax with the Console
class Drawback
 It does not work in a non-interactive environment (such as in an
IDE). Example:

import java.io.*;
Output:
E:\pgms>javac ConsoleDemo.java
public class ConsoleDemo { E:\pgms>java ConsoleDemo
public static void main(String[] args) Enter username : satya
{ Username : satya
// Create the console object Enter password :
Password : [C@3b9a45b3
Console cnsl= System.console();

if (cnsl == null) {
System.out.println("No console available");
return;
}

// Read line
String str = cnsl.readLine("Enter username : ");

// Print username
System.out.println("Username : " + str);

// Read password into character array


char[] ch = cnsl.readPassword("Enter password : ");

// Print password
System.out.println("Password : " + ch);
}
}
Writing console output in java
In java, there are two methods to write console output. Using the 2 following methods, we can
write output data to the console.

 Using print() and println() methods


 Using write() method

1. Writing console output using print() and println() methods


The PrintStream is a bult-in class that provides two methods print() and println() to write
console output. The print() and println() methods are the most widely used methods for
console output.
 Both print() and println() methods are used with System.out stream.
 The print() method writes console output in the same line. This method can be
used with console output only.
 The println() method writes console output in a separete line (new line). This
method can be used with console and also with other output sources.

2. Writing console output using write() method


Alternatively, the PrintStream class provides a method write() to write console output.
The write() method take integer as argument, and writes its ASCII equalent character on to the
console, it also accept escape sequences.
Output:
Example: E:\pgms>javac JavaPrintStreamWriteExample.java
E:\pgms>java JavaPrintStreamWriteExample
public class JavaPrintStreamWriteExample { vedha
public static void main(String[] args) { Successfully printed byte array to this stream.
//out is the object class PrintStream.
byte[] b= {118,101,100,104,97};
System.out.write(b,0,5);
System.out.print("\nSuccessfully printed byte array to this stream.");
}
}

File class:
The File is a built-in class in Java. In java, the File class has been defined in
the java.io package. The File class represents a reference to a file or directory. The File class
has various methods to perform operations like creating a file or directory, reading from a file,
updating file content, and deleting a file or directory.
S.No. Constructor with Description

1 File(String pathname)
It creates a new File instance by converting the givenpathname string into an abstract
pathname. If the given string isthe empty string, then the result is the empty abstract
pathname.

2 File(String parent, String child)


It Creates a new File instance from a parent abstractpathname and a child pathname
string. If parent is null then the new File instance is created as if by invoking
thesingle-argument File constructor on the given child pathname string.

3 File(File parent, String child)


It creates a new File instance from a parent abstractpathname and a child pathname
string. If parent is null then the new File instance is created as if by invoking
thesingle-argument File constructor on the given child pathname string.

4 File(URI uri)
It creates a new File instance by converting the given file: URI into an abstract
pathname.

The File class in java has the following methods.


Method Type Description
canRead() Boolean Tests whether the file is readable or not
canWrite() Boolean Tests whether the file is writable or not
createNewFile() Boolean Creates an empty file
delete() Boolean Deletes a file
exists() Boolean Tests whether the file exists
getName() String Returns the name of the file
getAbsolutePath() String Returns the absolute pathname of the file
length() Long Returns the size of the file in bytes
list() String[] Returns an array of the files in the directory
mkdir() Boolean Creates a directory
Example:

// In this Java program, we accepts a file or directory name from


// command line arguments. Then the program will check if
// that file or directory physically exist or not and
// it displays the property of that file or directory.

import java.io.File;

// Displaying file property


class fileProperty {
public static void main(String[] args)
{

// accept file name or directory name through


// command line args
String fname = args[0];

// pass the filename or directory name to File


// object
File f = new File(fname);

// apply File class methods on File object


System.out.println("File name :" + f.getName());
System.out.println("Path: " + f.getPath());
System.out.println("Absolute path:" + f.getAbsolutePath());
System.out.println("Parent:" + f.getParent());
System.out.println("Exists :" + f.exists()); Output:
E:\pgms>javac fileProperty.java E:\
pgms>java fileProperty myFile.txt File
if (f.exists()) {
name :myFile.txt
System.out.println("Is writable:"+ f.canWrite()); Path: myFile.txt
System.out.println("Is readable" + f.canRead()); Absolute path:E:\pgms\myFile.txt
System.out.println("Is a directory:" + Parent:null
f.isDirectory()); System.out.println("File Size in Exists :true
bytes " + f.length()); Is writable:true
Is readabletrue
} Is a directory:false
} File Size in bytes 755
}

FileWriter Class:
Java FileWriter class of java.io package is used to write data in character form to file.
Java FileWriter class is used to write character-oriented data to a file. This class
extends OutputStreamWriter. This class provides methods to write strings directly so we don't
need to convert string to a byte array.
o FileWriter is meant for writing streams of characters. For writing streams of raw
bytes, consider using a FileOutputStream.
o FileWriter creates the output file if it is not present already.

Hierarchy of Java FileWriter Class:

FileWriter extends OutputStreamWriter and Writer classes. It implements Closeable,


Flushable, Appendable, AutoCloseable interfaces.

Constructors of FileWriter Class

Constructor Description
FileWriter(String
This constructor creates a new file. It gets the file name in a string.
file)
This constructor creates a new file. It gets the file name in the File
FileWriter(File file)
object.

Methods of FileWriter Class


All the methods supported by FileWrite Class are mentioned in the table below.

Method Description
void write(String text) This method is used to write the string into FileWriter.

void write(char c) This method is used to write the char into FileWriter.

void write(char[] c) Thi method is used to write char array into FileWriter.

void flush() This method is used to flushes the data of FileWriter.


void close() This method is used to close the FileWriter.
Example:
import java.io.FileWriter;

public class FileWriterDemo {

public static void main(String args[]) {

String data = "This is the data in the output file";

try {
// Creates a FileWriter
FileWriter output = new FileWriter("output.txt");

// Writes the string to the file


output.write(data);
System.out.println("Data written to the file is successfully...");

// Closes the writer Output:


output.close(); E:\pgms> javac FileWriterDemo.java E:\
} pgms>java FileWriterDemo
catch (Exception e) { Data written to the file is successfully...
e.getStackTrace();
}
}
}

FileReader class:
The FileReader class of the java.io package can be used to read data (in characters) from files.
It extends the InputSreamReader class.

Create a FileReader
In order to create a file reader, we must import the java.io.FileReader package first. Once we
import the package, here is how we can create the file reader.
1. Using the name of the file
FileReader input = new FileReader(String name);
Here, we have created a file reader that will be linked to the file specified by the name.
2. Using an object of the file
FileReader input = new FileReader(File fileObj);
Here, we have created a file reader that will be linked to the file specified by the object of the
file.
Methods of FileReader
The the FileReader
class provides implementations for different methods present in
Reader
class.
read() Method
 read() - reads a single character from the reader
 read(char[] array) - reads the characters from the reader and stores in the specified array
 read(char[] array, int start, int length) - reads the number of characters equal to length from
the reader and stores in the specified array starting from the position start

For example:
we have a file named input.txt with the following content.
This is a line of text inside the file.
Let's try to read the file using FileReader.

import java.io.FileReader;

class Main {
public static void main(String[] args) {

// Creates an array of character


char[] array = new char[100];

try {
// Creates a reader using the FileReader
FileReader input = new FileReader("input.txt");

// Reads characters
input.read(array);
System.out.println("Data in the file: ");
System.out.println(array); Output
Data in the file:
This is a line of text inside the file.
// Closes the reader
input.close();
}
catch(Exception e) {
e.getStackTrace();
}
}
}

In the above example, we have created a file reader named input. The file reader is linked with
the file input.txt.
FileInputStream input = new FileInputStream("input.txt");
To read data from the file, we have used the read() method.
Note: The file input.txt should be present in the current working directory.

RandomAccessFile:

This class is used for reading and writing to random access file. A random access file behaves
like a large array of bytes. There is a cursor implied to the array called file pointer, by moving
the cursor we do the read write operations. If end-of-file is reached before the desired number
of byte has been read than EOFException is thrown. It is a type of IOException.

Constructor Description

RandomAccessFile(File Creates a random access file stream to read from, and


file, String mode) optionally to write to, the file specified by the File
argument.
RandomAccessFile(String name, Creates a random access file stream to read from, and
String mode) optionally to write to, a file with the specified name.

Access Modes
Using the RandomAccessFile, a file may created in th following modes.

 r - Creates the file with read mode; Calling write methods will result in an IOException.
 rw - Creates the file with read and write mode.
 rwd - Creates the file with read and write mode - synchronously. All updates to file
content is written to the disk synchronously.
 rws - Creates the file with read and write mode - synchronously. All updates to file
content or meta data is written to the disk synchronously.
Method:

Modifier Method Method


and
Type
void close() It closes this random access file stream and releases any system
resources associated with the stream.
int readInt() It reads a signed 32-bit integer from this file.

String readUTF() It reads in a string from this file.

void seek(long It sets the file-pointer offset, measured from the beginning of this
pos) file, at which the next read or write occurs.
void write(int b) It writes the specified byte to this file.

int read() It reads a byte of data from this file.

long length() It returns the length of this file.

Example:
import java.io.RandomAccessFile;
import java.io.*;
class RaFile
{
public static void main(String args[])throws IOException
{
RandomAccessFile rf=null;
try{
rf=new RandomAccessFile("output.txt","rw");

rf.seek(34);
Output:
rf.writeUTF("Hyderabad"); E:\>javac RaFile.java
rf.seek(10); E:\>java RaFile
int b; file to display capital
while((b=rf.read())!= -1) Hyderabad,,amaravathi
{
System.out.print((char)b);
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally{
if(rf != null)
{
rf.close();
}
}
}
}

Java Enum:
Enum, introduced in Java 5, is a special data type that consists of a set of pre-defined named
values separated by commas. These named values are also known as elements or enumerators
or enum instances. Since the values in the enum type are constant, we should always represent
them in UPPERCASE letters.

You can use an Enum type when we need a fixed set of pre-defined constant values that are
known at the compile-time itself. Examples can be days of the week, seasons of the year, etc.

The following characteristics make enum a ‘special’ class:

 enum constants cannot be overridden


 enum doesn’t support the creation of objects
 enum can’t extend other classes because it is internally extends fromEnum class
 enum can implement interfaces like classes.
Example:
enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
public class EnumTest {
Day day;

public EnumTest(Day day) {


this.day = day;
}
public void tellItLikeItIs() {
switch (day) {
case MONDAY:
case TUESDAY: Output:
case WEDNESDAY: E:\>javac EnumTest.java
case THURSDAY:
case FRIDAY: E:\>java EnumTest
WEEK DAYS
System.out.println("WEEK DAYS"); Weekends are best.
break;

case SATURDAY: case SUNDAY:


System.out.println("Weekends are best.");
break;

default:
System.out.println(" WORNG WEEK NAME");
break;
}
}

public static void main(String[] args) {


EnumTest firstDay = new EnumTest(Day.MONDAY);
firstDay.tellItLikeItIs();
EnumTest sixthDay = new EnumTest(Day.SATURDAY);
sixthDay.tellItLikeItIs();

}
}
Serialization:
Serialization is a mechanism of converting the state of an object into a byte stream.
Deserialization is the reverse process where the byte stream is used to recreate the actual
Java object in memory. This mechanism is used to persist the object.
The byte stream created is platform independent. So, the object serialized on one platform
can be deserialized on a different platform.
To make a Java object serializable we implement the java.io.Serializable interface.
The ObjectOutputStream class contains writeObject() method for serializing an Object.

public final void writeObject(Object obj)throws IOException


The ObjectInputStream class contains readObject() method for deserializing an object.

public final Object readObject()throws IOException,ClassNotFoundException


Advantages of Serialization
1. To save/persist state of an object.
2. To travel an object across a network.

// Java code for serialization and deserialization


// of a Java object
import java.io.*;
class Student implements java.io.Serializable
{
public int a;
public String b;

// Default constructor
public Student(int a, String b)
{
this.a = a;
this.b = b;
}
}
class Test
{
public static void main(String[] args)
{
Student object = new Student(1001, "ram");
String filename = "file.ser";

// Serialization
try
{
//Saving of object in a file
FileOutputStream file = new FileOutputStream(filename);
ObjectOutputStream out = new ObjectOutputStream(file);
// Method for serialization of
object out.writeObject(object);
out.close();
file.close();
System.out.println("Object has been serialized");
}
catch(IOException ex)
{
System.out.println("IOException is caught");
}
Student object1 = null;
// Deserialization
try
{
// Reading the object from a file
FileInputStream file = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file);

// Method for deserialization of object


object1 = (Student)in.readObject();

in.close();
file.close();

System.out.println("Object has been deserialized ");


System.out.println("a = " + object1.a);
System.out.println("b = " + object1.b);
Output:
}
E:\>java Test
catch(IOException ex) Object has been serialized
{ Object has been deserialized
System.out.println("IOException is caught"); a = 1001
} b = ram

catch(ClassNotFoundException ex)
{
System.out.println("ClassNotFoundException is caught");
}

}
}
Autoboxing and Unboxing:

The automatic conversion of primitive data types into its equivalent Wrapper type is known as
boxing and opposite operation is known as unboxing. This is the new feature of Java5. So java
programmer doesn't need to write the conversion code.

Advantage of Autoboxing and Unboxing:

 No need of conversion between primitives and Wrappers manually so less coding is


required.
Primitive Type Wrapper Class
boolean Boolean
Byte Byte
Char Character
float Float
int Integer
Long Long
short Short
Double Double

Example:
class BoxingExample1{
public static void main(String args[])
{ int a=50;
Output:
Integer a2=new Integer(a);//Boxing
Integer a3=5; //Boxing 50 5
System.out.println(a2+" "+a3);
}
}

Simple Example of Unboxing in java:

The automatic conversion of wrapper class type into corresponding primitive type, is known
as Unboxing. Let's see the example of unboxing:

class UnboxingExample1{
public static void main(String args[])
{ Integer i=new Integer(50);
int a=i;
System.out.println(a); 50
}}
Generics in Java:

Generics means parameterized types. The idea is to allow type (Integer, String, … etc.,
and user-defined types) to be a parameter to methods, classes, and interfaces. Using
Generics, it is possible to create classes that work with different data types.

Note: Generics does not work with primitive types (int, float, char, etc).

Advantage of Java Generics

There are mainly 3 advantages of generics. They are as follows:

1) Type-safety: We can hold only a single type of objects in generics. It doesn?t allow to
store other objects.

2) Type casting is not required: There is no need to typecast the object.

Before Generics, we need to type cast.

3) Compile-Time Checking: It is checked at compile time so problem will not occur at


runtime. The good programming strategy says it is far better to handle the problem at compile
time than runtime.
Java Generics Class
We can create a class that can be used with any type of data. Such a class is known as
Generics Class.

Example: Create a Generics Class


class Main {
public static void main(String[] args) {

// initialize generic class


// with Integer data
GenericsClass<Integer> intObj = new GenericsClass<>(5);
System.out.println("Generic Class returns: " + intObj.getData());

// initialize generic class


// with String data
GenericsClass<String> stringObj = new GenericsClass<>("Java Programming");
System.out.println("Generic Class returns: " + stringObj.getData());
}
}
// create a generics class
class GenericsClass<T> {
// variable of T type
private T data;

public GenericsClass(T data) {


this.data = data;
}

// method that return T type variable


public T getData() {
return this.data;
}
}
Output:
E:\>javac GenericsDemo.java

E:\>java GenericsDemo
Generic Class returns: 5
Generic Class returns: Java Programming
Java StringBuffer Class:

Java StringBuffer class is used to create mutable (modifiable) String objects. The StringBuffer
class in Java is the same as String class except it is mutable i.e. it can be changed.

Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it
simultaneously. So it is safe and will result in an order.

Modifier Method Description


and Type
public append(String s) It is used to append the specified string with this
synchronized string. The append() method is overloaded like
StringBuffer append(char), append(boolean), append(int),
append(float), append(double) etc.

public insert(int offset, String It is used to insert the specified string with this
synchronized s) string at the specified position. The insert()
StringBuffer method is overloaded like insert(int, char),
insert(int, boolean), insert(int, int), insert(int,
float), insert(int, double) etc.

public replace(int startIndex, It is used to replace the string from specified


synchronized int endIndex, String str) startIndex and endIndex.
StringBuffer
public delete(int startIndex, int It is used to delete the string from specified
synchronized endIndex) startIndex and endIndex.
StringBuffer
public reverse() is used to reverse the string.
synchronized
StringBuffer
public int capacity() It is used to return the current capacity.

public void ensureCapacity(int It is used to ensure the capacity at least equal to


minimumCapacity) the given minimum.
public char charAt(int index) It is used to return the character at the specified
position.
public int length() It is used to return the length of the string i.e.
total number of characters.
public String substring(int It is used to return the substring from the
beginIndex) specified beginIndex.
public String substring(int It is used to return the substring from the
beginIndex, int specified beginIndex and endIndex.
endIndex)

Example:
class StringBufferExample{
public static void main(String args[])
{ StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
Output:
Hellojava

StringBuffer reverse() Method

The reverse() method of the StringBuilder class reverses the current String.

StringBufferExample5.java

class StringBufferExample5{
public static void main(String args[])
{ StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
Output:
olleH

StringBuilder class:
StringBuilder class has been added in JDK1.5 which has same features like StringBuffer class.
StringBuilder class objects are also mutable as the stringBuffer Objects.
Difference:
StringBuffer is class is synchronized and StringBuilder is not.
Multithreading, The Collections Framework (java.util)
Multithreading: The Java thread model, Creating threads, Thread priorities, Synchronizing
threads, Interthread communication.
The Collections Framework (java.util): Collections overview, Collection Interfaces, The
Collectionclasses- Array List, Linked List, Hash Set, Tree Set, Priority Queue, Array Deque.
Hashtable, Properties, Stack, Vector, String Tokenizer, Bit Set, Date, Calendar, Random,
Formatter, Scanner.

Multitasking:

Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to


utilize the CPU. Multitasking can be achieved in two ways:

 Process-based Multitasking (Multiprocessing)


 Thread-based Multitasking (Multithreading)
1) Process-based Multitasking (Multiprocessing)
 Each process has an address in memory. In other words, each process allocates a separate
memory area.
 A process is heavyweight.
 Cost of communication between the process is high.
 Switching from one process to another requires some time for saving and loading registers,
memory maps, updating lists, etc.
2) Thread-based Multitasking (Multithreading)
 Threads share the same address space.
 A thread is lightweight.
 Cost of communication between the thread is low.

Thread:

The java programming language allows us to create a program that contains one or more parts that
can run simultaneously at the same time. This type of program is known as a multithreading
program. Each part of this program is called a thread. Every thread defines a separate path of
execution in java.

 A thread is a light weight process.


 A thread is a subpart of a process that can run individually.

In java, a thread goes through different states throughout its execution. These stages are called
thread life cycle states or phases. A thread may in any of the states like new, ready or runnable,
running, blocked or wait, and dead or terminated state. The life cycle of a thread in java is shown
in the following figure.
Let's look at each phase in detailed.
New
When a thread object is created using new, then the thread is said to be in the New state. This state
is also known as Born state.
Example
Thread t1 = new Thread();

Runnable / Ready
When a thread calls start( ) method, then the thread is said to be in the Runnable state. This state is
also known as a Ready state.
Example
t1.start( );
Running
When a thread calls run( ) method, then the thread is said to be Running. The run( ) method of a
thread called automatically by the start( ) method.
Blocked / Waiting
A thread in the Running state may move into the blocked state due to various reasons like sleep( )
method called, wait( ) method called, suspend( ) method called, and join( ) method called, etc.
When a thread is in the blocked or waiting state, it may move to Runnable state due to reasons like
sleep time completed, waiting time completed, notify( ) or notifyAll( ) method called, resume( )
method called, etc.
Example
Thread.sleep(1000);
wait(1000);
wait();
suspened();
notify();
notifyAll();
resume();
Dead / Terminated
A thread in the Running state may move into the dead state due to either its execution completed
or the stop( ) method called. The dead state is also known as the terminated state.
Creating threads in java:
In java, a thread is a lightweight process. Every java program executes by a thread called the main
thread. When a java program gets executed, the main thread created automatically. All other
threads called from the main thread.
The java programming language provides two methods to create threads, and they are listed
below.

 Using Thread class (by extending Thread class)


 Uisng Runnable interface (by implementing Runnable interface)

Extending Thread class


The java contains a built-in class Thread inside the java.lang package. The Thread class contains
all the methods that are related to the threads.
To create a thread using Thread class, follow the step given below.

 Step-1: Create a class as a child of Thread class. That means, create a class that extends
Thread class.
 Step-2: Override the run( ) method with the code that is to be executed by the thread. The
run( ) method must be public while overriding.
 Step-3: Create the object of the newly created class in the main( ) method.
 Step-4: Call the start( ) method on the object created in the above

step. Example:

class SampleThread extends Thread{


public void run() {
System.out.println("Thread is under Running...");
for(int i= 1; i<=10; i++) {
System.out.println("i = " + i);
}
}
}
public class MyThreadTest {
public static void main(String[] args)
{ SampleThread t1 = new SampleThread();
System.out.println("Thread about to start...");
t1.start();
}
}

Implementng Runnable interface


The java contains a built-in interface Runnable inside the java.lang package. The Runnable
interface implemented by the Thread class that contains all the methods that are related to the
threads.
To create a thread using Runnable interface, follow the step given below.

 Step-1: Create a class that implements Runnable interface.


 Step-2: Override the run( ) method with the code that is to be executed by the thread. The
run( ) method must be public while overriding.
 Step-3: Create the object of the newly created class in the main( ) method.
 Step-4: Create the Thread class object by passing above created object as parameter to the
Thread class constructor.
 Step-5: Call the start( ) method on the Thread class object created in the above step.

Example:
class SampleThread implements
Runnable{ public void run() {
System.out.println("Thread is under Running...");
for(int i= 1; i<=10; i++) {
System.out.println("i = " + i);
}
}
}
public class MyThreadTest {
public static void main(String[] args) {
SampleThread threadObject = new SampleThread();
Thread thread = new Thread(threadObject);
System.out.println("Thread about to start...");
thread.start();
}
}
Thread class:
The Thread class has the following consructors.

 Thread( )
 Thread( String threadName )
 Thread( Runnable objectName )
 Thread( Runnable objectName, String threadName )

The Thread classs contains the following methods.

Method Description
void run( ) Defines actual task of the thread.
void start( ) It moves thre thread from Ready state to Running state by calling run(
) method.
void setName(String) Assigns a name to the thread.
String getName( ) Returns the name of the thread.
void setPriority(int) Assigns priority to the thread.
int getPriority( ) Returns the priority of the thread.
long getId( ) Returns the ID of the thread.
int activeCount() Returns total number of thread under active.
currentThread( ) Returns the reference of the thread that currently in running
state. void sleep( long ) moves the thread to blocked state till the specified number of
milliseconds.
boolean isAlive( ) Tests if the thread is alive.
void yield( ) Tells to the scheduler that the current thread is willing to yield its
current use of a processor.
void join( ) Waits for the thread to end.

Note:
The Thread class in java also contains methods like stop( ), destroy( ), suspend( ), and resume( ).
But they are deprecated.

Thread priorities:

In a java programming language, every thread has a property called priority. Most of the
scheduling algorithms use the thread priority to schedule the execution sequence. In java, the
thread priority range from 1 to 10. Priority 1 is considered as the lowest priority, and priority 10 is
considered as the highest priority. The thread with more priority allocates the processor first.
The java programming language Thread class provides two methods setPriority(int),
and getPriority( ) to handle thread priorities.
The Thread class also contains three constants that are used to set the thread priority, and they are
listed below.
 MAX_PRIORITY - It has the value 10 and indicates highest priority.
 NORM_PRIORITY - It has the value 5 and indicates normal priority.
 MIN_PRIORITY - It has the value 1 and indicates lowest priority

Note:The default priority of any thread is 5 (i.e. NORM_PRIORITY).

setPriority( ) method
The setPriority( ) method of Thread class used to set the priority of a thread. It takes an integer
range from 1 to 10 as an argument and returns nothing (void).
The regular use of the setPriority( ) method is as follows.
Example
threadObject.setPriority(4);
or
threadObject.setPriority(MAX_PRIORITY);
getPriority( ) method
The getPriority( ) method of Thread class used to access the priority of a thread. It does not takes
anyargument and returns name of the thread as String.
The regular use of the getPriority( ) method is as follows.
Example
String threadName = threadObject.getPriority();
Example:

class SampleThread extends Thread{


public void run() {
System.out.println("Inside SampleThread");
System.out.println("Current Thread: " + Thread.currentThread().getName());
}
}
public class PriorityThread {
public static void main(String[] args) {
SampleThread threadObject1 = new SampleThread(); Output:
SampleThread threadObject2 = new SampleThread(); E:\pgms>javac PriorityThread.java
threadObject1.setName("first"); E:\pgms>java PriorityThread
threadObject2.setName("second"); Inside SampleThread
threadObject1.setPriority(4); Inside SampleThread
threadObject2.setPriority(Thread.MAX_PRIORITY); Current Thread: second
threadObject1.start(); Current Thread: first
threadObject2.start();
}
}
Note:In java, it is not guaranteed that threads execute according to their priority because it
depends on JVM specification that which scheduling it chooses.

Java Thread Synchronisation:


The java programming language supports multithreading. The problem of shared resources occurs
when two or more threads get execute at the same time. In such a situation, we need some way to
ensure that the shared resource will be accessed by only one thread at a time, and this is performed
by using the concept called synchronization.

Note: The synchronization is the process of allowing only one thread to access a shared resource
at a time.

In java, the synchronization is achieved using the following concepts.

 Mutual Exclusion
 Inter thread communication

Mutual Exclusion
Using the mutual exclusion process, we keep threads from interfering with one another while they
accessing the shared resource. In java, mutual exclusion is achieved using the following concepts.

 Synchronized method
 Synchronized block

Synchronized method
When a method created using a synchronized keyword, it allows only one object to access it at a
time. When an object calls a synchronized method, it put a lock on that method so that other
objects or thread that is trying to call the same method must wait, until the lock is released. Once
the lock is released on the shared resource, one of the threads among the waiting threads will be
allocated to the shared resource.
In the above image, initially the thread-1 is accessing the synchronized method and other threads
(thread-2, thread-3, and thread-4) are waiting for the resource (synchronized method). When
thread-1 completes it task, then one of the threads that are waiting is allocated with the
synchronized method, in the above it is thread-3.

Example:

class Printer {
synchronized void printobject(String s) {
System.out.println("\n---start---");
for (int i = 0; i < s.length(); i++)
System.out.print(s.charAt(i));
System.out.print("\n---end---");
} E:\pgms>javac SyncDemo.java
E:\pgms>java SyncDemo
}
---start---
11111111111111111111111
class Cabin extends Thread { ---end---
Printer pnr; ---start---
String str; aaaaaaaaaaa
---end---
---start---
Cabin(Printer pnr, String str) { xxxxxxxxxxxx
this.pnr = pnr; ---end---
this.str = str;
}

public void run() {


pnr.printobject(str);
}
}

class SyncDemo {
public static void main(String args[])throws InterruptedException {
Printer p = new Printer();
Cabin c1 = new Cabin(p, "11111111111111111111111");
Cabin c2 = new Cabin(p, "aaaaaaaaaaa");
Cabin c3 = new Cabin(p, "xxxxxxxxxxxx");

c1.start();
c2.start();
c3.start();

}
}
Synchronized block
The synchronized block is used when we want to synchronize only a specific sequence of lines in
a method. For example, let's consider a method with 20 lines of code where we want to
synchronize only a sequence of 5 lines code, we use the synchronized block.
The folllowing syntax is used to define a synchronized block.

Syntax
synchronized(object){
...
block code
...
}

Look at the following example code to illustrate synchronized block.

Example
class TicketCounter {
int availableSeats = 2;
void bookTicket(String name, int numberOfSeats) {
if((availableSeats >= numberOfSeats) && (numberOfSeats > 0)) {
System.out.println(name+" : "+ numberOfSeats + " Seats Booking Success");
availableSeats -= numberOfSeats;
} else {
System.out.println(name +" : Seats Not Available");
}
}
}
class TicketBookingThread extends Thread {
TicketCounter tc;
String name;
int seats;
TicketBookingThread(TicketCounter tc, String name, int seats) {
this.tc = tc;
this.name = name;
this.seats = seats;
}
public void run() { E:\pgms>javac SynchronizedBlockTest.java
synchronized(tc) { // synchronized block
tc.bookTicket(name, seats); E:\pgms>java SynchronizedBlockTest
Adithya : 2 Seats Booking Success
} Jai : Seats Not Available
}
}
public class SynchronizedBlockTest {
public static void main(String[] args) {
TicketCounter tc = new TicketCounter();
TicketBookingThread t1 = new TicketBookingThread(tc, "Adithya", 2);
TicketBookingThread t2 = new TicketBookingThread(tc, "Jai", 2);
t1.start();
t2.start();
}
}
Note: The complete code of a method may be written inside the synchronized block, where it
works similarly to the synchronized method.

Java Inter Thread Communication:


Inter thread communication is the concept where two or more threads communicate to solve the
problem of polling. In java, polling is the situation to check some condition repeatedly, to take
appropriate action, once the condition is true. That means, in inter-thread communication, a thread
waits until a condition becomes true such that other threads can execute its task. The inter-thread
communication allows the synchronized threads to communicate with each other.
Java provides the following methods to achieve inter thread communication.

 wait( )
 notify( )
 notifyAll( )

Method Description

void wait( ) It makes the current thread to pause its execution until other thread in the
same monitor calls notify( )

void notify( ) It wakes up the thread that called wait( ) on the same object.

void notifyAll() It wakes up all the threads that called wait( ) on the same object.

Let's look at an example problem of producer and consumer. The producer produces the item and
the consumer consumes the same. But here, the consumer cannot consume until the producer
produces the item, and producer cannot produce until the consumer consumes the item that
already been produced. So here, the consumer has to wait until the producer produces the item,
and the producer also needs to wait until the consumer consumes the same. Here we use the inter-
thread communication to implement the producer and consumer problem.
Example:

class Holder
{
String data;
synchronized void putFruit(String s)
{
if(data!=null)
{
try{ w
ait();
}catch(Exception e){}
}
data=s;
System.out.println(data+" placed");
notify();
}
synchronized String getFruit()
{
String str;
if(data==null)
{
try{
wait();
}catch(Exception e){}
}
str=data;
data=null;
System.out.println(str+" received");
notify();
return str;
}
}
class Producer extends Thread
{
String fruits[]={"apple","banana","grapes","mango","cherry"};
Holder h;
public void run()
{
for(int i=0;i<fruits.length;i++)
{
h.putFruit(fruits[i]);
try{
sleep(1000);
}catch(Exception e){}
}
}
}
class Consumer extends Thread{
Holder h;
public void run()
{
for(int i=0;i<5;i++)
{ Output:
h.getFruit(); E:\pgms>javac ConsProdThread.java
} E:\pgms>java ConsProdThread
} apple placed
} apple received
class ConsProdThread banana placed
{ banana received
public static void main(String args[]) grapes placed
{ grapes received
Holder h=new Holder(); mango placed
Producer p=new Producer(); mango received
Consumer c=new Consumer(); cherry placed
p.h=h; cherry received
c.h=h;
p.start();
c.start();
}
}
Note:All the methods wait( ), notify( ), and notifyAll( ) can be used only inside the synchronized
methods only.
Java Collection Framework
Java Collections Framework all classes are divided into following 3 different types of
classes.
Classes
1. Container Objects classes
2. Cursor Objects classes
3. Utility Objects classes
1. Container Objects classes: Following 4 Interfaces are called container objects
 List <T>  HashSet <T>, LinkedHashSet<T>
 Set <T>  Stack <T>, LinkedList<T>, ArrayList<T>,Vector<T>
 Map <K,V>  HashMap <K,V>, Hashtable<K,V>
 Queue <T>  LinkedList <T>
<T> Represents generic type parameter, i.e which type of elements are being stored.
2. Cursor objects are retrieving objects
 Enumeration
 Iterator
 ListIterator
3. Utility Objects: it is nothing but a class that is given to perform different operations
on container objects are called utility objects i.e two classes
 Collections class
 Arrays
The Collection in Java is a framework that provides architecture to store and manipulate the
group of objects.
1. Collections are the containers that groups multiple items in a single unit
2. It provides architecture to store and manipulate a group of objects
3. Using collections various operations can be performed on the data like
 searching,
 sorting,
 insertion,
 manipulation,
 deletion etc.
4. Java collection framework provide many Interfaces and classes
Iterable is the root interface of the Java collection classes. The Collection interface extends
Iterable interface, so all subtypes of Collection implement the Iterable interface. This interface
stands to represent data-structures whose value can be traversed one by one. This is an important
property.

Sets:
A set represents a group of elements arranged just like an array. The set will grow dynamically
when the elements are stored into it. A set will not allow duplicate elements. If we try to pass
for same element that is already available in the set, then it is not stored into the set.
List:
Lists are like sets. They store a group of elements. But lists allow duplicate values to be stored.
Queues:
A Queue represents arrangement of elements in FIFO (First In First Out) order. This means that
an element that is stored as a first element into the queue will be removed first from the
queue.
Maps:
Maps store elements in the form of key and value pairs. If the key is provided then it’s correspond
value can be obtained. Of course, the keys should have unique values.

Remember, in all the cases the 'elements' refer to 'objects' only. This means we cannot store
primitive data types in the collection objects. We can store only objects since the main aim of
collections is to handle objects only, not the primitive data types.

In the hierarchy we can divided into two groups


1. If your requirement is to group key-value pair, then choose MAP
2. If your requirement (operations are on only values) is to have only the values, then choose
collection interfaces

Retrieving Elements from Collections:


Following 4 ways to retrieve any element from a collection object
 Using for-each loop.
 Using Iterator interface.
 Using Listlterator interface.
 Using Enumeration interface.
1. For-each loop:
This is like for loop which repeatedly executes a group of statements for each element of
the collection. The format is:
for(variable : collection-object)
{
Statements:
}
2. Iterator Interface:
Iterator is an interface that contains methods to retrieve the elements one by one from a collection
object. It retrieves elements only in forward direction. It has 3methods:
Methods of Iterator
 hasNext() - returns true if there exists an element in the collection.
 next() - returns the next element of the collection.
 remove() - removes the last element returned by the next().
 forEachRemaining() - performs the specified action for each remaining element of
the collection.

3. ListIterator Interface:
ListIterator is an interface that contains methods to retrieve the elements from a collection object,
both in forward and reverse directions. It can retrieve the elements in forward and backward
direction. It has the following important methods:
Methods of ListIterator
The ListIterator interface provides methods that can be used to perform various operations on the
elements of a list.
 hasNext() - returns true if there exists an element in the list
 next() - returns the next element of the list
 nextIndex() returns the index of the element that the next() method will return
 previous() - returns the previous element of the list
 previousIndex() - returns the index of the element that the previous() method will return
 remove() - removes the element returned by either next() or previous()
 set() - replaces the element returned by either next() or previous() with the specified element

4. Enumeration Interface:
This interface is useful to retrieve elements one by one like Iterator.
It has 2 methods.
 hasMoreElements(): It returns true if more elements are left to iterate otherwise returns
false.
Syntax: public boolean hasMoreElements()
 nextElement(): It returns the next object of the enumeration.

HashSet Class:
HashSet represents a set of elements (objects). It does not guarantee the order of elements. Also it
does not allow the duplicate elements to be stored.

The important points about Java HashSet class are:

o HashSet stores the elements by using a mechanism called hashing.


o HashSet contains unique elements only.
o HashSet allows null value.
o HashSet class is non synchronized.
o HashSet doesn't maintain the insertion order. Here, elements are inserted on the basis of
their hashcode.
o HashSet is the best approach for search operations.
 We can write the HashSet class as :
class HashSet <T>
 We can create the object as :
HashSet <String> hs = new HashSet<String> ();
The following constructors are available in HashSet:
 HashSet();
 HashSet (int capacity); Here capacity represents how many elements can be stored
into the HashSet initially. This capacity may increase automatically when more number of
elements is being stored.

HashSet class Methods:

SN Modifier & Method Description


Type
1) boolean add(E e) It is used to add the specified element to this set if it is
not already present.
2) void clear() It is used to remove all of the elements from the set.

4) boolean contains(Object o) It is used to return true if this set contains the


specified element.
5) boolean isEmpty() It is used to return true if this set contains no
elements.
7) boolean remove(Object o) It is used to remove the specified element from this set
if it is present.
8) int size() It is used to return the number of elements in the set.

Example:
import java.util.HashSet; import
java.util.Iterator; public class
HashSetDemo {
public static void main(String[] args) {
//create a HashSet to store Strings
HashSet <String> hs = new HashSet<String> ();
//Store some String elements
hs.add ("Anil");
hs.add ("Akshara");
hs.add ("Babji");
hs.add ("Charan");
hs.add ("Raman");
System.out.println ("HashSet = " + hs);
//add an Iterator to hs HashSet = [Akshara, Raman, Babji, Anil, Charan]
Iterator<String> it = hs.iterator (); Elements Using Iterator:
//display element by element using Iterator Akshara
System.out.println ("Elements Using Iterator: "); Raman
while (it.hasNext() ) Babji
{ Anil
String s = (String) it.next (); Charan
System.out.println(s);
}
}}
Stack Class:
A stack represents a group of elements stored in LIFO (Last In First Out) order.
This means that the element which is stored as a last element into the stack will be the first
element to be removed from the stack. Inserting the elements (Objects) into the stack is called
push operation and removing the elements from stack is called pop operation.
Searching for an element in stack is called peep operation. Insertion and deletion of elements take
place only from one side of the stack, called top of the stack.

We can write a Stack class as:


class Stack <E>
e.g.: Stack<Integer> obj = new Stack<Integer>();
Method Modifier and Method Description
Type

empty() boolean The method checks the stack is empty or not.

push(E item) E The method pushes (insert) an element onto the top of the
stack.

pop() E The method removes an element from the top of the stack and
returns the same element as the value of that function.
peek() E The method looks at the top element of the stack without
removing it.

search(Object o) int The method searches the specified object and returns the
position of the object.

Example:
import java.util.*;
public class StackPushPopExample
{
public static void main(String args[])
{ Output: stack: []
//creating an object of Stack class push -> 20
Stack <Integer> stk = new Stack<>(); stack: [20]
System.out.println("stack: " + stk); push -> 13
//pushing elements into the stack
stack: [20, 13]
pushelmnt(stk, 20);
pushelmnt(stk, 13); push -> 89
pushelmnt(stk, 89); stack: [20, 13, 89]
pushelmnt(stk, 90); push -> 90
pushelmnt(stk, 11); stack: [20, 13, 89, 90]
pushelmnt(stk, 45); push -> 11
pushelmnt(stk, 18);
stack: [20, 13, 89, 90, 11]
//popping elements from the stack
popelmnt(stk); push -> 45
popelmnt(stk); stack: [20, 13, 89, 90, 11, 45]
//throws exception if the stack is empty push -> 18
try stack: [20, 13, 89, 90, 11, 45, 18]
{ pop -> 18
popelmnt(stk); stack: [20, 13, 89, 90, 11, 45]
}
pop -> 45
catch (EmptyStackException e)
{ stack: [20, 13, 89, 90, 11]
System.out.println("empty stack"); pop -> 11
} stack: [20, 13, 89, 90]
}
//performing push operation
static void pushelmnt(Stack stk, int x)
{
//invoking push() method
stk.push(new Integer(x));
System.out.println("push -> " + x);
//prints modified stack
System.out.println("stack: " + stk);
}
//performing pop operation
static void popelmnt(Stack stk)
{
System.out.print("pop -> ");
//invoking pop() method
Integer x = (Integer) stk.pop();
System.out.println(x);
//prints modified stack
System.out.println("stack: " + stk);
}
}
ArrayList Class:
Java ArrayList class uses a dynamic array for storing the elements.It extends AbstractList class
and implements List interface.
 Java ArrayList class can contain duplicate elements.
 Java ArrayList class maintains insertion order.
 Java ArrayList class is non synchronized. This means that when more than one thread acts
simultaneously on the ArrayList object, the results may be incorrect in some cases.
 Java ArrayList allows random access because array works at the index basis.
 In Java ArrayList class, manipulation is slow because a lot of shifting needs to be
occurred if any element is removed from the array list.

Constructors of ArrayList
Constructor Description

ArrayList() It is used to build an empty array list.

ArrayList(Collection<? extends It is used to build an array list that is initialized with the
E> c) elements of the collection c.

ArrayList(int capacity) It is used to build an array list that has the specified initial
capacity.

Methods of ArrayList
Method Description

void add(int index, E It is used to insert the specified element at the specified position in a
element) list.

boolean add(E e) It is used to append the specified element at the end of a list.

void clear() It is used to remove all of the elements from this list.

E get(int index) It is used to fetch the element from the particular position of the list.

boolean isEmpty() It returns true if the list is empty, otherwise false.

int lastIndexOf(Object o) It is used to return the index in this list of the last occurrence of the
specified element, or -1 if the list does not contain this element.

Object[] toArray() It is used to return an array containing all of the elements in this list
in the correct order.

Boolean contains(Object o) It returns true if the list contains the specified element.

int indexOf(Object o) It is used to return the index in this list of the first occurrence of the
specified element, or -1 if the List does not contain this element.

E remove(int index) It is used to remove the element present at the specified position in
the list.

boolean remove(Object o) It is used to remove the first occurrence of the specified element.

E set(int index, E element) It is used to replace the specified element in the list, present at the
specified position.

int size() It is used to return the number of elements present in the list.
Let's see the new generic example of creating java collection.
ArrayList<String> al=new ArrayList<String>();//creating new generic arraylist
In generic collection, we specify the type in angular braces. Now ArrayList is forced to have only
specified type of objects in it. If we try to add another type of object, it gives compile time error.

Example of Java ArrayList class by using Iterator interface:


import java.util.*;
class TestCollection1{
public static void main(String args[]){

ArrayList<String> al=new ArrayList<String>();//creating arraylist


al.add("Ravi");//adding object in arraylist Ravi
al.add("Vijay"); Vijay
al.add("Ravi"); Ravi
al.add("Ajay"); Ajay

Iterator itr=al.iterator();//getting Iterator from arraylist to traverse elements


while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

Vector:

ArrayList and Vector both implements List interface and maintains insertion order.
But there are many differences between ArrayList and Vector classes that are given below.

ArrayList Vector
1) ArrayList is not synchronized. 1) Vector is synchronized.
2) ArrayList increments 50% of current array 2) Vector increments 100% means doubles
size if number of element exceeds from its the array size if total number of element
capacity. exceeds than its capacity.
3) ArrayList is not a legacy class, it is 3) Vector is a legacy class
introduced in JDK 1.2.
4) ArrayList is fast because it is non- 4) Vector is slow because it is synchronized
synchronized. i.e. in multithreading environment, it will
hold the other threads in runnable or non-
runnable state until current thread releases the
lock of object.
5) ArrayLis tuses Iterator interface to traverse 5) Vector uses Enumeration interface to
the elements. traverse the elements. But it can use Iterator
also
Example of Java Vector:

import java.util.*;
class TestVector1{
public static void main(String args[]){
Vector<String> v=new Vector<String>();//creating vector
v.add("umesh");//method of Collection Umesh
v.addElement("irfan");//method of Vector Irfan
v.addElement("kumar"); kumar
//traversing elements using Enumeration
Enumeration e=v.elements();
while(e.hasMoreElements())
{ System.out.println(e.nextElement());
}}}

Linked list:

A linked list contains a group of elements in the form of nodes. Each node will have three fields-
the data field contatins data and the link fields contain references to previous and next nodes.

The important points about Java LinkedList are:

o Java LinkedList class can contain duplicate elements.


o Java LinkedList class maintains insertion order.
o Java LinkedList class is non synchronized.
o In Java LinkedList class, manipulation is fast because no shifting needs to occur.

A linked list is written in the form of:


class LinkedList<E>
we can create an empty linked list for storing String type elements (objects) as:
LinkedList<String> ll = new LinkedList<String> ();
LinkedList class constructors
The LinkedList class has the following constructors.

 LinkedList( ) - Creates an empty List.


 LinkedList(Collection c) - Creates a List with given collection of elements.

Methods of Java LinkedList:


Method Description

boolean add(E e) It is used to append the specified element to the end of


a list.
void addFirst(E e) It is used to insert the given element at the beginning of
a list.
void addLast(E e) It is used to append the given element to the end of a
list.
void clear() It is used to remove all the elements from a list.

boolean It is used to return true if a list contains a specified


contains(Object o) element.

E get(int index) It is used to return the element at the specified position


in a list.
E getFirst() It is used to return the first element in a list.

E getLast() It is used to return the last element in a list.

int indexOf(Object It is used to return the index in a list of the first


o) occurrence of the specified element, or -1 if the list
does not contain any element.

int It is used to return the index in a list of the last


lastIndexOf(Object occurrence of the specified element, or -1 if the list does
o) not contain any element.
E remove() It is used to retrieve and removes the first element of a
list.
E removeFirst() It removes and returns the first element from a list.
E removeLast() It removes and returns the last element from a list.

Object[] toArray() It is used to return an array containing all the elements


in a list in proper sequence (from first to the last
element).
int size() It is used to return the number of elements in a list.
Example:

import java.util.*;

public class LinkedListExample {

public static void main(String[] args) {

LinkedList<String> list_1 = new LinkedList<String>();


LinkedList list_2 = new LinkedList();

list_2.add(10);
list_2.add(20);
list_2.addFirst(5);
list_2.addLast(25);
list_2.offer(2);
list_2.offerFirst(1);
list_2.offerLast(10);
list_2.push(40);

list_1.addAll(list_2);
System.out.println("List_1: " + list_1);
System.out.println("List_2: " + list_2);
}
}
E:\pgms>javac LinkedListExample.java
Note: LinkedListExample.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

E:\pgms>java LinkedListExample
List_1: [40, 1, 5, 10, 20, 25, 2, 10]
List_2: [40, 1, 5, 10, 20, 25, 2, 10]
TreeSet class:

Java TreeSet class implements the Set interface that uses a tree for storage. It inherits AbstractSet
class and implements the NavigableSet interface. The objects of the TreeSet class are stored in
ascending order.

The important points about the Java TreeSet class are:

o Java TreeSet class contains unique elements only like HashSet.


o Java TreeSet class access and retrieval times are quiet fast.
o Java TreeSet class doesn't allow null element.
o Java TreeSet class is non synchronized.
o Java TreeSet class maintains ascending order.
o The TreeSet initial capacity is 16 elements.

Internal Working of The TreeSet Class

TreeSet is being implemented using a binary search tree, which is self-balancing just like a Red-
Black Tree. Therefore, operations such as a search, remove, and add consume O(log(N)) time.
The reason behind this is there in the self-balancing tree. It is there to ensure that the tree height
never exceeds O(log(N)) for all of the mentioned operations. Therefore, it is one of the efficient
data structures in order to keep the large data that is sorted and also to do operations on it.

TreeSet class:

public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>, Cloneable,


Serializable

TreeSet class constructors


The TreeSet class has the following constructors.

 TreeSet( ) - Creates an empty TreeSet in which elements will get stored in default natural
sorting order.
 TreeSet(Collection c) - Creates a TreeSet with given collection of elements.
 TreeSet(Comparator c) - Creates an empty TreeSet with the specified sorting order.
 TreeSet(SortedSet s) - This constructor is used to convert SortedSet to TreeSet.

Methods of TreeSet:
Method Description
boolean add(E element) Appends given element to the TreeSet.
boolean addAll(Collection c) Appends given collection of elements to the TreeSet.
E First( ) Returns the first (smallest) element from the invoking
TreeSet.
Method Description
E last( ) Returns the last (largest) element from the invoking TreeSet.
E higher(E obj) Returns the largest element e such that e>obj. If it does not
found returns null.
E lower(E obj) Returns the largest element e such that e<obj. If it does not
found returns null.
E ceiling(E obj) Returns the smallest element e such that e>=obj. If it does not
found returns null.
E floor(E obj) Returns the largest element e such that e<=obj. If it does not
found returns null.
SortedSet subSet(E fromElement, Returns a set of elements that lie between the given range
E toElement) which includes fromElement and excludes toElement.
boolean remove(Object element) Removes the first occurence of the given element from the
invoking TreeSet.
boolean removeAll(Collection c) Removes all the elements those are in the specified collection
from the invoking TreeSet.
void clear( ) Removes all the elements from the TreeSet.

int size( ) Returns the total number of elements in the invoking TreeSet.
boolean isEmpty( ) Returns true if the TreeSet is empty otherwise returns false.
boolean equals( ) Compares the specified object with invoking TreeSet
collection for equality.
boolean contains(Object element) Returns true if the HashSet contains given element otherwise
returns false.

Example:
import java.util.TreeSet;

class Main {
public static void main(String[] args) {

TreeSet<Integer> evenNumbers = new TreeSet<>();

// Using the add() method


evenNumbers.add(2); TreeSet: [2, 4, 6]
evenNumbers.add(4);
evenNumbers.add(6); New TreeSet: [1, 2, 4, 6]
System.out.println("TreeSet: " + evenNumbers);
TreeSet<Integer> numbers = new TreeSet<>();
numbers.add(1);

// Using the addAll() method


numbers.addAll(evenNumbers);
System.out.println("New TreeSet: " + numbers);
}
}

HashtTable:
In java, the package java.util contains a class called Hashtable which works like a HashMap but
it is synchronized. The Hashtable is a concrete class of Dictionary. It is used to store and manage
elements in the form of a pair of key and value.
The Hashtable stores data as a pair of key and value. In the Hashtable, each key associates with a
value. Any non-null object can be used as a key or as a value. We can use the key to retrieve the
value back when needed.
 The Hashtable class is no longer in use, it is obsolete. The alternate class is HashMap.
 The Hashtable class is a concrete class of Dictionary.
 The Hashtable class is synchronized.
 The Hashtable does no allow null key or value.
 The Hashtable has the initial default capacity 11.

Hashtable class declaration:


Let's see the declaration for java.util.Hashtable class.
public class Hashtable extends Dictionary implements Map, Cloneable, Ser ializable

The Hash table data structure stores elements in key-value pairs where
 Key- unique integer that is used for indexing the values
 Value - data that are associated with keys.
S. No. Methods with Description
1. V put(K key, V value) It inserts the specified key and value into the hash table.
2. void putAll(Map m)) It inserts all the elements of Map m into the invoking
Hashtable.
3. V get(Object key) It returns the value associated with the given key.
4. V remove(Object key) It returns the value associated with given key and
removes the same
5. boolean remove(Object key, It removes the specified values with the associated
Object value) specified keys from the hashtable.

6. boolean contains(Object value) It returns true if the specified value found within the hash
table, else return false.

7. V replace(K key, V value) It replaces the specified value for a specified key
8. void clear() It is used to remove all the lements of a Hashtable.
9. int size( ) It returns the total number of elements in the Hashtable.
10. boolean equals(Object o) It is used to compare the specified Object with the
Hashtable.
11. boolean isEmpty( ) It returns true if Hashtable has no elements; otherwise
returns false.

// Java program to demonstrate working of HashTable

import java.util.*;
class HashTable { Output:
public static void main(String args[])
{ {15=5643, 3=321, 123=432}
Hashtable<Integer, Integer>
ht = new Hashtable<Integer, Integer>();
ht.put(123, 432);
ht.put(12, 2345);
ht.put(15, 5643);
ht.put(3, 321);
ht.remove(12);
System.out.println(ht);
}}

Properties class:
Properties class is used to maintain the data in the key-value form. It takes both key and value as a
string. Properties class is a subclass of Hashtable. It provides the methods to store properties in a
properties file and to get the properties from the properties file. System.getProperties() returns the
all system properties.

Method Description
public void load(Reader r) It will load data from the Reader object.
public void load(InputStream is) It will load data from the InputStream object
It will load all of the properties represented
public void loadFromXML(InputStream in) by the XML document on the specified input
stream into this properties table.
public String getProperty(String key) It will return value based on the key.
public String getProperty(String key, String It will search for the property with the
defaultValue) specified key and return the value.
public void setProperty(String key, String value) It will call the put method of Hashtable.

It will print the property list out to the


public void list(PrintStream out)
specified output stream.

It will print the property list out to the


public void list(PrintWriter out)
specified output stream.
It will return an enumeration of all the keys
public Enumeration<?> propertyNames()
from the property list.
It will return a set of keys from the property
public Set<String> stringPropertyNames() list where the key and its corresponding value
are strings.

It will write the properties in the writer


public void store(Writer w, String comment)
object.

public void store(OutputStream os, String It will write the properties in the
comment) OutputStream object.

public void storeToXML(OutputStream os, It will write the properties in the writer object
String comment) for generating XML documents.

It will write the properties in the writer object


public void storeToXML(Writer w, String
for generating XML documents with the
comment, String encoding)
specified encoding.

Example:

import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
public class PropetiesTest {
public static void main(String[] args) {

Properties prop = new Properties();


Set props;
String str;

//Set the properties value


prop.setProperty("database", "oracle10g");
prop.setProperty("username", "system");
prop.setProperty("password", "oracle");

//Get key set


props = prop.keySet();
//Print the properties
Iterator iterator = props.iterator();
while(iterator.hasNext()) {
str = (String) iterator.next();
System.out.println("Prpperty: " + str + ", Property Value: " + prop.getProperty(str));
}

}
}
Output:
Prpperty: password, Property Value: oracle
Prpperty: database, Property Value: oracle10g
Prpperty: username, Property Value: system

Priority Queue:

The PriorityQueue class is a part of java collection framework. It is available inside


the java.util package. The PriorityQueue class extends AbstractQueue class and
implements Serializable interface.

 The PriorityQueue is a child class of AbstractQueue


 The PriorityQueue implements interface Serializable.
 The PriorityQueue allows to store duplicate data values, but not null values.
 The PriorityQueue maintains the order of insertion.
 The PriorityQueue used priority heap to organize its elements.

Methods of PriorityQueue:

 add() - Inserts the specified element to the queue. If the queue is full, it throws
an exception.
 offer() - Inserts the specified element to the queue. If the queue is full, it returns false.
 remove() - removes the specified element from the queue
 poll() - returns and removes the head of the queue
 peek() - returns the head of the queue.
 toArray() - Converts a priority queue to an array and returns it.
 size() - Returns the length of the priority queue
 contains(element) - Searches the priority queue for the specified element. If the element
is found, it returns true, if not it returns false.
Example:
import java.util.PriorityQueue;

class Main {
public static void main(String[] args) {

// Creating a priority queue


PriorityQueue<Integer> numbers = new PriorityQueue<>();
numbers.add(2);
numbers.add(4);
numbers.add(1);
numbers.add(5);
numbers.add(3);
System.out.println("PriorityQueue: " + numbers);

// Using the peek() method


int number = numbers.peek();
System.out.println("Accessed Element: " + number);
}
}
Output:
PriorityQueue: [1, 3, 2, 5, 4]

Accessed Element: 1

ArrayDeque:

ArrayDeque class to implement queue and deque data structures using arrays.

o Unlike Queue, we can add or remove elements from both sides.


o Null elements are not allowed in the ArrayDeque.
o ArrayDeque is not thread safe, in the absence of external synchronization.
o ArrayDeque has no capacity restrictions.
o ArrayDeque is faster than LinkedList and Stack.

Creation of ArrayDeque

public class ArrayDeque<E> extends AbstractCollection<E> implements Deque<E>, Cloneable,


Serializable

Methods of ArrayDeque:

 add() - inserts the specified element at the end of the array deque
 addFirst() - inserts the specified element at the beginning of the array deque
 addLast() - inserts the specified at the end of the array deque (equivalent to add())
 offer() - inserts the specified element at the end of the array deque
 offerFirst() - inserts the specified element at the beginning of the array deque
 offerLast() - inserts the specified element at the end of the array deque
 getFirst() - returns the first element of the array deque
 getLast() - returns the last element of the array deque
 peek() - returns the first element of the array deque
 peekFirst() - returns the first element of the array deque (equivalent to peek())
 peekLast() - returns the last element of the array deque
 poll() - returns and removes the first element of the array deque
 pollFirst() - returns and removes the first element of the array deque (equivalent to poll())
 pollLast() - returns and removes the last element of the array deque
 remove() - returns and removes an element from the first element of the array deque
 remove(element) - returns and removes the specified element from the head of the array deque
 removeFirst() - returns and removes the first element from the array deque (equivalent
to remove())
 removeLast() - returns and removes the last element from the array deque

Example:
class Main {
public static void main(String[] args) {
ArrayDeque<String> animals= new ArrayDeque<>();

// Using add()
animals.add("Dog");
animals.add("elephant"); ArrayDeque: [Cat, Dog, elephant, chitha, rabbit, Horse]
animals.add("chitha");
animals.add("rabbit"); ArrayDeque: [Dog, elephant, rabbit, Horse]

// Using addFirst()
animals.addFirst("Cat");

// Using addLast()
animals.addLast("Horse");
System.out.println("ArrayDeque: " + animals);
animals.remove("chitha");
animals.poll();
System.out.println("ArrayDeque: " + animals);

}
}
StringTokenizer:

The java.util.StringTokenizer class allows you to break a String into tokens. It is simple way to
break a String. It is a legacy class of Java.
In the StringTokenizer class, the delimiters can be provided at the time of creation or one by one
to the tokens.

Constructors of StringTokenizer:

Constructor Description
StringTokenizer(String str) It creates StringTokenizer with specified string.
StringTokenizer(String str, It creates StringTokenizer with specified string and delimiter.
String delim)
StringTokenizer(String str, It creates StringTokenizer with specified string, delimiter and
String delim, boolean returnValue. If return value is true, delimiter characters are
returnValue) considered to be tokens. If it is false, delimiter characters serve
to separate tokens.
Methods of the StringTokenizer Class:

Methods Description
boolean hasMoreTokens() It checks if there is more tokens available.
String nextToken() It returns the next token from the StringTokenizer object.
String nextToken(String delim) It returns the next token based on the delimiter.
boolean hasMoreElements() It is the same as hasMoreTokens() method.
Object nextElement() It is the same as nextToken() but its return type is Object.
int countTokens() It returns the total number of tokens.

Example

import java.util.StringTokenizer;
public class StringTokenizer1
{
/* Driver Code */
public static void main(String args[])
{
/* StringTokenizer object */
StringTokenizer st = new StringTokenizer("Demonstrating methods from StringTokenizer
class"," ");
/* Checks if the String has any more tokens */
while (st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
}
}
Output:
Demonstrating
methods
from
StringTokenizer
class
BitSet:

The Java BitSet class implements a vector of bits. The BitSet grows automatically as more bits
are needed. The BitSet class comes under java.util package. The BitSet class extends the Object
class and provides the implementation of Serializable and Cloneable interfaces.

Each component of bit set contains at least one Boolean value. The contents of one BitSet may be
changed by other BitSet using logical AND, logical OR and logical exclusive OR operations. The
index of bits of BitSet class is represented by positive integers.

Each element of bits contains either true or false value. Initially, all bits of a set have the false
value.

import java.util.BitSet;
public class BitSetDemo {

public static void main(String args[]) {


BitSet bits1 = new BitSet(16);
BitSet bits2 = new BitSet(16);

// set some bits


for(int i = 0; i < 16; i++) {
if((i % 2) == 0) bits1.set(i);
if((i % 5) != 0) bits2.set(i);
}

System.out.println("Initial pattern in bits1: ");


System.out.println(bits1); System.out.println("\
nInitial pattern in bits2: ");
System.out.println(bits2);

// AND bits
bits2.and(bits1);
System.out.println("\nbits2 AND bits1: ");
System.out.println(bits2);

// OR bits
bits2.or(bits1);
System.out.println("\nbits2 OR bits1: ");
System.out.println(bits2);

// XOR bits
bits2.xor(bits1);
System.out.println("\nbits2 XOR bits1: ");
System.out.println(bits2);
}
}

Output:

Initial pattern in bits1:


{0, 2, 4, 6, 8, 10, 12, 14}

Initial pattern in bits2:


{1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14}

bits2 AND bits1:


{2, 4, 6, 8, 12, 14}

bits2 OR bits1:
{0, 2, 4, 6, 8, 10, 12, 14}

bits2 XOR bits1:


{}

Date:

The java.util.Date class represents date and time in java. It provides constructors and methods to
deal with date and time in java.

The java.util.Date class implements Serializable, Cloneable and Comparable<Date> interface. It is


inherited by java.sql.Date, java.sql.Time and java.sql.Timestamp interfaces.

After Calendar class, most of the constructors and methods of java.util.Date class has been
deprecated.

No. Constructor Description


1) Date() Creates a date object representing current date and time.
2) Date(long Creates a date object for the given milliseconds since January 1,
milliseconds) 1970, 00:00:00 GMT.

Important Methods
 boolean after(Date date) : Tests if current date is after the given date.
 boolean before(Date date) : Tests if current date is before the given date.
 int compareTo(Date date) : Compares current date with given date. Returns 0 if the
argument Date is equal to the Date; a value less than 0 if the Date is before the Date
argument; and a value greater than 0 if the Date is after the Date argument.
 long getTime() : Returns the number of milliseconds since January 1, 1970, 00:00:00
GMT represented by this Date object.
 void setTime(long time) : Changes the current date and time to given time.

Example:
import java.util.Date;
public class DateDemo {

public static void main(String args[]) {


// Instantiate a Date object
Date date = new Date();

// display time and date using toString()


System.out.println(date.toString());
date.setTime(20345612L);
System.out.println("change date:" + date);

}
}
Output:
Tue Jan 01 05:31:30 IST 2023
change date:Thu Jan 01 11:09:05 IST 1970

Calendar class:

Calendar class is an abstract class in Java that provides methods for multiple operations such as
displaying the year, month, day, hour, etc. It inherits the Object class and implements the
Comparable, Serializable, and Cloneable interfaces.

Java Calendar class declaration

Let's see the declaration of java.util.Calendar class.

public abstract class Calendar extends Object


implements Serializable, Cloneable, Comparable<Calendar>

Calendar’s getInstance method returns a Calendar object whose calendar fields have been
initialized with the current date and time:
Calendar rightNow = Calendar.getInstance();

Example:
import java.util.Calendar;
public class CalendarExample1 {
public static void main(String[] args)
{ Calendar calendar = Calendar.getInstance();
System.out.println("The current date is : " + calendar.getTime());
calendar.add(Calendar.DATE, -15);
System.out.println("15 days ago: " + calendar.getTime());
calendar.add(Calendar.MONTH, 4);
System.out.println("4 months later: " + calendar.getTime());
calendar.add(Calendar.YEAR, 2);
System.out.println("2 years later: " + calendar.getTime());
}
}

Output:
The current date is : Thu Jan 19 18:47:02 IST 2017
15 days ago: Wed Jan 04 18:47:02 IST 2017
4 months later: Thu May 04 18:47:02 IST 2017
2 years later: Sat May 04 18:47:02 IST 2019

get(Calendar.DAY_OF_WEEK): returns 1 (Calendar.SUNDAY) to 7 (Calendar.SATURDAY).


get(Calendar.YEAR): returns year
get(Calendar.MONTH): returns 0 (Calendar.JANUARY) to 11 (Calendar.DECEMBER).
get(Calendar.DAY_OF_MONTH),
get(Calendar.DATE): 1 to 31
get(Calendar.HOUR_OF_DAY): 0 to 23
get(Calendar.MINUTE): 0 to 59
get(Calendar.SECOND): 0 to 59
get(Calendar.MILLISECOND): 0 to 999
get(Calendar.HOUR): 0 to 11, to be used together with Calendar.AM_PM.
get(Calendar.AM_PM): returns 0 (Calendar.AM) or 1 (Calendar.PM).

Example
int day = calendar.get(Calendar.DATE);

Formatter:

The Formatter is a built-in class in java used for layout justification and alignment, common
formats for numeric, string, and date/time data, and locale-specific output in java programming.
The Formatter class is defined as final class inside the java.util package.
The Formatter class implements Cloneable and Flushable interface.
Java Date Format

There are two classes for formatting dates in Java: DateFormat and SimpleDateFormat.
The java.text.DateFormat class provides various methods to format and parse date and time in
java in language-independent manner. The DateFormat class is an abstract class. java.text. The
Format is the parent class and java.text.SimpleDateFormat is the subclass of java.text.DateFormat
class.

In Java, converting the date into the string is called formatting and vice-versa parsing. In other
words, formatting means date to string, and parsing means string to date.

final String format(Date date) converts given Date object into string.
static final DateFormat getInstance() returns date/time formatter with short formatting style for
date and time.

Example:
import java.util.*;
import java.text.*;

class FormatDemo {
public static void main(String[] args) {
DateFormat dateFormat = new SimpleDateFormat("HH:mm");
Calendar cal = Calendar.getInstance();
String y = dateFormat.format(cal.getTime());
System.out.println(y);
}
}
Output:
06:30
Applet: Basics, Architecture, Applet Skeleton, requesting repainting, using the status window, passing
parameters to applets

GUI Programming with Swings – The origin and design philosophy of swing, components and containers,
layout managers, event handling, using a push button, jtextfield, jlabel and image icon, the swing buttons, jtext
field, jscrollpane, jlist, jcombobox, trees, jtable, An overview of jmenubar, jmenu and jmenuitem, creating a
main menu, showmessagedialog, showconfirmdialog, showinputdialog, showoptiondialog, jdialog, create a
modeless dialog.

Accessing Databases with JDBC: Types of Drivers, JDBC Architecture, JDBC classes and Interfaces, Basic
steps in developing JDBC applications, Creating a new database and table with JDBC.

Applet:

Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:
o It works at client side so less response time.
o Secured
o It can be executed by browsers running under many platforms, including Linux,
Windows, Mac Os etc.
Drawback of Applet
o Plugin is required at client browser to execute applet.

Applet Architecture:
1) An applet is a window-based program.
2) Applets are event driven
An applet waits until an event occurs. The run-time system notifies the applet about an
event by calling an event handler that has been provided by the applet. Once this happens, the
applet must take appropriate action and then quickly return.
3) The user initiates interaction with an applet—not the other way around.
The user interacts with the applet as he or she wants, when he or she wants. These
interactions are sent to the applet as events to which the applet must respond.
Examples:
 when the user clicks the mouse inside the applet’s window, a mouse-clicked event is
generated.
 If the user presses a key while the applet’s window has input focus, a keypress event is
generated.
 applets can contain various controls, such as push buttons and check boxes. When the
user interacts with one of these controls, an event is generated.
Types of applets
A web page can contain two types of applets:
1. Local applet
2. Remote applet
Local applets

Local applets are developed and stored locally, and therefore do not require an Internet
connection to be located because the directory is located on the local system.

<applet
codebase = " MyAppPath "
code = "FaceApplet.class"
width = 120
height = 120>
</applet>

Remote applets
Remote applets are stored in a remote computer and an Internet connection is needed to access
them. The remote applet is designed and developed by other developers. To find and load a
remote applet, you need to know the address of the network applet, i.e., the Uniform Resource
Locator (URL).

<applet
codebase = "http://www.myconnect.com/applets/"
code = "FaceApplet.class"
width = 120
height =120>
</applet>

Difference Between Local Applet and Remote Applet


The following table describes the key differences between Local applet and Remote applet.

Local Applet Remote Applet

There is no need to define the Applet's URL


We need to define the Applet's URL in Remote
in Local Applet. Applet.

Local Applet is available on our computer. Remote Applet is not available on our computer.

In order to use it or access it, we don't In order to use it or access it on our computer, we
need Internet Connection. need an Internet Connection.

It is written on our own and then It was written by another developer.


embedded into the web pages.

We don't need to download it. It is available on a remote computer, so we need to


download it to our system.

Applet Life Cycle in Java


The applet life cycle can be defined as the process of how the object is created, started, stopped,
and destroyed during the entire execution of its application. It basically has five core methods
namely init(), start(), stop(), paint() and destroy().These methods are invoked by the browser to
execute.
Methods of Applet Life Cycle

Whenever an applet class is created, an instance of it gets created thereby allowing us to use all
the methods of the class. In applet, there is no need of calling a method explicitly, these are
automatically invoked by the browser.

Method 1: init() Syntax

public void init()


{
// To initialize objects
}
 This is the first method that is being called
 All the variables are initialized here
 This method is only called once during the run time
 It is generally invoked during the time of initialization
Method 2: start() Syntax

public void start()


{
// To start the applet code
}
 It is called after the init method
 Used for starting an applet
 It is also used for restarting an applet in case it is stopped

Method 3: paint() Syntax


public void paint(Graphics graphics)
{
// Any shape's code
}
 This method is used for painting various shapes like squares, rectangles, etc.
 It has parameter of type graphic class, which enable the feature of painting in the applet.
 The graphics class parameter contains graphics context which is used for displaying the
output of the applet.

Method 4: stop() Syntax

public void stop()


{
// To stop the applet code
}
 This method is invoked whenever the browser is stopped, minimized, or because of
abrupt failure within an application.
 Generally after the stop method, the start method can be used.
 It deals with the cleaning of the code, the method is called when the browser leaves the
HTML document when the applet is running.

Method 5: destroy() Syntax

public void destroy()


{
// To destroy the applet
}
 Once we are done with the applet work, this method destroys the application and is
invoked only once.
 Once the applet is destroyed, it can’t be restored.
 It is called when the environment determines that the applet needs to be completely
removed from the memory.
Examples of an Applet Life Cycle in Java

import java.applet.Applet;
import java.awt.Graphics;

import java.awt.*;

/* <applet code="AppletLifeCycle.class" width="350" height="150"> </applet> */


public class AppletLifeCycle extends Applet {
public void init() {
setBackground(Color.cyan);
setForeground(Color.red);
System.out.println("init() is invoked");
}
public void start() {
System.out.println("Start() is invoked");
}
public void paint(Graphics g) {
System.out.println("paint() is invoked");
g.drawString("hi students", 20, 50);
}
public void stop() {
System.out.println("Stop() is invoked");
}
public void destroy() {
System.out.println("Destroy)() is invoked");
}
}

Difference between Application and Applet:

Application
 They are similar to Java programs.
 They can be executed independently without using web browser.
 It requires a ’main’ function for it to be executed.
 Java applications have full access to local file system and network.
 They can access all kinds of resources that are available to the system.
 They can execute the programs with the help of the local system.
 An application program is required when a task needs to be directly performed for the user.

Applets
 They are small Java programs.
 They have been designed to be included with HTML documents.
 They need Java enabled web browser to be executed.
 It doesn’t need a main function to get executed.
 It doesn’t have local disk and network access.
 It can access the browser specific services only.
 They can’t access the local system.
 They can’t execute programs from local machines.
 It is required to perform small tasks or it can be used as a part of a task.

using the status window:


An applet can output a message to the status window of the browser or applet viewer on which
it is running.
• To do so, call showStatus( ) with the string that you want displayed.
• The status window is a good place to give the user feedback about what is occurring in
the applet, suggest options, or possibly report some types of errors.
The following applet demonstrates showStatus( ):

// Using the Status Window.


import java.awt.*;
import java.applet.*;
/*< applet code="StatusWindow" width=300 height=50>
</applet> */
public class StatusWindow extends Applet
{
public void init()
{
setBackground(Color.cyan);
}
// Display msg in applet window.
public void paint(Graphics g)
{
g.drawString("This is in the applet window.", 10, 20);
showStatus("This is shown in the status window.");
}
}
passing parameters to applets:
As just discussed, the APPLET tag allows us to pass parameters to our applet. To retrieve a
parameter, use the getParameter( ) method. It returns the value of the specified parameter in
the form of a String object. Thus, for numeric and boolean values, you will need to convert
their string representations into their internal formats. Here is an example that demonstrates
passing parameters:

Example:
import java.awt.*;
import java.applet.*;
public class MyApplet extends Applet
{
String n;
String a;
public void init()
{
n = getParameter("name");
a = getParameter("age");
}
public void paint(Graphics g)
{
g.drawString("Name is: " + n, 20, 20);
g.drawString("Age is: " + a, 20, 40);
}
}
/*
<applet code="MyApplet" height="300" width="500">
<param name="name" value="Ramesh" />
<param name="age" value="25" />
</applet>
*/
Java AWT:
Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based applications
in java. Java AWT components are platform-dependent i.e. components are displayed
according to the view of operating system. AWT is heavyweight i.e. its components are using
the resources of OS.
The java.awt package provides classes for AWT api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.

Java AWT Hierarchy:


Container:

The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extend Container class are known as container such as
Frame, Dialog and Panel.

Window

The window is the container that have no borders and menu bars. You must use frame, dialog
or another window for creating a window.

Panel

The Panel is the container that doesn't contain title bar and menu bars. It can have other
components like button, textfield etc.

Frame

The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.

Useful Methods of Component class

Method Description
public void add(Component c) inserts a component on this component.
public void setSize(int width,int height) sets the size (width and height) of the component.
public void setLayout(LayoutManager m) defines the layout manager for the component.
public void setVisible(boolean status) changes the visibility of the component, by default
false.
Introduction to swings

The origin and design philosophy of swing:


Swing in java is part of Java foundation class which is lightweight and platform independent. It
is used for creating window based applications. It includes components like button, scroll bar,
text field etc.
Swing in Java is a lightweight GUI toolkit which has a wide variety of widgets for building
optimized window based applications. It is a part of the JFC( Java Foundation Classes). It is
build on top of the AWT API and entirely written in java. It is platform independent unlike
AWT and has lightweight components.

Swing Features:

 Light Weight − Swing components are independent of native Operating System's API as
Swing API controls are rendered mostly using pure JAVA code instead of underlying
operating system calls.
 Rich Controls − Swing provides a rich set of advanced controls like Tree, TabbedPane,
slider, colorpicker, and table controls.
 Highly Customizable − Swing controls can be customized in a very easy way as visual
apperance is independent of internal representation.
 Pluggable look-and-feel − SWING based GUI Application look and feel can be changed
at run-time, based on available values.
Container Class
Any class which has other components in it is called as a container class. For building GUI
applications at least one container class is necessary.

Following are the three types of container classes:

1. Panel – It is used to organize components on to a window


2. Frame – A fully functioning window with icons and titles
3. Dialog – It is like a pop up window but not fully functional like the frame

Difference Between AWT and Swing


AWT SWING

 Platform Dependent  Platform Independent

 Does not follow MVC  Follows MVC

 Lesser Components  More powerful components

 Does not support pluggable look and feel  Supports pluggable look and feel

 Heavyweight  Lightweight
MVC Architecture

Swing API architecture follows loosely based MVC architecture in the following manner.
 Model represents component's data.
 View represents visual representation of the component's data.
 Controller takes the input from the user on the view and reflects the changes in
Component's data.
 Swing component has Model as a seperate element, while the View and Controller part
are clubbed in the User Interface elements. Because of which, Swing has a pluggable
look-and-feel architecture.

A Swing API hierarchy in Java is shown below:

Layout Managers

A layout manager arranges the child components of a container. It positions and sets the size of
components within the container’s display area according to a particular layout scheme. The
layout manager’s job is to fit the components into the available area while maintaining the
proper spatial relationships among the components. Swing comes with a few standard layout
managers that will collectively handle most situations; you can make your own layout
managers if you have special requirements.

FlowLayout

The FlowLayout manager is the default Layout Manager for Applets and Panels. It is the most
basic of the layout managers. It places components, left to right, within the container. If it runs
out of room on one "line," it wraps around to the next line.

BorderLayout

The BorderLayout manager is the default Layout Manager for Frames. It places one component
in the center of the Frame and four components at the top, bottom, left, and right margins.

GridLayout

The GridLayout manager tiles the enclosing container. It organizes components in a two-
dimensional grid, specified in the constructor. Components are added, beginning with the top
left corner, left to right, from top row to bottom row.
GridBagLayout

It is a strong layout that organizes all the components into a grid of cells and keeps the object's
aspect ratio even when the container is modified. The size of the cells in this arrangement may
vary. It allocates components with a constant horizontal and vertical spacing. Using this
feature, we can set a default alignment for elements inside the columns or rows.

Event Delegation Method:

Event handling:

Event Handling is the mechanism that controls the event and decides what should happen if an
event occurs. This mechanism has the code which is known as event handler that is executed
when an event occurs. Java Uses the Delegation Event Model to handle the events. This model
defines the standard mechanism to generate and handle the events. Let's have a brief
introduction to this model.

The Delegation Event Model has the following key participants namely:

Source - The source is an object on which event occurs. Source is responsible for providing
information of the occurred event to it's handler. Java provides classes for source object.

Listener - It is also known as event handler. Listener is responsible for generating response to
an event. From java implementation point of view the listener is also an object. Listener waits
until it receives an event. Once the event is received , the listener process the event and then
returns.

Note: As Interfaces contains abstract methods which need to implemented by the registered
class to handle events.

JButton

The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. It inherits
AbstractButton class.

JButton class declaration

Let's see the declaration for javax.swing.JButton class.

1. public class JButton extends AbstractButton implements Accessible

Commonly used Constructors:

Constructor Description
JButton() It creates a button with no text and icon.

JButton(String s) It creates a button with the specified text.

JButton(Icon i) It creates a button with the specified icon object.


Example:
import javax.swing.*;
public class ButtonExample {
public static void main(String[] args)
{ JFrame f=new JFrame("Button
Example"); JButton b=new JButton("Click
Here"); b.setBounds(50,100,95,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}

Output:

JCheckBox:

The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off
(false). Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on ".It
inherits JToggleButton class.
JCheckBox class declaration

Let's see the declaration for javax.swing.JCheckBox class.

1. public class JCheckBox extends JToggleButton implements Accessible

Commonly used Constructors:

Constructor Description

JJCheckBox() Creates an initially unselected check box button with


no text, no icon.

JChechBox(String s) Creates an initially unselected check box with text.

JCheckBox(String text, boolean Creates a check box with text and specifies whether or
selected) not it is initially selected.

JCheckBox(Action a) Creates a check box where properties are taken from


the Action supplied.

import javax.swing.*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("C++");
checkBox1.setBounds(100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckBoxExample();
}}
Output:

JRadioButton:

The JRadioButton class is used to create a radio button. It is used to choose one option from
multiple options. It is widely used in exam systems or quiz.

It should be added in ButtonGroup to select one radio button only.

JRadioButton class declaration

Let's see the declaration for javax.swing.JRadioButton class.

1. public class JRadioButton extends JToggleButton implements Accessible

Commonly used Constructors:

Constructor Description

JRadioButton() Creates an unselected radio button with no text.

JRadioButton(String s) Creates an unselected radio button with specified


text.

JRadioButton(String s, boolean Creates a radio button with the specified text and
selected) selected status.
import javax.swing.*;
public class RadioButtonExample
{ JFrame f;
RadioButtonExample(){
f=new JFrame();
JRadioButton r1=new JRadioButton("A) Male");
JRadioButton r2=new JRadioButton("B) Female");
r1.setBounds(75,50,100,30);
r2.setBounds(75,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(r1);
bg.add(r2);
f.add(r1);
f.add(r2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new RadioButtonExample();
}
}

Output:
JLabel:

The object of JLabel class is a component for placing text in a container. It is used to display a
single line of read only text. The text can be changed by an application but a user cannot edit it
directly. It inherits JComponent class.

JLabel class declaration

Let's see the declaration for javax.swing.JLabel class.

1. public class JLabel extends JComponent implements SwingConstants, Accessible

Commonly used Constructors:

Constructor Description

JLabel() Creates a JLabel instance with no image and with


an empty string for the title.

JLabel(String s) Creates a JLabel instance with the specified text.

JLabel(Icon i) Creates a JLabel instance with the specified


image.

JLabel(String s, Icon i, int Creates a JLabel instance with the specified text,
horizontalAlignment) image, and horizontal alignment.

import javax.swing.*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("First Label.");
l1.setBounds(50,50, 100,30);
l2=new JLabel("Second Label.");
l2.setBounds(50,100, 100,30);
f.add(l1); f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}

Output:

JTextField:

The object of a JTextField class is a text component that allows the editing of a single line text.
It inherits JTextComponent class.

JTextField class declaration

Let's see the declaration for javax.swing.JTextField class.

1. public class JTextField extends JTextComponent implements SwingConstants

Commonly used Constructors:

Constructor Description

JTextField() Creates a new TextField

JTextField(String text) Creates a new TextField initialized with the specified text.

JTextField(String text, int Creates a new TextField initialized with the specified text
columns) and columns.

JTextField(int columns) Creates a new empty TextField with the specified number
of columns.
import javax.swing.*;
class TextFieldExample
{
public static void main(String args[])
{
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
t1=new JTextField("Welcome to Javatpoint.");
t1.setBounds(50,100, 200,30);
t2=new JTextField("AWT Tutorial");
t2.setBounds(50,150, 200,30);
f.add(t1); f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}

Output:
JTextArea:

The object of a JTextArea class is a multi line region that displays text. It allows the editing of
multiple line text. It inherits JTextComponent class

JTextArea class declaration

Let's see the declaration for javax.swing.JTextArea class.

1. public class JTextArea extends JTextComponent

Commonly used Constructors:

Constructor Description

JTextArea() Creates a text area that displays no text initially.

JTextArea(String s) Creates a text area that displays specified text initially.

JTextArea(int row, int Creates a text area with the specified number of rows and
column) columns that displays no text initially.

JTextArea(String s, int row, Creates a text area with the specified number of rows and
int column) columns that displays specified text.

import javax.swing.*;
public class TextAreaExample
{
TextAreaExample(){
JFrame f= new JFrame();
JTextArea area=new JTextArea("Welcome to javatpoint");
area.setBounds(10,30, 200,200);
f.add(area);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new TextAreaExample();
}}
Output:

JList:

The object of JList class represents a list of text items. The list of text items can be set up so
that the user can choose either one item or multiple items. It inherits JComponent class.

JList class declaration

Let's see the declaration for javax.swing.JList class.

1. public class JList extends JComponent implements Scrollable, Accessible

Commonly used Constructors:

Constructor Description

JList() Creates a JList with an empty, read-only, model.

JList(ary[] listData) Creates a JList that displays the elements in the


specified array.

JList(ListModel<ary>dataModel) Creates a JList that displays elements from the


specified, non-null, model.
import javax.swing.*;
public class ListExample
{
ListExample(){
JFrame f= new JFrame();
DefaultListModel<String> l1 = new DefaultListModel<>();
l1.addElement("Item1");
l1.addElement("Item2");
l1.addElement("Item3");
l1.addElement("Item4");
JList<String> list = new JList<>(l1);
list.setBounds(100,100, 75,75);
f.add(list);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ListExample();
}}

Output:
JComboBox:

The object of Choice class is used to show popup menu of choices. Choice selected by user is
shown on the top of a menu. It inherits JComponent class.

JComboBox class declaration

Let's see the declaration for javax.swing.JComboBox class.

1. public class JComboBox extends JComponent implements ItemSelectable, ListDataList


ener, ActionListener, Accessible

Commonly used Constructors:

Constructor Description

JComboBox() Creates a JComboBox with a default data model.

JComboBox(Object[] items) Creates a JComboBox that contains the elements in the


specified array.

JComboBox(Vector<?> Creates a JComboBox that contains the elements in the


items) specified Vector.

import javax.swing.*;
public class ComboBoxExample
{ JFrame f;
ComboBoxExample(){
f=new JFrame("ComboBox Example");
String country[]={"India","Aus","U.S.A","England","Newzealand"};
JComboBox cb=new JComboBox(country);
cb.setBounds(50, 50,90,20);
f.add(cb);
f.setLayout(null);
f.setSize(400,500);
f.setVisible(true);
}
public static void main(String[] args) {
new ComboBoxExample();
} }
Output:

JScrollPane:

A JscrollPane is used to make scrollable view of a component. When screen size is limited, we
use a scroll pane to display a large component or a component whose size can change
dynamically.

Constructors

Constructor Purpose

JScrollPane() It creates a scroll pane. The Component parameter, when


present, sets the scroll pane's client. The two int parameters,
JScrollPane(Component) when present, set the vertical and horizontal scroll bar
policies (respectively).
JScrollPane(int, int)

JScrollPane(Component,
int, int)

import java.awt.FlowLayout;
import javax.swing.JFrame;
import
javax.swing.JScrollPane;
import javax.swing.JtextArea;

public class JScrollPaneExample {

private static void createAndShowGUI() {

// Create and set up the window.


final JFrame frame = new JFrame("Scroll Pane Example");

// Display the window.


frame.setSize(500, 500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// set flow layout for the frame


frame.getContentPane().setLayout(new FlowLayout());

JTextArea textArea = new JTextArea(20, 20);


JScrollPane scrollableTextArea = new JScrollPane(textArea);

scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROL
LBAR_ALWAYS);
scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBA
R_ALWAYS);

frame.getContentPane().add(scrollableTextArea);
}
public static void main(String[] args) {

javax.swing.SwingUtilities.invokeLater(new Runnable() {

public void run() {


createAndShowGUI();
}
});
}
}
Output:
JDBC

Java Database Connectivity (JDBC) is an application programming interface (API) for the
programming language Java, which defines how a client may access any kind of tabular data,
especially relational database. It is part of Java Standard Edition platform, from Oracle
Corporation. It acts as a middle layer interface between java applications and database. The
JDBC classes are contained in the Java Package java.sql and javax.sql.

JDBC helps you to write Java applications that manage these programming activities:

 Import the packages: ...


 Register the drivers: ...
 Establish a connection: ...
 Create a statement: ...
 Execute the query: ...
 Retrieve results: ...
 Close the connections

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 Type-1 driver

Type-1 driver or JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The
JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function calls. Type-1
driver is also called Universal driver because it can be used to connect to any of the databases.

 As a common driver is used in order to interact with different databases, the data
transferred through this driver is not so secured.
 The ODBC bridge driver is needed to be installed in individual client machines.
 Type-1 driver isn’t written in java, that’s why it isn’t a portable driver.
 This driver software is built-in with JDK so no need to install separately.
 It is a database independent driver.

Type-2 driver:
JDBC Drivers Types
JDBC driver implementations vary because of the wide variety of operating systems and
hardware platforms in which Java operates. Sun has divided the implementation types into four
categories, Types 1, 2, 3, and 4, which is explained below −
Type 1 − JDBC-ODBC Bridge Driver
In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client
machine. Using ODBC, requires configuring on your system a Data Source Name (DSN) that
represents the target database.
When Java first came out, this was a useful driver because most databases only supported
ODBC access but now this type of driver is recommended only for experimental use or when
no other alternative is available.

The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of this kind of driver.
Type 2 − JDBC-Native API
In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls, which are
unique to the database. These drivers are typically provided by the database vendors and used
in the same manner as the JDBC-ODBC Bridge. The vendor-specific driver must be installed
on each client machine.
If we change the Database, we have to change the native API, as it is specific to a database and
they are mostly obsolete now, but you may realize some speed increase with a Type 2 driver,
because it eliminates ODBC's overhead.
The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.
Type 3 − JDBC-Net pure Java
In a Type 3 driver, a three-tier approach is used to access databases. The JDBC clients use
standard network sockets to communicate with a middleware application server. The socket
information is then translated by the middleware application server into the call format required
by the DBMS, and forwarded to the database server.
This kind of driver is extremely flexible, since it requires no code installed on the client and a
single driver can actually provide access to multiple databases.

You can think of the application server as a JDBC "proxy," meaning that it makes calls for the
client application. As a result, you need some knowledge of the application server's
configuration in order to effectively use this driver type.
Your application server might use a Type 1, 2, or 4 driver to communicate with the database,
understanding the nuances will prove helpful.
Type 4 − 100% Pure Java
In a Type 4 driver, a pure Java-based driver communicates directly with the vendor's database
through socket connection. This is the highest performance driver available for the database and
is usually provided by the vendor itself.
This kind of driver is extremely flexible, you don't need to install special software on the client
or server. Further, these drivers can be downloaded dynamically.

MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their
network protocols, database vendors usually supply type 4 drivers.

You might also like