Java Lecture Notes
Java Lecture Notes
LECTURE NOTES
Year / Semester: II / IV
List of PSO’s
PSO 1: Establishment of Mathematical and computer systems concepts: To use
mathematical and system concepts to solve multidisciplinary problems using appropriate
mathematical analysis, system and programming concepts on various computing
environments.
PSO 2: Establishment of communication and information concepts: To inculcate good
breadth of knowledge to apply and enhance informatics and communication technologies
PSO 3: Establishment of Business, Technological concepts: The ability to interpret and
respond to business agility with relevant software tools and skills and provide newer ideas and
innovations in information technology research
L T P C Hrs
U20EST467 PROGRAMMING IN JAVA 3 0 0 3 45
Course Objectives
• To gain and explore the knowledge of java programming
• To know the principles of inheritances, packages, interfaces
• To get familiarized to generic programming, multithreading concepts.
• To gain and explore the advanced concepts in Java.
• To explore database connectivity
Course Outcomes
After completion of the course, the students will be able to
CO1 - Write a maintainable java program for a given algorithm and implement the same. (K2)
CO2 - Demonstrate the use of inheritance, interface and package in relevant applications. (K3)
CO3 - Create java applications using exception handling, thread and generic programming. (K3)
CO4 - Build java distributed applications using Collections and IO streams. (K3)
CO5 - Exemplify simple graphical user interfaces using GUI components and database programs. (K3)
Text Books
1. Herbert Schildt, “Java: The Complete Reference”, TMH Publishing Company Ltd, 11 th Edition,
2018.
2. Sagayaraj, Denis, Karthik, Gajalakshmi, “JAVA Programming for core and advanced learners”,
Universities Press Private Limited, 2018.
3. Herbert Schildt, “The Complete Reference JAVA 2”, TMH, Seventh Edition, 2006.
Web References
1. http://www.ibm.com/developerworks/java/
2. http://docs.oracle.com/javase/tutorial/rmi/.
3. IBM’s tutorials on Swings, AWT controls and JDBC.
4. https://www.edureka.co/blog
5. https://www.geeksforgeeks.org
CO-POs/PSOs Mapping
Program Specific
Program Outcomes (POs)
COs Outcomes (PSOs)
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2 PSO3
1 2 1 - - 2 - - - - - - - 3 2 1
2 3 2 1 1 3 - - - - - - - 3 2 1
3 3 2 1 1 3 - - - - - - - 3 2 1
4 3 2 1 1 3 - - - - - - - 3 2 1
5 3 2 1 1 3 - - - - - - - 3 2 1
Correlation Level: 1-Low, 2-Medium, 3- High
The History and Evolution of Java - Byte code - Java buzzwords - Data types – Variables
– Arrays – operators - Control statements - Type conversion and casting. Concepts of
classes and objects: Basic Concepts of OOPs – Constructors - Static keyword - Final with
data - Access control - This key word - Garbage collection - Nested classes and inner
classes - String class.
What is Computer?
A computer is a device that can accept human instruction processes it and responds to it or a
computer is a computational device which is used to process the data under the control of a
computer program. Program is a sequence of instruction along with data.
The basic components of a computer are:
• Input unit
• Central Processing Unit (CPU)
• Output unit
The CPU is further divided into three parts-
• Memory unit
• Control unit
• Arithmetic Logic unit
What is a Program?
• A program is a set of instructions given to a computer to perform a specific
operation.
• While executing the program, raw data is processed into a desired output format.
• These computer programs are written in a programming language which are high
level languages.
• High level languages are nearly human languages which are more complex then the
computer understandable language which are called machine language, or low level
language.
• So after knowing the basics, we are ready to create a very simple and basic program.
Like we have different languages to communicate with each other, likewise, we have
different languages like C, C++, C#, Java, python, etc to communicate with the
computers.
• The computer only understands binary language (the language of 0’s and 1’s) also
called machine-understandable language or low-level language but the programs we
are going to write are in a high-level language which is almost similar to human
language.
Java Terminology
Bytecode:
As discussed above, javac compiler of JDK compiles the java source code into bytecode so that
it can be executed by JVM. The bytecode is saved in a .class file by compiler.
Garbage Collector:
• In Java, programmers can’t delete the objects. To delete or recollect that memory JVM
has a program called Garbage Collector. Garbage Collector can recollect the of objects
that are not referenced. So Java makes the life of a programmer easy by handling
memory management.
• However, programmers should be careful about their code whether they are using
objects that have been used for a long time. Because Garbage cannot recover the
memory of objects being referenced.
ClassPath
• The classpath is the file path where the java runtime and Java compiler looks for .class
files to load. By default, JDK provides many libraries. If you want to include external
libraries they should be added to the classpath.
• Java bytecode is the instruction set for the Java Virtual Machine. It acts similar to an
assembler which is an alias representation of a C++ code.
• As soon as a java program is compiled, java bytecode is generated. In more apt terms,
java bytecode is the machine code in the form of a .class file.
• With the help of java bytecode we achieve platform independence in java.
Platform Independent:
• Java is platform independent because it is different from other languages like C,
C++, etc. which are compiled into platform specific machines while Java is a write
once, run anywhere language. A platform is the hardware or software environment in
which a program runs.
• There are two types of platforms software-based and hardware-based. Java provides
a software-based platform.
• The Java platform differs from most other platforms in the sense that it is a software-
based platform that runs on the top of other hardware-based platforms. It has two
components:
o Runtime Environment
o API(Application Programming Interface)
• Java code can be run on multiple platforms, for example, Windows, Linux, Sun
Solaris, Mac/OS, etc. Java code is compiled by the compiler and converted into
bytecode. This bytecode is a platform-independent code because it can be run on
multiple platforms, i.e., Write Once and Run Anywhere (WORA).
Secured
• Java is best known for its security. With Java, we can develop virus-free systems.
Java is secured because:
• No explicit pointer
• Java Programs run inside a virtual machine sandbox
• Classloader: Classloader in Java is a part of the Java Runtime Environment(JRE)
which is used to load Java classes into the Java Virtual Machine dynamically. It adds
security by separating the package for the classes of the local file system from those
that are imported from network sources.
• Bytecode Verifier: It checks the code fragments for illegal code that can violate
access 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 because:
• It uses strong memory management.
• There is a lack of pointers that avoids security problems.
• There is automatic garbage collection in java which runs on the Java Virtual
Machine to get rid of objects which are not being used by a Java application
anymore.
• There are exception handling and the type checking mechanism in Java. All these
points make Java robust.
Architecture-neutral:
• Java is architecture neutral because there are no implementation dependent features,
for example, the size of primitive types is fixed.
• In C programming, int data type occupies 2 bytes of memory for 32-bit architecture
and 4 bytes of memory for 64-bit architecture. However, it occupies 4 bytes of
memory for both 32 and 64-bit architectures in Java.
Portable:
Java is portable because it facilitates you to carry the Java bytecode to any platform. It
doesn't require any implementation.
High-performance:
Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code. It is still a little bit slower than a compiled language (e.g.,
C++). Java is an interpreted language that is why it is slower than compiled languages, e.g., C,
C++, etc.
Distributed:
Java is distributed because it facilitates users to create distributed applications in Java.
RMI and EJB are used for creating distributed applications. This feature of Java makes us able
to access files by calling the methods from any machine on the internet.
Multi-threaded:
A thread is like a separate program, executing concurrently. We can write Java programs
that deal with many tasks at once by defining multiple threads. The main advantage of multi-
threading is that it doesn't occupy memory for each thread. It shares a common memory area.
Threads are important for multi-media, Web applications, etc.
Dynamic:
• Java is a dynamic language. It supports 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).
Example
public class MyFirstJavaProgram
{
/* This is my first java program.
This will print 'Hello World' as the output */
public static void main(String []args)
{
System.out.println("Hello World"); // prints Hello World
}
}
Let's look at how to save the file, compile, and run the program. Please follow the
subsequent steps −
1. Open notepad and add the code as above.
2. Save the file as: MyFirstJavaProgram.java.
3. Open a command prompt window and go to the directory where you saved the class.
Assume it's C:\.
4. Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If there are
no errors in your code, the command prompt will take you to the next line (Assumption:
The path variable is set).
5. Now, type ' java MyFirstJavaProgram ' to run your program.
6. You will be able to see ' Hello World ' printed on the window.
Basic Syntax:
1. About Java programs, it is very important to keep in mind the following points.
2. Case Sensitivity − Java is case sensitive, which means identifier Hello and hello would
have a different meaning in Java.
3. Class Names − For all class names, the first letter should be in Upper Case. If several
words are used to form a name of the class, each inner word's first letter should be in
Upper Case.
Example: class MyFirstJavaClass
4. Method Names − All method names should start with a Lower Case letter. If several
words are used to form the name of the method, then each inner word's first letter should
be in Upper Case.
Example: public void myMethodName()
5. Program File Name − Name of the program file should exactly match the class name.
import java.io.*;
class GFG
{
public static void main(String[] args)
{
// prints Hello World
System.out.println("Hello World");
}
}
Output
Hello World
Explanation:
1. Comments: Comments are used for explaining code and are used in a similar manner
in Java or C or C++. Compilers ignore the comment entries and do not execute them. Comments
can be of a single line or multiple lines.
Example
byte myNum = 100;
short myNum = 5000;
int myNum = 5; // Integer (whole number)
long myNum = 15000000000L;
float myFloatNum = 5.99f; // Floating point number
double myNum = 19.99d;
char myLetter = 'D'; // Character
boolean myBool = true; // Boolean
String myText = "Hello"; // String
Java Variables:
• A variable is a container which holds the value while the Java program is executed. A
variable is assigned with a data type.
• Variable is a name of memory location. There are three types of variables in java: local,
instance and static.
• Variable is name of reserved area allocated in memory. In other words, it is a name of
memory location. It is a combination of "vary + able" that means its value can be
changed.
The general rules for constructing names for variables (unique identifiers) are:
1. Names can contain letters, digits, underscores, and dollar signs
2. Names must begin with a letter
3. Names should start with a lowercase letter and it cannot contain whitespace
4. Names can also begin with $ and _ (but we will not use it in this tutorial)
5. Names are case sensitive ("myVar" and "myvar" are different variables)
6. Reserved words (like Java keywords, such as int or boolean) cannot be used as names
Types of Variables:
There are three types of variables in Java:
1. local variable
2. instance variable
3. static variable
1) 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.
A local variable cannot be defined with "static" keyword.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called
instance variable. It is not declared as static.
It is called instance variable because its value is instance specific and is not shared
among instances.
3) Static variable
A variable which is declared as static is called static variable. It cannot be local. You can
create a single copy of static variable and share among all the instances of the class. Memory
allocation for static variable happens only once when the class is loaded in the memory.
Operators:
Operator in Java is a symbol which is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
1. Unary Operator,
2. Arithmetic Operator,
3. Shift Operator,
4. Relational Operator,
5. Bitwise Operator,
6. Logical Operator,
7. Ternary Operator and
8. Assignment Operator
Example:
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(~a);//-11 (minus of total positive value which starts from 0)
System.out.println(~b);//9 (positive of total minus, positive starts from 0)
System.out.println(!c);//false (opposite of boolean value)
System.out.println(!d);//true
}
}
Arrays:
• 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, 2nd
element is stored on 1st index and so on.
Advantages:
1. Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
2. Random access: We can get any data located at an index position.
Disadvantages:
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.
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; System.out.println(cars[0]);
// Outputs Volvo
Array Length
To find out how many elements an array has, use the length property:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; System.out.println(cars.length); //
Outputs 4
Multidimensional Arrays:
A multidimensional array is an array containing one or more arrays.
Control statements:
A control statement in java is a statement that determines whether the other statements will be
executed or not. It controls the flow of a program. An ‘if’ statement in java determines the
sequence of execution between a set of two statements.
Control Statements can be divided into three categories, namely
1. Selection statements
2. Iteration statements
3. Jump statements
Simple if statement:
if statement is the most simple decision making statement. It is used to decide whether a
certain statement or block of statements will be executed or not i.e if a certain condition is true
then a block of statement is executed otherwise not.
Syntax:
if(condition)
{
// Statements to execute if condition is true
}
Here, condition after evaluation will be either true or false. if statement accepts boolean
values – if the value is true then it will execute the block of statements under it.
If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by default if
statement will consider the immediate one statement to be inside its block. For example,
if(condition)
statement1;
statement2;
// Here if the condition is true, if block will consider only statement1 to be inside its
block.
Example:
// Java program to illustrate If statement
class IfDemo
{
public static void main(String args[])
{
int i = 10;
if (i > 15)
System.out.println("10 is less than 15");
// This statement will be executed
// as if considers one statement by default
System.out.println("I am Not in if");
}
}
if-else:
The if statement alone tells us that if a condition is true it will execute a block of
statements and if the condition is false it won’t. But what if we want to do something else if the
condition is false. Here comes the else statement. We can use the else statement with if
statement to execute a block of code when the condition is false.
Syntax:
if (condition)
{ // Executes this block if // condition is true }
else
{ // Executes this block if // condition is false }
Example:
// Java program to illustrate if-else statement
class IfElseDemo
{
public static void main(String args[])
if (i < 15)
System.out.println("i is smaller than 15");
else
System.out.println("i is greater than 15");
}
}
Output:
i is smaller than 15
Nested-if:
A nested if is an if statement that is the target of another if or else. Nested if statements means
an if statement inside an if statement. Yes, java allows us to nest if statements within if
statements. i.e, we can place an if statement inside another if statement.
Syntax:
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}
Example:
// Java program to illustrate nested-if
statement
class NestedIfDemo
{
public static void main(String args[]) {
int i = 10;
if (i == 10)
{
if (i < 15)
System.out.println("i is smaller than 15");
if (i < 12)
System.out.println("i is smaller than 12 too");
else
System.out.println("i is greater than 15");
}
}
if-else-if ladder:
Here, a user can decide among multiple options.The if statements are executed from the top
down. As soon as one of the conditions controlling the if is true, the statement associated with
that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then
the final else statement will be executed.
Example:
// Java program to illustrate if-else-if ladder
class ifelseifDemo
{
public static void main(String args[])
{
int i = 20;
if (i == 10)
System.out.println("i is 10");
else if (i == 15)
System.out.println("i is 15");
else if (i == 20)
System.out.println("i is 20");
else
System.out.println("i is not present");
}
}
Switch-case:
The switch statement is a multiway branch statement. It provides an easy way to
dispatch execution to different parts of code based on
the value of the expression.
Syntax:
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
case valueN:
statementN;
break;
default:
statementDefault;
}
• Expression can be of type byte, short, int char or an enumeration. Beginning with JDK7,
expression can also be of type String.
• Duplicate case values are not allowed.
• The default statement is optional.
Example:
// Java program to illustrate switch-case
class SwitchCaseDemo
{
public static void main(String args[])
{
int i = 9;
switch (i)
{
case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
default:
System.out.println("i is greater than 2.");
}
}
Jump Statements:
• Java supports three jump statement: break, continue and return.
• These three statements transfer control to other part of the program.
Example:
// Java program to illustrate using
// break to exit a loop
class BreakLoopDemo
{
public static void main(String args[])
{
// Initially loop is set to run from 0-9
for (int i = 0; i < 10; i++)
{
// terminate loop when i is 5.
if (i == 5)
break;
Continue:
• Sometimes it is useful to force an early iteration of a loop. That is, you might want to
continue running the loop but stop processing the remainder of the code in its body for
this particular iteration.
• This is, in effect, a goto just past the body of the loop, to the loop’s end.
• The continue statement performs such an action.
Example:
class ContinueDemo
{
public static void main(String args[])
{
for (int i = 0; i < 10; i++)
{
// If the number is even
// skip and continue
if (i%2 == 0)
continue;
// If number is odd, print it
System.out.print(i + " ");
}
}
}
Return
The return statement is used to explicitly return from a method. That is, it causes a program
control to transfer back to the caller of the method.
Example:
class Return
{
public static void main(String args[])
Loops in Java
In programming languages, loops are used to execute a set of instructions/functions repeatedly
when some conditions become true. There are three types of loops in Java.
• for loop
• while loop
• do-while loop
Example:
//Java Program to demonstrate the example of for loop
//which prints table of 1
public class ForExample {
public static void main(String[] args) {
//Code of Java for loop
for(int i=1;i<=10;i++){
System.out.println(i);
}
}
}
Example:
//A Java program to demonstrate the use of labeled for loop
public class LabeledForExample {
public static void main(String[] args) {
//Using Label for outer and for loop
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break aa;
}
System.out.println(i+" "+j);
}
}
}
}
Syntax:
while(condition)
{
//code to be executed
}
Example:
public class WhileExample {
public static void main(String[] args) {
int i=1;
while(i<=10){
System.out.println(i);
i++;
}
}
}
}
Example:
public class WhileExample2 {
public static void main(String[] args) {
while(true){
System.out.println("infinitive while loop");
} } }
Example:
public class DoWhileExample {
public static void main(String[] args) {
int i=1;
do{
System.out.println(i);
i++;
}while(i<=10);
}
}
Narrowing Casting
• Narrowing casting must be done manually by placing the type in parentheses in front of
the value:
Example
public class Main
{
public static void main(String[] args)
{
double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting: double to int
System.out.println(myDouble); // Outputs 9.78
System.out.println(myInt); // Outputs 9
}
}
1 Type casting is a mechanism in which one Type conversion allows a compiler to convert one
data type is converted to another data type data type to another data type at the compile time of
using a casting () operator by a a program or code.
programmer.
2 It can be used both compatible data type Type conversion is only used with compatible data
and incompatible data type. types, and hence it does not require any casting
operator.
8 There is a possibility of data or information In type conversion, data is unlikely to be lost when
being lost in type casting. converting from a small to a large data type.
OOPs Concepts:
• Class
• Objects
• Data Abstraction
• Encapsulation
• Inheritance
• Polymorphism
• Dynamic Binding
• Message Passing
1. Class:
a) A class is a user-defined data type. It consists of data members and member functions,
which can be accessed and used by creating an instance of that class.
b) It represents the set of properties or methods that are common to all objects of one type.
A class is like a blueprint for an object.
c) For Example:
d) Consider the Class of Cars.
e) There may be many cars with different names and brands but all of them will share some
common properties like all of them will have 4 wheels, Speed Limit, Mileage range, etc.
So here, Car is the class, and wheels, speed limits, mileage are their properties.
5. Polymorphism:
a. The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form.
b. For example, A person at the same time can have different characteristics. Like a
man at the same time is a father, a husband, an employee. So the same person posses
different behavior in different situations. This is called polymorphism.
6. Dynamic Binding:
a. In dynamic binding, the code to be executed in response to the function call is
decided at runtime.
b. Dynamic binding means that the code associated with a given procedure call is not
known until the time of the call at run time.
c. Dynamic Method Binding One of the main advantages of inheritance is that some
derived class D has all the members of its base class B. Once D is not hiding any of
the public members of B, then an object of D can represent B in any context where a
B could be used. This feature is known as subtype polymorphism.
• For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It
is used to write, so writing is its behavior.
• An object is an instance of a class. A class is a template or blueprint from which objects
are created. So, an object is the instance(result) of a class.
Object Definitions:
• An object is a real-world entity.
• An object is a runtime entity.
• The object is an entity which has state and behavior.
• The object is an instance of a class.
Method in Java
• In Java, a method is like a function which is used to expose the behavior of an object.
• Advantage of Method
• Code Reusability
• Code Optimization
New Keyword
• The new keyword is used to allocate memory at runtime. All objects get memory in
Heap memory area.
• In this example, we have created a Student class which has two data members id and
name. We are creating the object of the Student class by new keyword and printing the
object's value.
File: Student.java
//Defining a Student class.
class Student{
//defining fields
int id;//field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[]) {
//Creating an object or instance
Student s1=new Student();//creating an object of Student
//Printing values of the object
System.out.println(s1.id); //accessing member through reference variable
System.out.println(s1.name);
}
}
File: TestStudent1.java
//Java Program to demonstrate having the main method in
//another class
//Creating Student class.
class Student{
int id;
String name;
}
//Creating another class TestStudent1 which contains the main method
class TestStudent1{
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
3 Ways to initialize object
There are 3 ways to initialize object in Java.
• By reference variable
• By method
• By constructor
As you can see in the above figure, object gets the memory in heap memory area. The
reference variable refers to the object allocated in the heap memory area. Here, s1 and s2
both are reference variables that refer to the objects allocated in memory.
ArrayOfObjects.java
public class ArrayOfObjects
{
public static void main(String args[])
{
//create an array of product object
Product[] obj = new Product[5] ;
//create & initialize actual product objects using constructor
obj[0] = new Product(23907,"Dell Laptop");
obj[1] = new Product(91240,"HP 630");
obj[2] = new Product(29823,"LG OLED TV");
obj[3] = new Product(11908,"MI Note Pro Max 9");
obj[4] = new Product(43590,"Kingston USB");
//display the product object data
System.out.println("Product Object 1:");
Constructor
• In Java, a constructor is a block of codes similar to the method. It is called when an
instance of the class is created. At the time of calling constructor, memory for the object
is allocated in the memory.
• It is a special type of method which is used to initialize the object.
• Every time an object is created using the new() keyword, at least one constructor is
called.
• It calls a default constructor if there is no constructor available in the class. In such case,
Java compiler provides a default constructor by default.
• There are two types of constructors in Java: no-arg constructor, and parameterized
constructor.
• Note: It is called constructor because it constructs the values at the time of object
creation. It is not necessary to write a constructor for a class. It is because java compiler
creates a default constructor if your class doesn't have any.
A constructor must not have a return type. A method must have a return
type.
The Java compiler provides a default constructor if The method is not provided by the
you don't have any constructor in a class. compiler in any case.
The constructor name must be same as the class The method name may or may not
name. be same as the class name.
Private Y` N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
1) By nulling a reference:
• Employee e=new Employee();
• e=null;
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(){}
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(){}
Type Description
Member Inner Class A class created within class and outside method.
String Class
• In Java, string is basically an object that represents sequence of char values. An array of
characters works same as Java string.
• For example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
• is same as:
String s="javatpoint";
• Java String class provides a lot of methods to perform operations on strings such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(),
substring() etc.
• The Java String is immutable which means it cannot be changed. Whenever we change
any string, a new instance is created. For mutable strings, you can use StringBuffer and
StringBuilder classes.
1) String Literal
• Java String literal is created by using double quotes. For Example:
• String s="welcome";
• Each time you create a string literal, the JVM checks the "string constant pool" first. If
the string already exists in the pool, a reference to the pooled instance is returned. If the
string doesn't exist in the pool, a new string instance is created and placed in the pool.
For example:
• String s1="Welcome";
• String s2="Welcome";//It doesn't create a new instance
• In the above example, only one object will be created. Firstly, JVM will not find any
string object with the value "Welcome" in string constant pool, that is why it will create
a new object.
• After that it will find the string with the value "Welcome" in the pool, it will not create a
new object but will return the reference to the same instance.
• String objects are stored in a special memory area known as the "string constant pool".
• Why Java uses the concept of String literal?
• To make Java more memory efficient (because no new objects are created if it exists
already in the string constant pool).
2) By new keyword
• String s=new String("Welcome");//creates two objects and one reference varable
• In such case, JVM will create a new string object in normal (non-pool) heap
memory, and the literal "Welcome" will be placed in the string constant pool. The
variable s will refer to the object in a heap (non-pool).
public clas s StringExample{
public static void main(String args[]){
String s1="java";//creating string by java string literal
1 char charAt(int index) returns char value for the particular index
4 static String format(Locale l, String returns formatted string with given locale.
format, Object... args)
6 String substring(int beginIndex, int returns substring for given begin index and end
endIndex) index.
10 boolean equals(Object another) checks the equality of string with the given
object.
13 String replace(char old, char new) replaces all occurrences of the specified char
value.
20 int indexOf(int ch, int fromIndex) returns the specified char value index starting
with given index.
22 int indexOf(String substring, int returns the specified substring index starting
fromIndex) with given index.
2) String is slow and consumes more StringBuffer is fast and consumes less memory
memory when you concat too many when you cancat strings.
strings because every time it creates
new instance.
3) String class overrides the equals() StringBuffer class doesn't override the equals()
method of Object class. So you can method of Object class.
compare the contents of two strings by
equals() method.
Inheritance: Basic concepts – Forms of inheritance – Super key word – method overriding
– Abstract classes – Dynamic method dispatch – The Object class. Packages: Defining –
Creating and Accessing – importing packages. Interfaces: Defining – Implementing –
Applying – Variables and extending interfaces
• Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented
programming system).
• The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and
fields of the parent class. Moreover, you can add new methods and fields in your current
class also.
• Inheritance represents the IS-A relationship which is also known as a parent-
child relationship.
• Why use inheritance in java
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.
• Reusability: As the name specifies, reusability is a mechanism which facilitates you to
reuse the fields and methods of the existing class when you create a new class. You can
use the same fields and methods already defined in the previous class.
• class Subclass-name extends Superclass-name
o {
o //methods and fields
o }
• The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.
• In the terminology of Java, a class which is inherited is called a parent or superclass, and
the new class is called child or subclass.
Inheritance – Single
Import java.io.*;
import java.util.Scanner;
class Student
{
Inheritance – Hierarchical
import java.io.*;
import java.util.Scanner;
class Player
{
public int number;
String name, role, country;
public void method()
{
Scanner ob = new Scanner(System.in);
System.out.print("Enter player name :");
name=ob.nextLine();
System.out.print("Enter Jersey number :");
number=ob.nextInt();
System.out.print("Enter the Nationality :");
country=ob.nextLine();
country=ob.nextLine();
} }
class Batsman extends Player
{ float avg;
public void method1()
{
Scanner ob = new Scanner(System.in);
System.out.print("Enter the Role of Batsman :"); role=ob.nextLine();
System.out.print("Enter Batting Average:"); avg=ob.nextFloat();
}
public void display()
{
Inheritance – Multilevel
import java.util.*;
class Grandparent
{
protected long aadharno;
public String gpname;
String address;
String relegion;
public void getgp()
{
Scanner s1=new Scanner(System.in);
System.out.print("\nEnter the aadhar number:");
aadharno=s1.nextLong();
System.out.print("\nEnter the Grand Parent name:");
gpname=s1.next();
System.out.print("\nEnter the address:");
address=s1.next();
}
}
class Parent extends Grandparent
{
String pname,occ;
public void getp()
{
Scanner s2=new Scanner(System.in);
System.out.print("\nEnter the Parent name:");
pname=s2.next();
System.out.print("\nEnter the Occupation:");
SUPER KEYWORD
• The super keyword in Java is a reference variable which is used to refer immediate
parent class object.
• Whenever you 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
• super can be used to refer immediate parent class instance variable.
• super can be used to invoke immediate parent class method.
• super() can be used to invoke immediate parent class constructor.
• Note: super() is added in each class constructor automatically by compiler if there is
no super() or this().
Example:
class Vehicle
{
intmaxSpeed = 120;
}
class Car extends Vehicle
{
intmaxSpeed = 180;
void display()
{
class Test
{
public static void main(String[] args)
{
Car small = new Car();
small.display();
}
}
voiddisplay()
{
message();
Super.message();
}
}
classTest
{
publicstaticvoidmain(String args[])
{
Student s = newStudent();
s.display();
}
}
• Super keyword can also be used to access the parent class constructor. One more
important thing is that, ‘’super” can call both parametric and default constructor.
Example:
class Person
{
Person()
{
System.out.println("Person class Constructor");
}
}
class Test
{
public static void main(String[] args)
{
Student s = new Student();
}
}
METHOD OVERRIDING:
• Overriding is a feature that allows a subclass or child class to provide a specific
implementation of a method that is already provided by one of its super-classes or
parent classes.
• When a method in a subclass has the same name, same parameters or signature and
same return type(or sub-type) as a method in its super-class, then the method in the
subclass is said to override the method in the super-class.
Example:
classParent
{
voidshow()
{
System.out.println("Parent's show()");
}
}
classMain
{
publicstaticvoidmain(String[] args)
{
Parent obj = newChild();
obj.show();
}
}
Output:
Parent's show()
Child's show()
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 you type the text and send the message. You don't know
the internal processing about the message delivery.
• Abstraction lets you focus on what the object does instead of how it does it.
• Ways to achieve Abstraction
• There are two ways to achieve abstraction in java
o Abstract class (0 to 100%)
o Interface (100%)
abstract class A
{
2 Resolve static binding use type of the class Dynamic binding uses object to
mechanism and fields resolve binding
4. Type of private, final and static methods and Virtual methods use dynamic
Methods variables uses static binding binding
class Bank{
float getRateOfInterest(){return 0;}
}
class SBI extends Bank{
float getRateOfInterest(){return 8.4f;}
}
class ICICI extends Bank{
float getRateOfInterest(){return 7.3f;}
}
class AXIS extends Bank{
float getRateOfInterest(){return 9.7f;}
}
class TestPolymorphism
{
public static void main(String args[]){
Bank b;
//we don't know what object will be returned from this method
• The Object class provides some common behaviors to all the objects such as object
can be compared, object can be cloned, object can be notified etc.
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
CloneNotSupportedException object.
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
nanos)throws InterruptedException milliseconds 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
InterruptedException notifies (invokes notify() or notifyAll() method).
protected void finalize()throws Throwable is invoked by the garbage collector before object is
being garbage collected.
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");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
• If you import a package, all the classes and interface of that package will be
imported excluding the classes and interfaces of the subpackages. Hence, you need
to import the subpackage as well.
• Note: Sequence of the program must be package then import then class.
Subpackage in java
• Package inside the package is called the subpackage. It should be created to categorize the
package further.
• Let's take an example, Sun Microsystem has definded a package named java that contains
many classes like System, String, Reader, Writer, Socket etc.
• These classes represent a particular group e.g. Reader and Writer classes are for
Input/Output operation, Socket and ServerSocket classes are for networking etc and so on.
• So, Sun has subcategorized the java package into subpackages such as lang, net, io etc. and
put the Input/Output related classes in io package, Server and ServerSocket classes in net
packages and so on.
• Example of Subpackage
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
• How to send the class file to another directory or drive?
• There is a scenario, I want to put the class file of A.java source file in classes folder of c:
drive. For example:
//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
• 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
• Ways to load the class files or jar files
• There are two ways to load the class files temporary and permanent.
• Temporary
o By setting the classpath in the command prompt
o By -classpath switch
• Permanent
o By setting the classpath in the environment variables
o By creating the jar file, that contains all the class files, and copying the jar file in
the jre/lib/ext folder.
Example
package pack;
import java.io.*;
public class Compute
{
int a,b;
public void add(int a,int b)
{
Defining Interface
• The Java compiler adds public and abstract keywords before the interface method.
Moreover, it adds public, static and final keywords before data members.
Implementing Interface
Extending interface
Example
interface ISports
{
public void SetTeam(String t1,String t2, int score1, int score2);
public void ShowResult();
}
c.SetTeam("India", "England",240,220);
h.SetTeam("India", "Germany",3,2);
c.ShowResult();
h.ShowResult();
Output:
Summary
statement 10; Suppose there are 10 statements in your program and there occurs an exception at
statement 5, the rest of the code will not be executed i.e. statement 6 to 10 will not be executed.
If we perform exception handling, the rest of the statement will be executed. That is why we use
exception handling in Java.
• There are mainly two types of exceptions: checked and unchecked. Here, an error is
considered as the unchecked exception. According to Oracle, there are three types of
exceptions:
o Checked Exception
o Unchecked Exception
o Error
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Keyword Description
The "try" keyword is used to specify a block where we should place exception code.
Try The try block must be followed by either catch or finally. It means, we can't use try
block alone.
The "catch" block is used to handle the exception. It must be preceded by try block
Catch which means we can't use catch block alone. It can be followed by finally block
later.
The "finally" block is used to execute the important code of the program. It is
finally
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 doesn't throw an exception.
It specifies that there may occur an exception in the method. It is always used with
method signature
The wrong formatting of any value may occur NumberFormatException. Suppose I have a
string variable that has characters, converting this variable into digit will occur
NumberFormatException.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
As displayed in the above example, the rest of the code is not executed (in such case, the rest of
the code statement is not printed).
There can be 100 lines of code after exception. So all the code after exception will not be
executed.
Output:
java.lang.ArithmeticException: / by zero rest of the code
Example:
public class TestFinallyBlock2{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main ava.lang.ArithmeticException:/ by zero
finally block is always executed
rest of the code...
throw exception;
4) Throw is used within the method. Throws is used with the method signature.
5) You cannot throw multiple You can declare multiple exceptions e.g.
exceptions. public void method()throws
IOException,SQLException.
1) Final is used to apply restrictions on class, Finally is used to place Finalize is used to
method and variable. Final class can't be important code, it will perform clean up
inherited, final method can't be overridden be executed whether processing just before
and final variable value can't be changed. exception is handled or object is garbage
not. collected.
Output:
Exception occured: InvalidAgeException:not valid
rest of the code…
Multithreading
• Multithreading in Java is a process of executing multiple threads simultaneously.
• A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing
and multithreading, both are used to achieve multitasking.
• However, we use multithreading than multiprocessing because threads use a shared
memory area. They don't allocate separate memory area so saves memory, and context-
switching between the threads takes less time than process.
• Java Multithreading is mostly used in games, animation, etc.
21. static boolean interrupted() It tests whether the current thread has been
interrupted.
24. static boolean holdLock() It returns true if and only if the current
thread holds the monitor lock on the
specified object.
36. static void setDefaultUncaug It sets the default handler invoked when a
htExceptionHand thread abruptly terminates due to an
ler() uncaught exception
• New
The thread is in new state if you create an instance of Thread class but before the
invocation of start() method.
• Runnable
The thread is in runnable state after invocation of start() method, but the thread
scheduler has not selected it to be the running thread.
• Running
The thread is in running state if the thread scheduler has selected it.
• Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
• Terminated
A thread is in terminated or dead state when its run() method exits.
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be
executed by a thread. Runnable interface have only one method named run().
public void run(): is used to perform action for a thread.
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following
tasks:
• A new thread starts(with new callstack).
• The thread moves from New state to the Runnable state.
• When the thread gets a chance to execute, its target run() method will run.
Example
import java.io.*;
class AnimalThread implements Runnable
{
public void run()
{
for (int x = 1; x < 4; x++)
{
System.out.println("Run by " + Thread.currentThread().getName());
try
{
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
Thread.sleep(10000);
System.out.println("Thread State of Cat in Main method after sleep: " + cat.getState());
System.out.println("Thread State of Dog in Main method after sleep: " + dog.getState());
System.out.println("Thread State of Cow in Main method after sleep: " + cow.getState());
}
}
Synchronization in Java
• Synchronization in java is the capability to control the access of multiple threads to any
shared resource.
• Java Synchronization is better option where we want to allow only one thread to access
the shared resource.
Thread Synchronization
• There are two types of thread synchronization mutual exclusive and inter-thread
communication.
• Mutual Exclusive
o Synchronized method.
o Synchronized block.
o static synchronization.
• Cooperation (Inter-thread communication in java)
• Mutual Exclusive
• Mutual Exclusive helps keep threads from interfering with one another while sharing
Output:
5
10
15
20
25
100
200
300
400
500
class Table{
void printTable(int n){
synchronized(this){//synchronized block
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}//end of the method
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
Static Synchronization
• If you make any static method as synchronized, the lock will be on the class not on object.
Deadlock in java
• Deadlock in java is a part of multithreading. Deadlock can occur in a situation when a
thread is waiting for an object lock, that is acquired by another thread and second thread is
waiting for an object lock that is acquired by first thread. Since, both threads are waiting for
each other to release the lock, the condition is called deadlock.
1) wait() method
Causes current thread to release the lock and wait until either another thread invokes the notify()
method or the notifyAll() method for this object, or a specified amount of time has elapsed.
The current thread must own this object's monitor, so it must be called from the synchronized
method only otherwise it will throw exception.
Method Description
public final void wait(long timeout)throws waits for the specified amount of time.
InterruptedException
2) notify() method
• Wakes up a single thread that is waiting on this object's monitor. If any threads are
waiting on this object, one of them is chosen to be awakened. The choice is arbitrary
and occurs at the discretion of the implementation. Syntax:
• public final void notify()
3) notifyAll() method
• Wakes up all threads that are waiting on this object's monitor. Syntax:
• public final void notifyAll()
Why wait(), notify() and notifyAll() methods are defined in Object class not Thread class?
• It is because they are related to lock and object has a lock.
• Difference between wait and sleep?
Let's see the important differences between wait and sleep methods.
wait() sleep()
wait() method releases the lock sleep() method doesn't release the lock.
should be notified by notify() or notifyAll() after the specified amount of time, sleep is
methods completed.
Java Enumeration
• The Enum in Java is a data type which contains a 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), season (SPRING, SUMMER, WINTER, and AUTUMN or FALL), colors (RED,
YELLOW, BLUE, GREEN, WHITE, and BLACK) etc.
• According to the Java naming conventions, we should have all constants in capital letters.
So, we have enum constants in capital letters.
• Java Enums can be thought of as classes which have a fixed set of constants (a variable that
does not change).
• The Java enum constants are static and final implicitly. It is available since JDK 1.5.
• Enums are used to create our own data type like classes. The enum data type (also known as
Enumerated Data Type) is used to define an enum in Java. Unlike C/C++, enum in Java is
more powerful. Here, we can define an enum either inside the class or outside the class.
• Java Enum internally inherits the Enum class, so it cannot inherit any other class, but it can
implement many interfaces. We can have fields, constructors, methods, and main methods
in Java enum.
Output:
WINTER
SPRING
SUMMER
FALL
class EnumExample1
{
Output:
WINTER
SPRING
SUMMER
FALL
Value of WINTER is: WINTER
Index of WINTER is: 0
Index of SUMMER is: 2
Output:50 5
Simple Example of Unboxing in java:
The automatic conversion of wrapper class type into corresponding primitive type, is known
as Unboxing.
class UnboxingExample1{
public static void main(String args[]){
Integer i=new Integer(50);
int a=i;
System.out.println(a);
}
}
Output:int
Output: Integer
Collections in Java
● The Collection in Java is a framework that provides an architecture to store and
manipulate the group of objects.
● Java Collections can achieve all the operations that you perform on a data such as
searching, sorting, insertion, manipulation, and deletion.
● Java Collection means a single unit of objects. Java Collection framework provides
many interfaces (Set, List, Queue, Deque) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
What is Collection in Java: A Collection represents a single unit of objects, i.e., a group.
What is a framework in Java
● It provides readymade architecture.
● It represents a set of classes and interfaces.
● It is optional.
What is Collection framework
● The Collection framework represents a unified architecture for storing and manipulating
a group of objects. It has:
● Interfaces and its implementations, i.e., classes
● Algorithm
SortedSet tailSet(E fromElement) It returns a set of elements that are greater than or equal
to the specified element.
NavigableSet tailSet(E It returns a set of elements that are greater than or equal
fromElement, boolean inclusive) to (if, inclusive is true) the specified element.
boolean contains(Object o) It returns true if this set contains the specified element.
boolean remove(Object o) It is used to remove the specified element from this set
if it is present.
void clear() It is used to remove all of the elements from this set.
Iterable Interface
● The Iterable interface is the root interface for all the collection classes. The Collection
interface extends the Iterable interface and therefore all the subclasses of Collection
interface also implement the Iterable interface.
● It contains only one abstract method. i.e.,
● Iterator<T> iterator()
● It returns the iterator over the elements of type T.
Collection Interface
● The Collection interface is the interface which is implemented by all the classes in the
collection framework. It declares the methods that every collection will have. In other
words, we can say that the Collection interface builds the foundation on which the
collection framework depends.
● Some of the methods of Collection interface are Boolean add ( Object obj), Boolean
addAll ( Collection c), void clear(), etc. which are implemented by all the subclasses of
Collection interface.
List Interface
● List interface is the child interface of Collection interface. It inhibits a list type data
structure in which we can store the ordered collection of objects. It can have duplicate
values.
● List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.
● To instantiate the List interface, we must use :
● List <data-type> list1= new ArrayList();
● List <data-type> list2 = new LinkedList();
● List <data-type> list3 = new Vector();
● List <data-type> list4 = new Stack();
● There are various methods in List interface that can be used to insert, delete, and access
the elements from the list.
LinkedList :
● LinkedList implements the Collection interface. It uses a doubly linked list internally to
store the elements. It can store the duplicate elements. It maintains the insertion order
and is not synchronized. In LinkedList, the manipulation is fast because no shifting is
required.
Consider the following example.
import java.util.*;
public class TestJavaCollection2{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
Vector :
• Vector uses a dynamic array to store the data elements. It is similar to ArrayList. However,
It is synchronized and contains many methods that are not the part of Collection framework.
• Consider the following example.
import java.util.*;
public class TestJavaCollection3{
public static void main(String args[]){
Vector<String> v=new Vector<String>();
v.add("Ayush");
v.add("Amit");
v.add("Ashish");
v.add("Garima");
Iterator<String> itr=v.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ayush
Amit
Ashish
Garima
Stack :
● The stack is the subclass of Vector. It implements the last-in-first-out data structure, i.e.,
Stack. The stack contains all of the methods of Vector class and also provides its
methods like boolean push(), boolean peek(), boolean push(object o), which defines its
properties.
● Consider the following example.
import java.util.*;
public class TestJavaCollection4{
public static void main(String args[]){
Stack<String> stack = new Stack<String>();
stack.push("Ayush");
stack.push("Garvit");
stack.push("Amit");
stack.push("Ashish");
stack.push("Garima");
stack.pop();
Iterator<String> itr=stack.iterator();
Queue Interface
● Queue interface maintains the first-in-first-out order. It can be defined as an ordered list
that is used to hold the elements which are about to be processed. There are various
classes like PriorityQueue, Deque, and ArrayDeque which implements the Queue
interface.
● Queue interface can be instantiated as:
● Queue<String> q1 = new PriorityQueue();
● Queue<String> q2 = new ArrayDeque();
● There are various classes that implement the Queue interface, some of them are given
below.
PriorityQueue
● The PriorityQueue class implements the Queue interface. It holds the elements or
objects which are to be processed by their priorities. PriorityQueue doesn't allow null
values to be stored in the queue. Consider the following example.
import java.util.*;
public class TestJavaCollection5{
public static void main(String args[]){
PriorityQueue<String> queue=new PriorityQueue<String>();
queue.add("Amit Sharma");
queue.add("Vijay Raj");
queue.add("JaiShankar");
queue.add("Raj");
System.out.println("head:"+queue.element());
System.out.println("head:"+queue.peek());
System.out.println("iterating the queue elements:");
Iterator itr=queue.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
queue.remove();
queue.poll();
System.out.println("after removing two elements:");
Iterator<String> itr2=queue.iterator();
while(itr2.hasNext()){
}System.out.println(itr2.next());
}
Deque Interface
● Deque interface extends the Queue interface. In Deque, we can remove and add the
elements from both the side. Deque stands for a double-ended queue which enables us to
perform the operations at both the ends.
● Deque can be instantiated as:
● Deque d = new ArrayDeque();
ArrayDeque
● ArrayDeque class implements the Deque interface. It facilitates us to use the Deque.
Unlike queue, we can add or delete the elements from both the ends.
● ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.
● Consider the following example.
import java.util.*;
public class TestJavaCollection6{
public static void main(String[] args) {
//Creating Deque and adding elements
Deque<String> deque = new ArrayDeque<String>();
deque.add("Gautam");
deque.add("Karan");
deque.add("Ajay");
//Traversing elements
for (String str : deque) {
System.out.println(str);
}
}
}
Output:
Gautam
Karan
Ajay
Set Interface
● Set Interface in Java is present in java.util package. It extends the Collection interface. It
represents the unordered set of elements which doesn't allow us to store the duplicate
items. We can store at most one null value in Set. Set is implemented by HashSet,
LinkedHashSet, and TreeSet.
HashSet
HashSet class implements Set Interface. It represents the collection that uses a hash table for
storage. Hashing is used to store the elements in the HashSet. It contains unique items.
Consider the following example.
import java.util.*;
public class TestJavaCollection7{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Vijay
Ravi
Ajay
LinkedHashSet
Linked Hash Set class represents the LinkedList implementation of Set Interface. It extends the
HashSet class and implements Set interface. Like HashSet, It also contains unique elements. It
maintains the insertion order and permits null elements.
Output:
Ravi
Vijay
Ajay
TreeSet
• Java TreeSet class implements the Set interface that uses a tree for storage. Like
HashSet, TreeSet also contains unique elements. However, the access and retrieval
time of TreeSet is quite fast. The elements in TreeSet stored in ascending order.
• Consider the following example:
import java.util.*;
public class TestJavaCollection9{
public static void main(String args[]){
//Creating and adding elements
TreeSet<String> set=new TreeSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ajay
Ravi
Vijay
Example 2
/* Ways to iterate the elements of the collection in Java
There are various ways to traverse the collection elements:
By Iterator interface, By for-each loop. By ListIterator interface. By for loop.
By forEach() method.
By forEachRemaining() method.*/
import java.util.*;
class ArrayList4{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
System.out.println("Traversing list through List Iterator:");
//Here, element iterates in reverse order
ListIterator<String> list1=list.listIterator(list.size());
while(list1.hasPrevious())
{
String str=list1.previous();
System.out.println(str);
}
System.out.println("Traversing list through for loop:");
for(int i=0;i<list.size();i++)
{
System.out.println(list.get(i));
}
System.out.println("Traversing list through forEach() method:");
//The forEach() method is a new feature, introduced in Java 8.
list.forEach(a->{ //Here, we are using lambda expression
System.out.println(a);
});
System.out.println("Traversing list through forEachRemaining() method:");
Iterator<String> itr=list.iterator();
itr.forEachRemaining(a-> //Here, we are using lambda expression
{
System.out.println(a);
});
}
}
Example 3
import java.util.*;
class SortArrayList
{
public static void main(String args[])
Java Vector
• Vector is like the dynamic array which can grow or shrink its size. Unlike array, we can
store n-number of elements in it as there is no size limit. It is a part of Java Collection
framework since Java 1.2.
• It is found in the java.util package and implements the List interface, so we can use all
the methods of List interface here.
• It is similar to the ArrayList, but with two differences-
• Vector is synchronized.
• Java Vector contains many legacy methods that are not the part of a collections
framework.
2) addAll() It is used to append all of the elements in the specified collection to the end of
this Vector.
3) addElement() It is used to append the specified component to the end of this vector. It
increases the vector size by one.
4) capacity() It is used to get the current capacity of this vector.
12) ensureCapacity() It is used to increase the capacity of the vector which is in use, if necessary. It
ensures that the vector can hold at least the number of components specified by
the minimum capacity argument.
13) equals() It is used to compare the specified object with the vector for equality.
15) forEach() It is used to perform the given action for each element of the Iterable until all
elements have been processed or the action throws an exception.
16) get() It is used to get an element at the specified position in the vector.
18) indexOf() It is used to get the index of the first occurrence of the specified element in the
vector. It returns -1 if the vector does not contain the element.
19) insertElementAt( It is used to insert the specified object as a component in the given vector at the
) specified index.
20) isEmpty() It is used to check if this vector has no components.
21) iterator() It is used to get an iterator over the elements in the list in proper sequence.
23) lastIndexOf() It is used to get the index of the last occurrence of the specified element in the
vector. It returns -1 if the vector does not contain the element.
24) listIterator() It is used to get a list iterator over the elements in the list in proper sequence.
25) remove() It is used to remove the specified element from the vector. If the vector does
not contain the element, it is unchanged.
26) removeAll() It is used to delete all the elements from the vector that are present in the
specified collection.
27) removeAllEleme It is used to remove all elements from the vector and set the size of the vector to
nts() zero.
28) removeElement() It is used to remove the first (lowest-indexed) occurrence of the argument from
37) size() It is used to get the number of components in the given vector.
38) sort() It is used to sort the list according to the order induced by the specified
Comparator.
39) spliterator() It is used to create a late-binding and fail-fast Spliterator over the elements in
the list.
40) subList() It is used to get a view of the portion of the list between fromIndex, inclusive,
and toIndex, exclusive.
41) toArray() It is used to get an array containing all of the elements in this vector in correct
order.
42) toString() It is used to get a string representation of the vector.
43) trimToSize() It is used to trim the capacity of the vector to the vector's current size.
Example
import java.util.*;
public class VectorExample1
{
public static void main(String args[])
{
//Create an empty vector with initial capacity 4
Vector<String> vec = new Vector<String>(4);
//Adding elements to a vector
vec.add("Tiger");
vec.add("Lion");
vec.add("Dog");
Java Stack
• The stack is a linear data structure that is used to store the collection of objects. It is
based on Last-In-First-Out (LIFO). Java collection framework provides many
interfaces and classes to store the collection of objects. One of them is the Stack
class that provides different operations such as push, pop, search, etc.
• In this section, we will discuss the Java Stack class, its methods, and implement the
stack data structure in a Java program. But before moving to the Java Stack class have
a quick view of how the stack works.
• The stack data structure has the two most important operations that are push and pop.
The push operation inserts an element into the stack and pop operation removes an
element from the top of the stack. Let's see how they work on stack.
Let's push 20, 13, 89, 90, 11, 45, 18, respectively into the stack.
Empty Stack: If the stack has no element is known as an empty stack. When the stack is
empty the value of the top variable is -1.
When we push an element into the stack the top is increased by 1. In the following figure,
Push 12, top=0
Push 6, top=1
Push 9, top=2
When we pop an element from the stack the value of top is decreased by 1. In the following
figure, we have popped 9
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 of Stack
import java.util.*;
class Stackeg
{
public static void main(String args[])
{
//creating an instance of Stack class
Stack<Integer> stk= new Stack<>();
// checking stack is empty or not
boolean result = stk.empty();
System.out.println("Is the stack empty? " + result);
// pushing elements into stack
stk.push(78);
result = stk.empty();
System.out.println("Is the stack empty? " + result);
stk.pop();
System.out.println("Elements in Stack: " + stk);
// Access element from the top of the stack
Integer num = stk.peek();
//prints stack
System.out.println("Element at top: " + num);
int location = stk.search(113);
System.out.println("Location of 113: " + location);
// Find the size of the Stack
int x=stk.size();
System.out.println("The stack size is: "+x);
}
}
boolean add(object) It is used to insert the specified element into this queue and return true upon
success.
boolean offer(object) It is used to insert the specified element into this queue.
Object remove() It is used to retrieves and removes the head of this queue.
Object poll() It is used to retrieves and removes the head of this queue, or returns null if this
queue is empty.
Object element() It is used to retrieves, but does not remove, the head of this queue.
Object peek() It is used to retrieves, but does not remove, the head of this queue, or returns null
if this queue is empty.
import java.util.*;
class TestCollection12{
public static void main(String args[]){
PriorityQueue<String> queue=new PriorityQueue<String>
queue.add("Amit");
queue.add("Vijay");
queue.add("Karan");
queue.add("Jai");
queue.add("Rahul");
System.out.println("head:"+queue.element());
System.out.println("head:"+queue.peek());
System.out.println("iterating the queue elements:");
Iterator itr=queue.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
queue.remove();
queue.poll();
System.out.println("after removing two elements:");
Iterator<String> itr2=queue.iterator();
while(itr2.hasNext()){
System.out.println(itr2.next());
}
}
}
Output:head:Amit
head:Amit
iterating the queue elements: Amit
Jai Karan
Vijay
Rahul
after removing two elements: Karan
Rahul
Vijay
Object remove() It is used to retrieves and removes the head of this deque.
ArrayDeque class
• The ArrayDeque class provides the facility of using deque and resizable-array. It inherits
AbstractCollection class and implements the Deque interface.
boolean add(E e) It is used to add the specified element to this set if it is not
already present.
boolean addAll(Collection<? It is used to add all of the elements in the specified collection to
extends E> c) this set.
SortedSet headSet(E It returns the group of elements that are less than the specified
toElement) element.
NavigableSet headSet(E It returns the group of elements that are less than or equal to(if,
toElement, boolean inclusive) inclusive is true) the specified element.
SortedSet tailSet(E It returns a set of elements that are greater than or equal to the
fromElement) specified element.
boolean remove(Object o) It is used to remove the specified element from this set if it is
present.
void clear() It is used to remove all of the elements from this set.
Object clone() It returns a shallow copy of this TreeSet instance.
E first() It returns the first (lowest) element currently in this sorted set.
E last() It returns the last (highest) element currently in this sorted set.
int size() It returns the number of elements in this set.
OUTPUT
Ajay
Ravi
Vijay
Highest Value: 12
Lowest Value: 66
Initial Set: [A, B, C, D, E]
Reverse Set: [E, D, C, B, A]
Head Set: [A, B, C]
SubSet: [B, C, D, E]
TailSet: [D, E]
OutputStream vs InputStream
• The explanation of OutputStream and InputStream classes are given below:
• OutputStream
• Java application uses an output stream to write data to a destination; it may be a file, an
array, peripheral device or socket.
• InputStream
• Java application uses an input stream to read data from a source; it may be a file, an array,
peripheral device or socket.
OutputStream class
• OutputStream class is an abstract class. It is the superclass of all classes representing an
output stream of bytes. An output stream accepts output bytes and sends them to some
sink.
Useful methods of OutputStream
Method Description
1) public void write(int)throws is used to write a byte to the current output stream.
IOException
2) public void write(byte[])throws is used to write an array of byte to the current output
IOException stream.
3) public void flush()throws IOException flushes the current output stream.
4) public void close()throws IOException is used to close the current output stream.
OutputStream Hierarchy
3) public void close()throws IOException is used to close the current input stream.
InputStream Hierarchy
Method Description
protected void finalize() It is used to clean up the connection with the file output stream.
void write(byte[] ary) It is used to write ary.length bytes from the byte array to the file
output stream.
void write(byte[] ary, int off, int len) It is used to write len bytes from the byte array starting at
offset off to the file output stream.
void write(int b) It is used to write the specified byte to the file output stream.
FileChannel getChannel() It is used to return the file channel object associated with the file
output stream.
FileDescriptor getFD() It is used to return the file descriptor associated with the stream.
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[])
{
try
{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
String s="Welcome to javaTpoint.";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}
Method Description
int available() It is used to return the estimated number of bytes that can be read from
the input stream.
int read() It is used to read the byte of data from the input stream.
int read(byte[] b) It is used to read up to b.length bytes of data from the input stream.
int read(byte[] b, int off, int It is used to read up to len bytes of data from the input stream.
len)
long skip(long x) It is used to skip over and discards x bytes of data from the input stream.
FileChannel getChannel() It is used to return the unique FileChannel object associated with the file
input stream.
BufferedOutputStream(OutputStream It creates the new buffered output stream which is used for
os, int size) writing the data to the specified output stream with a specified
buffer size.
void write(int b) It writes the specified byte to the buffered output stream.
void write(byte[] b, int off, int len) It write the bytes from the specified byte-input stream
into a specified byte array, starting with the given offset
int available() It returns an estimate number of bytes that can be read from the input stream
without blocking by the next invocation method for the input stream.
int read() It read the next byte of data from the input stream.
int read(byte[] b, int off, It read the bytes from the specified byte-input stream into a specified byte
int ln) array, starting with the given offset.
void close() It closes the input stream and releases any of the system resources
associated with the stream.
void reset() It repositions the stream at a position the mark method was last called on
this input stream.
void mark(int readlimit) It sees the general contract of the mark method for the input stream.
long skip(long x) It skips over and discards x bytes of data from the input stream.
boolean markSupported() It tests for the input stream to support the mark and reset methods.
int read(byte[] b) It is used to read the number of bytes from the input stream
int read(byte[] b, int off, int len) It is used to read len bytes of data from the input stream.
int readInt() It is used to read input bytes and return an int value.
char readChar() It is used to read two input bytes and returns a char value.
double readDouble() It is used to read eight input bytes and returns a double value.
boolean readBoolean() It is used to read one input byte and return true if byte is non
zero, false if byte is zero.
int skipBytes(int x) It is used to skip over x bytes of data from the input stream.
String readUTF() It is used to read a string that has been encoded using the UTF-
8 format.
void readFully(byte[] b) It is used to read bytes from the input stream and store them
into the buffer array.
void readFully(byte[] b, int off, It is used to read len bytes from the input stream.
int len)
int read() It is used to read the next byte of data from the input stream.
boolean markSupported() It is used to test if the input stream support mark and reset method.
void mark(int readlimit) It is used to mark the current position in the input stream.
Java - ObjectStreamClass
ObjectStreamClass act as a Serialization descriptor for class. This class contains the name and
serialVersionUID of the class.
Fields
Modifier and Type Field Description
static ObjectStreamField[] NO_FIELDS serialPersistentFields value indicating no serializable
fields
Methods
Modifier and Type Method Description
Class<?> forClass() It returns the class in the local VM that this
version is mapped to.
Static ObjectStreamClass lookup(Class<?> cl) It finds the descriptor for a class that can be
serialized.
Static ObjectStreamClass lookupAny(Class<?> It returns the descriptor for any class, regardless
cl) of whether it implements Serializable.
String toString() It returns a string describing this
ObjectStreamClass.
import java.io.ObjectStreamClass;
import java.util.Calendar;
public class ObjectStreamClassExample {
public static void main(String[] args) {
}
}
String readLine(String fmt, Object... It provides a formatted prompt then reads the
args) single line of text from the console.
Console format(String fmt, Object... It is used to write a formatted string to the console
args) output stream.
Console printf(String format, Object... It is used to write a string to the console output
args) stream.
Output
Java Reader
Java Reader is an abstract class for reading character streams. The only methods that a
subclass must implement are read(char[], int, int) and close(). Most subclasses, however,
will override some of the methods to provide higher efficiency, additional functionality, or
both.
Fields
Modifier and Field Description
Type
protected Object lock The object used to synchronize operations on this stream.
Methods
Modifier and Method Description
Type
abstract int read(char[] cbuf, int off, int len) It reads characters into a portion of an
array.
Example
import java.io.*;
public class ReaderExample {
public static void main(String[] args) {
try {
Reader reader = new FileReader("file.txt");
int data = reader.read();
while (data != -1) {
System.out.print((char) data);
Java Writer
It is an abstract class for writing to character streams. The methods that a subclass must
implement are write(char[], int, int), flush(), and close(). Most subclasses will override some
of the methods defined here to provide higher efficiency, functionality or both.
Fields
Modifier and Field Description
Type
protected Object lock The object used to synchronize operations on this stream.
Constructor
Modifier Constructor Description
Methods
Modifier and Method Description
Type
abstract void write(char[] cbuf, int off, int len) It writes a portion of an array of
characters.
Void write(String str, int off, int len) It writes a portion of a string.
FileWriter(File file) Creates a new file. It gets file name in File object.
Class methods
Method Description
void write(char[] cbuf, int off, int len) It is used to write a portion of an array of characters.
void write(String s, int off, int len) It is used to write a portion of a string.
BufferedReader(Reader rd, int size) It is used to create a buffered character input stream that
uses the specified size for an input buffer.
int read(char[] cbuf, int off, It is used for reading characters into a portion of an array.
int len)
boolean markSupported() It is used to test the input stream support for the mark and reset
method.
String readLine() It is used for reading a line of text.
boolean ready() It is used to test whether the input stream is ready to be read.
void reset() It repositions the stream at a position the mark method was last
called on this input stream.
void mark(int It is used for marking the present position in a stream.
readAheadLimit)
void close() It closes the input stream and releases any of the system
resources associated with the stream.
int i;
while((i=br.read())!=-1){
Another example of reading data from console until user writes stop
In this example, we are reading and printing the data until the user prints stop.
import java.io.*;
public class BufferedReaderExample{
public static void main(String args[])throws Exception{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
String name="";
Output
j : 106
a : 97
v : 118
a : 97
t : 116
p : 112
: 111
i : 105
n : 110
t : 116
void write(char[] c, int off, int len) It is used to write a character to the buffer.
void write(String str, int off, int len) It is used to write a portion of string to the buffer.
void println(boolean b) It prints the specified boolean value and terminates the line.
void println(char c) It prints the specified char value and terminates the line.
void println(char[] c) It prints the specified character array values and terminates
the line.
void println(int i) It prints the specified int value and terminates the line.
void println(long l) It prints the specified long value and terminates the line.
void println(float f) It prints the specified float value and terminates the line.
void println(double d) It prints the specified double value and terminates the line.
void println(String s) It prints the specified string value and terminates the line.
void println(Object obj) It prints the specified object value and terminates the line.
void printf(Object format, It writes the formatted string to the current stream.
Object... args)
void printf(Locale l, Object It writes the formatted string to the current stream.
format, Object... args)
void format(Object format, It writes the formatted string to the current stream using
void format(Locale l, Object It writes the formatted string to the current stream using
format, Object... args) specified format.
Output:
Printing simple integer: x = 100
Formatted with precison: PI = 3.14
Formatted to specific width: n = 5.2000
Formatted to right margin: n = 2324435.2500
Java Scanner
• Scanner class in Java is found in the java.util package. Java provides various ways to
read input from the keyboard, the java.util.Scanner class is one of them.
• The Java Scanner class breaks the input into tokens using a delimiter which is
whitespace by default. It provides many methods to read and parse various primitive
values.
• The Java Scanner class is widely used to parse text for strings and primitive types
using a regular expression. It is the simplest way to get input in Java. By the help of
Scanner in Java, we can get input from the user in primitive types such as int, long,
double, byte, float, short, etc.
• The Java Scanner class extends Object class and implements Iterator and Closeable
interfaces.
• The Java Scanner class provides nextXXX() methods to return the type of value such
as nextInt(), nextByte(), nextShort(), next(), nextLine(), nextDouble(), nextFloat(),
nextBoolean(), etc. To get a single character from the scanner, you can call
next().charAt(0) method which returns a single character.
Java Scanner Class Declaration
public final class Scanner
extends Object
implements Iterator<String>
3) Stream<MatchR findAll() It is used to find a stream of match results that match the
esult> provided pattern string.
4) String findInLine() It is used to find the next occurrence of a pattern
constructed from the specified string, ignoring delimiters.
6) Boolean hasNext() It returns true if this scanner has another token in its
input.
7) Boolean hasNextBigDe It is used to check if the next token in this scanner's input
cimal() can be interpreted as a BigDecimal using the
nextBigDecimal() method or not.
8) Boolean hasNextBigInt It is used to check if the next token in this scanner's input
eger() can be interpreted as a BigDecimal using the
nextBigDecimal() method or not.
9) boolean hasNextBoole It is used to check if the next token in this scanner's input
an() can be interpreted as a Boolean using the nextBoolean()
method or not.
10) boolean hasNextByte( It is used to check if the next token in this scanner's input
) can be interpreted as a Byte using the nextBigDecimal()
method or not.
11) boolean hasNextDoub It is used to check if the next token in this scanner's input
le() can be interpreted as a BigDecimal using the nextByte()
method or not.
12) boolean hasNextFloat( It is used to check if the next token in this scanner's input
) can be interpreted as a Float using the nextFloat() method
or not.
13) boolean hasNextInt() It is used to check if the next token in this scanner's input
can be interpreted as an int using the nextInt() method or
not.
15) boolean hasNextLong( It is used to check if the next token in this scanner's input
) can be interpreted as a Long using the nextLong()
method or not.
16) boolean hasNextShort It is used to check if the next token in this scanner's input
() can be interpreted as a Short using the nextShort()
method or not.
17) IOException ioException() It is used to get the IOException last thrown by this
Scanner's readable.
18) Locale locale() It is used to get a Locale of the Scanner class.
19) MatchResult match() It is used to get the match result of the last scanning
operation performed by this scanner.
20) String next() It is used to get the next complete token from the scanner
which is in use.
21) BigDecimal nextBigDecim It scans the next token of the input as a BigDecimal.
al()
22) BigInteger nextBigInteger It scans the next token of the input as a BigInteger.
()
23) Boolean nextBoolean() It scans the next token of the input into a boolean value
and returns that value.
24) Byte nextByte() It scans the next token of the input as a byte.
25) Double nextDouble() It scans the next token of the input as a double.
26) Float nextFloat() It scans the next token of the input as a float.
27) Int nextInt() It scans the next token of the input as an Int.
28) String nextLine() It is used to get the input string that was skipped of the
Scanner object.
29) Long nextLong() It scans the next token of the input as a long.
30) Short nextShort() It scans the next token of the input as a short.
31) Int radix() It is used to get the default radix of the Scanner use.
32) Void remove() It is used when remove operation is not supported by this
implementation of Iterator.
38) Scanner useLocale() It is used to sets this scanner's locale object to the
specified locale.
39) Scanner useRadix() It is used to set the default radix of the Scanner which is
in use to the specified radix.
Java - 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
Constructor Description
RandomAccessFile(File file, String mode) Creates a random access file stream to read
from, and optionally to write to, the file
specified by the File argument.
RandomAccessFile(String name, String mode) Creates a random access file stream to read
from, and optionally to write to, a file with the
specified name.
Methods
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.
void seek(long pos) It sets the file-pointer offset, measured from the beginning of this
file, at which the next read or write occurs.
void writeDouble(double It converts the double argument to a long using the
v) doubleToLongBits method in class Double, and then writes that
long value to the file as an eight-byte quantity, high byte first.
Example
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileExample {
static final String FILEPATH ="myFile.TXT";
public static void main(String[] args) {
try {
System.out.println(new String(readFromFile(FILEPATH, 0, 18)));
writeToFile(FILEPATH, "I love my country and my people", 31);
} catch (IOException e) {
e.printStackTrace();
} }
private static byte[] readFromFile(String filePath, int position, int size)
throws IOException {
RandomAccessFile file = new RandomAccessFile(filePath, "r");
file.seek(position);
byte[] bytes = new byte[size];
file.read(bytes);
file.close();
return bytes;
}
private static void writeToFile(String filePath, String data, int position)
throws IOException {
RandomAccessFile file = new RandomAccessFile(filePath, "rw");
file.seek(position);
file.write(data.getBytes());
file.close();
} }
Method Description
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.
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
What is JFC
• The Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.
Hierarchy of Java Swing classes
• The hierarchy of java swing API is given below.
Method Description
public void setLayout(LayoutManager m) sets the layout manager for the component.
Constructor Description
Constructor Description
JRadioButton(Strings, Creates a radio button with the specified text and selected status.
boolean selected)
Methods Description
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.add(b6);f.add(b7);f.add(b8);f.add(b9);
f.setLayout(new GridLayout(3,3));
//setting grid layout of 3 rows and 3 columns
• The current version of JDBC is 4.3. It is the stable release since 21st September, 2017. It
is based on the X/Open SQL Call Level Interface. The java.sql package contains classes
and interfaces for JDBC API.
• A list of popular interfaces of JDBC API are given below: