java Notes UNITS 1-5[1]pdf
java Notes UNITS 1-5[1]pdf
Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year 1995. James Gosling is known
as the father of Java. Before Java, its name was Oak. Since Oak was already a registered company, so James Gosling and his
team changed the name from Oak to Java.
Platform: Any hardware or software environment in which a program runs, is known as a platform. Since Java has a
runtime environment (JRE) and API, it is called a platform.
History of Java
1.History of Java
2.Java Version History
The history of Java is very interesting. Java was originally designed for interactive television, but it was too advanced
technology for the digital cable television industry at the time. The history of Java starts with the Green Team. Java team
members (also known as Green Team), initiated this project to develop a language for digital devices such as set-top boxes,
televisions, etc. However, it was best suited for internet programming. Later, Java technology was incorporated by Netscape.
The principles for creating Java programming were "Simple, Robust, Portable, Platform-independent, Secured, High
Performance, Multithreaded, Architecture Neutral, Object-Oriented, Interpreted, and Dynamic". Java was developed by
James Gosling, who is known as the father of Java, in 1995. James Gosling and his team members started the project in the
early '90s.
Currently, Java is used in internet programming, mobile devices, games, e-business solutions, etc. Following are given
significant points that describe the history of Java.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991. The small team
of sun engineers called Green Team.
2) Initially it was designed for small, embedded systems in electronic appliances like set-top boxes.
3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.
5) Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries like the U.S.A., France, Germany,
Romania, etc.
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.
7) Why had they chose the name Java for Java language? The team gathered to choose a new name. The suggested words
were "dynamic", "revolutionary", "Silk", "jolt", "DNA", etc. They wanted something that reflected the essence of the
technology: revolutionary, dynamic, lively, cool, unique, and easy to spell, and fun to say.
According to James Gosling, "Java was one of the top choices along with Silk". Since Java was so unique, most of the team
members preferred Java than other names.
8) Java is an island in Indonesia where the first coffee was produced (called Java coffee). It is a kind of espresso bean. Java
name was chosen by James Gosling while having a cup of coffee nearby his office.
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
12) JDK 1.0 was released on January 23, 1996. After the first release of Java, there have been many additional features
added to the language. Now Java is being used in Windows applications, Web applications, enterprise applications, mobile
applications, cards, etc. Each new version adds new features in Java.
Features of Java
The primary objective of Java programming language creation was to make it portable, simple and secure programming
language. Apart from this, there are also some excellent features which play an important role in the popularity of this
language. The features of Java are also known as Java buzzwords.
A list of the most important features of the Java language is given below.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to Sun Microsystem, Java
language is a simple programming language because:
o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit pointers, operator
overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic Garbage Collection in Java.
Object-oriented
Java is an object-oriented programming language. Everything in Java is an object. Object-oriented means we organize our
software as a combination of different types of objects that incorporate both data and behaviour.Object-oriented
programming (OOPs) is a methodology that simplifies software development and maintenance by providing some rules.
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Platform Independent
Java is platform independent because it is different from other languages like C, C++, etc. which are compiled into platform
specific machines while Java is a write once, run anywhere language. A platform is the hardware or software environment in
which a program runs.
There are two types of platforms software-based and hardware-based. Java provides a software-based platform.The Java
platform differs from most other platforms in the sense that it is a software-based platform that runs on top of other
hardware-based platforms. It has two components:
1. Runtime Environment
2. API(Application Programming Interface)
Java code can be executed on multiple platforms, for example, Windows, Linux, Sun Solaris, Mac/OS, etc. Java code is
compiled by the compiler and converted into bytecode. This bytecode is a platform-independent code because it can be run
on multiple platforms, i.e., Write Once and Run Anywhere (WORA).
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is secured because:
• No explicit pointer
• Java Programs run inside a virtual machine sandbox
o 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.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate access rights to objects.
o Security Manager: It determines what resources a class can access such as reading and writing to the local
disk.
Java language provides these securities by default. Some security can also be provided by an application developer explicitly
through SSL, JAAS, Cryptography, etc.
Robust
Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for example, the size of primitive types
is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of memory for 64-bit
architecture. However, it occupies 4 bytes of memory for both 32 and 64-bit architectures in Java.
Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require any implementation.
High-performance
Java is faster than other traditional interpreted programming languages because Java bytecode is "close" to native code. It is
still a little bit slower than a compiled language (e.g., C++). Java is an interpreted language that is why it is slower than
compiled languages, e.g., C, C++, etc.
Distributed
Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB are used for
creating distributed applications. This feature of Java makes us able to access files by calling the methods from any
machine on the internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that deal with many tasks at once
by defining multiple threads. The main advantage of multi-threading is that it doesn't occupy memory for each thread. It
shares a common memory area. Threads are important for multi-media, Web applications, etc.
Dynamic
Java is a dynamic language. It supports the dynamic loading of classes. It means classes are loaded on demand. It also
supports functions from its native languages, i.e., C and C++.
Java supports dynamic compilation and automatic memory management (garbage collection).
First Java Program | Hello World Example
1.Software Requirements
2.Creating Hello Java Example
3.Resolving javac is not recognized
In this section, we will learn how to write the simple program of Java. We can write a simple hello Java program easily after
installing the JDK.
To create a simple Java program, you need to create a class that contains the main method. Let's understand the requirement
first.
For executing any Java program, the following software or application must be properly installed.
o Install the JDK if you don't have installed it, download the JDK and install it.
o Set path of the jdk/bin directory. http://www.javatpoint.com/how-to-set-path-in-java
o Create the Java program
o Compile and run the Java program
. class Simple{
. public static void main(String args[]){
. System.out.println("Hello Java");
. }
. }
Output:
Hello Java
Compilation Flow:
When we compile Java program using javac tool, the Java compiler converts the source code into byte code.
Parameters used in First Java Program
Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().
To write the simple program, you need to open notepad by start menu -> All Programs -> Accessories -> Notepad and
write a simple program as we have shownbelow:
As displayed in the above diagram, write the simple program of Java in notepad and saved it as Simple.java. In order to
compile and run the above program, you need to open the command prompt by start menu -> All Programs -> Accessories
-> command prompt. When we have done with all the steps properly, it shows the following output:
To compile and run the above program, go to your current directory first; my current directory is c:\new. Write here:
If you want to get the detailed knowledge of Java Virtual Machine, move to the next page. Firstly, let's see the differences
between the JDK, JRE, and JVM.
JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it doesn't physically exist. It is a
specification that provides a runtime environment in which Java bytecode can be executed. It can also run those programs
which are written in other languages and compiled to Java bytecode.
JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are platform dependent because the
configuration of each OS is different from each other. However, Java is platform independent. There are three notions of the
JVM: specification, implementation, and instance.
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java Runtime Environment is a set of
software tools which are used for developing Java applications. It is used to provide the runtime environment. It is the
implementation of JVM. It physically exists. It contains a set of libraries + other files that JVM uses at runtime.
The implementation of JVM is also actively released by other companies besides Sun Micro Systems.
JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software development environment
which is used to develop Java applications and applets. It physically exists. It contains JRE + development tools.
JDK is an implementation of any one of the below given Java Platforms released by Oracle Corporation:
1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.
In Java language, primitive data types are the building blocks of data manipulation. These are the most basic data types
available in Java language.
Java is a statically-typed programming language. It means, all variables must be declared before its use. That is why
we need to declare variable's type and name.
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
The Boolean data type is used to store only two possible values: true and false. This data type is used for simple flags that
track true/false conditions.
The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.
Example:
The byte data type is an example of primitive data type. It isan 8-bit signed two's complement integer. Its value-range lies
between -128 to 127 (inclusive). Its minimum value is -128 and maximum value is 127. Its default value is 0.
The byte data type is used to save memory in large arrays where the memory savings is most required. It saves space because
a byte is 4 times smaller than an integer. It can also be used in place of "int" data type.
Example:
The short data type is a 16-bit signed two's complement integer. Its value-range lies between -32,768 to 32,767 (inclusive).
Its minimum value is -32,768 and maximum value is 32,767. Its default value is 0.
The short data type can also be used to save memory just like byte data type. A short data type is 2 times smaller than an
integer.
Example:
The int data type is a 32-bit signed two's complement integer. Its value-range lies between - 2,147,483,648 (-2^31) to
2,147,483,647 (2^31 -1) (inclusive). Its minimum value is - 2,147,483,648and maximum value is 2,147,483,647. Its default
value is 0.
The int data type is generally used as a default data type for integral values unless if there is no problem about memory.
Example:
. int a = 100000, int b = -200000
The long data type is a 64-bit two's complement integer. Its value-range lies between -9,223,372,036,854,775,808(-2^63) to
9,223,372,036,854,775,807(2^63 -1)(inclusive). Its minimum value is - 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used when you need a range of values more than
those provided by int.
Example:
The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range is unlimited. It is recommended to use
a float (instead of double) if you need to save memory in large arrays of floating point numbers. The float data type should
never be used for precise values, such as currency. Its default value is 0.0F.
Example:
. float f1 = 234.5f
The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is unlimited. The double data type
is generally used for decimal values just like float. The double data type also should never be used for precise values, such as
currency. Its default value is 0.0d.
Example:
. double d1 = 12.3
The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000' (or 0) to '\uffff' (or 65,535
inclusive).The char data type is used to store characters.
Java 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.
In Java, array is an object of a dynamically generated class. Java array inherits the Object
class, and implements the Serializable as well as Cloneable interfaces. We can store primitive
values or objects in an array in Java. Like C/C++, we can also create single dimentional or
multidimentional arrays in Java.
Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.
Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
o Random access: We can get any data located at an index position.
Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It doesn't grow
its size at runtime. To solve this problem, collection framework is used in Java which
grows automatically.
. arrayRefVar=new datatype[size];
Example of Java Array
Let's see the simple example of java array, where we are going to declare, instantiate,
initialize and traverse an array.
Output:
10
20
70
40
50
.
.
Example2://Java Program to illustrate the use of declaration, instantiation
. //and initialization of Java array in a single line
. class Testarray1{
. public static void main(String args[]){
. int a[]={33,3,4,5};//declaration, instantiation and initialization
. //printing array
. for(int i=0;i<a.length;i++)//length is the property of array
. System.out.println(a[i]);
. }}
Output:
33
3
4
5
. arr[0][0]=1;
. arr[0][1]=2;
. arr[0][2]=3;
. arr[1][0]=4;
. arr[1][1]=5;
. arr[1][2]=6;
. arr[2][0]=7;
. arr[2][1]=8;
. arr[2][2]=9;
Example of Multidimensional Java Array
Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional
array.
Output:
123
245
445
Output:
012
3456
78
Operators in Java
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.
multiplicative */%
Arithmetic
additive +-
bitwise inclusive OR |
Ternary ternary ?:
= += -= *= /= %= &= ^= |=
Assignment assignment
<<= >>= >>>=
The Java unary operators require only one operand. Unary operators are used to perform
various operations i.e.:
10
12
12
10
22
21
-11
9
false
true
15
5
50
2
0
21
The Java left shift operator << is used to shift all of the bits in a value to the left side of a
specified number of times.
40
80
80
240
The Java right shift operator >> is used to move the value of the left operand to right by the
number of bits specified by the right operand.
. public OperatorExample{
. public static void main(String args[]){
. System.out.println(10>>2);//10/2^2=10/4=2
. System.out.println(20>>2);//20/2^2=20/4=5
. System.out.println(20>>3);//20/2^3=20/8=2
. }}
Output:
2
5
2
5
5
-5
1073741819
The logical && operator doesn't check the second condition if the first condition is false. It
checks the second condition only if the first one is true.
The bitwise & operator always checks both conditions whether first condition is true or false.
false
false
false
10
false
11
The logical || operator doesn't check the second condition if the first condition is true. It
checks the second condition only if the first one is false.
The bitwise | operator always checks both conditions whether first condition is true or false.
true
true
true
10
true
11
Java Ternary operator is used as one line replacement for if-then-else statement and used a lot
in Java programming. It is the only conditional operator which takes three operands.
Another Example:
14
16
13
9
18
9
Java Assignment Operator Example: Adding short
20
Java compiler executes the code from top to bottom. The statements in the code are executed
according to the order in which they appear. However, Java provides statements that can be
used to control the flow of Java code. Such statements are called control flow statements. It is
one of the fundamental features of Java, which provides a smooth flow of program.
1. break statement
2. continue statement
Decision-Making statements:
As the name suggests, decision-making statements decide which statement to execute and
when. Decision-making statements evaluate the Boolean expression and control the program
flow depending upon the result of the condition provided. There are two types of decision-
making statements in Java, i.e., If statement and switch statement.
1) If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the program is
diverted depending upon the specific condition. The condition of the If statement gives a
Boolean value, either true or false. In Java, there are four types of if-statements given below.
1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement
1) Simple if statement:
It is the most basic statement among all control flow statements in Java. It evaluates a
Boolean expression and enables the program to enter a block of code if the expression
evaluates to true.
. if(condition) {
. statement 1; //executes when condition is true
. }
Consider the following example in which we have used the if statement in the java code.
Student.java
Student.java
x + y is greater than 20
2) if-else statement
The if-else statement is an extension to the if-statement, which uses another block of code,
i.e., else block. The else block is executed if the condition of the if-block is evaluated as false.
Syntax:
. if(condition) {
. statement 1; //executes when condition is true
. }
. else{
. statement 2; //executes when condition is false
. }
Consider the following example.
Student.java
3) if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements. In
other words, we can say that it is the chain of if-else statements that create a decision tree
where the program may enter in the block of code where the condition is true. We can also
define an else statement at the end of the chain.
Advertisement
Syntax of if-else-if statement is given below.
. if(condition 1) {
. statement 1; //executes when condition 1 is true
. }
. else if(condition 2) {
. statement 2; //executes when condition 2 is true
. }
. else {
. statement 2; //executes when all the conditions are false
. }
Consider the following example.
Student.java
4. Nested if-statement
Advertisement
In nested if-statements, the if statement can contain a if or if-else statement inside another if
or else-if statement.
. if(condition 1) {
. statement 1; //executes when condition 1 is true
. if(condition 2) {
. statement 2; //executes when condition 2 is true
. }
. else{
. statement 2; //executes when condition 2 is false
. }
. }
Consider the following example.
Student.java
Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement contains
multiple blocks of code called cases and a single case is executed based on the variable which
is being switched. The switch statement is easier to use instead of if-else-if statements. It also
enhances the readability of the program.
Advertisement
Points to be noted about switch statement:
o The case variables can be int, short, byte, char, or enumeration. String type is also
supported since version 7 of Java
o Cases cannot be duplicate
o Default statement is executed when any of the case doesn't match the value of
expression. It is optional.
o Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
o While using switch statements, we must notice that the case expression will be of the
same type as the variable. However, it will also be a constant value.
The syntax to use the switch statement is given below.
. switch (expression){
. case value1:
. statement1;
. break;
. .
. .
. .
. case valueN:
. statementN;
. break;
. default:
. default statement;
. }
Consider the following example to understand the flow of the switch statement.
Student.java
While using switch statements, we must notice that the case expression will be of the same
type as the variable. However, it will also be a constant value. The switch permits only int,
string, and Enum type variables to be used.
Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while some
condition evaluates to true. However, loop statements are used to execute the set of
instructions in a repeated order. The execution of the set of instructions depends upon a
particular condition.
In Java, we have three types of loops that execute similarly. However, there are differences in
their syntax and condition checking time.
1. for loop
2. while loop
3. do-while loop
In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check
the condition, and increment/decrement in a single line of code. We use the for loop only
when we exactly know the number of times, we want to execute the block of code.
Consider the following example to understand the proper functioning of the for loop in java.
Calculation.java
Java provides an enhanced for loop to traverse the data structures like array or collection. In
the for-each loop, we don't need to update the loop variable. The syntax to use the for-each
loop in java is given below.
Calculation.java
Java
C
C++
Python
JavaScript
The while loop is also used to iterate over the number of statements multiple times. However,
if we don't know the number of iterations in advance, it is recommended to use a while loop.
Unlike for loop, the initialization and increment/decrement doesn't take place inside the loop
statement in while loop.
It is also known as the entry-controlled loop since the condition is checked at the start of the
loop. If the condition is true, then the loop body will be executed; otherwise, the statements
after the loop will be executed.
. while(condition){
. //looping statements
. }
The flow chart for the while loop is given in the following image.
Calculation .java
The do-while loop checks the condition at the end of the loop after executing the loop
statements. When the number of iteration is not known and we have to execute the loop at
least once, we can use do-while loop.
It is also known as the exit-controlled loop since the condition is not checked in advance. The
syntax of the do-while loop is given below.
. do
. {
. //statements
. } while (condition);
The flow chart of the do-while loop is given in the following image.
Consider the following example to understand the functioning of the do-while loop in Java.
Calculation.java
Jump Statements
Jump statements are used to transfer the control of the program to the specific statements. In
other words, jump statements transfer the execution control to the other part of the program.
There are two types of jump statements in Java, i.e., break and continue.
As the name suggests, the break statement is used to break the current flow of the program
and transfer the control to the next statement outside a loop or switch statement. However, it
breaks only the inner loop in the case of the nested loop.
The break statement cannot be used independently in the Java program, i.e., it can only be
written inside the loop or switch statement.
Consider the following example in which we have used the break statement with the for loop.
BreakExample.java
. public class BreakExample {
.
. public static void main(String[] args) {
. // TODO Auto-generated method stub
. for(int i = 0; i<= 10; i++) {
. System.out.println(i);
. if(i==6) {
. break;
. }
. }
. }
. }
Output:
0
1
2
3
4
5
6
Calculation.java
0
1
2
3
4
5
Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the
specific part of the loop and jumps to the next iteration of the loop immediately.
Consider the following example to understand the functioning of the continue statement in
Java.
UNIT-II
java package
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined packages.
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
. //save as Simple.java
. package mypack;
. public class Simple
. {
. public static void main(String args[])
. {
. System.out.println("Welcome to package");
. }
. }
If you are not using any IDE, you need to follow the syntax given below:
. javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to
keep the package within the same directory, you can use . (dot).
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The .
represents the current folder.
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but
not subpackages.
The import keyword is used to make the classes and interface of another package accessible
to the current package.
. //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();
. }
. }
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
. //save by A.java
.
. package pack;
. public class A{
. public void msg(){System.out.println("Hello");}
. }
. //save by B.java
. package mypack;
. import pack.A;
.
. class B{
. public static void main(String args[]){
. A obj = new A();
. obj.msg();
. }
. }
Output:Hello
If you use fully qualified name then only declared class of this package will be accessible.
Now there is no need to import. But you need to use fully qualified name every time when
you are accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.
. //save by A.java
. package pack;
. public class A{
. public void msg(){System.out.println("Hello");}
. }
. //save by B.java
. package mypack;
. class B{
. public static void main(String args[]){
. pack.A obj = new pack.A();//using fully qualified name
. obj.msg();
. }
. }
Output:Hello
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.
Output:Hello subpackage
Exception Handling
The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that the normal flow of the application can be maintained.
In this tutorial, we will learn about Java exceptions, it's types, and the difference between
checked and unchecked exceptions.
In Java, an exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.
The core advantage of exception handling is to maintain the normal flow of the application.
An exception normally disrupts the normal flow of the application; that is why we need to
handle exceptions. Let's consider a scenario:
. statement 1;
. statement 2;
. statement 3;
. statement 4;
. statement 5;//exception occurs
. statement 6;
. statement 7;
. statement 8;
. statement 9;
. statement 10;
Suppose there are 10 statements in a Java program and an exception occurs at statement 5;
the rest of the code will not be executed, i.e., statements 6 to 10 will not be executed.
However, when we perform exception handling, the rest of the statements will be executed.
That is why we use exception handling in Java.
The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two
subclasses: Exception and Error. The hierarchy of Java Exception classes is given below:
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. An error is considered as
the unchecked exception. However, according to Oracle, there are three types of exceptions
namely:
1. Checked Exception
2. Unchecked Exception
3. Error
1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and Error are
known as checked exceptions. For example, IOException, SQLException, etc. Checked
exceptions are checked at compile-time.
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions. For
example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException,
etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
3) Error
Java provides five keywords that are used to handle the exception. The following table
describes each.
Keyword Description
Let's see an example of Java Exception Handling in which we are using a try-catch statement
to handle the exception.
JavaExceptionExample.java
Output:
There are given some scenarios where unchecked exceptions may occur. They are as follows:
. int a=50/0;//ArithmeticException
If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.
. String s=null;
. System.out.println(s.length());//NullPointerException
3) A scenario where NumberFormatException occurs
. String s="abc";
. int i=Integer.parseInt(s);//NumberFormatException
When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may
be other reasons to occur ArrayIndexOutOfBoundsException. Consider the following
statements.
Multithreading in Java
Multithreading in Java is a process of executing multiple threads simultaneously.
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.
1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.
o Each process has an address in memory. In other words, each process allocates a
separate memory area.
o A process is heavyweight.
o Cost of communication between the process is high.
o Switching from one process to another requires some time for saving and
loading registers, memory maps, updating lists, etc.
Threads are independent. If there occurs exception in one thread, it doesn't affect other
threads. It uses a shared memory area.
As shown in the above figure, a thread is executed inside the process. There is context-
switching between the threads. There can be multiple processes inside the OS, and one
process can have multiple threads.
In Java, a thread always exists in any one of the following states. These states are:
1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated
New: Whenever a new thread is created, it is always in the new state. For a thread in the new
state, the code has not been run yet and thus has not begun its execution.
Active: When a thread invokes the start() method, it moves from the new state to the active
state. The active state contains two states within it: one is runnable, and the other is running.
o Runnable: A thread, that is ready to run is then moved to the runnable state. In the
runnable state, the thread may be running or may be ready to run at any given instant
of time. It is the duty of the thread scheduler to provide the thread time to run, i.e.,
moving the thread the running state.
A program implementing multithreading acquires a fixed slice of time to each
individual thread. Each and every thread runs for a short span of time and when that
allocated time slice is over, the thread voluntarily gives up the CPU to the other
thread, so that the other threads can also run for their slice of time. Whenever such a
scenario occurs, all those threads that are willing to run, waiting for their turn to run,
lie in the runnable state. In the runnable state, there is a queue where the threads lie.
o Running: When the thread gets the CPU, it moves from the runnable to the running
state. Generally, the most common change in the state of a thread is from runnable to
running and again back to runnable.
Blocked or Waiting: Whenever a thread is inactive for a span of time (not permanently) then,
either the thread is in the blocked state or is in the waiting state.
For example, a thread (let's say its name is A) may want to print some data from the printer.
However, at the same time, the other thread (let's say its name is B) is using the printer to
print some data. Therefore, thread A has to wait for thread B to use the printer. Thus, thread
A is in the blocked state. A thread in the blocked state is unable to perform any execution and
thus never consume any cycle of the Central Processing Unit (CPU). Hence, we can say that
thread A remains idle until the thread scheduler reactivates thread A, which is in the waiting
or blocked state.
When the main thread invokes the join() method then, it is said that the main thread is in the
waiting state. The main thread then waits for the child threads to complete their tasks. When
the child threads complete their job, a notification is sent to the main thread, which again
moves the thread from waiting to the active state.
If there are a lot of threads in the waiting or blocked state, then it is the duty of the thread
scheduler to determine which thread to choose and which one to reject, and the chosen thread
is then given the opportunity to run.
Timed Waiting: Sometimes, waiting for leads to starvation. For example, a thread (its name
is A) has entered the critical section of a code and is not willing to leave that critical section.
In such a scenario, another thread (its name is B) has to wait forever, which leads to
starvation. To avoid such scenario, a timed waiting state is given to thread B. Thus, thread
lies in the waiting state for a specific span of time, and not forever. A real example of timed
waiting is when we invoke the sleep() method on a specific thread. The sleep() method puts
the thread in the timed wait state. After the time runs out, the thread wakes up and start its
execution from when it has left earlier.
Terminated: A thread reaches the termination state because of the following reasons:
o When a thread has finished its job, then it exists or terminates normally.
o Abnormal termination: It occurs when some unusual events such as an unhandled
exception or segmentation fault.
A terminated thread means the thread is no more in the system. In other words, the thread is
dead, and there is no way one can respawn (active after kill) the dead thread.
The following diagram shows the different states involved in the life cycle of a thread.
Java Threads | How to create a thread in Java
Thread class:
Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.
o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to
be executed by a thread. Runnable interface have only one method named run().
Starting a thread:
The start() method of Thread class is used to start a newly created thread. It performs the
following tasks:
FileName: Multi.java
thread is running...
FileName: Multi3.java
thread is running...
If you are not extending the Thread class, your class object would not be treated as a thread
object. So you need to explicitly create the Thread class object. We are passing the object of
your class that implements Runnable so that your class run() method may execute.
We can directly use the Thread class to spawn new threads using the constructors defined
above.
FileName: MyThread1.java
My first thread
FileName: MyThread2.java
My new thread
Now the thread is running ...
There can be a lot of usage of Java this keyword. In Java, this is a reference variable that refers to the current
object.
The this keyword can be used to refer current class instance variable. If there is ambiguity between the instance
variables and parameters, this keyword resolves the problem of ambiguity.
Let's understand the problem if we don't use this keyword by the example given below:
. class Student{
. int rollno;
. String name;
. float fee;
. Student(int rollno,String name,float fee){
. rollno=rollno;
. name=name;
. fee=fee;
. }
. void display(){System.out.println(rollno+" "+name+" "+fee);}
. }
. class TestThis1{
. public static void main(String args[]){
. Student s1=new Student(111,"ankit",5000f);
. Student s2=new Student(112,"sumit",6000f);
. s1.display();
. s2.display();
. }}
Output:
0 null 0.0
0 null 0.0
In the above example, parameters (formal arguments) and instance variables are same. So, we are using this
keyword to distinguish local variable and instance variable.
. class Student{
. int rollno;
. String name;
. float fee;
. Student(int rollno,String name,float fee){
. this.rollno=rollno;
. this.name=name;
. this.fee=fee;
. }
. void display(){System.out.println(rollno+" "+name+" "+fee);}
. }
.
. class TestThis2{
. public static void main(String args[])
. {
. Student s1=new Student(111,"ankit",5000f);
. Student s2=new Student(112,"sumit",6000f);
. s1.display();
. s2.display();
. }}
Output:
You may invoke the method of the current class by using the this keyword. If you don't use the this keyword,
compiler automatically adds this keyword while invoking the method. Let's see the example
. class A{
. void m(){System.out.println("hello m");}
. void n(){
. System.out.println("hello n");
. //m();//same as this.m()
. this.m();
. }
. }
. class TestThis4{
. public static void main(String args[]){
. A a=new A();
. a.n();
. }}
Output:
hello n
hello m
3) this() : to invoke current class constructor
The this() constructor call can be used to invoke the current class constructor. It is used to reuse the constructor.
In other words, it is used for constructor chaining.
. class A{
. A(){System.out.println("hello a");}
. A(int x){
. this();
. System.out.println(x);
. }
. }
. class TestThis5{
. public static void main(String args[]){
. A a=new A(10);
. }}
Output:
hello a
10
The this keyword can also be passed as an argument in the method. It is mainly used in the event handling. Let's
see the example:
. class S2{
. void m(S2 obj){
. System.out.println("method is invoked");
. }
. void p(){
. m(this);
. }
. public static void main(String args[]){
. S2 s1 = new S2();
. s1.p();
. }
. }
Output:
method is invoked
In event handling (or) in a situation where we have to provide reference of a class to another one. It is used to
reuse one object in many methods.
We can pass the this keyword in the constructor also. It is useful if we have to use one object in multiple classes.
Let's see the example:
. class B{
. A4 obj;
. B(A4 obj){
. this.obj=obj;
. }
. void display(){
. System.out.println(obj.data);//using data member of A4 class
. }
. }
.
. class A4{
. int data=10;
. A4(){
. B b=new B(this);
. b.display();
. }
. public static void main(String args[]){
. A4 a=new A4();
. }
. }
Output:10
We can return this keyword as an statement from the method. In such case, return type of the method must be
the class type (non-primitive). Let's see the example:
Hello java
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.
We can use super keyword to access the data member or field of parent class. It is used if parent class and child
class have same fields.
. class Animal{
. String color="white";
. }
. class Dog extends Animal{
. String color="black";
. void printColor(){
. System.out.println(color);//prints color of Dog class
. System.out.println(super.color);//prints color of Animal class
. }
. }
. class TestSuper1{
. public static void main(String args[]){
. Dog d=new Dog();
. d.printColor();
. }}
Output:
black
white
In the above example, Animal and Dog both classes have a common property color. If we print color property, it
will print the color of current class by default. To access the parent property, we need to use super keyword.
The super keyword can also be used to invoke parent class method. It should be used if subclass contains the
same method as parent class. In other words, it is used if method is overridden.
. class Animal{
. void eat(){System.out.println("eating...");
. }
. }
. class Dog extends Animal{
. void eat(){System.out.println("eating bread...");
. }
. void bark(){System.out.println("barking...");
. }
. void work(){
. super.eat();
. bark();
. }
. }
. class TestSuper2{
. public static void main(String args[]){
. Dog d=new Dog();
. d.work();
. }}
Output:
eating...
barking...
In the above example Animal and Dog both classes have eat() method if we call eat() method from Dog class, it
will call the eat() method of Dog class by default because priority is given to local.
The super keyword can also be used to invoke the parent class constructor. Let's see a simple example:
. class Animal{
. Animal(){System.out.println("animal is created");}
. }
. class Dog extends Animal{
. Dog(){
. super();
. System.out.println("dog is created");
. }
. }
. class TestSuper3{
. public static void main(String args[])
. {
. Dog d=new Dog();
. }}
Output:
animal is created
dog is created
UNIT-III
Java I/O
Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of a stream to make I/O operation fast. The java.io package contains all the
classes required for input and output operations.
Java I/O revolves around two primary concepts: streams and readers/writers.
Streams: Streams represent a sequence of data. In Java, there are two types of streams: input streams
and output streams. Input streams are used to read data from a source, while output streams are used
to write data to a destination. Streams can be categorized into byte streams (InputStream and
OutputStream) and character streams (Reader and Writer).
Readers/Writers: Readers and writers are specialized stream classes designed for handling character
data. They provide a convenient way to read from and write to character-based data sources. Readers
read character data from input streams, while writers write character data to output streams.
Stream
A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream because it
is like a stream of water that continues to flow.
In Java, 3 streams are created for us automatically. All these streams are attached with the console.
Let's see the code to print output and an error message to the console.
. System.out.println("simple message");
. System.err.println("error message");
Let's see the code to get input from console.
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.
Let's understand the working of Java OutputStream and InputStream class by the figure given below.
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.
Method Description
public void write(int) throws IOException It is used to write a byte to the current output stream.
public void flush() throws IOException It flushes the current output stream.
public void close() throws IOException It is used to close the current output stream.
OutputStream Hierarchy
InputStream Class
InputStream class is an abstract class. It is the superclass of all classes representing an input stream of
bytes.
Method Description
public void close() throws IOException It is used to close the current input stream.
InputStream Hierarchy
Java I/O Classes
1. Java provides a rich set of classes for performing I/O operations. Some of the key classes
include:
2. InputStream and OutputStream: These abstract classes form the foundation for byte-
oriented I/O operations. They provide methods for reading and writing bytes from/to various
sources and destinations.
3. Reader and Writer: These abstract classes are used for character-based I/O operations. They
provide methods for reading and writing characters from/to character-based streams.
4. FileInputStream and FileOutputStream: These classes allow reading from and writing to
files in a byte-oriented manner.
5. FileReader and FileWriter: These classes enable reading from and writing to files using
character-oriented operations.
6. BufferedInputStream and BufferedOutputStream: These classes provide buffering
capabilities, which can significantly improve I/O performance by reducing the number of
system calls.
7. BufferedReader and BufferedWriter: These classes offer buffered reading and writing of
character data, enhancing I/O efficiency when working with character-based streams.
1. File Handling: Java I/O is extensively used for reading from and writing to files. Developers
can manipulate files, create directories, and perform file-related operations using Java's file
I/O classes.
2. Network Communication: Java's socket classes (Socket and ServerSocket) facilitate
network communication by enabling data exchange between client and server applications
over TCP/IP.
3. Serialization: Java's serialization mechanism allows objects to be converted into a stream of
bytes for storage or transmission. It is particularly useful for storing object state or
transferring objects between applications.
4. Data Processing: Java I/O is integral to data processing tasks such as parsing text files,
processing CSV data, and interacting with databases through JDBC (Java Database
Connectivity).
When working with Java I/O, consider the following best practices:
1. Use Try-with-Resources: Always use the try-with-resources statement when working with
streams to ensure proper resource management. This automatically closes the streams when
they are no longer needed, preventing resource leaks.
2. Use Buffered I/O: Whenever possible, use buffered I/O classes to minimize the number of
system calls and improve performance.
3. Handle Exceptions Gracefully: Handle I/O exceptions gracefully by implementing error
handling mechanisms such as logging or error propagation.
4. Use NIO for Performance: For high-performance I/O operations, consider using Java's NIO
(New I/O) package, which provides non-blocking I/O features and enhanced performance.
Console in Java
In this section, we will learn everything about the Console in Java, i.e., what a console is, how we can use the
console, how we can implement output in the console, how we can take input using the console, etc.
What is a Console?
To run a program, we might need input from the programmer or user according to the requirement. We cannot
always take input just from the program. Sometimes, we can take the input from the console or terminal too.
The process of taking input from the console is introduced by the concept of Java Console. Java programming
language provides several ways in order to take input from the console and provide its corresponding output on
the same console.
Java Console
Using the Console in Java, we can consider taking input and displaying the output. Generally, Console is mainly
meant for taking input. There are three ways to take the input from the Java console. They are:
A class that is used to scan inputs within the program is known as the Scanner class. We use this class to take
the input within the program by creating an abject in the Scanner class. It is one of the easiest ways to scan the
input from the user using the console. It is used to scan all the regular expressions in Java. The Scanner class is
available in the util package. So, in order to scan the inputs using the Scanner class, we need to import the "
Java.util " package.
There are different methods used for scanning different data types. The type of method that we consider depends
on the data type of the input that we want to take. There are eight methods in the Scanner class, as there are
eight general Primitive data types.
1. nextByte()
The method that deals with reading a Byte value from the user are nextByte()
2. nextDouble()
The method that deals with reading a Double value from the user are nextDouble()
3. nextFloat()
The method that deals with reading a Float value from the user are nextFloat()
4. nextInt()
The method that deals with reading an Int value from the user are nextInt()
5. nextLine()
The method that deals with reading a String value from the user are nextLine()
6. nextLong()
The method that deals with reading a Long value from the user are nextLong()
7. nextShort()
The method that deals with reading a Short value from the user are nextShort()
nextBoolean()
The method that deals with reading a Boolean value from the user are nextBoolean()A program that
demonstrates Scanner class to scan an input:
o This class provides several methods according to the data type used and that match the user's
requirement.
o It is the basic class used to scan an input that runs on almost all versions of Java.
Disadvantages of Scanner class:
o It runs and executes a little slower as the data must be parsed before being executed.
o The methods that are part of the class " Scanner " are not synchronized.
It is one of the classical methods of taking input from the user ( sometimes by using a console also ). A new
statement, " InputStreamReader " is also introduced along with the " BufferedReader " in order to scan the input
values using BufferedReader. Let us look at the mechanism of BufferedReader with its syntax followed by a
program.
1. readLine()
The method " readLine() " is used to scan the String values from the user.
2. parseInt()
The method " Integer.parseInt() " is used to scan the integer values from the user.
3. parseDouble()
The method " Double.parseDouble() " is used to scan the double values from the user.
4. parseFloat()
The method " Float.parseFloat() " is used to scan the float values from the user.
. import Java.io.BufferedReader;
. import Java.io.InputStreamReader;
. import Java.io.*;
.
. public class Demo
. {
. public static void main(String[] args) throws IOException
. {
. // initiate InputStreamReader class initially
. // and create an object within the class
. // InputStreamReader
. InputStreamReader obj1 = new InputStreamReader(System.in);
.
. // you can take the input using the BufferReader class
. // and by using the object created in the
. // InputStreamReader class
. BufferedReader obj2 = new BufferedReader(obj1);
.
. // scanning a string
. System.out.print("Enter a String: ");
. String s = obj2.readLine();
.
. // scanning a integer value
. System.out.print("Enter an integer value: ");
. int x = Integer.parseInt(obj2.readLine());
.
. // scanning a float value
. System.out.print("Enter a float value: ");
. float y = Float.parseFloat(obj2.readLine());
.
. // scanning a double value
. System.out.print("Enter a double value: ");
. double z = Double.parseDouble(obj2.readLine());
.
. // printing the values using the print statement
.
. // Printing the String
. System.out.print("The entered String is: ");
. System.out.println(s);
.
. // printing the value of integer entered
. System.out.print("The entered value of integer is: ");
. System.out.println(x);
.
. // printing the value of float entered
. System.out.print("The entered value of float is: ");
. System.out.println(y);
.
. // printing the value of double entered
. System.out.print("The entered value of double is: ");
. System.out.println(z);
.
. }
. }
Input:
o All the methods that are provided by this class are completely synchronized.
o It is the mandatory class used to scan an input, mainly during the " Multi-threading " concept.
o This class has a large Buffer compared to the Scanner class.
o The speed of execution is faster when compared to the Scanner class.
Disadvantages of BufferedReader class
The methods present in the BufferedReader class are not in-built but should be parsed while using.
The class " Console " in Java was introduced from Java version 1.5 and was brought into charge from that
version. It was one of the most anticipated usages in Java Programming language. The class " Console " can be
accessed through the package " Java.io " which is the basic package that is used in all programs constructed in
Java. There are several methods that are embedded within the " Console " class. Let us study all those methods
in the upcoming statements.
One of the major advantages of using the class " Console " in Java is that the confidential data or information
like passwords are hidden while taking input as well as printing output. This is the major reason for preferring
the Console class in Java. Not only this feature, but the methods of the console that can be read are also always
synchronized. But, the Console class can only be executed on command prompt or terminal but not on any other
IDE platforms. Basically, the class " Console " in Java does not have a specified syntax. The syntax and usage
of the " Console " class change depending on the purpose and situation the program is being performed.
1. readLine()
The method that is used to read a single line of text or String from the console is the " readLine() "
method. This method can be accessed or used when an object is created within the String class.
2. readLine( String, Object )
The method that is used to provide a prompt that is formatted priorly in order to receive an input from
the console is the " readLine( String, Object ) " method. This method can be used when an object is
created within a String class. The only difference between the method " readLine() " and the method "
readLine( String, Object ) " is the type and number of arguments that are being passed through those
methods.
3. readPassword()
The method that is used to read or scan a password as an input in a way such that the input taken is
shown or visible at any time on the screen is the " readPassword() " method. The data type that is
supposed to be considered in this method is a Character array or " char[] ".
4. readPassword( String, Object )
The method that is used to read or scan a password as an input in a confidential way such that the input
taken is shown or visible any time on the screen along with providing a formatted prompt is the "
readPassword( String, Object ) " method. The data type that is supposed to be considered in this
method is a Character array or " char[] ".
5. reader()
The method is called by an object created in the class " Reader() " which handles and relates to the
console. This method also helps in the creation of the object in the class " Reader() ".
6. Console printf( String, Object )
The method that is used in order to print a string within the output of the console is " printf() ". It can
be accessed using the class " Console() ".
7. flush()
The method that is used to clear all the statements or the matter present on the console is " flush() ". It
is a general method which is neither creates an object nor will be accessed by an object created within a
particular class. It just removes the matter on the console screen. Its return data type is generally " void
".
8. Console format( String, Object )
The method that prints a formatted string ( when asked for print ) on the output screen of the console is
the " format( String, Object ) " method. We generally use this in order to have a classified string that is
arranged perfectly as per the requirement. This method can be accessed and is also a part of the class "
Console ".
Not only these methods, but there are also several other methods that are a part of the class " Console ". The
usage of the methods depends on the way the program runs and the operation that the program wants to perform.
Input 2:
The Java PrintWriter class implements the Writer class. It is used to print the formatted
representation of objects to the text output stream.
It provides convenient methods for writing various data types, such as integers, doubles, and
strings, to a file or any other output destination. PrintWriter is often used in conjunction with
other I/O classes like FileWriter or BufferedWriter to write data to files efficiently. One
advantage of using PrintWriter is its ability to automatically handle line breaks and
conversions of primitive data types to text representations. Additionally, it offers methods for
formatting output using printf-style formatting. Overall, PrintWriter simplifies the process of
writing formatted text data to output streams in Java applications.
Class Declaration
Example:
.
. Example2:
. import java.io.File;
. import java.io.PrintWriter;
. public class PrintWriterExample {
. public static void main(String[] args) throws Exception {
. //Data to write on Console using PrintWriter
. PrintWriter writer = new PrintWriter(System.out);
. writer.write("Javatpoint provides tutorials of all technology.");
. writer.flush();
. writer.close();
. //Data to write in File using PrintWriter
. PrintWriter writer1 =null;
. writer1 = new PrintWriter(new File("D:\\testout.txt"));
. writer1.write("Like Java, Spring, Hibernate, Android, PHP etc.");
. writer1.flush();
. writer1.close();
. }
. }
Output
String handling
In Java, Strings are the type of objects that can store the sequence of characters enclosed
by double quotes and every character is stored in 16 bits i.e using UTF 16-bit encoding. A
string acts the same as an array of characters. Java provides a robust and flexible API for
handling strings, allowing for various operations such as concatenation, comparison,
and manipulation.
Example:
String name = “Geeks”;
String num = “1234”
Ex-1:
public class Geeks {
// Main Function
public static void main(String args[])
{
System.out.println(str);
}
}
Ex-2:
// Java Program to Create a String
import java.io.*;
class GFG {
public static void main (String[] args) {
// String literal
String s1="String1";
System.out.println(s1);
To make Java more memory efficient (because no new objects are created if it exists
already in the string constant pool).
Example:
String demoString = “GeeksforGeeks”;
in s_builder.
3. String substring (int i) Return the substring from the ith index character
to end.
4. String substring (int i, int j) Returns the substring from i to j-1 index.
5. String concat( String str) Concatenates specified string to the end of this
string.
6. int indexOf (String s) Returns the index within the string of the first
occurrence of the specified string.
If String s is not present in input string then -1 is
returned as the default value.
7. int indexOf (String s, int i) Returns the index within the string of the first
occurrence of the specified string, starting at the
specified index.
8. Int lastIndexOf( String s) Returns the index within the string of the last
occurrence of the specified string.
If String s is not present in input string then -1 is
returned as the default value.
9. boolean equals( Object otherObj) Compares this string to the specified object.
13. String toLowerCase() Converts all the characters in the String to lower
case.
14. String toUpperCase() Converts all the characters in the String to upper
case.
16. String replace (char oldChar, Returns new string by replacing all occurrences
char newChar) of oldChar with newChar.
Note: s1 is still feeksforfeeks and s2 is
geeksgorgeeks
17. boolean contains(CharSequence Returns true if string contains contains the given
sequence) string.
19. boolean startsWith(String prefix) Return true if string starts with this prefix.
The string concat() method concatenates (appends) a string to the end of another string. It
returns the combined string. It is used for string concatenation in Java. It
returns NullPointerException if any one of the strings is Null.
In this article, we will learn how to concatenate two strings in Java.
Program to Concatenate Two Strings using concat() Method in Java
Below is the simplest method to concatenate the string in Java. We will be using
the concat() method of String class to append one string to the end of another and return the
new string.
// Java Program to Illustrate concat() method of String.
class GFG {
public static void main(String args[]) {
// String Initialization
String s = "Geeks";
// Use concat() method for string concatenation
s = s.concat("forGeeks");
System.out.println(s);
}
}
Output
GeeksforGeeks
Here are some important features and methods of the StringBuffer class:
• StringBuffer objects are mutable, meaning that you can change the contents of the
buffer without creating a new object.
• The initial capacity of a StringBuffer can be specified when it is created, or it can be
set later with the ensureCapacity() method.
• The append() method is used to add characters, strings, or other objects to the end of
the buffer.
• The insert() method is used to insert characters, strings, or other objects at a specified
position in the buffer.
• The delete() method is used to remove characters from the buffer.
• The reverse() method is used to reverse the order of the characters in the buffer.
// Creating StringBuffer
StringBuffer s = new StringBuffer();
There are several advantages of using StringBuffer over regular String objects in Java:
• Mutable: StringBuffer objects are mutable, which means that you can modify the
contents of the object after it has been created. In contrast, String objects are immutable,
which means that you cannot change the contents of a String once it has been created.
• Efficient: Because StringBuffer objects are mutable, they are more efficient than
creating new String objects each time you need to modify a string. This is especially true if
you need to modify a string multiple times, as each modification to a String object creates
a new object and discards the old one.
StringBuffer class is used to create mutable (modifiable) strings. The StringBuffer class in
Java is the same as the String class except it is mutable i.e. it can be changed.
Constructors of StringBuffer Class
Constructor Description Syntax
StringBuffer(String It accepts a
str) string argument that sets
the initial contents of the
StringBuffer s
StringBuffer object and
= new StringBuffer(“GeeksforGeeks”);
reserves room for 16 more
characters without
reallocation.
capacity() the total allocated capacity can be found by the capacity( ) method.
This method returns the char value in this sequence at the specified
charAt()
index.
Constructors of StringToken
Let us consider ‘str’ as the string to be tokenized. In that case we have three constructor
cases as mentioned below:
Constructor Description
Simple.java
. import java.util.StringTokenizer;
. public class Simple{
. public static void main(String args[]){
. StringTokenizer st = new StringTokenizer("my name is khan"," ");
. while (st.hasMoreTokens()) {
. System.out.println(st.nextToken());
. }
. }
. }
Output:
my
name
is
Khan
Test.java
. import java.util.*;
.
. public class Test {
. public static void main(String[] args) {
. StringTokenizer st = new StringTokenizer("my,name,is,khan");
.
. // printing next token
. System.out.println("Next token is : " + st.nextToken(","));
. }
. }
Output:
Next token is : my
StringTokenizer1.java
. import java.util.StringTokenizer;
. public class StringTokenizer1
. {
. /* Driver Code */
. public static void main(String args[])
. {
. /* StringTokenizer object */
. StringTokenizer st = new StringTokenizer("Demonstrating methods from StringTok
enizer class"," ");
. /* Checks if the String has any more tokens */
. while (st.hasMoreTokens())
. {
. System.out.println(st.nextToken());
. }
. }
. }
Output:
Demonstrating
methods
from
StringTokenizer
class
StringTokenizer4.java
. import java.util.StringTokenizer;
. public class StringTokenizer3
. {
. /* Driver Code */
. public static void main(String args[])
. {
. /* StringTokenizer object */
. StringTokenizer st = new StringTokenizer("Hello Everyone Have a nice day"," ");
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).
A framework provides a ready-made structure of classes and interfaces for building software
applications efficiently. It simplifies adding new features by offering reusable components
that perform similar tasks, eliminating the need to create a framework from scratch for each
new project. This approach enhances object-oriented design, making development quicker,
more consistent, and reliable.
The Collection framework represents a unified architecture for storing and manipulating a
group of objects. It enhances code efficiency and readability by offering various data
structures, including arrays, linked lists, trees, and hash tables, tailored to different
programming needs. It has:
Before the Collection Framework was introduced in JDK 1.2, Java's approach to collections
was using Arrays, Vectors, and Hash tables lacked a common interface. This meant each type
of collection had its own set of methods, syntax, and constructors, with no standardization or
correlation between them.
This made it difficult for users to remember the diverse functionalities of each collection type
and hindered code consistency and reusability. The disparate nature of these collections
highlighted the need for a unified Collection Framework to simplify and standardize
collection operations in Java.
Hierarchy of Collection Framework
Let's see the hierarchy of Collection framework. The java.util package contains all
the classes and interfaces for the Collection framework.
The Java Collections Framework is structured around key interfaces-Collection, List, Set,
Queue, and Map. Each tailored for specific data management tasks. Implementations like
ArrayList, HashSet, and HashMap offer practical solutions for working with these collections,
giving Java developers a versatile set of tools for efficient data handling.
o Class: A class is a blueprint from which individual objects are created. It encapsulates
data for objects through fields (attributes) and defines behavior via methods. Classes
support inheritance, allowing one class to inherit the properties and methods of
another, facilitating code reuse and polymorphism.
o Interface: An interface is a reference type in Java that can contain constants and
abstract methods (methods without a body). Interfaces specify what a class must do
but not how it does it, enforcing a set of methods that the class must implement.
Interfaces are used to achieve abstraction and multiple inheritance in Java.
Collections class
Collections class in Java is one of the utility classes in Java Collections Framework. The
java.util package contains the Collections class in Java. Java Collections class is used with
the static methods that operate on the collections or return the collection. All the methods
of this class throw the NullPointerException if the collection or object passed to the
methods is null.
Collection Class declaration
The syntax of the Collection class declaration is mentioned below:
public class Collections extends Object
1. ArrayList
ArrayList is a class implemented using a list interface, in that provides the functionality of
a dynamic array where the size of the array is not fixed.
Syntax:
ArrayList<_type_> var_name = new ArrayList<_type_>();
2. Vector
Vector is a Part of the collection class that implements a dynamic array that can grow or
shrink its size as required.
Syntax:
public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess,
Cloneable, Serializable
3. Stack
Stack is a part of Java collection class that models and implements a Stack data structure. It
is based on the basic principle of last-in-first-out(LIFO) .
Syntax:
public class Stack<E> extends Vector<E>
4. LinkedList
LinkedList class is an implementation of the LinkedList data structure. It can store the
elements that are not stored in contiguous locations and every element is a separate object
with a different data part and different address part.
Syntax:
LinkedList name = new LinkedList();
5. HashSet
HashSet is implemented using the Hashtable data structure. It offers constant time
performance for the performing operations like add, remove, contains, and size.
Syntax:
public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable,
Serializable
6. LinkedHashSet
7. TreeSet
TreeSet class is implementations of the SortedSet interface in Java that uses a Tree for
storage. The ordering of the elements is maintained by a set using their natural ordering
whether an explicit comparator is provided or not.
Syntax:
TreeSet t = new TreeSet(Collection col);
8. PriorityQueue
The PriorityQueue is based on the priority heap. The elements of the priority queue are
ordered according to the natural ordering, or by a Comparator provided at queue
construction time, depending on which constructor is used.
Syntax:
public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable
9. ArrayDeque
The ArrayDeque class in Java is an implementation of the Deque interface that uses a
resizable array to store its elements. The ArrayDeque class provides constant-time
performance for inserting and removing elements from both ends.
Syntax:
public class ArrayDeque<E> extends
AbstractCollection<E> implements Deque<E>, Cloneable,Serializable
10. HashMap
HashMap Class is similar to HashTable but the data unsynchronized. It stores the data in
(Key, Value) pairs, and you can access them by an index of another type.
Syntax:
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable
11. EnumMap
12. AbstractMap
The AbstractMap class is a part of the Java Collection Framework. It implements the Map
interface to provide a structure to it, by doing so it makes the further implementations
easier.
Syntax:
public abstract class AbstractMap<K,V> extends Object, implements Map<K,V>
13. TreeMap
It returns a view of a
2) static <T> Queue<T> asLifoQueue() Deque as a Last-in-
first-out (LIFO) Queue.
It is used to returns a
static <E> dynamically typesafe
4) checkedCollection()
Collection<E> view of the specified
collection.
It is used to returns a
dynamically typesafe
5) static <E> List<E> checkedList()
view of the specified
list.
It is used to returns a
static <K,V> dynamically typesafe
6) checkedMap()
Map<K,V> view of the specified
map.
It is used to returns a
static <K,V> dynamically typesafe
7) checkedNavigableMap()
NavigableMap<K,V> view of the specified
navigable map.
It is used to returns a
static <E> dynamically typesafe
8) checkedNavigableSet()
NavigableSet<E> view of the specified
navigable set.
It is used to returns a
dynamically typesafe
9) static <E> Queue<E> checkedQueue()
view of the specified
queue.
It is used to returns a
dynamically typesafe
10) static <E> Set<E> checkedSet()
view of the specified
set.
Collection is a group of objects, which are known as elements. It is the root interface in the
collection hierarchy. This interface is basically used to pass around the collections and
manipulate them where the maximum generality is desired.
There are many methods defined in the Collection interface. These are as follows:
Method Description
Syntax
Now it's time to execute a Java program to illustrate the advantage of the Java Iterator
interface. The below code produces an ArrayList of city names. Then we initialize an iterator
applying the iterator () method of the ArrayList. After that, the list is traversed to represent
each element.
JavaIteratorExample.java
. import java.io.*;
. import java.util.*;
. public class JavaIteratorExample {
. public static void main(String[] args)
. {
. ArrayList<String> cityNames = new ArrayList<String>();
. cityNames.add("Delhi");
. cityNames.add("Mumbai");
. cityNames.add("Kolkata");
. cityNames.add("Chandigarh");
. cityNames.add("Noida");
. // Iterator to iterate the cityNames
. Iterator iterator = cityNames.iterator();
. System.out.println("CityNames elements : ");
. while (iterator.hasNext())
. System.out.print(iterator.next() + " ");
. }
. }
Output:
CityNames elements:
Delhi Mumbai Kolkata Chandigarh Noida
The map interface in Java is a structure that holds a set of key-value pairs where each key is
unique and points to one value only. It is a component of the java.util package and is being
widely used in Java programming to structure and get data in an ordered manner. A Map is
useful if you have to search, update or delete elements on the basis of a key.
• No Duplicates in Keys: Ensures that keys are unique. However, values can be
duplicated.
• Null Handling: Allows one null key in implementations like HashMap
and LinkedHashMap and allows multiple null values in most implementations.
• Thread-Safe Alternatives: Use ConcurrentHashMap for thread-safe operations
also, wrap an existing Map using Collections.synchronizedMap() for synchronized
access.
// Java Program Implementing HashMap
import java.util.HashMap;
import java.util.Map;
Class Description
This method is used in Java Map Interface to clear and remove all of the
clear()
elements or mappings from a specified Map collection.
This method is used in Map Interface in Java to create a set out of the
entrySet() same elements contained in the map. It basically returns a set view of the
map or we can create a new set and store the map elements into them.
This method is used in Java Map Interface to check for equality between
equals(Object) two maps. It verifies whether the elements of one map passed as a
parameter is equal to the elements of this map or not.
This method is used in Map Interface to generate a hashCode for the given
hashCode()
map containing keys and values.
This method is used to check if a map is having any entry for key and
isEmpty()
value pairs. If no mapping exists, then this returns true.
This method is used in Map Interface to return a Set view of the keys
keySet() contained in this map. The set is backed by the map, so changes to the
map are reflected in the set, and vice-versa.
This method is used in Java Map Interface to associate the specified value
put(Object, Object)
with the specified key in this map.
This method is used in Map Interface in Java to copy all of the mappings
putAll(Map)
from the specified map to this map.
This method is used in Map Interface to remove the mapping for a key
remove(Object)
from this map if it is present in the map.
Hierarchy of Map
Interface in Java
Method Action Performed
It provides multiple sorting sequences, i.e., you can sort the elements on the basis of any data
member, for example, rollno, name, age or anything else.
Method Description
It compares the first object with the second
public int compare(Object obj1, Object obj2)
object.
public void sort(List list, Comparator c): is used to sort the elements of List by the given
Comparator.
Let's see the example of sorting the elements of List on the basis of age and name. In this
example, we have created 4 java classes:
1. Student.java
2. AgeComparator.java
3. NameComparator.java
4. Simple.java
Student.java
This class contains three fields rollno, name and age and a parameterized constructor.
. class Student{
. int rollno;
. String name;
. int age;
. Student(int rollno,String name,int age){
. this.rollno=rollno;
. this.name=name;
. this.age=age;
. }
. }
AgeComparator.java
This class defines comparison logic based on the age. If the age of the first object is greater
than the second, we are returning a positive value. It can be anyone such as 1, 2, 10. If the age
of the first object is less than the second object, we are returning a negative value, it can be
any negative value, and if the age of both objects is equal, we are returning 0.
. import java.util.*;
. class AgeComparator implements Comparator{
. public int compare(Object o1,Object o2){
. Student s1=(Student)o1;
. Student s2=(Student)o2;
.
. if(s1.age==s2.age)
. return 0;
. else if(s1.age>s2.age)
. return 1;
. else
. return -1;
. }
. }
NameComparator.java
This class provides comparison logic based on the name. In such case, we are using the
compareTo() method of String class, which internally provides the comparison logic.
. import java.util.*;
. class NameComparator implements Comparator
. {
. public int compare(Object o1,Object o2)
. {
. Student s1=(Student)o1;
. Student s2=(Student)o2;
.
. return s1.name.compareTo(s2.name);
. }
. }
complete example using a comparator to sort a list of cars by year:
brand = b;
model = m;
year = y;
}}
if (a.year < b.year) return -1; // The first car has a smaller year
if (a.year > b.year) return 1; // The first car has a larger year
}}
Collections.sort(myCars, myComparator);
}}
Output:
Ford Mustang 1970
BMW X5 1999
Honda Accord 2006
In the world of programming, efficient data manipulation is often a critical requirement. Java,
being one of the most popular programming languages, offers a variety of tools and interfaces
to help achieve this efficiently. One such interface is the RandomAccess interface, which
plays a vital role in enabling random access to data structures. In this section, we will dive
into the world of random access in Java, exploring what the RandomAccess interface is, how
it works, and provide practical examples to illustrate its usage.
The RandomAccess interface is a marker interface in Java, which means it doesn't declare
any methods of its own. Instead, it serves as a marker to indicate that a class implementing it
supports efficient random-access operations. By implementing this interface, a class
essentially tells Java that it can provide faster access to elements, typically using indices or
keys.
The primary reason for using the RandomAccess interface is to indicate that a class has
optimized its data structure for random access. This information can be beneficial for
algorithms and data structures that rely on efficient random access. When a class implements
RandomAccess, it signals that operations like accessing elements by index or key will be fast
and efficient.
Let's take a look at a practical example to understand this better. Suppose we have a large list
of data, and we want to access elements at random indices frequently. If the data structure
used to store this list implements the RandomAccess interface, we can expect faster
performance compared to a non-RandomAccess data structure.
In this example, we will create a custom class that implements the RandomAccess interface
to store a list of integers efficiently. We will then compare the performance of random access
with and without the interface.
RandomAccessDemo.java
. import java.util.ArrayList;
. import java.util.List;
. import java.util.RandomAccess;
. // Define a custom class that implements the RandomAccess interface
. class CustomList implements RandomAccess {
. private List<Integer> data;
. // Constructor to initialize the data list
. public CustomList() {
. data = new ArrayList<>();
. }
. // Method to add an element to the custom list
. public void add(int element) {
. data.add(element);
. }
. // Method to get an element at a specified index
. public int get(int index) {
. return data.get(index);
. }
. }
The java.util package is a standard package of Java SDK. It contains the collections framework, legacy collection
classes, event model, date and time facilities, internationalization, and miscellaneous utility classes. This package is
very useful as it provides commonly used Collections like ArrayList, HashMap, Set etc. Java.util provides
StrinTokenizer classes for String operations and similarly other utility classes for event model handlings, date and
time operations and lot more. This reference will take you through simple and practical methods available
in java.util package.
import java.util.*;
Here we've used * operator to import all classes from java.util package and now any class can be used in the program.
In case of specific class, for example ArrayList, we can import a class using following syntax:
import java.util.ArrayList;
Java.util package classes contains utility classes like collections frameworks, String operations utilities, Date and
Time operations utilities. Following list shows some of the categories of classes of java.util package.
•
Collections − ArrayList, HashMap, Dictionary are few of the classes of large set of Collection classes availble in
java.util package. These classes provides commonly used operations on large data sets.
•
•
Date Time Operations − GregorianCalendar, Timezone are some of the classes of utility classes availble in java.util
package. These classes provides commonly used operations on date and time.
•
•
String Manipulations − StringTokenizer is an important utility class availble in java.util package. This class provides
a lot of operations to manipulate strings.
•
•
Enumerations − Enumeration class of java.util package provides operations on set of values like iterations,
comparison etc.
•
•
Exceptions − java.util package contains various commonly occuring exceptions like
ConcurrentModificationException, InputMismatchException etc.
•
• ArrayDeque − This class provides resizable-array and implements the Deque interface. This class and its
iterator implement all of the optional methods of the Collection and Iterator interfaces.
• ArrayList − This class provides resizable-array and implements the List interface. The ArrayList class
extends AbstractList and implements the List interface. ArrayList supports dynamic arrays that can grow as needed.
• Arrays − This class contains a static factory that allows arrays to be viewed as lists. The ArrayList class
contains various methods for manipulating arrays (such as sorting and searching).
• BitSet − This class creates a special type of array that holds bit values. The BitSet array can increase in size
as needed. This makes it similar to a vector of bits. This is a legacy class but it has been completely re-engineered in
Java 2, version 1.4. The Java BitSet class implements a vector of bits that grows as needed.
• Calendar − This class is an abstract class that provides methods for converting between a specific instant in
time and a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR, and so on, and for
manipulating the calendar fields, such as getting the date of the next week.
• Collections − This class consists exclusively of static methods that operate on or return collections.
• Currency − This class represents a currency. The Currency class is designed so that there's never more than
one Currency instance for any given currency, this is the reason behind no public constructor.
• Date − This class represents a specific instant in time, with millisecond precision.
• Dictionary − This class is the abstract parent of any class, such as Hashtable, which maps keys to values.
• EnumMap − This class is a specialized Map implementation for use with enum keys. All of the keys in an
enum map must come from a single enum type that is specified, explicitly or implicitly, when the map is created.
• EnumSet − This class is a specialized Set implementation for use with enum keys. All of the keys in an
enum set must come from a single enum type that is specified, explicitly or implicitly, when the set is created.
• Formatter − This class provides support for layout justification and alignment, common formats for
numeric, string, and date/time data, and locale-specific output.
• GregorianCalendar − This class is a concrete subclass of Calendar and provides the standard calendar
system used by most of the world. It is a hybrid calendar that supports both the Julian and Gregorian calendar systems
with the support of a single discontinuity, which corresponds by default to the Gregorian date when the Gregorian
calendar was instituted.
• HashMap − This class is the Hash table based implementation of the Map interface.
• HashSet − This class implements the Set interface, backed by a hash table.
• HashTable − This class implements a hashtable, which maps keys to values.
Example of java.util.ArrayList
Java AWT
Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI) or windows-based
applications in Java.
Java AWT components are platform-dependent i.e. components are displayed according to the view of operating system.
AWT is heavy weight i.e. its components are using the resources of underlying operating system (OS).
The java.awt package provides classes for AWT API such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
Java AWT calls the native platform calls the native platform (operating systems) subroutine for creating API components
like TextField, ChechBox, button, etc.
For example, an AWT GUI with components like TextField, label and button will have different look and feel for the
different platforms like Windows, MAC OS, and Unix. The reason for this is the platforms have different view for their
native components and AWT directly calls the native subroutine that creates those components.
In simple words, an AWT application will look like a windows application in Windows OS whereas it will look like a Mac
application in the MAC OS.
All the elements like the button, text fields, scroll bars, etc. are called components. In Java AWT, there are classes for each
component as shown in above diagram. In order to place every component in a particular position on a screen, we need to
add them to a container.
Container
The Container is a component in AWT that can contain another components like buttons, textfields, labels etc. The classes
that extends Container class are known as container such as Frame, Dialog and Panel.
It is basically a screen where the where the components are placed at their specific locations. Thus it contains and controls
the layout of components.
Note: A container itself is a component (see the above diagram), therefore we can add a container inside
container.
Types of containers:
1. Window
2. Panel
3. Frame
4. Dialog
Window
The window is the container that have no borders and menu bars. You must use frame, dialog or another window for creating
a window. We need to create an instance of Window class to create this container.
Panel
The Panel is the container that doesn't contain title bar, border or menu bar. It is generic container for holding the
components. It can have other components like button, text field etc. An instance of Panel class creates a container, in which
we can add components.
Frame
The Frame is the container that contain title bar and border and can have menu bars. It can have other components like
button, text field, scrollbar etc. Frame is most widely used container while developing an AWT application.
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.
AWTExample1.java
Let's see a simple example of AWT where we are creating instance of Frame class. Here, we are creating a TextField, Label
and Button component on the Frame.
AWTExample2.java
Changing the state of an object is known as an event. For example, click on button, dragging mouse etc. The java.awt.event
package provides many event classes and Listener interfaces for event handling.
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
Registration Methods
For registering the component with the Listener, many classes provide the registration methods. For example:
o Button
We can put the event handling code into one of the following places:
1. Within class
2. Other class
3. Anonymous class
. import java.awt.*;
. import java.awt.event.*;
. class AEvent extends Frame implements ActionListener{
. TextField tf;
. AEvent(){
.
. //create components
. tf=new TextField();
. tf.setBounds(60,50,170,20);
. Button b=new Button("click me");
. b.setBounds(100,120,80,30);
.
. //register listener
. b.addActionListener(this);//passing current instance
.
. //add components and set size, layout and visibility
. add(b);add(tf);
. setSize(300,300);
. setLayout(null);
. setVisible(true);
. }
. public void actionPerformed(ActionEvent e){
. tf.setText("Welcome");
. }
. public static void main(String args[]){
. new AEvent();
. }
. }
public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the above example that
sets the position of the component it may be button, textfield etc.
. import java.awt.*;
. import java.awt.event.*;
. class AEvent2 extends Frame{
. TextField tf;
. AEvent2(){
. //create components
. tf=new TextField();
. tf.setBounds(60,50,170,20);
. Button b=new Button("click me");
. b.setBounds(100,120,80,30);
. //register listener
. Outer o=new Outer(this);
. b.addActionListener(o);//passing outer class instance
. //add components and set size, layout and visibility
. add(b);add(tf);
. setSize(300,300);
. setLayout(null);
. setVisible(true);
. }
. public static void main(String args[]){
. new AEvent2();
. }
. }
. import java.awt.event.*;
. class Outer implements ActionListener{
. AEvent2 obj;
. Outer(AEvent2 obj){
. this.obj=obj;
. }
. public void actionPerformed(ActionEvent e){
. obj.tf.setText("welcome");
. }
. }
. import java.awt.*;
. import java.awt.event.*;
. class AEvent3 extends Frame{
. TextField tf;
. AEvent3(){
. tf=new TextField();
. tf.setBounds(60,50,170,20);
. Button b=new Button("click me");
. b.setBounds(50,120,80,30);
.
. b.addActionListener(new ActionListener(){
. public void actionPerformed(){
. tf.setText("hello");
. }
. });
. add(b);add(tf);
. setSize(300,300);
. setLayout(null);
. setVisible(true);
. }
. public static void main(String args[]){
. new AEvent3();
. }
. }
The Delegation Event model is defined to handle events in GUI programming languages. The GUI stands for
Graphical User Interface, where a user graphically/visually interacts with the system.
The GUI programming is inherently event-driven; whenever a user initiates an activity such as a mouse activity,
clicks, scrolling, etc., each is known as an event that is mapped to a code to respond to functionality to the user.
This is known as event handling.
In this section, we will discuss event processing and how to implement the delegation event model in Java. We
will also discuss the different components of an Event Model.
Java support event processing since Java 1.0. It provides support for AWT ( Abstract Window Toolkit), which is
an API used to develop the Desktop application. In Java 1.0, the AWT was based on inheritance. To catch and
process GUI events for a program, it should hold subclass GUI components and override action() or
handleEvent() methods. The below image demonstrates the event processing.
But, the modern approach for event processing is based on the Delegation Model. It defines a standard and
compatible mechanism to generate and process events. In this model, a source generates an event and forwards
it to one or more listeners. The listener waits until it receives an event. Once it receives the event, it is processed
by the listener and returns it. The UI elements are able to delegate the processing of an event to a separate
function.
The key advantage of the Delegation Event Model is that the application logic is completely separated from the
interface logic.
In this model, the listener must be connected with a source to receive the event notifications. Thus, the events
will only be received by the listeners who wish to receive them. So, this approach is more convenient than the
inheritance-based event model (in Java 1.0).
In the older model, an event was propagated up the containment until a component was handled. This needed
components to receive events that were not processed, and it took lots of time. The Delegation Event model
overcame this issue.
o Events
o Events Sources
o Events Listeners
Events
The Events are the objects that define state change in a source. An event can be generated as a reaction of a user
while interacting with GUI elements. Some of the event generation activities are moving the mouse pointer,
clicking on a button, pressing the keyboard key, selecting an item from the list, and so on. We can also consider
many other user operations as events.
The Events may also occur that may be not related to user interaction, such as a timer expires, counter exceeded,
system failures, or a task is completed, etc. We can define events for any of the applied actions.
Event Sources
A source is an object that causes and generates an event. It generates an event when the internal state of the
object is changed. The sources are allowed to generate several different types of events.
A source must register a listener to receive notifications for a specific event. Each event contains its registration
method. Below is an example:
A source should contain a method that unregisters a specific type of event from the listener if not needed. Below
is an example of the method that will remove the event from the listener.
. public void removeTypeListener(TypeListener e2?)
From the above syntax, the Type is an event name, and e2 is the reference of the listener. For example, to
remove the keyboard listener, the removeKeyListener() method will be called.
The source provides the methods to add or remove listeners that generate the events. For example, the
Component class contains the methods to operate on the different types of events, such as adding or removing
them from the listener.
Event Listeners
An event listener is an object that is invoked when an event triggers. The listeners require two things; first, it
must be registered with a source; however, it can be registered with several resources to receive notification
about the events. Second, it must implement the methods to receive and process the received notifications.
The methods that deal with the events are defined in a set of interfaces. These interfaces can be found in the
java.awt.event package.
For example, the MouseMotionListener interface provides two methods when the mouse is dragged and moved.
Any object can receive and process these events if it implements the MouseMotionListener interface.
Types of Events
The foreground events are those events that require direct interaction of the user. These types of events are
generated as a result of user interaction with the GUI component. For example, clicking on a button, mouse
movement, pressing a keyboard key, selecting an option from the list, etc.
The Background events are those events that result from the interaction of the end-user. For example, an
Operating system interrupts system failure (Hardware or Software).
To handle these events, we need an event handling mechanism that provides control over the events and
responses.
Advertisement
The Delegation Model is available in Java since Java 1.1. it provides a new delegation-based event model using
AWT to resolve the event problems. It provides a convenient mechanism to support complex Java programs.
Design Goals
The below is a Java program to handle events implementing the event deligation model:
TestApp.java:
. import java.awt.*;
. import java.awt.event.*;
. public class TestApp {
. public void search() {
. // For searching
. System.out.println("Searching...");
. }
. public void sort() {
. // for sorting
. System.out.println("Sorting....");
. }
. static public void main(String args[]) {
. TestApp app = new TestApp();
. GUI gui = new GUI(app);
. }
. }
. class Command implements ActionListener {
. static final int SEARCH = 0;
. static final int SORT = 1;
. int id;
. TestApp app;
. public Command(int id, TestApp app) {
. this.id = id;
. this.app = app;
. }
.
. public void actionPerformed(ActionEvent e) {
. switch(id) {
. case SEARCH:
. app.search();
. break;
. case SORT:
. app.sort();
. break;
. }
. }
. }
.
. class GUI {
.
. public GUI(TestApp app)
. {
. Frame f = new Frame();
. f.setLayout(new FlowLayout());
. Command searchCmd = new Command(Command.SEARCH, app);
. Command sortCmd = new Command(Command.SORT, app);
.
. Button b;
. f.add(b = new Button("Search"));
. b.addActionListener(searchCmd);
. f.add(b = new Button("Sort"));
. b.addActionListener(sortCmd);
.
. List l;
. f.add(l = new List());
. l.add("Alphabetical");
. l.add("Chronological");
. l.addActionListener(sortCmd);
. f.pack();
. f.show();
. }
. }
Output:
It is called a passive control as it does not create any event when it is accessed. To create a label, we need to create the object
of Label class.
Method inherited
The above methods are inherited by the following classes:
o java.awt.Component
o java.lang.Object
LabelExample.java
. import java.awt.*;
.
. public class LabelExample {
. public static void main(String args[]){
.
. // creating the object of Frame class and Label class
. Frame f = new Frame ("Label example");
. Label l1, l2;
.
. // initializing the labels
. l1 = new Label ("First Label.");
. l2 = new Label ("Second Label.");
.
. // set the location of label
. l1.setBounds(50, 100, 100, 30);
. l2.setBounds(50, 150, 100, 30);
.
. // adding labels to the frame
. f.add(l1);
. f.add(l2);
.
. // setting size, layout and visibility of frame
. f.setSize(400,400);
. f.setLayout(null);
. f.setVisible(true);
. }
. }
Output:
When we press a button and release it, AWT sends an instance of ActionEvent to that button by calling processEvent on
the button. The processEvent method of the button receives the all the events, then it passes an action event by calling its
own method processActionEvent. This method passes the action event on to action listeners that are interested in the action
events generated by the button.
To perform an action on a button being pressed and released, the ActionListener interface needs to be implemented. The
registered new listener can receive events from the button by calling addActionListener method of the button. The Java
application can use the button's action command as a messaging protocol.
1. void setText (String text) It sets the string message on the button
Example 1:
ButtonExample.java
. import java.awt.*;
. public class ButtonExample {
. public static void main (String[] args) {
.
. // create instance of frame with the label
. Frame f = new Frame("Button Example");
.
. // create instance of button with label
. Button b = new Button("Click Here");
.
. // set the position for the button in frame
. b.setBounds(50,100,80,30);
.
. // add button to the frame
. f.add(b);
. // set size, layout and visibility of frame
. f.setSize(400,400);
. f.setLayout(null);
. f.setVisible(true);
. }
. }
To compile the program using command prompt type the following commands
. C:\Users\Anurati\Desktop\abcDemo>javac ButtonExample.java
If there's no error, we can execute the code using:
. C:\Users\Anurati\Desktop\abcDemo>java ButtonExample
Output:
o java.awt.Component
o java.lang.Object
CheckboxExample1.java
. // importing AWT class
. import java.awt.*;
. public class CheckboxExample1
. {
. // constructor to initialize
. CheckboxExample1() {
. // creating the frame with the title
. Frame f = new Frame("Checkbox Example");
. // creating the checkboxes
. Checkbox checkbox1 = new Checkbox("C++");
. checkbox1.setBounds(100, 100, 50, 50);
. Checkbox checkbox2 = new Checkbox("Java", true);
. // setting location of checkbox in frame
. checkbox2.setBounds(100, 150, 50, 50);
. // adding checkboxes to frame
. f.add(checkbox1);
. f.add(checkbox2);
.
. // setting size, layout and visibility of frame
. f.setSize(400,400);
. f.setLayout(null);
. f.setVisible(true);
. }
. // main method
. public static void main (String args[])
. {
. new CheckboxExample1();
. }
. }
Output:
Note: CheckboxGroup enables you to create radio buttons in AWT. There is no special control for creating
radio buttons in AWT.
. import java.awt.*;
. public class CheckboxGroupExample
. {
. CheckboxGroupExample(){
. Frame f= new Frame("CheckboxGroup Example");
. CheckboxGroup cbg = new CheckboxGroup();
. Checkbox checkBox1 = new Checkbox("C++", cbg, false);
. checkBox1.setBounds(100,100, 50,50);
. Checkbox checkBox2 = new Checkbox("Java", cbg, true);
. checkBox2.setBounds(100,150, 50,50);
. f.add(checkBox1);
. f.add(checkBox2);
. f.setSize(400,400);
. f.setLayout(null);
. f.setVisible(true);
. }
. public static void main(String args[])
. {
. new CheckboxGroupExample();
. }
. }
Output:
o java.awt.Component
o java.lang.Object
ChoiceExample1.java
o java.awt.Component
o java.lang.Object
ListExample1.java
It can be added to top-level container like Frame or a component like Panel. The Scrollbar class extends
the Component class.
o java.awt.Component
o java.lang.Object
ScrollbarExample1.java
When we enter a key in the text field (like key pressed, key released or key typed), the event is sent to TextField. Then
the KeyEvent is passed to the registered KeyListener. It can also be done using ActionEvent; if the ActionEvent is enabled
on the text field, then the ActionEvent may be fired by pressing return key. The event is handled by
the ActionListener interface.
Method Inherited
The AWT TextField class inherits the methods from below classes:
1. java.awt.TextComponent
2. java.awt.Component
3. java.lang.Object
The text area allows us to type as much text as we want. When the text in the text area becomes larger than the viewable area,
the scroll bar appears automatically which helps us to scroll the text up and down, or right and left.
o static int SCROLLBARS_BOTH - It creates and displays both horizontal and vertical scrollbars.
o static int SCROLLBARS_HORIZONTAL_ONLY - It creates and displays only the horizontal scrollbar.
o static int SCROLLBARS_VERTICAL_ONLY - It creates and displays only the vertical scrollbar.
o static int SCROLLBARS_NONE - It doesn't create or display any scrollbar in the text area.
Class constructors:
Sr. no. Constructor Description
Methods Inherited
The methods of TextArea class are inherited from following classes:
o java.awt.TextComponent
o java.awt.Component
o java.lang.Object
TextAreaExample .java
The LayoutManagers are used to arrange components in a particular manner. The Java LayoutManagers facilitates us to
control the positioning and size of the components in GUI forms. LayoutManager is an interface that is implemented by all
the classes of layout managers. There are the following classes that represent the layout managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.
Java BorderLayout
The BorderLayout is used to arrange the components in five regions: north, south, east, west, and center. Each region (area)
may contain one component only. It is the default layout of a frame or window. The BorderLayout provides five constants
for each region:
FileName: Border.java
. import java.awt.*;
. import javax.swing.*;
.
. public class Border
. {
. JFrame f;
. Border()
. {
. f = new JFrame();
.
. // creating buttons
. JButton b1 = new JButton("NORTH");; // the button will be labeled as NORTH
. JButton b2 = new JButton("SOUTH");; // the button will be labeled as SOUTH
. JButton b3 = new JButton("EAST");; // the button will be labeled as EAST
. JButton b4 = new JButton("WEST");; // the button will be labeled as WEST
. JButton b5 = new JButton("CENTER");; // the button will be labeled as CENTER
.
. f.add(b1, BorderLayout.NORTH); // b1 will be placed in the North Direction
. f.add(b2, BorderLayout.SOUTH); // b2 will be placed in the South Direction
. f.add(b3, BorderLayout.EAST); // b2 will be placed in the East Direction
. f.add(b4, BorderLayout.WEST); // b2 will be placed in the West Direction
. f.add(b5, BorderLayout.CENTER); // b2 will be placed in the Center
.
. f.setSize(300, 300);
. f.setVisible(true);
. }
. public static void main(String[] args) {
. new Border();
. }
. }
Output:
Example of BorderLayout class: Using BorderLayout(int hgap, int vgap) constructor
The following example inserts horizontal and vertical gaps between buttons using the parameterized constructor
BorderLayout(int hgap, int gap)
FileName: BorderLayoutExample.java
. // import statement
. import java.awt.*;
. import javax.swing.*;
. public class BorderLayoutExample
. {
. JFrame jframe;
. // constructor
. BorderLayoutExample()
. {
. // creating a Frame
. jframe = new JFrame();
. // create buttons
. JButton btn1 = new JButton("NORTH");
. JButton btn2 = new JButton("SOUTH");
. JButton btn3 = new JButton("EAST");
. JButton btn4 = new JButton("WEST");
. JButton btn5 = new JButton("CENTER");
. // creating an object of the BorderLayout class using
. // the parameterized constructor where the horizontal gap is 20
. // and vertical gap is 15. The gap will be evident when buttons are placed
. // in the frame
. jframe.setLayout(new BorderLayout(20, 15));
. jframe.add(btn1, BorderLayout.NORTH);
. jframe.add(btn2, BorderLayout.SOUTH);
. jframe.add(btn3, BorderLayout.EAST);
. jframe.add(btn4, BorderLayout.WEST);
. jframe.add(btn5, BorderLayout.CENTER);
. jframe.setSize(300,300);
. jframe.setVisible(true);
. }
. // main method
. public static void main(String argvs[])
. {
. new BorderLayoutExample();
. }
. }
Output:
The add() method of the JFrame class can work even when we do not specify the region. In such a case, only the latest
component added is shown in the frame, and all the components added previously get discarded. The latest component
covers the whole area. The following example shows the same.
FileName: BorderLayoutWithoutRegionExample.java
. // import statements
. import java.awt.*;
. import javax.swing.*;
.
. public class BorderLayoutWithoutRegionExample
. {
. JFrame jframe;
.
. // constructor
. BorderLayoutWithoutRegionExample()
. {
. jframe = new JFrame();
.
. JButton btn1 = new JButton("NORTH");
. JButton btn2 = new JButton("SOUTH");
. JButton btn3 = new JButton("EAST");
. JButton btn4 = new JButton("WEST");
. JButton btn5 = new JButton("CENTER");
.
. // horizontal gap is 7, and the vertical gap is 7
. // Since region is not specified, the gaps are of no use
. jframe.setLayout(new BorderLayout(7, 7));
.
. // each button covers the whole area
. // however, the btn5 is the latest button
. // that is added to the frame; therefore, btn5
. // is shown
. jframe.add(btn1);
. jframe.add(btn2);
. jframe.add(btn3);
. jframe.add(btn4);
. jframe.add(btn5);
.
. jframe.setSize(300,300);
. jframe.setVisible(true);
. }
.
. // main method
. public static void main(String argvs[])
. {
. new BorderLayoutWithoutRegionExample();
. }
. }
Output:
Java AWT MenuItem and Menu
The object of MenuItem class adds a simple labeled menu item on menu. The items used in a menu must belong to the
MenuItem or any of its subclass.
The object of Menu class is a pull down menu component which is displayed on the menu bar. It inherits the MenuItem class.
. import java.awt.*;
. class MenuExample
. {
. MenuExample(){
. Frame f= new Frame("Menu and MenuItem Example");
. MenuBar mb=new MenuBar();
. Menu menu=new Menu("Menu");
. Menu submenu=new Menu("Sub Menu");
. MenuItem i1=new MenuItem("Item 1");
. MenuItem i2=new MenuItem("Item 2");
. MenuItem i3=new MenuItem("Item 3");
. MenuItem i4=new MenuItem("Item 4");
. MenuItem i5=new MenuItem("Item 5");
. menu.add(i1);
. menu.add(i2);
. menu.add(i3);
. submenu.add(i4);
. submenu.add(i5);
. menu.add(submenu);
. mb.add(menu);
. f.setMenuBar(mb);
. f.setSize(400,400);
. f.setLayout(null);
. f.setVisible(true);
. }
. public static void main(String args[])
. {
. new MenuExample();
. }
. }
Output:
Java AWT Dialog
The Dialog control represents a top level window with a border and a title used to take some form of input from the user. It
inherits the Window class.
Frame vs Dialog
Frame and Dialog both inherits Window class. Frame has maximize and minimize buttons but Dialog doesn't have.
. import java.awt.*;
. import java.awt.event.*;
. public class DialogExample {
. private static Dialog d;
. DialogExample() {
. Frame f= new Frame();
. d = new Dialog(f , "Dialog Example", true);
. d.setLayout( new FlowLayout() );
. Button b = new Button ("OK");
. b.addActionListener ( new ActionListener()
. {
. public void actionPerformed( ActionEvent e )
. {
. DialogExample.d.setVisible(false);
. }
. });
. d.add( new Label ("Click button to continue."));
. d.add(b);
. d.setSize(300,300);
. d.setVisible(true);
. }
. public static void main(String args[])
. {
. new DialogExample();
. }
. }
Output:
Filedialog Java
In Java programming, handling files is a common task that developers often encounter. Whether it's reading from or writing
to files, selecting specific files for processing, or managing file-related operations, having a straightforward way to interact
with the file system is essential. Java's FileDialog class offers a convenient solution for these file-handling tasks, providing a
user-friendly interface for file selection and manipulation. In this section, we will explore the functionalities of the File
Dialog class in Java, along with comprehensive examples and output demonstrations.
FileDialog Examples:
Let's delve into some illustrative examples to comprehend the practical implementation of the FileDialog class in Java.
FileDialogExample.java
. import java.awt.FileDialog;
. import java.awt.Frame;
. public class FileDialogExample {
. public static void main(String[] args) {
. // Create a Frame, which is a graphical window to host the FileDialog.
. Frame frame = new Frame("File Dialog Example");
. // Create a FileDialog with a title, "Select File."
. FileDialog fileDialog = new FileDialog(frame, "Select File");
. // Display the FileDialog, allowing the user to select a file.
. fileDialog.setVisible(true);
. // Retrieve the name of the selected file.
. String file = fileDialog.getFile();
. // Check if a file was selected.
. if (file == null) {
. // No file was selected; print a message to the console.
. System.out.println("No file selected");
. } else {
. // A file was selected; print the selected file's name to the console.
. System.out.println("Selected file: " + file);
. }
. }
. }
Output:
Java uses the concept of a stream to make I/O operation fast. The java.io package contains all the classes required for input
and output operations.
Streams: Streams represent a sequence of data. In Java, there are two types of streams: input streams and output streams.
Input streams are used to read data from a source, while output streams are used to write data to a destination. Streams can
be categorized into byte streams (InputStream and OutputStream) and character streams (Reader and Writer).
Readers/Writers: Readers and writers are specialized stream classes designed for handling character data. They provide a
convenient way to read from and write to character-based data sources. Readers read character data from input streams,
while writers write character data to output streams.
Stream
A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream because it is like a stream of water
that continues to flow.
In Java, 3 streams are created for us automatically. All these streams are attached with the console.
Let's see the code to print output and an error message to the console.
. System.out.println("simple message");
. System.err.println("error message");
Let's see the code to get input from console.
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.
Let's understand the working of Java OutputStream and InputStream class by the figure given below.
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.
Method Description
public void write(int) throws IOException It is used to write a byte to the current output stream.
public void write(byte[])throws IOException It is used to write an array of byte to the current output stream.
public void flush() throws IOException It flushes the current output stream.
public void close() throws IOException It is used to close the current output stream.
OutputStream Hierarchy
InputStream Class
InputStream class is an abstract class. It is the superclass of all classes representing an input stream of bytes.
Method Description
It reads the next byte of data from the input stream. It returns -
public abstract int read() throws IOException
1 at the end of the file.
public void close() throws IOException It is used to close the current input stream.
InputStream Hierarchy
1. File Handling: Java I/O is extensively used for reading from and writing to files. Developers can manipulate files,
create directories, and perform file-related operations using Java's file I/O classes.
2. Network Communication: Java's socket classes (Socket and ServerSocket) facilitate network communication by
enabling data exchange between client and server applications over TCP/IP.
3. Serialization: Java's serialization mechanism allows objects to be converted into a stream of bytes for storage or
transmission. It is particularly useful for storing object state or transferring objects between applications.
4. Data Processing: Java I/O is integral to data processing tasks such as parsing text files, processing CSV data, and
interacting with databases through JDBC (Java Database Connectivity).
The ByteStream classes are divided into two types of classes, i.e., InputStream and OutputStream. These classes are abstract
and the super classes of all the Input/Output stream classes.
InputStream Class
The InputStream class provides methods to read bytes from a file, console or memory. It is an abstract class and can't be
instantiated; however, various classes inherit the InputStream class and override its methods. The subclasses of InputStream
class are given in the following table.
SN Class Description
The InputStream class contains various methods to read the data from an input stream. These methods are overridden by the
classes that inherit the InputStream class. However, the methods are given in the following table.
SN Method Description
OutputStream Class
The OutputStream is an abstract class that is used to write 8-bit bytes to the stream. It is the superclass of all the output
stream classes. This class can't be instantiated; however, it is inherited by various subclasses that are given in the following
table.
SN Class Description
The OutputStream class provides various methods to write bytes to the output streams. The methods are given in the
following table.
SN Method Description
Example:
The following example uses the ByteArrayInputStream to create an input stream from a byte array "content". We use the
read() method to read the content from an input stream. We have also used the write() method on a FileOutputStream object
to write the byte array content in the file.
. import java.io.ByteArrayInputStream;
. import java.io.File;
. import java.io.FileInputStream;
. import java.io.FileNotFoundException;
. import java.io.FileOutputStream;
. import java.io.IOException;
.
.
. public class InputOutputStreamExample {
.
.
. public static void main(String[] args) throws IOException {
. // TODO Auto-generated method stub
. byte content[] = "Jtp is the best website to learn new technologies".getBytes();
. ByteArrayInputStream inputStream = new ByteArrayInputStream(content);
.
. inputStream.read(content);
.
. File newFile = new File("/Users/MyUser/Desktop/MyNewFile.doc");
. FileOutputStream outputStream = new FileOutputStream(newFile);
. outputStream.write(content);
.
. }
.
.
. }
Output:
A new file MyNewFile.doc will be created on desktop with the content "Jtp is the best website to learn new technologies".
However, the CharacterStream classes are mainly used to read characters from the source and write them to the destination.
For this purpose, the CharacterStream classes are divided into two types of classes, I.e., Reader class and Writer class.
Reader Class
Reader class is used to read the 16-bit characters from the input stream. However, it is an abstract class and can't be
instantiated, but there are various subclasses that inherit the Reader class and override the methods of the Reader class. All
methods of the Reader class throw an IOException. The subclasses of the Reader class are given in the following table.
SN Class Description
SN Method Description
Writer Class
Writer class is used to write 16-bit Unicode characters to the output stream. The methods of the Writer class generate
IOException. Like Reader class, Writer class is also an abstract class that cannot be instantiated; therefore, the subclasses of
the Writer class are used to write the characters onto the output stream. The subclasses of the Writer class are given in the
below table.
SN Class Description
To write the characters to the output stream, the Write class provides various methods given in the following table.
SN Method Description
Serialization in Java
Serialization in Java is a mechanism of writing the state of an object into a byte-stream. It is mainly used in Hibernate, RMI,
JPA, EJB and JMS technologies.
The reverse operation of serialization is called deserialization where byte-stream is converted into an object. The
serialization and deserialization process is platform-independent, it means you can serialize an object on one platform and
deserialize it on a different platform.
For serializing the object, we call the writeObject() method of ObjectOutputStream class, and for deserialization we call
the readObject() method of ObjectInputStream class.
We must have to implement the Serializable interface for serializing the object.
It is mainly used to travel object's state on the network (that is known as marshalling).
java.io.Serializable interface
Serializable is a marker interface (has no data member and method). It is used to "mark" Java classes so that the objects of
these classes may get a certain capability. The Cloneable and Remote are also marker interfaces.
The Serializable interface must be implemented by the class whose object needs to be persisted.
The String class and all the wrapper classes implement the java.io.Serializable interface by default.
Student.java
. import java.io.Serializable;
. public class Student implements Serializable{
. int id;
. String name;
. public Student(int id, String name) {
. this.id = id;
. this.name = name;
. }
. }
In the above example, Student class implements Serializable interface. Now its objects can be converted into stream. The
main class implementation of is showed in the next code.
ObjectOutputStream class
The ObjectOutputStream class is used to write primitive data types, and Java objects to an OutputStream. Only objects that
support the java.io.Serializable interface can be written to streams.
Constructor
1) public ObjectOutputStream(OutputStream out) throws It creates an ObjectOutputStream that writes to the specified
IOException {} OutputStream.
Important Methods
Method Description
2) public void flush() throws IOException {} It flushes the current output stream.
3) public void close() throws IOException {} It closes the current output stream.
ObjectInputStream class
Constructor
1) public ObjectInputStream(InputStream in) throws It creates an ObjectInputStream that reads from the specified
IOException {} InputStream.
Important Methods
Method Description
Persist.java
. import java.io.*;
. class Persist{
. public static void main(String args[]){
. try{
. //Creating the object
. Student s1 =new Student(211,"ravi");
. //Creating stream and writing the object
. FileOutputStream fout=new FileOutputStream("f.txt");
. ObjectOutputStream out=new ObjectOutputStream(fout);
. out.writeObject(s1);
. out.flush();
. //closing the stream
. out.close();
. System.out.println("success");
. }catch(Exception e){System.out.println(e);}
. }
. }
Output:
success