Ecap615 Java
Ecap615 Java
ECAP615
Edited by
Balraj Kumar
Programming In Java
Edited By:
Balraj Kumar
CONTENT
Unit 1: Introduction 1
Harjinder Kaur, Lovely Professional University
Unit 2: Arrays and Strings 23
Harjinder Kaur, Lovely Professional University
Objectives
After this unit you will be able to:
• Understand the importance of Java programming.
• Learn the comparative analysis between java and C++.
• Identify the various features of Java.
• Know the different operators and data types of java.
• Learn the basics of JDK,JRE, and JVM
• Understand the working of JDK,JRE, and JVM
• Learn the basic concept and needsof wrapper classes.
Introduction
Java is an important object-oriented programming language that is used in the software industry today.
Object-Oriented Programming is also known as OOP. Objects are the basic elements of object-oriented
programming. OOPS (Object Oriented Programming System) is used to describe a computer application that
comprises multiple objects connected. It is a type of programming language in which the programmers not
only define the data type of a data structure (files, arrays, and so on) but also define the behavior of the data
structure. Therefore, the data structure becomes an object, which includes both data and functions.
Programming in JAVA
Simple
Object
Robust
Oriented
High Platform
Performan Independe
ce nt
Features of Java
Distribute
Secure
d
Multi
Interpreted
threaded
Architectur
Dynamic
al Neutral
Simple: Various features make Java a simple language, which can be easily learned and effectively used. Java
does not use pointers explicitly, thereby making it easy to write and debug programs. Java is capable of
delivering a bug-free system due to its strong memory management. It also has an automatic memory
allocation and de-allocation system in place.
(a) Inheritance: It is the technique of creating new classes by making use of the behavior of the existing
classes. This is done by extending the behavior of the existing classes just by adding additional features as
required, thus bringing in the reusability of existing code.
(b) Encapsulation: It refers to the bundling of data along with the methods that act on that data.
(c) Polymorphism: Polymorphism, which means one name multiple forms, is the ability of a reference
variable to change behavior according to the instance of the object that it holds.
(d) Dynamic binding: It is the method of providing maximum functionality to a program by resolving the type
of object at runtime.
Robust: Java supports some features such as automatic garbage collection, strong memory allocation,
powerful exception handling, and a type checking mechanism. The compiler checks the program for errors
and the interpreter checks for any run time errors, thus preventing the system crash. These features make Java
robust.
Distributed: The protocols like HTTP and FTP, which are extensively used over the Internet are developed
using Java. Programmers who work on the Internet can call functions with the help of these protocols and can
secure access to the files that are present on any remote machine on the Internet. This is made possible by
writing codes on their local system itself.
Portable: The feature ‘write-once run anywhere, anytime’ makes Java portable, provided that the system has
JVM. Java standardizes the data size, irrespective of the operating system or the processor. These features
make Java a portable language.
Dynamic: A Java program also includes a significant amount of runtime information that is used to
verify and resolve access to objects at runtime. This allows the code to link dynamically securely
and appropriately.
Secure: Memory pointers are not explicitly used in Java. All programs in Java are run under a Java
execution environment. Therefore, while downloading an applet program using the Internet, Java
does not allow any virus or other harmful code to access the system as it confines it to the Java
execution environment.
Performance: In Java, a program is compiled into an intermediate representation, which is called
Java bytecode. This code can be executed on any system that has a JVM running on it. Earlier
attempts to achieve cross-platform operability accomplished it at the cost of performance. Java
bytecode is designed in such a manner that it is easy to directly translate the bytecode into the
native machine code by using a just-in-time compiler. This helps in achieving high performance.
Multithreaded: The primary objective that led to the development of Java was to meet the real-world
requirement of creating interactive and networked programs. To accomplish this, Java provides
multithreaded programming, which permits a programmer to write programs that can do many
things simultaneously.
Interpreted: Java programs can be directly run from the source code. The source code is read by the
interpreter program and translated into computations. The source code generated is platform-
independent. As an interpreted language, Java has an error debugging facility that can trace any
error occurring in the program.
Architecture Neutral: These features of Java have made it a popular programming language.Java is
also known as an architectural neutral language. In this era ofnetworks, easy migration of
applications to different computer systems having different hardwarearchitectures and/or
operating systems is necessary. The Java compiler generates an object fileformat that is architecture-
neutral. This permits a Java application to execute anywhere on thenetwork and many different
processors, given the presence of the Java runtime system.
Programming in JAVA
1.4 Sample Program
Let us understand the sections of the Java program in detail:
Package Section: This section consists of the first statement that is permitted in a Java file. Thisfirst
statement is called the package statement. It gives the name of the package and
providesinformation to the compiler that all the classes defined in the respective program are
related to thispackage.
Caution: In Java, the class name and the file name must be the same. Also, since Java is case-sensitive,
oneshould always provide the same case letters for both file name and class name.
After compiling and interpreting, a program is run. To run a program, follow the instructions given
below:
1. Go to the command prompt.
2. Select the drive (and the folder) where the program file is saved.
Example: Type the following program and save it in a file with the name "FirstProgram.java"
classFirstProgram
{
public static void main(String args[ ])
{
System.out.println("My first program in Java");
}
}
The process to compile and run the above-given example is described in the following steps
1. In the command prompt, type the directory name, and the file name.
Example: c:\jdk\programs>javac FirstProgram.java
Example C:\jdk\programs > java FirstProgram
1.5 Operators
In real-time, programs are required to perform a lot more than just simple input and output
operations. All computer languages provide tools to perform some predefined operations. To
facilitate this, there are different types of operators provided in Java. These are arithmetic operators,
relational operators, logical operators, and conditional operators. These operators are assigned a
certain kind of precedence so that the compiler evaluates the operations based on their precedence.
This helps when there are multiple operators in one statement.There are many types of operators in
Java which are given below:
Unary Operator: The Java unary operators require only one operand. Unary operators are used to
performing various operations i.e.:
Programming in JAVA
additive +-
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
Ternary ternary ?:
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
Boolean Data Type:The Boolean data type is used to store only two possible values:
true
false.
Short Data Type: The short data type is a 16-bit signed two's complement integer. Its value-range
lies between -32,768 to 32,767 (inclusive). A short data type is 2 times smaller than an integer.
int data type: The int data type is a 32-bit signed two's complement integer. Its value-range lies
between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive).
Programming in JAVA
Double Data Type: The double data type is a double-precision 64-bit IEEE 754 floating-point. Its
value range is unlimited. The double data type is generally used for decimal values just like float.
Figure 4:JDK
It contains all the related sets of libraries and files to build and compile the java program.Without
JDK we cant build any java program. The following are the basic tools that become the foundation
of the Java Development Kit.
Javac: Javac is the compiler for the Java programming language.It is used to compile the .java file.It
creates a class file that can be run by using the java command.
Example: c:javaTestFile.class
Javadoc:JavaDoc is an API documentation generator for the Java language, which generates
documentation in HTML format from Java source code.
Appletviewer:Appletviewer runs and debugs applets without a web browser, it is a standalone
command-line program to run Java applets.
Jar:The jar is (manage Java archive) a package file format that contains class, text, images, and
sound files for a Java application or applet gathered into a single compressed file.
Working of JVM
The JVM performs the following operation:
• Loads code
• Verifies code
• Executes code
• Provides runtime environment
JVM Architecture
1) Classloader
The class loader is a subsystem used for loading class files. It performs three major functions viz.
Loading, Linking, and Initialization.
2) Method Area
JVM Method Area stores class structures like metadata, the constant runtime pool, and the code for
methods.
Programming in JAVA
3) Heap
All the Objects, their related instance variables, and arrays are stored in the heap. This memory is
common and shared across multiple threads.
4) JVM language Stacks
Java language Stacks store local variables, and it’s partial results. Each thread has its own JVM
stack, created simultaneously as the thread is created.A new frame is created whenever a method is
invoked, and it is deleted when the method invocation process is complete.
5) PC Registers
PC register stores the address of the Java virtual machine instruction which is currently executing.
In Java, each thread has its separate PC register.
6) Native Method Stacks
Native method stacks hold the instruction of native code depending on the native library. It is
written in another language instead of Java.
7) Execution Engine
It is a type of software used to test hardware, software, or complete systems.The test execution
engine never carries any information about the tested product.
8) Native Method interface
The Native Method Interface is a programming framework that Java code which is running in a
JVM to call by libraries and native applications.
9) Native Method Libraries
Native Libraries is a collection of the Native Libraries(C, C++) that are needed by the Execution
Engine.
Working of JRE
The workflow is explained below. ClassLoader(It is also called the Primordial ClassLoader.) It
loads the various classes dynamically in the JVM (Java Virtual Machine), which are essential for
executing the program. After JVM started following three class loader are used:
Bootstrap class loader: A Bootstrap Classloader is a Machine code thatkickstarts the operation
when the JVM calls it. Its job is to load the first pure Java ClassLoader. Bootstrap ClassLoader loads
classes from the location rt.jar.
Extension class loader: The Extension ClassLoader is a child of Bootstrap ClassLoader and loads
the extensions of core java classes from the respective JDK Extension library.
System class loader: An Application ClassLoader is also known as a System ClassLoader. It loads
the Application type classes found in the environment variable CLASSPATH, -classpath, or -cp
command-line option. The Application ClassLoader is a child class of Extension ClassLoader.
Byte code verifier:The bytecode verifier acts as a sort of gatekeeper: it ensures that code passed to
the Java interpreter is in a fit state to be executed and can run without fear of breaking
the Java interpreter. Imported code is not allowed to execute by any means until after it has passed
the verifier's tests.It verifies the byte code during the run time so that the code doesn’t make any
disturbance for the interpreter. The codes are interpreted, only if it passes the tests of the bytecode
verifier that check the formatting and for illegal code.
Interpreter: When the class is loaded and the code gets verified, then it reads the assembly code
line by line and processes the following two functions:It executes the Byte Code. It makes
appropriate calls to the integrated hardware.
Table 3: Difference Between JDK,JRE, and JVM
The full form of JDK is Java The full form of JRE is Java The full form of JVM is Java
Development Kit. Runtime Environment. Virtual Machine.
JDK is a software It is a software bundle that JVM executes Java byte code
development kit to develop provides Java class libraries and provides an environment
Programming in JAVA
applications in Java. with the necessary for executing it.
components to run Java code.
JDK comes with the installer. JRE only containsan JVM bundled in both software
environment to execute JDK and JRE.
source code.
It contains tools for It contains class libraries and Software development tools
developing, debugging, and other supporting files that are not included in JVM.
monitoring java code. JVM requires to execute the
program.
It contains tools for It contains class libraries and Software development tools
developing, debugging, and other supporting files that are not included in JVM.
monitoring java code. JVM requires to execute the
program.
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
Programming in JAVA
2. Wrapper classes are immutable, that is, we cannot change any value after assigning it to a
wrapper
class.
Example :Injava.lang.Integer, java.langis the name of the wrapper library, and Integer is
the wrapper name.
All the numeric wrapper classes provide a method to convert a numeric string into a
primitive value.
Syntax: public static type parseType (String Number)
• parseInt()
• parseFloat()
• parseDouble()
• parseLong()
All the wrapper classes provide a static method toStringto provide the string representation
of the primitive values.
Syntax: public static String toString (type value)
Example: public static String toString (int a)
All numeric wrapper classes have a static method valueOf, which is used to create a new
object initialized to the value represented by the specified string.
Syntax: public static DataTypevalueOf (String s)
Example:
• Integer i = Integer.valueOf (“135”);
• Double d = Double.valueOf (“13.5”);
Character Class
Character is a wrapper around a char.nThe constructor for Character is :
Character(char ch)
• Here, ch specifies the character that will be wrapped by the Character object being created.
• To obtain the char value contained in a Character object, call charValue( ), shown here:
Boolean Class
Boolean is a wrapper around boolean values.It defines these constructors:
Boolean(booleanboolValue)
Boolean(String boolString)
In the first version, boolValue must be either true or false. In the second version, if boolString
contains the string “true” (in uppercase or lowercase), then the new Boolean object will be true.
Otherwise, it will be false.To obtain a boolean value from a Boolean object, use booleanvalue(),
shown here:
booleanbooleanValue( )
It returns the boolean equivalent of the invoking object.
Example, byte to Byte, char to Character, int to Integer, long to Long, float to Float, boolean to
Boolean, double to Double, and short to Short.
//Program for Autoboxing
public class AutoBoxingTest {
public static void main(String args[]) {
intnum = 10; // int primitive
Integer obj = Integer.valueOf(num); // creating a wrapper class object
System.out.println(num + " " + obj);
}
}
Output: 10 10
The automatic conversion of wrapper type into its corresponding primitive type is known as
unboxing.It is the reverse process of autoboxing.
//Program for Unboxing
public class UnboxingTest {
public static void main(String args[]) {
Integer obj = new Integer(10); // Creating Wrapper class object
intnum = obj.intValue(); // Converting the wrapper object to primitive datatype
System.out.println(num + " " + obj);
}
}
Output: 10 10
Programming in JAVA
...
classNestedClass {
...
}}
Inner Class(Non-
Static Nested Class)
Anonymous
Classes
Type Description
Programming in JAVA
class Inner{
void msg(){System.out.println("data is "+data);} //
}
public static void main(String args[]){
TestMemberOuter1 obj=new TestMemberOuter1();
TestMemberOuter1.Inner in=obj.new Inner();
The inner class object is always associated with A static nested class object is not associated
the outer class object. with the outer class object.
Inside the inner class, static members can’t be Inside the static nested class, static members
declared. can be declared.
As the main() method can’t be declared, the As the main() method can be declared, the
regular inner class can’t be invoked directly static nested class can be invoked directly from
from the command prompt. the command prompt.
Both static and non-static members of an outer Only a static member of an outer class can be
class can be accessed directly. accessed directly.
Summary
Java was developed by Sun Microsystems initially to offer solutions for household appliances. But,
finally, it evolved as a fully functional programming language.
Java has many features such as platformindependence, simplicity, object-oriented capability,
portability, and so on that differentiates it from other programming languages and makes it
important.
The structure of a Java program consists of a comment lines’ section, package section, import
statements’ section, interface statements’ section, class definitions’ section, and main method class
section.
All Java keywords have predefined meanings and distinct functions. They must be written in
lowercase letters.
Every variable has a data type associated with it, which indicates the type and the size of values
that can be stored in that variable.
Programming in JAVA
Data types are of two types – primitive and non-primitive data types. Primitive data types are
inbuilt
in any programming language and are used for categorically storing information or data that may
or may not be interchangeable. Non-primitive data types are defined by the user.
In Java, operators such as arithmetic operators, relational operators, logical operators, and
conditional operators are used to perform some predefined operations.
Keywords
boolean: Java boolean keyword is used to declare a variable as a boolean type. It can hold True
andFalse values only.
char: Java char keyword is used to declare a variable that can hold unsigned 16-bit Unicode
characters
class: Java class keyword is used to declare a class.
float: Java float keyword is used to declare a variable that can hold a 32-bit floating-point number.
Object: Object means a real-world entity such as a pen, chair, table, computer, watch, etc.
Initialize: Allocate an initial value to a java program.
Instance Variable: A variable that is relevant to a single instance (an object belonging to a class is
aninstance of that class) of a class.
Primitive Data Types: Special group of data types that represents a single value such as
numbers,characters, or Boolean values.
Wrapper Library: Library of wrappers of all the primitive data types.
OOP: Object-Oriented Programming.
Operators’ Precedence: Order in which the operators are executed during expression evaluation.
Self Assessment
1 _______________ is the mechanism that enables us to combine the information and provide
abstraction.
2 All keywords must be written in _____________ letters.
3 The keyword _______ is used to declare the constants.
4 While comparing primitive variables, the actual values are compared, but while comparing
reference variables, the ___________ are compared.
5 ___________ data types are used to categorically store information or data that may or may
not be interchangeable, and that is built-in.
6 When variables, constants, and operators that are arranged according to the syntax of the
programming language are combined, an _____________ ____________ is formed.
7 Which of the following option leads to the portability and security of Java?
8 Which concept of Java is achieved by combining methods and attribute into a class?
A. Encapsulation
B. Inheritance
C. Polymorphism
D. Abstraction
9 Which is the Logical operator in Java that works with a Single Operand?
A. Logical AND
B. Logical OR
C. Logical Exclusive OR
D. Logical NOT
10 What is the output of a Logical OR (|) operation if one of the inputs/operands is true?
A. false
B. true
C. true or false
D. None of the above
A. long
B. bool
C. double
D. float
A. It can extend exactly one class and implement exactly one interface.
B. It can extend exactly one class and can implement multiple interfaces.
C. It can extend exactly one class or implement exactly one interface.
D. It can implement multiple interfaces regardless of whether it also extends a class.
A. Public
B. Private
C. Protected
Programming in JAVA
6. Arithmetic 7. A 8. A 9. D 10. B
Expression
Review Questions
1. Analyze different features of Java, which has made Java an important programming
language.
2. “Structure of a Java program consists of six sections.” Justify.
3. “Declaration of a variable involves specifying the data type of the variable.” Discuss.
4. “Primitive variables and reference variables are different from each other.” Justify.
5. “In every Java program, different types of data are used.” Elaborate.
6. 11. “Increment and decrement operators are used to increment or decrement values.”
Elaborate.
7. 12. “To run a program in Java, the user can use a command prompt.” Discuss.
8. “Nested classes enhance the readability and maintainability of code”. Comment.
9. “A wrapper class is a class that envelops the value of every primitive data type.” Discuss.
Further Readings
Balagurusamy E. Programming with Java_A Primer 3e. New Delhi
Schildt. H. Java 2 The Complete Reference, 5th ed. New York: McGraw-Hill/Osborne.
King, K. N. (2000). Java programming: from the beginning. WW Norton & Co., Inc.
Sanchez, J., & Canton, M. P. (2002). Java programming for engineers. CRC Press
Web Links
www.roseindia.net/java/java-introduction/java-features.shtml
www.tech-faq.com/java-data-types.html - United States
http://java.sun.com/j2se/press/bama.html
http://docstore.mik.ua/orelly/java/javanut/ch03_01.htm
http://www.java-tips.org/java-se-tips/java.lang/what-is-a-final-class.html
https://www.javatpoint.com/java-basics
https://www.geeksforgeeks.org/java-programming-basics/
Harjinder Kaur, Lovely Professional University Unit 02: Arrays and Strings
Objectives
After this unit you will be able to:
• Learn the basic concept of Arrays.
• Understand the different types of Arrays.
• Implement the difference in one-dimensional and multi-dimensional Arrays.
• Learn the basic concept of Strings.
• Understand the ways of creating Strings.
• Use different String Functions.
• Implement the various methods of StringBuffer and StringBuilder Class.
• Differentiate between StringBuffer and StringBuilder Class.
• Understand the different types of access specifiers.
• Implementation of different types of inheritance.
Introduction
Every programming language has some important concepts that make programming more
easyandeffective. Arrays and strings are such important concepts and are available in Java. The
concept ofarrays is used in a program when similar types of values for a large number of data items
Programming in JAVA
are to bestored by the user. Arrays can be used for many applications such as performing
calculations onstatistical data and representing the state of a game.
Example: To store the salaries of all the employees of a company, a declaration of thousands
of variables will be required. Also, the name of every variable must be unique. In such situations,
arrays can be used for simple and easy storage.
An array is an object that contains a fixed number of values of a single data type and an array
objectconsists of several variables. These variables are called array elements. In Java, arrays can
becreated dynamically. The number of variables can be even zero; in such cases, the array is said to
beempty. Once the array is declared, continuous space is allocated in the memory for storing
thesevariables. The elements in the array are accessed by referring to their index value.
We can define a string as a collection of characters. Java handles character strings by using two
finalclasses, namely, Stringclass and StringBufferclass. The Stringclass is used to implement
characterstrings that are immutable and read-only after the creation and initialization of the string.
TheStringBufferclass is used to implement dynamic character strings.
2.1 Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate variables
for each value.It is an object which contains elements of a similar data type.The elements of an array
are stored in a contiguous memory location. 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 the 1st index, and so on.
Declaring an Array
As variables are declared before their usage in the program, so are arrays. To declare an array, define
thevariable type with square bracketsafter the type, followed by the name of the identifier.:
type var-name[];
OR
type[] var-name;
Creating an Array
We create arrays after declaring them. We have to specify the length of the array by using a
constructorthat is called for the creation of a particular object. The new keyword is used for creating
an array,which is followed by the number of elements to be contained in that array (in square
brackets). In anyprogram, the array length is fixed when the array is created. We know that an
array is used to representa group of entities with the same data type in adjacent memory locations
and these data items are givena common name.
Example: students[5];
Here, the name of the array is students, which is of size (index value) 5. Thiscomplete group of
values is known as an array, and the individual values arecalled the array elements.
Initializing an Array
After the creation of an array, we need to initialize it and give a value. This means memory is
allocatedto that array, and this is done with the help of a new operator, or simply at the time of
declaration. If anarray of integers is not initialized in the program, it will start the index numbers
from 0 as it isautomatically initialized to 0 at the time of creation.
Programming in JAVA
Instantiating an Array
When an array is declared, only a reference of an array is created. The general form of new as it
applies to one-dimensional arrays appears as follows:
var-name = new type [size];
Here, type specifies the type of data being allocated, size specifies the number of elements in the
array, and var-name is the name of the array variable that is linked to the array. That is, to use new to
allocate an array, you must specify the type and number of elements to allocate.
Did you know? We cannot resize an array after it has been declared.
Points to Remember:
Array Literal
In a situation, where the size of the array and variables of array are already known, array literals
can be used.
Example:
// Program implementing 1dimensional Array
class arrayExample{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=30;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Output
10
20
30
40
50
Task: Write a program to find the maximum and minimum values in an array.
Programming in JAVA
Example
//Java Program to implement 2-dimensional array
class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{4,5,6},{7,8,9}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}
Output:
123
Syntax:
data_type[1st dimension][2nd dimension][]..[Nth dimension] array_name = new
data_type[size1][size2]….[sizeN];
where:
• data_type: Type of data to be stored in the array. For example: int, char, etc.
• dimension:Thedimension of the array created. For example: 1D, 2D, etc.
• array_name: Name of the array
• size1, size2, …, sizeN: Sizes of the dimensions respectively.
Task: Write a program to multiply two matrices and print the product.
Example: The array int[ ][ ] x = new int[10][20] can store a total of (10*20) = 200 elements.
2.4 Strings
A string is a sequence of characters but it’s not a primitive type.When we create a string in java, it
creates an object of type String. A string is an immutable object which means that it cannot be
changed once it is created.A string is the only class where operator overloading is supported in
java. We can concat two strings using the + operator. For example "a"+"b"="ab".Java provides two
useful classes for String manipulation – StringBuffer and StringBuilder.
Strings in Java are Objects that are backed internally by a char array.Since arrays are
immutable(cannot grow), Strings are immutable as well.Whenever a change to a String is made, an
entirely new String is created.A String variable contains a collection of characters surrounded by
double-quotes.
Syntax:
<String_Type><string_variable> = "<sequence_of_string>";
Example
• String s1 = "abc";
• String s2 = "xyz";
Programming in JAVA
• String s3 = "123";
• String s4 = "A";
will be stored in the String Constant Pool.
When you create string objects using new keyword like below, they will be stored in the heap
memory.
Example:
• String s5 = new String("abc");
• char[] c = {'J', 'A', 'V', 'A'};
• String s6 = new String(c);
• String s7 = new String(new StringBuffer());
One more interesting thing about String Constant Pool is that pool space is allocated to an
object depending upon its content. There will be no two objects in the pool having the same
content.
Example:
String str = "abc";
When we create a String using double quotes, JVM looks in the String pool to find if any other
String is stored with the same value. If found, it just returns the reference to that String object else it
creates a new String object with a given value and stores it in the String pool.
Example:
String str = new String("abc");
char[ ] a = {'a', 'b', 'c'};
String str2 = new String(a);
Example
public class StringDemo {
public static void main(String args[ ]) {
char[ ] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
String helloString = new String(helloArray);
System.out.println( helloString );
}
}
Output
Hello
Programming in JAVA
2.6 String Methods
A String in Java is an object, which contains methods that can perform certain operations on strings
which are as follows:
• String Length.
• String Concatenation.
• Finding a Character in a String.
• To convert the case of a String.
• Comparison of Strings.
• contains
String Length
The accessor method that you can use with strings is the length() method, which returns the
number of characters contained in the string object.Methods used to obtain information about an
object are known as accessor methods.
Example:
public class Main {
public static void main(String[] args) {
String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println("The length of the txt string is: " + txt.length());
}
}
Output: 26
String Concatenation
• Strings are more commonly concatenated with the + operator
• The + operator can be used between strings to combine them.
Example:
"Hello," + " world" + "!“
results in −"Hello, world!"
public class StringDemo {
public static void main(String args[]) {
String string1 = "saw I was ";
System.out.println("Dot " + string1 + "Tod");
}
}
Output:
Dot saw I was Tod
You can also use the concat() method with string literals for concatenation.
Syntax:
string1.concat(string2);
This returns a new string that is string1 with string2 added to it at the end.
Example:
"My name is ".concat("Zara");
Example:
public class Main {
public static void main(String[] args) {
String txt = "Please locate where 'locate' occurs!";
System.out.println(txt.indexOf("locate"));
}
}
Output: 7 //Java counts positions from zero. 0 is the first position in a string, 1 is the second, 2 is
the third .
Example:
String txt = "Hello World";
System.out.println(txt.toUpperCase()); // Outputs "HELLO WORLD"
System.out.println(txt.toLowerCase()); // Outputs "hello world"
Comparison of Strings
String class provides equals() and equalsIgnoreCase()methods to compare two strings. These
methods compare the value of a string to check if two strings are equal or not. It returns true if two
strings are equal and false if not.
Example
public class StringEqualExample
{
public static void main(String[] args)
{ //creating two string object
String s1 = "abc";
String s2 = "abc";
String s3 = "def";
String s4 = "ABC";
System.out.println(s1.equals(s2));//true
System.out.println(s2.equals(s3));//false
System.out.println(s1.equals(s4));//false;
System.out.println(s1.equalsIgnoreCase(s4));//true } }
String class implements Comparable interface, which provides compareTo() and
compareToIgnoreCase() methods and it compares two strings lexicographically.Both strings are
converted into Unicode values for comparison and return an integer value that can be greater than,
Programming in JAVA
less than, or equal to zero. If strings are equal then it returns zero or else it returns either greater or
less than zero.
Example
public class StringCompareToExample {
public static void main(String[] args)
{
String a1 = "abc";
String a2 = "abc";
String a3 = "def";
String a4 = "ABC";
System.out.println(a1.compareTo(a2));//0
System.out.println(a2.compareTo(a3));//less than 0
System.out.println(a1.compareTo(a4));//greater than 0
System.out.println(a1.compareToIgnoreCase(a4));//0
}}
Contains
Java String contains() methods that check if the string contains a specified sequence of characters or
not.This method returns true if the string contains a specified sequence of characters, else returns
false.
Example
public class StringContainsExample
{
public static void main(String[] args)
{
String s = "Hello World"; System.out.println(s.contains("W"));//true
System.out.println(s.contains("X"));//false
}}
Programming in JAVA
• It contains some particular sequence of characters, but the length and content of the
sequence can be changed through certain method calls.
• They are safe for use by multiple threads.
• Every string buffer has a capacity.
Table 1: StringBuffer Constructors
Constructor Description
Method Description
insert(int offset, String s) It is used to insert the specified string with this
string at the specified position.
replace(int startIndex, int endIndex, String str) is used to replace the string from specified
startIndex and endIndex.
delete(int startIndex, int endIndex) is used to delete the string from specified
startIndex and endIndex.
substring(int beginIndex, int endIndex) It is used to return the substring from the
specified beginIndex and endIndex.
Example
//Program to implement StringBufferappend() method
class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
Example
// Program to implement StringBufferinsert() method
class StringBufferExample2{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
Example
// Program to implement StringBufferreplace() method
class StringBufferExample3{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb); //prints HJavalo
}
}
Example
// Program to implement StringBufferdelete() method
class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
Programming in JAVA
System.out.println(sb);//prints Hlo
}
}
Example
// Program to implement StringBufferreverse()method
class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb); //prints olleH
}
}
Example
// Program to implement StringBuffercapacity() method
class StringBufferExample6{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity()); //default 16
sb.append("Hello");
System.out.println(sb.capacity()); //now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity()); //now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}
Example
// Program to implement StringBufferensureCapacity() method
class StringBufferExample7{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity()); //now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity()); //now (16*2)+2=34 i.e (oldcapacity*2)+2
sb.ensureCapacity(10); //now no change
System.out.println(sb.capacity()); //now 34
sb.ensureCapacity(50); //now (34*2)+2
System.out.println(sb.capacity()); //now 70
}
Constructor Description
StringBuilder Methods
The following are the various methods used by StringBuilder class:
Append()
public class StringBuilderExample
{
public static void main(String[] args)
{
StringBuilder sb = new StringBuilder("Hello "); sb.append("World");// now original string is
changed
System.out.println(sb);// prints Hello World
}
}
Insert()
StringBuilder sb = new StringBuilder("HellWorld");
Programming in JAVA
sb.insert(4, "o ");
System.out.println(sb); // prints Hello World
Capacity()
StringBuilder sb=new StringBuilder();
System.out.println(sb.capacity()); // default value 16
sb.append("Java");
System.out.println(sb.capacity()); // still 16
sb.append("Hello StringBuilder Class!");
System.out.println(sb.capacity()); // (16*2)+2
Reverse()
StringBuilder sb = new StringBuilder("lived");
sb.reverse();
System.out.println(sb);// prints devil
Table 4: StringBuffer v/s StringBuilder
StringBuffer StringBuilder
Operates slower due to thread safety feature Better performance compared to StringBuffer
Has some extra methods – substring, length, Not needed because these methods are present
capacity, etc. in String too.
StringBuffer is less efficient than StringBuilder. StringBuilder is more efficient than StringBuffer.
Outside
package
Access Within Within Outside
by
Modifier class package package
subclass
only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Example
//Program for the implementation of Private Access Specifier
class A{
private int data=40;
private void msg()
{
System.out.println("Hello java");
}
}
public class Simple{
public static void main(String args[])
{
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
In this example, we have created two classes A and Simple. A class contains private data
members and private methods. We are accessing these private members from outside the class,
so there is a compile-time error.
Example
//Program for the implementation Default Access Specifier
package pack;
class A{
void msg(){System.out.println("Hello");
Programming in JAVA
}
In the example, the scope of class A and its method msg() is the default so it cannot be accessed
from outside the package.
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
//Compile Time Error
obj.msg();
//Compile Time Error
}
}
In this example, we have created two packages pack and a mypack. We are accessing the A
class from outside its package, since the A class is not public, so it cannot be accessed from
outside the package.
Example
//Program for the implementation protected Access Specifier
package pack;
public class A{
protected void msg()
{
System.out.println("Hello");} }
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output: hello
In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this
package is declared as protected, so it can be accessed from outside the class only through
inheritance.
Example
//Program for the implementation of public Access Specifier
package pack;
public class A{
public void msg()
2.11 Inheritance
Inheritance is an important pillar of OOP(Object-Oriented Programming). It is the mechanism in
java by which one class is allowed to inherit the features(fields and methods) of another class. The
idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent
class. Moreover, you can add new methods and fields to your current class also.Inheritance
represents the IS-A relationship which is also known as a parent-child relationship.
Syntax:
class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates that you are making a new class that derives from an existing class.
The meaning of "extends" is to increase the functionality
Important Terms
Class: A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created.
Sub Class/Child Class: A subclass is a class that inherits the other class. It is also called a derived
class, extended class, or child class.
Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is
also called a base class or a parent class.
Reusability: As the name specifies, reusability is a mechanism that facilitates you to reuse the fields
and methods of the existing class when you create a new class. You can use the same fields and
methods already defined in the previous class.
Class
Reusability
Programming in JAVA
Figure 8: Terms of Inheritance
Types of inheritance
The following figure shows the various types of inheritance available in java.
Inheritance is one of the object-oriented concepts. It is a process, where one object inherits the
properties of another. Similarly, class inheritance means that a class derives a set of properties and
methods of a parent class or base class. To inherit a base class to its subclass, a keyword extends is
used in the subclass definition.
Single Inheritance
When a subclass is derived directly from its parent class or superclass, it is known as
simpleinheritance. In simple inheritance, there is only a subclass and its superclass. It is also
referred to assingle inheritance or one-level inheritance.
Task: Write a simple inheritance program to show one subclass manager and its superclass
employee.
Multilevel Inheritance
Multi-level inheritance was introduced to enhance the concept of inheritance. When a subclass
isderived from another subclass or derived class, it is known as the multi-level inheritance. In
multi-levelinheritance, the subclass is the child class for its superclass and this superclass is the
subclass foranother superclass. Multi-level inheritance can go up to any number of levels.
Example
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark()
{System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep()
{System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[])
{
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Programming in JAVA
As you can see in the example given below, BabyDog class inherits the Dog class which again
inherits the Animal class, so there is a multilevel inheritance.
weeping...
barking...
eating...
Hierarchal Inheritance
In Hierarchical Inheritance, the multiple child classes inherit the single class, or the single class is
inherited by multiple child classes.A structure having one parentand more child class. Child classes
must be connectedwith only Parent classes.
Multiple Inheritance
When the child class extends from more than one superclass, it is known as multiple
inheritance.However, Java does not support multiple inheritance.To achieve multiple inheritance in
Java, we must use the interface.
Example
interface AnimalEat {
void eat();
}
interface AnimalTravel {
void travel();
Hybrid Inheritance
Hybrid Inheritance is a combination of both Single Inheritance and Multiple Inheritance. Since
java doesn’t support multiple inheritances with classes, hybrid inheritance is also not possible with
classes. In java, we can achieve hybrid inheritance only through Interfaces.
Programming in JAVA
Default superclass.
Inheriting Constructors.
Lab Exercise
1. Write a program to print the sum of two matrices.
2. Write a program to swap the values of two arrays, and print the output.
Summary
In a Java program, the length of an array is fixed and it starts with zero (0).
An array can be created with or without using the newoperator.
Initialization of an array can be done at the time of array declaration, or after the
arraycreation.
Array length specifies the number of array elements in an array.
One-dimensional arrays are defined as a variables’ list comprising the data of the same
type.
Generally, two-dimensional or 2D arrays are referred to as one-dimensional arrays’ lists.
2D arrays are represented in a row-column form
A string is a sequence of characters that is created using the String class.
The length of a string refers to the number of characters in a string.
An array that contains strings is a string array.
The string class consists of some methods for creating string objects. These methods are
called Stringmethods.
The StringBufferclass is a peer class of String, which is used for strings’ alteration.
To inherit a base class to its subclass, a keyword extendsis used in the subclass definition.
We can change the access level of fields, constructors, methods, and classes by applying
the access modifier to them
Keywords
StringBuilder():Creates an empty string builder with a default capacity of 16 (16 empty elements).
Access Specifier: Controls the access to the names that follow it, up to the next access specifier or
theend of the class declaration.
Self Assessment
1. Which of the following methods is used to create object a’s string representation?
A. a.toString( )
B. StringTokenizer.countTokens( )
C. str1.append (str2)
D. str2 = str1.replace(‘a’, ‘b’);
2. Which of these methods of String class can be used to test strings for equality?
A. isequal()
B. isequals()
C. equal()
D. equals()
A. I
B. like
C. Java
D. IlikeJava
Programming in JAVA
public static void main(String args[])
{
String obj = "I LIKE JAVA";
System.out.println(obj.charAt(3));
}
}
A. I
B. L
C. K
D. E
5. Which of these operators can be used to concatenate two or more String objects?
A. +
B. +=
C. &
D. ||
6. Which of this methods of class String is used to obtain a length of String object?
A. get()
B. Sizeof()
C. lengthof()
D. length()
A. java.util
B. java.lang
C. ArrayList
D. None of the mentioned
8. What is the value returned by unction compareTo() if the invoking string is less than the
string compared?
A. zero
B. a value less than zero
C. a value greater than zero
D. None of the mentioned
9. Which of these data type value is returned by the equals() method of String class?
A. char
B. int
C. boolean
D. All of the mentioned
A. objects
B. object references
C. primitive data type
D. None of the above
A. create
B. dynamic
C. ArrayList
D. New
13. To declare a one-dimensional array, you will use this general form
14. In Java, each array object has a final field named . . . . that stores the size of the array.
A. width
B. size
C. length
D. distance
A. -1
B. 0
C. 1
D. Any integer
6. D 7. B 8. B 9. C 10. A
Programming in JAVA
Review Questions
1. “In an array, the memory is allocated for the same data type sequentially and is given a
common name.” Justify.
2. “An array can also be created without using the new operator as Java supports dynamic
array allocation.” Justify with an example.
3. “After the creation of an array, it should be initialized and given a value.” Discuss.
4. “Various string methods are used for different tasks of string manipulation.” Discuss
those methods with examples.
5. “The StringBufferclass consists of some methods that can be used for the manipulation of
the objects of that class.” Elaborate.
6. With an example explain the various access specifiers.
7. Why do we need to use inheritance? Explain the concept of superclass and subclass?
Further Readings
Balagurusamy E. Programming with Java 3e Primer. New Delhi: Tata McGrawPublishers.
Schildt H. Java A Beginner’s Guide, 3rd ed. New York: Mc-Graw Hill.
Arnold, K., Gosling, J., & Holmes, D. (2005). The Java programming language. Addison
WesleyProfessional.
Haggar, P. (2000). Practical Java: programming language guide. Addison-Wesley Professional.
Web Links
http://www.javabeginner.com/learn-java/java-string-comparison
http://www.leepoint.net/notesjava/data/strings/55stringTokenizer/10stringtokenizer.ht
ml
http://admashmc.com/main/images/Lec_Notes/javaarray.pdf
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
https://www.w3schools.com/java/java_arrays.asp
https://www.baeldung.com/java-arrays-guide
Objectives
• Learn the basic concept of ArrayList Class, listiterator
• Understand the different constructors and basic operations of ArrayList Class
• Analyze the different methods of the listiterator.
• Learn the basic concept of LinkedList class.
• Understand the different constructors of the LinkedList class.
• Analyze the basic methods of the LinkedList class.
• Know the concept of TreeSet class, its constructors, and methods.
• Explore the concept of PriorityQueueclass and its various methods
Introduction
An ArrayList in Java represents a resizable list of objects. We can add, remove, find, sort, and
replace elements in this list. It is part of the collections framework. It extends AbstractList which
implements the List interface. The List extends Collection and Iterable interfaces in hierarchical
order.ArrayList’s give great performance on get() and set() methods, but do not perform well on
add() and remove() methods when compared to a LinkedList.
Features of ArrayList
ArrayList inherits AbstractList class and implements the List interface.
ArrayList is initialized by the size. Elements can be randomly accessed using index
positions. Index starts with '0'.
In ArrayList, the size is increased automatically if the collection grows or shrinks if
the objects are removed from the collection.
ArrayListcan not be used for primitive types, like int, char, etc. We need a wrapper
class for such cases.
ArrayList in Java can be seen as a vector in C++.
ArrayList is not Synchronized. Its equivalent synchronized class in Java is Vector.
Creation of ArrayList
importjava.util.ArrayList;
ArrayList<String> cars = new ArrayList<String>();
Points to Remember
• ArrayList class can contain duplicate elements.
• ArrayList class maintains insertion order.
• ArrayList class is non-synchronized.
• ArrayList allows random access because the array works onan index basis.
• In ArrayList, manipulation is a little bit slower because a lot of shifting needs to occur if
any element is removed from the array list.
Constructor Description
1. Adding Elements: Here we are discussing about add() method of Java.util.ArrayList class.
This method is used for adding an element to the ArrayList.
add(Object) : This method adds an object to the arraylist.
add(int index, Object) : It adds the object to the array list at the given index.
Example
// Program to add elements in an ArrayList
importjava.util.ArrayList;
public class ArrList {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Maruti");
cars.add("Ford");
cars.add("Mahindra");
cars.add("Mazda");
System.out.println(cars);
}}
Output
PS C:\Users\ OneDrive\Documents\cap615>javac ArrList.java
PS C:\Users\ OneDrive\Documents\cap615> java ArrList
[Maruti, Ford, Mahindra, Mazda]
2. Changing Elements :We can use the setmethod to change an element in ArrayList. We
provide the index and new element, this method then updates the element present at
the given index with the new given element.
importjava.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
cars.set(0, "Opel");
System.out.println(cars);
} }
Output:
PS C:\Users\ OneDrive\Documents\cap615>javac ChList.java
PS C:\Users\ OneDrive\Documents\cap615> java ChList
[Opel, BMW, Ford, Mazda]
3. Removing Elements :We use remove() method to remove elements from an ArrayList,
Same as add() method, this method also has few variations.
remove(Object): This method removes an object from the arraylist.
remove(int index): It removes the object from the array list at the given index.
Example
//Program to implement remove() method
importjava.util.ArrayList;
public class ReList {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Maruti");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
System.out.println("Before Removal\n "+ cars);
cars.remove(0);
System.out.println("After Removal\n"+ cars);
} }
Output :
PS C:\Users\OneDrive\Documents\cap615>javac ReList.java
PS C:\Users\OneDrive\Documents\cap615> java ReList
Before Removal
[Maruti, BMW, Ford, Mazda]
After Removal
[BMW, Ford, Mazda]
4. Access an Item: ArrayListget(int index) method is used for fetching an element from the
list. We need to specify the index while calling the get method and it returns the value
present at the specified index.Inthe below example we are getting a few elements of an
ArrayList by using the get method.
Example
// Implementation of get() method
importjava.util.ArrayList;
public class AccList {
public static void main(String[] args) {
ArrayList<String> items = new ArrayList<String>();
items.add("PEN");
items.add("ERASER");
items.add("FEVICOL");
items.add("PENCIL");
System.out.println(items);
System.out.println(items.get(0));
} }
Output :
PS C:\Users\ OneDrive\Documents\cap615>javac AccList.java
PS C:\Users\ OneDrive\Documents\cap615> java AccList
[PEN, ERASER, FEVICOL, PENCIL]
PEN
5. ArrayList Size: By using the size() method of the ArrayList class we can easily determine
the size of the ArrayList. This method returns the number of elements of ArrayList.
Example:
//Implementation of size() method
importjava.util.ArrayList;
public class SizeList {
public static void main(String[] args) {
ArrayList<String> items = new ArrayList<String>();
items.add("PEN");
items.add("ERASER");
items.add("FEVICOL");
items.add("PENCIL");
System.out.println(items);
System.out.println(items.get(0));
} }
Output
PS C:\Users\ OneDrive\Documents\cap615>javac SizeList.java
PS C:\Users\ OneDrive\Documents\cap615> java SizeList
[PEN, ERASER, FEVICOL, PENCIL]
4
6. Loop Through an ArrayList:
7. Sort an ArrayList: An ArrayList can be sorted by using the sort() method of the Collections
class in Java. It accepts an object of ArrayList as a parameter to be sorted and returns an
ArrayList sorted in the ascending order according to the natural ordering of its elements.
Example
//Implementation of sort() method
importjava.util.*;
importjava.util.ArrayList;
3.4 ListIterator
The ListIterator interface of the Java collections framework provides the functionality to
accesselements of a list.It is bidirectional. This means it allows us to iterate elements of a list in both
directions.It has no current element; its cursor position always lies between the element that would
be returned by a call to the previous() and the element that would be returned by a call to next().
Features of ListIterator
• It is useful for listing implemented classes.
• Available since java 1.2.
• It supports bi-directional traversal. i.e both forward and backward direction.
Position of Cursor
Declaration of ListIterator
public interface ListIterator<E> extends Iterator<E>
Where E represents the generic type i.e any parameter of any type/user-defined object.
Methods of ListIterator
ListIterator is a bi-directional iterator. For this functionality, it has two kinds of methods:
1. Forward direction iteration: Returns true if the iteration has more elements .
hasNext() :The hasNext() method returns true if there exists an element in the list.
next() :The next() method returns the next element of the list.
nextIndex(): This method returns the index of the element that the next() method will return.
Backward direction iterator: With the help of this method we can access the elements in the
backward direction.
Declaration
public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cl
oneable, Serializable.
The following table illustrates the various LinkedList constructors along with their descriptions.
LinkedList constructors
Constructor Description
LinkedList Methods
The following table shows the various methods of LinkedList and their usage.
Methods of LinkedList
Method Description
Example
//Operations Link list
importjava.util.LinkedList;
public class LL {
public static void main(String[] args) {
LinkedList<String> item = new LinkedList<String>();
item.add("Pencil");
item.add("Scale");
item.add("Pen");
item.add("Sweets");
System.out.println(item);
item.addFirst("Mazda");
System.out.println(item);
item.addLast("Mazda");
System.out.println(item);
item.removeFirst();
System.out.println(item);
item.removeLast();
System.out.println(item);
System.out.println(item.getFirst());
System.out.println(item.getLast());
}
}
Output:
PS C:\Users\ OneDrive\Documents\cap615>javac LL.java
PS C:\Users\ OneDrive\Documents\cap615> java LL
[Pencil, Scale, Pen, Sweets]
[Mazda, Pencil, Scale, Pen, Sweets]
[Mazda, Pencil, Scale, Pen, Sweets, Mazda]
[Pencil, Scale, Pen, Sweets, Mazda]
[Pencil, Scale, Pen, Sweets]
Pencil
Sweets
The Java TreeSet class implements the NavigableSet interface, as seen in the figure above. In a
hierarchical sequence, the NavigableSet interface extends the SortedSet, Set, Collection, and Iterable
interfaces.
Important Points
Like HashSet, the Java TreeSet class only has unique elements.
The access and retrieval timings for the Java TreeSet class are quite quick.
Null elements are not allowed in the Java TreeSet class.
The TreeSet class in Java isn't synchronized.
The TreeSet class in Java keeps ascending order.
Creating a TreeSet
To make a tree set, we must first import the java.util.TreeSet package. Here's how to make a TreeSet
in Java after we've imported the package.
Syntax:
TreeSet<Integer> numbers = new TreeSet<>();
We've generated a TreeSet without any arguments in this case.
Syntax: If we want to make an empty TreeSet named TS with external sorting phenomena, we can
do so as follows:
TreeSet TS= new TreeSet(Comparator comp);
TreeSet(Collection): This function creates a TreeSet object that contains all of the elements from the
specified collection, with the elements stored in their natural sorting order. In a nutshell, this
function is used whenever a conversion from a Collection object to a TreeSet object is required.
Syntax: If we want to make a TreeSet named TS, we can do it by following these steps:
TreeSet TS = new TreeSet(Collection coll);
TreeSet(SortedSet): This function Object() { [native code] } creates a TreeSet object that contains all
of the elements from the given sortedset, with the elements stored in their default natural sorting
order. In a nutshell, this function converts a SortedSet object into a TreeSet object.
Syntax: If we want to make a TreeSet named TS, we can do it by following these steps:
TreeSet TS = new TreeSet(SortedSetsts);
The iterator() method can be used to access the items of a tree set.
We must import the java.util.Iterator package to use this method.
Remove Elements
Navigation Methods
• first() –This method returns the first element of the set
• last() –This method returns the last element of the set
• pollFirst() –It returns and removes the first element from the set
• pollLast() –It returns and removes the last element from the set
• higher(element) - Returns the lowest element in the set of elements greater than the
supplied element.
• lower(element) - Returns the most significant element among those less than the supplied
element.
• ceiling(element) - Returns the element with the lowest value among those that are bigger
than the supplied element. It returns the element supplied as an argument if the element
passed exists in a tree set.
• floor(element) - Returns the most significant element among those less than the supplied
element. It returns the element supplied as an argument if the element passed exists in a
tree set.
headset(): All the elements of a tree set before the specified element are returned by the headSet()
method.
tailSet(): The tailSet() method retrieves all elements in a tree set that come after the supplied
element, including the specified element.
subset(): subSet of (e1, bv1, e2, bv2) All elements between e1 and e2, including e1, are returned by
the subSet() function.
The bv1 and bv2 arguments are optional. bv1 has a default value of true, while bv2 has a default
value of false.
Example
// Implementation of TreeSet Class
importjava.util.*;
classTSExample{
public static void main(String args[]){
//Creating and adding elements
TreeSet<String> list=new TreeSet<String>();
list.add("Good");
list.add("Great");
list.add("Welcome");
list.add("Happy");
//Traversing elements
Iterator<String> it=list.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
Output:
PS C:\Users\ OneDrive\Documents\cap615>javac TSExample.java
PS C:\Users\ OneDrive\Documents\cap615> java TSExample
Good
Great
Happy
Welcome
Syntax:
public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable
where E denotes the type of elements in the queue. The class implements Serializable, Iterable<E>,
Collection<E>, and Queue<E> interfaces are implemented by this class.
Insertion of elements
• add(): Adds the provided element to the queue via the add() method. If the queue is full,
an exception is thrown.
• offer(): Adds an element to the queue with the given name. It returns false if the queue is
full.
Example
//Accessing of PQ elements
importjava.util.PriorityQueue;
classAccessPq {
public static void main(String[] args) {
// Creating a priority queue
PriorityQueue<Integer>num = new PriorityQueue<>();
num.add(14);
num.add(12);
num.add(11);
System.out.println("PriorityQueue: " + num);
// Using the peek() method
int num1 = num.peek();
System.out.println("Accessed Element: " + num1);
}
}
Output:
PS C:\Users\ OneDrive\Documents\cap615\programs>javac AccessPq.java
PS C:\Users\ OneDrive\Documents\cap615\programs> java AccessPq
PriorityQueue: [11, 14, 12]
Accessed Element: 11
Removal of elements
We utilize the following methods to remove PriorityQueue elements:
• poll(): This methods returns and removes the head of the queue.
• remove(): It removes the specified element from the queue.
Summary
Because a lot of shifting needs to happen if any element is deleted from the array list,
ArrayList manipulation is a little slower than LinkedList in Java.
Duplicate elements are possible in the Java ArrayList class.
The poll, remove, peek, and element queue retrieval actions all access the element at the
top of the queue.
The get() method returns the element at the given index, whereas the set() method
modifies it.
An object of type LinkedList<T> represents an ordered sequence of items of type T, but
the objects are stored in nodes connected by pointers.
A TreeSet cannot contain random items since the sorted order of the objects it contains
must be determined.
When a TreeSet compares two objects, it does not use the equals() function. Instead, the
compareTo() method is used.
Consumers can use priority queues to consume higher priority messages first, followed by
lower priority ones.
We can't make a PriorityQueue of non-comparable objects.
Keywords
ArrayList: Arraylist is also known as a resizable array, which can be found in the java util package.
add(): Adds the provided element to the queue via the add() method. If the queue is full, an
exception is thrown.
Iterator(): The iterator() method can be used to access the items of a tree set.
poll(): It will give us the latest item and also remove it from the queue.
TreeSet: TreeSet is one of the most notable Java implementations of the SortedSet interface that
stores data in a Tree.
first():If TreeSet is not null, this method will return the first element, otherwise it will throw
NoSuchElementException.
Self Assessment
1. Which of these return type of hasNext() method of an iterator?
A. Integer
B. Double
C. Boolean
D. Collections Object
2. Which of these methods can be used to move to the next element in a collection?
A. next()
B. move()
C. shuffle()
D. hasNext()
A. Setiterator
B. ListIterator
C. Literator
D. None of the mentioned
A. lists
B. sets
C. maps
D. All of the above
A. 0
B. 1
C. -1
D. EMPTY
7. Which of these is a method of ListIterator used to obtain the index of the previous element?
A. previous()
B. previousIndex()
C. back()
D. goBack()
8. The add and remove methods of TreeSet have a time complexity of:
A. O(n)
B. O(n + 1)
C. O(1)
D. O(log n)
A. [1, 3, 5, 8, 9]
B. [3, 4, 1, 8, 9]
C. [9, 8, 4, 3, 1]
D. [1, 3, 4, 8, 9]
A. ArrayList
B. HashSet
C. TreeSet
D. All the answers are true
A. Java TreeSet class access and retrieval times are quite fast.
B. Java TreeSet class is non-synchronized.
C. Java TreeSet class maintains ascending order.
D. All of the above.
A. True
B. False
C. Can’t say
D. May be
14. Which of these classes can generate an array that can increase and decrease in size
automatically?
A. ArrayList()
B. DynamicList()
C. LinkedList()
D. MallocList()
15. Which of this method of the ArrayList class is used to obtain the present size of an object?
A. size()
B. length()
C. index()
D. capacity()
6. D 7. B 8. D 9. B 10. D
Review Questions
1. How do you find the number of elements present in an ArrayList give the appropriate
example?
2. Explain the various constructors and methods used in TreeSet class.
3. What is the use of ListIterator class? Explain the various methods of ListIterator class.
4. With an example explain the basic operations that we can perform using ArrayList.
5. What are priority queues? Explain the various methods that we can perform on Priority
queues?
6. Write a note on the following:
a) offer()
b) poll()
c) peek()
7. Write a program for the implementation of ListIterator class.
Further Readings
Reges, S., &Stepp, M. (2014). Building Java Programs. Pearson.
Sedgewick, R. (2002). Algorithms in Java, Parts 1-4. Addison-Wesley Professional.
Goodrich, M. T., Tamassia, R., &Goldwasser, M. H. (2014). Data structures and algorithms in
Java. John Wiley & Sons.
Arnold, K., Gosling, J., & Holmes, D. (2005). The Java programming language. Addison
Wesley Professional.
Gosling, J., Holmes, D. C., & Arnold, K. (2005). The Java programming language.
Web Links
https://www.freecodecamp.org/news/priority-queue-implementation-in-java/
https://www.geeksforgeeks.org/arraylist-in-java/
https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html
https://www.baeldung.com/java-tree-set
https://beginnersbook.com/2013/12/treeset-class-in-java-with-example/
https://www.programiz.com/java-programming/priorityqueue
https://www.softwaretestinghelp.com/java-priority-queue-tutorial/
Harjinder Kaur, Lovely Professional University Unit 04: More on Collection Framework
Objectives
• Learn the basic concept of Comparable and Comparator interface.
• Differentiate between Comparable and Comparator interface.
• Know the basic concept of priorities class and Lambda Expressions.
• Understand and implement various constructors and methods of properties class and
Lambda Expressions.
Introduction
The Java collections framework is a dependable, high-performance system that allows diverse
collections to work together to handle and manage data in the most effective way possible.
Dynamic arrays, linked lists, hash tables, trees, and other Java collection interfaces and classes are
examples. The framework is structured in such a way that the extension and implementation of
collection classes and interfaces to the implementing class are simple.
Each data collection implements an underlying algorithm, such as a linked list, hash set, or tree set,
that can be inherited by the child class. There are two sorts of components in the collection
framework:
Collection Interfaces: They are abstract data types that are used to represent collections. They
make it possible to manipulate collections regardless of their representation specifics. Because Java
is an object-oriented programming language, it works primarily through a hierarchical framework.
Collection Classes:They give the collection interfaces concrete implementations. Collection classes
are reusable data structures.
Comparable
Comparator
Programming in JAVA
The user-defined class's objects are ordered using the Java Comparable interface.This interface is
part of java.lang package and only has one method, compare To (Object).It only has a single sorting
sequence, which means you can only sort the elements by a single data member. It might be
anything from a rollno to a name to an age.
A comparable object is capable of comparing itself with another object. The class itself must
implements java.lang.Comparable interface to compare its instances.
compareTo(Object o) method
It compares the current object to the supplied object. public int compare To(Object o) compares the
current object to the specified object.
If the current object is greater than the requested object, it returns a positive integer.
If the current object is less than the requested object, the value will be negative.
If the current object is equal to the requested object, the value is zero.
We can categorize the following elements:
Example:
//Implementation of Comparable interface
class Stu implements Comparable<Stu>{
int roll;
String name;
int age;
Stu(int roll,Stringname,int age){
this.roll=roll;
this.name=name;
this.age=age;
}
public int compareTo(Stu s){
if(roll==s.roll)
return 0;
else if(roll>s.roll)
return 1;
else
return -1;
}
}
// Sorting of elements
import java.util.*;
public class SortAsc{
public static void main(String args[]){
ArrayList<Stu>arrl=new ArrayList<Stu>();
arrl.add(new Stu(1,"Seerat",34));
arrl.add(new Stu(13,"Kawar",16));
arrl.add(new Stu(4,"Deepak",33));
Collections.sort(arrl);
for(Stu s:arrl){
System.out.println(s.roll+" "+s.name+" "+s.age);
}
}
}
Output
PS C:\Users\ OneDrive\Documents\cap615\programs>javac SortAsc.java
PS C:\Users\ OneDrive\Documents\cap615\programs> java SortAsc
4 Deepak 33
13 Kawar 16
1 Seerat 34
Example
// Java program to demonstrate working of Comparator interface
import java.io.*;
import java.lang.*;
import java.util.*;
// A class to represent a student.
class Stu {
int roll;
String name;
int age;
Programming in JAVA
// Constructor
public Stu(int roll, String name, int age)
{
this.roll = roll;
this.name = name;
this.age = age;
}
// Used to print student details in main()
public String toString()
{
return this.roll + " " + this.name + " "+ this.age;
}
}
class Sortedage implements Comparator<Stu> {
// Used for sorting in ascending order ofroll number
public int compare(Stu s, Stu s1)
{
return s.age - s1.age;
}
}
// Driver class
class AscSort {
public static void main(String[] args)
{
ArrayList<Stu>arrl = new ArrayList<Stu>();
arrl.add(new Stu(11, "Seerat", 32));
arrl.add(new Stu(13, "Deepak", 50));
arrl.add(new Stu(12, "Shallu", 24));
System.out.println("Before Sorting");
for (int i = 0; i<arrl.size(); i++)
System.out.println(arrl.get(i));
Collections.sort(arrl, new Sortedage());
System.out.println("\nAfter Sorting");
System.out.println("\nAge");
for (int i = 0; i<arrl.size(); i++)
System.out.println(arrl.get(i));
Collections.sort(arrl, new Sortedname());
System.out.println("\nNames");
for (int i = 0; i<arrl.size(); i++)
System.out.println(arrl.get(i));
}
}
Output
PS C:\Users\ OneDrive\Documents\cap615\programs>javac AscSort.java
PS C:\Users\ OneDrive\Documents\cap615\programs> java AscSort
Before Sorting
11 Seerat 32
13 Deepak 50
12 Shallu 24
After Sorting
Age
12 Shallu 24
11 Seerat 32
13 Deepak 50
Names
13 Deepak 50
11 Seerat 32
12 Shallu 24
Comparable Comparator
Programming in JAVA
We can sort the list elements of We can sort the list elements of
Comparable type by Comparator type by the
Collections.sort(List) method. Collections.sort(List,Comparator)met
hod.
Notes: The Properties class, like its parent class (HashTable), saves data using the hash code of
its keys, hence the order in which its components are stored and shown isn't guaranteed.
Constructor Description
Example
// Creation of properties file
user=Good Day
password=Ahead
//Program to read the data from properties file.
import java.util.*;
import java.io.*;
public class ReadP {
public static void main(String[] args)throws Exception{
FileReader reader=new FileReader("db.properties");
Properties p=new Properties();
p.load(reader);
System.out.println(p.getProperty("user"));
System.out.println(p.getProperty("password"));
}
}
Output
PS C:\Users\ OneDrive\Documents\cap615\programs>javac ReadP.java
PS C:\Users\ OneDrive\Documents\cap615\programs> java ReadP
Good Day
Ahead
Notes: For the creation of property files you have to save the file using the .properties
extension.
• Properties class to create the properties file.
Example
//Creation of properties class
import java.util.*;
import java.io.*;
public class CreatP {
public static void main(String[] args)throws Exception{
Properties p=new Properties();
p.setProperty("name","Harseerat");
p.setProperty("email","[email protected]");
p.store(new FileWriter("RR.properties"),"First Properties Example");
}
}
Output
PS C:\Users\ OneDrive\Documents\cap615\programs>javac CreatP.java
PS C:\Users\ OneDrive\Documents\cap615\programs> java CreatP
After this a property file is being created with the name RR.
#First Properties Example
#Mon Nov 22 13:49:37 IST 2021
[email protected]
name=Harseerat
• Properties class to get all the system properties.
Programming in JAVA
Example
// To get all System Properties
import java.util.*;
import java.io.*;
public class GetS {
public static void main(String[] args)throws Exception{
Properties p=System.getProperties();
Set set=p.entrySet();
Iterator itr=set.iterator();
while(itr.hasNext()){
Map.Entry entry=(Map.Entry)itr.next();
System.out.println(entry.getKey()+" = "+entry.getValue());
}
}
}
Output
PS C:\Users\ OneDrive\Documents\cap615\programs>javac GetS.java
PS C:\Users\ OneDrive\Documents\cap615\programs> java GetS
java.runtime.name = Java(TM) SE Runtime Environment
sun.boot.library.path = C:\Program Files\Java\jre1.8.0_181\bin
java.vm.version = 25.181-b13
java.vm.vendor = Oracle Corporation
java.vendor.url = http://java.oracle.com/
path.separator = ;
java.vm.name = Java HotSpot(TM) 64-Bit Server VM
file.encoding.pkg = sun.io
user.country = IN
user.script =
sun.java.launcher = SUN_STANDARD
sun.os.patch.level =
java.vm.specification.name = Java Virtual Machine Specification
user.dir = C:\Users\Harjinder Kaur\OneDrive\Documents\cap615\programs
java.runtime.version = 1.8.0_181-b13
java.awt.graphicsenv = sun.awt.Win32GraphicsEnvironment
java.endorsed.dirs = C:\Program Files\Java\jre1.8.0_181\lib\endorsed
os.arch = amd64
Lambda expressions are similar to methods, except they don't require a name and can be used
directly within a method's body.A single parameter plus an expression make up the most basic
lambda expression:
Syntax
parameter -> expression
Wrap several parameters in parenthesis if you're using more than one.
Example
// Program to implement Lambda Expression
class LExp
{
public static void main(String args[])
{
// Creating an ArrayList with elements
// {1, 2, 3, 4}
ArrayList<Integer>arrL = new ArrayList<Integer>();
arrL.add(1);
arrL.add(2);
arrL.add(3);
arrL.add(4);
// Using lambda expression to print all elements of arrL
arrL.forEach(n ->System.out.println(n));
// Using lambda expression to print Odd elements of arrL
arrL.forEach(n ->{ if (n%2 == 0) System.out.println("even" +n); });
}
}
Output
PS C:\Users\ OneDrive\Documents\cap615\programs>javac LExp.java
PS C:\Users\ OneDrive\Documents\cap615\programs> java LExp
1
2
3
4
even2
even4
Syntax
(parameter1, parameter2) -> expression
Example
// Java program to demonstrate working of lambda expressions with two parameters
public class Lexpt
{
Programming in JAVA
Notes:Lambda expressions are just like functions and they accept parameters just like
functions.
Points to Remember
A lambda expression can have zero, one, or more statements in its body.
Curly brackets are not required when there is only one statement, and the anonymous
function's return type is the same as the body expression's.
When multiple statements are present, they must be enclosed in curly brackets, and the
anonymous function's return type must be the same as the type of the value returned
within the code block, or void if nothing is returned.
Summary
The Properties class can also be used to create new properties in the form of key-value
pairs, with the key and value both being String objects.
Properties class is the subclass of Hashtable.
The Properties class provides methods to get data from the properties file and store data
into the properties file. Moreover, it can be used to get the properties of a system.
The lambda expression should have the same number of parameters as the method, as
well as the same return type.
As a result, a Java lambda expression is a function that can be constructed independently
of any class.
If the lambda expression has to return a value, a return statement should be included in
the code block.
Lambda expressions are similar to methods, except they don't require a name and can be
used directly within a method's body.
Keywords
Properties defaults:A default property list linked with a Properties object is stored in this variable.
Comparator:When a user-defined class does not implement the Comparable interface, the
Comparator interface is used to compare objects of that class.
Comparable:Each class that implements the Comparable interface must organize its objects in a
specific order.
Lambda expressions: A lambda expression is a small piece of code that takes in input and outputs a
value.
Programming in JAVA
compare(Object o1,Object o2): This method is used by the comparator interface to compare two
objects.
equals(Object O): It's used to compare the current object to the one that's been specified.
Self Assessment
1. What is the value of "emu".compareTo("emu")
A. a negative integer
B. 0
C. a positive integer
D. unpredictable
A. Y.compareTo(X) is positive
B. Y.compareTo(X) is negative
C. Y.compareTo(X) is zero
D. Y.compareTo(X) is unknown
A. toCompare
B. compare
C. compareTo
D. compareWith
A. interface
B. class
C. framework and interface
D. framework and class
5. Which of these interfaces declares the core method that all collections will have?
A. set
B. EventListner
C. Comparator
D. Collection
A. toCompare()
B. compare()
C. compareTo()
D. compareWith()
A. Different
B. Same
C. Both
D. None
A. Comparator
B. Comparable
C. Both
D. None
A. String
B. Object
C. void
D. Function
A. Data as code
B. Code as data
C. None of the above
D. All
A. Procedural programming
Programming in JAVA
B. Data programming
C. Functional programming
D. All
15. Which of these is a class that uses String as a key to store the value in an object?
A. Array
B. ArrayList
C. Dictionary
D. Properties
6. B 7. A 8. B 9. D 10. C
Review Questions
1. In Java, how do you utilize comparator and comparable? Give example.
2. Differentiate between comparable and comparator interfaces.
3. With example define the concept of lambda expressions? Explain the different types of
lambda expressions.
4. Write a program to implement lambda expression accepting two parameters.
5. What is the use of properties class? Describe the various constructors used in properties
class.
6. With example elucidate the various methods of properties class.
Further Readings
Subramaniam, V. (2014). Functional programming in Java: harnessing the power of Java 8
Lambda expressions. Pragmatic Bookshelf.
Sharan, K. (2014). Beginning Java 8 Language Features: Lambda Expressions, Inner Classes,
Threads, I/O, Collections, and Streams. Apress.
Warburton, R. (2014). Java 8 Lambdas: Pragmatic Functional Programming. " O'Reilly
Media, Inc.".
Bloch, J. (2008). Effective java. Addison-Wesley Professional.
Murach, J. (2011). Murach's Java Programming (p. 836). Murach.
Web Links
https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html
https://www.baeldung.com/java-8-comparator-comparing
https://java-programming.mooc.fi/part-10/2-interface-comparable
https://howtodoinjava.com/java/collections/java-comparable-interface/
https://www.scientecheasy.com/2020/12/java-properties.html/
https://www.w3schools.com/java/java_lambda.asp
https://www.programiz.com/java-programming/lambda-expression
Objectives
After this unit you will be able to:
• Learn the basic concept of Multithreading.
• Understand the different ways of implementing Multithreading.
• Understand the various stages in the life cycle of a thread.
• Learn the various methods of implementing thread states.
• Understand the concept of thread communication and the Process of Thread
Communication
• Know the difference between wait and sleep.
Introduction
Java programming language has many important and useful concepts. One such concept is the
Thread. A thread can be referred to as a single sequential flow of control within a program or the
unit of execution within a process. A process is normally broken down into tasks and these tasks
are further broken down into threads.
Example: Consider the modern operating system, which allows multiple programs to run at
once. While typing a document in a system, one can simultaneously listen to music and browse the
net. This indicates that the operating system installed in the computer allows multitasking.
Similarly, the execution of several processes in a program can also be done simultaneously. Hot
Java web browser is an example of such an application, which allows the user to browse a Web
page while downloading an image, or playing animations or audio files at the same time.
A thread has a beginning, a sequence of steps for execution, and an end. A thread is not considered
as a program, but it runs within a program. Every program contains at least one thread called a
primary thread. In Java, the main( ) method is an example of a primary thread.
5.1 Threads
Before we talk about multithreading, let’s discuss threads.A thread is a lightweight smallest part of
a process that can run concurrently with the other parts(other threads) of the same process. Threads
are independent because they all have a separate path of execution that’s the reason if an exception
occurs in one thread, it doesn’t affect the execution of other threads.All threads of a process share a
common memory.The process of executing multiple threads simultaneously is known as
multithreading.
A process made up of only one thread is called a single-threaded process. A single-threaded
process performs only one task at a time whereas, a process having more than one thread, called a
multithreaded process, performs different tasks and interacts with other processes at the same time.
Figure 1 is the schematic representation of a single-threaded and a multi-threaded process.
In Java, java.lang.Threadclass creates and controls each thread. A Java program has many threads,
and these threads run either asynchronously or synchronously. Multithreading in Java is a process
of executing two or more threads simultaneously to maximum utilization of the CPU. Java’s
multithreading system is built upon the Thread class, its methods, and its companion
interface, Runnable.Each thread runs parallel to the other.
Multiple threads don't allocate separate memory areas, hence they save memory.It is possible in
multithreaded programming to start a new task even when the current task is not completed. Multithreading is
conceptual programming, where a program is divided into two or more subprograms, which can be
implemented at the same time in parallel. Multithreading is also known as multiplethreads of execution. If the
application performs many different tasks concurrently, then the threads may access shared data variables to
work collaboratively.
Advantages
• The users are not blocked because threads are independent, and we can perform multiple
operations at times.
• As such, the threads are independent, the other threads won't get affected if one thread
meets an exception.
Example :// Code for thread creation by extending the Thread class
ClassMultithreadingDemo extends Thread {
public void run()
{
try {
// Displaying the thread that is running
System.out.println("Thread " + Thread.currentThread().getId()+ " is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}}}
// Main Class
public class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (inti = 0; i< n; i++) {
MultithreadingDemo object
= new MultithreadingDemo();
object.start();
}
}
}
Example: Java code for thread creation by implementing the Runnable Interface
class MultithreadingDemo1 implements Runnable {
public void run()
{
try {
// Displaying the thread that is running
System.out.println("Thread " + Thread.currentThread().getId()+ " is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}}}
// Main Class
class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (inti = 0; i< n; i++) {
Thread object= new Thread(new MultithreadingDemo());
object.start();
}}}
• New
• Runnable
• Blocked
• Waiting
• Timed Waiting
• Terminated
New state
When a new thread is created, it is ina new state. The thread has not yet started to run when a
thread is in this state.When a thread lies in the new state, its code is yet to be run and hasn’t started
to execute.
Runnable State
A thread that is ready to run is moved to a runnable state. In this state, a thread might be running
or it might be ready to run at any instant of time. It is the responsibility of the thread scheduler to
give the thread, time to run.A multi-threaded program allocates a fixed amount of time to each
thread. Every thread runs for a short while and then pauses and relinquishes the CPU to another
thread so that other threads can get a chance to run. When this happens, all such threads that are
ready to run, waiting for the CPU and the currently running thread lies in a runnable state.
Blocked/Waiting state
When a thread is temporarily inactive, then it’s in one of the following states:
Blocked: When a thread is waiting for I/O to complete, it lies in the blocked state. It’s the
responsibility of the thread scheduler to reactivate and schedule a blocked/waiting thread.
A thread in this state cannot continue its execution any further until it is moved to a
runnable state.
Waiting: A thread is in the blocked state when it tries to access a protected section of code
that is currently locked by some other thread. When the protected section is unlocked, the
schedule picks one of the threads which is blocked for that section and moves it to the
runnable state. Whereas, a thread is waiting when it waits for another thread on a
condition. When this condition is fulfilled, the scheduler is notified and the waiting thread
is moved to a runnable state.
Timed Waiting
A thread lies in a timed waiting state when it calls a method with a time-out parameter. A thread
lies in this state until the timeout is completed or until a notification is received.
Example: when a thread calls sleep or a conditional wait, it is moved to a timed waiting state.
Terminated State
A thread terminates because of either of the following reasons:
• Because it exists normally.
• This happens when the code of the thread has entirely executed by the program.
• Because there occurred some unusual erroneous event, like segmentation fault or an
unhandled exception.
Example:If the loop in run( ) method has fifty iterations, then the life of the thread will be fifty
iterations of the loop.
wait() It tells the calling thread to give up the lock and go to sleep until some other thread
enters the same monitor and calls notify().
notify() It wakes up one single thread that is called wait() on the same object. It should be
noted that calling notify() does not give up a lock on a resource.
notifyAll() It wakes up all the threads that are called wait() on the same object.
Inter-thread Communication
Inter-thread communication or co-operation is all about allowing synchronized threads to
communicate with each other.It is the process in which two threads communicate with each other
by using wait (), notify (), and notifyAll () methods.The Thread which is required updation has to
call the wait() method on the required object then immediately the Thread will be entered into a
waiting state.So, The Thread which is performing the updation of an object is responsible to give
notification by calling notify () method.After getting notification the waiting thread will get those
updation.
There are three ways for the threads to communicate with each other.
Firstly, all the threads share the same memory space. If the threads share the same object, thenthese
threads share access to that object's data member and thus communicate with each other.
In a second way, threads communicate by using thread control methods. The second way includes
1) suspend( ): By using this method, a thread can suspend itself and wait till another thread
resumes it.
2) resume( ): By using this method, a thread can wake up another waiting thread through its
resume( ) method and then run concurrently.
3) join( ): By using this method, the caller thread can wait for the completion of the called
thread.
Thirdly, threads communicate by using the following three methods:
1) wait( ): This method tells the calling thread to examine and make the calling thread wait
untilanother calls the same threads to notify( ) or notifyAll( ) or a timeout occurs.
2) notify( ): This method wakes only the first waiting thread on the same object.
3) notifyAll( ): This method wakes up all the threads that have been called by wait( ) on the
sameobject.
}
}
public class WaitNotify
{
public static void main(String[] args)throws InterruptedException
{
passenger p = new passenger();
p.start();
synchronized (p)
{
System.out.println("passenger is waiting for the bus ");
p.wait();
System.out.println("passenger got notification");
}
System.out.println("after "+p.total+" time");
}
}
Caution: The three methods wait( ), notify( ), and notifyAll( ) must only be called from the
synchronized methods.
}
public class InterThread //class InterThread is declared
{
public static void main(String[ ] args)
{
Sort s=new Sort( );
new Construct(s);
new User(s);
}
}
Output:
C:\nisha>javac InterThread.java
C:\nisha>java InterThread
Produce: 1
consume: 1
In this program, two threads Construct and User share the synchronizedmethods of the class Sort.
At the time of program execution, the put( ) method of theConstructclass is invoked, which
increments the variable numby1. Afterproducing1 by the Construct, the method get( ) is invoked
by the User class,which retrieves the produced number and returns it to the output. Thus, the
usercannot retrieve the number without producing it.
wait() sleep()
wait() method releases the lock. sleep() method doesn't release the lock.
should be notified by notify() or notifyAll() after the specified amount of time, sleep is
methods. completed.
Lab Exercise
1. Write a program to create multiple threads.
2. Write a program that checks whether a given number is a prime using both the Thread class and
Runnable Interface.
Summary
A thread can be referred to as a sequential flow of control within a program or the unit of
execution within a process.
The Thread class is defined in the pre-defined package java.lang, which needs to be
imported into the program code, so that our classes are aware of their definition.
Keywords
Thread: A thread is a lightweight sub-process, the smallest unit of processing.
Multithreading: Multithreading refers to a process of executing two or more threads
simultaneously for maximum utilization of the CPU.
run( ): Method used to implement the code that needs to be executed by our thread.
start( ): Method that causes the thread to move into the Runnable state.
suspend( ): By using this method, a thread can suspend itself and wait till another thread resumes it.
resume( ): By using this method, a thread can wake up another waiting thread through its resume( )
method and then run concurrently.
join( ): By using this method, the caller thread can wait for the completion of the called thread.
wait( ): This method tells the calling thread to examine and make the calling thread wait until
another calls the same threads to notify( ) or notifyAll( ) or a timeout occurs.
notify( ): This method wakes only the first waiting thread on the same object.
notifyAll( ): This method wakes up all the threads that have been called by wait( ) on the same
object.
Self Assessment
1. What does sleep in Thread class do?
A. Causes the thread, which sleep is invoked on, to sleep (temporarily cease execution) for the
specified number of milliseconds
B. Causes the currently executing thread to sleep (temporarily cease execution) for the
specified number of milliseconds
C. Causes the main( ) thread to sleep for the specified number of milliseconds
D. Causes the currently executing thread to wait (temporarily cease execution) for
2. Which state does the thread enter, when a thread class is created at any instance?
A. New thread
B. Runnable
C. Not Runnable
D. Dead
A. By multithreading CPU idle time is minimized, and we can make maximum use of it
B. By multitasking CPU idle time is minimized, and we can make maximum use of it
C. Two threads in Java can have the same priority
D. A thread can exist only in two states, running and blocked
A. Start ()
B. Run ()
C. Execute ()
D. Launch ()
A. implementing Thread
B. extending Thread
C. extending Runnable
D. All of the above
A. Multiprocessing
B. Multipurpose
C. Multithreading
D. All of the above
9. Which of these methods is used to find out that a thread is still running or not?
A. run()
B. Alive()
C. isAlive()
D. checkout()
A. Runnable
B. Connections
C. Set
D. MapConnections
A. String
B. System
C. Thread
D. Runnable
A. Integer
B. Float
C. double
D. long
13. The wait(), notify(), and notifyAll() methods are present in which class or interface?
A. Object class
B. Thread class
C. Runnable class
D. None of these
14. The wait(), notify(), and notifyAll() methods can be called from?
15. When a thread calls the wait() method, which of the following options is valid?
A. Immediately the thread will enter into the waiting state without releasing any lock.
B. A thread will release the lock of that object but may not immediately.
C. A thread will release all acquired locks and immediately enter into the waiting state.
D. A thread will immediately release the lock of that particular object and enter into the waiting
state.
6. B 7. B 8. C 9. C 10. A
Review Questions
1. “A thread that is created, must be bound to the run( ) method of an object”. Comment.
2. “When a thread is alive, it indicates it is in one of its several states”. Justify.
3. “The second way that is used to create a thread is, by creating a new class that extends
Thread, andthen creating an instance of that class”. Elaborate.
4. “Understanding the life cycle of a thread is very important, especially at the time of
developingcodes using threads”. Elaborate.
5. What are the different states of a thread, or what is thread lifecycle?
6. Withanexample explain the different methods of creating a User thread?
7. “There are three ways for the threads to communicate with each other”. Elaborate.
Further Readings
E Balagurusamy, Programming with Java_A Primer 3e, New Delhi
Herbert Schildt, The Complete Reference, 7th edition, Tata McGraw Hill
Horton, I. (2005). Ivor Horton's Beginning Java 2. John Wiley & Sons.
Lewis, B., & Berg, D. J. (2000). Multithreaded programming with Java technology. Prentice Hall
Professional.
Arnold, K., Gosling, J., & Holmes, D. (2005). The Java programming language. Addison
Wesley Professional.
Web Links
https://www.javatpoint.com/multithreading-in-java
https://www.geeksforgeeks.org/multithreading-in-java/
https://www.mygreatlearning.com/blog/multithreading-in-java/
https://www.scientecheasy.com/2020/08/inter-thread-communication-in-java.html/
https://dotnettutorials.net/lesson/inter-thread-communication-in-java/
Objectives
After this unit you will be able to:
• Learn the basic concept of suspending and resuming a thread.
• Implement suspend() and resume().
• Know the basic concept of Deadlock.
• Understand the various methods of stopping a thread.
• Implementation of a deadlock situation and its solution.
Introduction
In Java, a simple program may contain many threads. Each thread may perform different
tasks.Sometimes, it becomes necessary to suspend the execution of a thread for a while. This can
bedone by using suspend( ) method of the class Thread. The time needs to be specified till
thethread remains suspended and then we can restart the thread by using the resume( ) method of
the classThread. If a thread is suspended, it can be restarted. But if a thread is stopped by using the
stop( )method,it cannot be restarted again.These methods were used in the earlier systems of Java,
but they are not used in the latest versionbecause sometimes suspend( ) and stop( ) methods of the
class Thread cause system failure. Therefore,therun( ) method is used in the latest version of Java
instead of the above-mentioned methods. So, the run() method checks when a thread should be
suspended, resumed, or stopped.
As we have seen in the life cycle diagram, there are several inbuilt methods provided to us by the
thread class to change the state of a thread. One of them is the suspend() method.It is used to
change the thread from a Running state to a Suspended/Blocked state.
Example
//Program for the implementation of suspending method
public class Testing extends Thread
{
public void run()
{
try
{
for(inti=0;i<7;i++)
{
Thread.sleep(500);
System.out.println(this.getName() + ": " + i);
}
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
public static void main(String args[])
{
Testing srd1=new Testing();
Testing srd2=new Testing();
srd1.setName("First");
srd2.setName("Second");
srd1.start();
srd2.start();
try
{
Thread.sleep(1000);
srd1.suspend();
System.out.println("Suspending thread First");
Thread.sleep(1000);
srd1.resume();
System.out.println("Resuming thread First");
Thread.sleep(1000);
srd2.suspend();
System.out.println("Suspending thread Second");
Thread.sleep(1000);
srd2.resume();
System.out.println("Resuming thread Second");
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
Output :
PS C:\Users\OneDrive\Documents\cap615\programs>javac Testing.java
PS C:\Users\OneDrive\Documents\cap615\programs> java Testing
Second: 0
First: 0
Suspending thread First
Second: 1
Second: 2
Resuming thread First
First: 1
Second: 3
First: 2
Second: 4
Suspending thread Second
First: 3
First: 4
Resuming thread Second
Second: 5
First: 5
Second: 6
First: 6
Example
// Implementation of resume() method
public class Resume implements Runnable {
Thread-1 2
Starting Thread-0...
Thread-0 0
Thread-0 1
Thread-0 2
Caution: Do not create too many threads, as it may consume more CPU time than
executing theprogram.
6.3 Deadlock
Deadlock describes a situation where two or more threads are blocked forever, waiting for each
other. A Java multithreaded program may suffer from the deadlock condition because
the synchronized keyword causes the executing thread to block while waiting for the lock, or
monitor, associated with the specified object. thesynchronized keyword is used to make the class or
method thread-safe which means only one thread can have a lock of synchronized method and use
it, other threads have to wait till the lock releases and anyone of them acquire that lock. It is
important to use if our program is running in a multi-threaded environment where two or more
threads execute simultaneously. But sometimes it also causes a problem which is called Deadlock.
Example: One thread enters the monitor on object A, and another thread enters the monitoron
object B. If the thread in A tries to call any synchronized method on B, itbecomes blocked. But, if the
thread in B tries to access any synchronized methodon A, then the thread waits for a while since it
should release its lock on Bso that the first thread can complete.
Deadlock is considered as an error, which is difficult to debug because of two reasons:
1. It occurs rarely when two threads time-slice in the correct way.
2. It may have more than two synchronized objects and two threads.
Example
//Program to implement deadlock.
public class DeadLock
{
public static void main(String[] args)
{
final String rs1 = "Group1";
final String rs2 = "Group2";
synchronized (rs2)
{
System.out.println("Thread 2: locked resource 1");
}
}
}
};
t1.start();
t2.start();
}
}
Output:
PS C:\Users\ OneDrive\Documents\cap615\programs>javac DeadLock.java
PS C:\Users\ OneDrive\Documents\cap615\programs> java DeadLock
Thread 1: locked resource 1
Thread 1: locked resource 2
Thread 2: locked resource 2
Thread 2: locked resource 1
Deadlock Solution
Avoid Unnecessary Locks: We can have a lock for only those members who are required. Having a
lock unnecessarily can lead to a deadlock.
Avoid Nested Locks:A deadlock mainly happens when we give locks to multiple threads. Avoid
giving a lock to multiple threads if we already have given to one.
Using Thread.join() Method:A deadlock condition appears when one thread is waiting for another
to finish. If this condition occurs we can use Thread.join() with the maximum time the execution
will take.
Use Lock Ordering:Always assign a numeric value to each lock. Before acquiring the lock with a
higher numeric value, acquire the locks with a lower numeric value.
Lock Time-out:We can also specify the time for a thread to acquire a lock. If a thread does not
acquire a lock, the thread must wait for a specific time before retrying to acquire a lock.
Just changing the order of the locks prevent the program from going into a deadlock situation
Task: Write a program that displays the name of the thread that executes the main method.
Example
// Implementation of stopping a thread using a boolean flag
classMyThread implements Runnable {
// to stop the thread
privatebooleanexit;
private String name;
Thread t;
MyThread(String threadname)
{ name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
exit = false;
t.start(); // Starting the thread
}
// execution of thread starts from run() method
public void run()
{
inti = 0;
while (!exit) {
System.out.println(name + ": " + i);
i++;
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
System.out.println("Caught:" + e);
}
}
System.out.println(name + " Stopped.");
}
// for stopping the thread
public void stop()
{
exit = true;
}
}
// Main class
public class MainB {
public static void main(String args[])
{
// creating two objects t1 & t2 of MyThread
MyThread t1 = new MyThread("First thread");
MyThread t2 = new MyThread("Second thread");
try {
Thread.sleep(500);
t1.stop(); // stopping thread t1
t2.stop(); // stopping thread t2
Thread.sleep(500);
}
catch (InterruptedException e) {
System.out.println("Caught:" + e);
}
System.out.println("Exiting the main Thread");
}
}
Output:
PS C:\Users\ OneDrive\Documents\cap615>javac MainB.java
PS C:\Users\ OneDrive\Documents\cap615> java MainB
New thread: Thread[First thread,5,main]
New thread: Thread[Second thread,5,main]
First thread: 0
Second thread: 0
Second thread: 1
First thread: 1
First thread: 2
Second thread: 2
Second thread: 3
First thread: 3
First thread: 4
Second thread: 4
First thread Stopped.
Second thread Stopped.
Exiting the main Thread
Example:
// Implementation of stopping a threadusingThread.interrupt() method
classMyThread implements Runnable {
Thread t;
MyThread()
{
t = new Thread(this);
System.out.println("New thread: " + t);
t.start(); // Starting the thread
}
// execution of thread starts from run() method
public void run()
{
while (!Thread.interrupted()) {
System.out.println("Thread is running");
}
System.out.println("Thread has stopped.");
}}
// Main class
public class Main {
public static void main(String args[])
{
// creating objects t1 of MyThread
MyThread t1 = new MyThread();
try {
Thread.sleep(1);
// t1 is an object of MyThread
// which has an object t
// which is of type Thread
t1.t.interrupt();
Thread.sleep(5);
}
catch (InterruptedException e) {
System.out.println("Caught:" + e);
}
System.out.println("Exiting the main Thread");
}}
Output
PS C:\Users\ OneDrive\Documents\cap615>javac MainA.java
PS C:\Users\ OneDrive\Documents\cap615> java MainA
New thread: Thread[Thread-0,5,main]
Thread is running
Thread is running
Thread is running
Thread is running
Thread has stopped.
Exiting the main Thread
Summary
Sometimes, it is necessary to suspend the execution of a thread. This can be done by
suspend( ) method.
Thread can be restarted by using the resume( ) method. Thread can be stopped by using
the stop( ) method.
Deadlock describes a situation where two or more threads are blocked forever, waiting for
each other.
The resume() method of thread class is only used with suspend() method. This method is
used to resume a thread that was suspended using suspend() method.
If a thread is suspended, it can be restarted. But if a thread is stopped by using the stop( )
method, it cannot be restarted again.
The synchronized keyword is used to make the class or method thread-safe which means
only one thread can have a lock of synchronized method and use it, other threads have to
wait till the lock releases and anyone of them acquire that lock.
Deadlock is caused because of the synchronized keyword because it blocks the executing
thread to wait for the lock.
A synchronized block ensures that only one thread executes inside it at a time.
Keywords
suspend():This method puts a thread in the suspended state and can be resumed using the resume()
method.
synchronized:synchronized keyword is used to make the class or method thread-safe.The keyword
ensures that only one thread can access the resource at a given point in time.
stop():The stop() method of the Thread class terminates the thread execution. Once a thread is
stopped, it cannot be restarted by the start() method.
resume() :The resume( ) method is also deprecated. It does not cause problems, but cannot be used
without the suspend( ) method as its counterpart.
Self Assessment
1. By using which of the following method can the suspend thread be revived?
A. suspend() method
B. start() method
C. resume() method
D. end() method
3. The . . . . . . . . . . method of the thread is called before the . . . . . . . . . method and carries out
any initialization.
A. suspend, resume
B. start, run
C. start, stop
D. resume, suspend
4. Which method is used to suspend threads that don’t need to run when the applet is not
visible?
A. destroy()
B. paint()
C. stop()
D. start()
A. wait()
B. sleep()
C. suspend()
D. All
7. ______________is used to change the thread from a Running state to Blocked state.
A. suspend() method
B. start() method
C. resume() method
D. end() method
A. this
B. synchronized
C. super
D. static
10. Deadlock is a situation when the thread is waiting for another thread to release the acquired
object.
A. TRUE
B. FALSE
C. Can be true or false
A. run()
B. wait()
C. notify()
D. suspend()
14. Which of the following will directly stop the execution of a Thread?
A. notify()
B. notifyall()
C. wait()
D. exits synchronized code
A. kill()
B. stop()
C. destroy()
D. dead()
6. D 7. A 8. C 9. B 10. A
Review Questions
1. “Deadlock is a special type of error that needs to be avoided in multitasking”. Elaborate.
2. “Java's synchronized keyword ensures that only one thread at a time is in a critical
region”.Comment.
3. “Each thread may perform different tasks. Sometimes, it becomes necessary to suspend
theexecution of a thread for a period of time”. Comment.
4. How we can resume from a suspended thread? Explain with the help of an example?
5. With an example explain the different methods of stopping a thread.
6. Explain the different methods used for avoiding deadlocks.
Further Readings
Herbert Schildt, The Complete Reference, 7th edition, Tata McGraw Hill
D. Samanta, Object-Oriented Programming with C++ and Java
Carver, R. H., & Tai, K. C. (2005). Modern multithreading: implementing, testing, and
Debugging Multithreaded Java and C++/Pthreads/Win32 programs. John Wiley & Sons.
Lewis, B., & Berg, D. J. (2000). Multithreaded programming with Java technology. Prentice-
Hall Professional.
Horstmann, C. S., & Cornell, G. (2001). Core Java 2: Fundamentals (Vol. 1). Prentice-Hall
Professional.
Web Links
http://www.herongyang.com/Java/Deadlock-What-Is-Deadlock.html
http://java.sun.com/docs/books/jls/second_edition/html/memory.doc.html
http://tim.oreilly.com/pub/a/onjava/excerpt/jthreads3_ch6/index1.html
https://www.edureka.co/blog/deadlock-in-java/
https://www.javatpoint.com/deadlock-in-java
https://medium.com/javarevisited/deadlock-in-java-multi-threading-627aaaaa0e02
Objective
• Understand the basic concept of thread synchronization and its declaration.
• Implementation of thread synchronization and Exception handling in a multithreaded
environment.
• Know the basics of Exception Handling and implementation in multithreaded
environment.
Introduction
Threads run concurrently and are independent of each other. This indicates that the threads run in
their own space, without being concerned about the status and activities of the other threads that
are running concurrently. During this process, threads do not require any method or outside
resources, and as a result, threads do not communicate with each other. These types of threads are
generally called asynchronous threads. Sharing the same resource (variable/method) by two or
more threads is the major problem suffered by asynchronous threads, as only one thread can access
a resource at a time. Let us assume that two threads Thread1 and Thread2 are the producers and
the consumer processes respectively. These two threads share the same data. A situation can arise
in which either the producer produces the data faster than it is consumed or the consumer retrieves
the data faster than it is produced. This problem is schematically represented in Figure 1.
To avoid and solve the above problem, Java uses a monitor, which is commonly known as
asemaphore. This prevents the data from being corrupted by multiple threads. We can implement
Programming in JAVA
amonitor by using the keyword synchronized to synchronize threads so that they can
intercommunicatewith each other. This mechanism allows two or more threads to share the
resources sequentially. Java's synchronized keyword ensures that only one thread at a time is in a
critical region. Thisregion is a locked area, where only one thread at a time is run (or locked).
Therefore, once the thread isin its critical region, no other thread can enter into that critical region,
and the thread has to wait untiland unless the current thread leaves its critical region.
Synchronized Methods
If any method is specified with the keyword synchronized, it will be executed by only one thread at atime. For
any thread to execute the synchronized method, first, it has to obtain the object's lock.However, if the lock is
held by another thread, then the calling thread has to wait. These methods areuseful in situations where
different methods need to be executed concurrently so that these methodscan intercommunicate and
manipulate the state of an object.
Example
//Program to illustrate the synchronized method.
class share extends Thread //class share is declared using the keyword extends
{
static String msg[ ]={"Following", "is", "a", "synchronized", "variable"}; //msg is
declared as static
share(String threadname)
//share is called with the parameter threadname
{
super(threadname); //super class is declared
}
public void run( ) //run( ) method is invoked
{
display(getName( )); //displays the name of the thread
}
public synchronized void display(String threadN)
{
for(int k=0; k<=4; k++)
System.out.println(threadN+msg[k]);
try
{
this.sleep(1500); //thread is made to sleep
} catch(Exception e) { }
}
}
}
public class SynchroThread1
{
public static void main(String[ ] args)
{
share T1=new share("Thread 1:"); //a new thread is created
T1.start( ); //thread is started
share T2=new share("Thread 2:"); //a new thread is created
T2.start( );//thread is started
}
}
Output
SynchroThread1
Thread 1: Following
Thread 1: is
Thread 1: a
Thread 1: synchronized
Thread 1: variable
Thread 2: Following
Thread 2: is
Thread 2: a
Thread 2: synchronized
Thread 2: variable
Task: Write a program to illustrate the synchronization of the print method that displays
thefollowing output:
My name is Rahul
I am working in ABC Company.
Example
// Program for the implementation of synchronized block.
Programming in JAVA
class Table
{
synchronized void printTable(int n)
{
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
}
try
{
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class MyThread1 extends Thread
{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(10);
}
}
public class SynchEx
{
public static void main(String[] args)
{
Table obj=new Table();
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output
PS C:\Users\OneDrive\Documents\cap615\programs>javac SynchEx.java
PS C:\Users\OneDrive\Documents\cap615\programs> java SynchEx
5
10
15
20
25
10
20
30
40
50
Programming in JAVA
exception object is created andhanded over to the run time system, it is called throwing an
exception.
Types of
Exceptions
Checked Unchecked
Checked: 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.
1. NoSuchFieldException: This exception is thrown when the user tries to use any field or
variable in a class that does not exist.
2. ClassNotFoundException: This exception is thrown when the user tries to access a class
that is not defined in the program.
3. IllegalAccessException: This exception is thrown when access to a class is denied.
4. Interrupted Exception: This exception is thrown when a thread is interrupted in a
processing, waiting, or sleeping state.
5. NoSuchMethodException: This exception is thrown when the user tries to access a method
that does not exist in the program.
Unchecked:The classes that inherit the RuntimeException are known as unchecked exceptions.
Forexample, ArithmeticException, NullPointerException,ArrayIndexOutOfBoundsException,
etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
Examples of unchecked exceptions are:
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.
Exception Keywords
try:The "try" keyword is used to indicate a block where an exception code should be placed. This
means we can't just utilize the try block. Either catch or finally must come after the try block.
catch:To handle the exception, the "catch" block is invoked. It must be preceded by a try block,
thus we can't just use catch block. It can be followed by a later finally block.
throw:The "throw" keyword is used to throw an exception.
throws:Exceptions are declared with the "throws" keyword. It specifies that an exception may
occur in the method. There isn't any exception thrown. It's usually used in conjunction with a
method signature.
finally:The "finally" block is used to run the program's required code. Whether or whether an
exception is handled, it is run.
Task:Write a program to illustrate the use of try and catch and finally keywords.
When only try and catch are used in a program, their combination is called the try-catch block.
Thisblock is used to catch a Java exception. Only one exception type can be handled by every catch
block,and more than one catch clause can be used in a single try block. In the try-catch block, the try
blocksurrounds a statement that may cause the occurrence of the exception, and the catch block
follows thetry block. On the occurrence of the exception, a code (that should be executed) is
specified in this catchblock.
Some of the terminologies used within exception handling are:
Throwing: A process through which an exception is generated and thrown into the program.
Catching: Capturing a currently occurred exception and also executing statements that may help
in resolving those exceptions.
Catch Block: The block of code that tries to handle the exception.
Stack Trace: A series of method calls that brings back the control to the point where the exception
had occurred.
An exception handler comprises two core sections, namely:
The Try Block: It includes some code, which might throw an exception (generate an error).
The Catch Block:It includes the error handling code. It means that it determines the strategy to be
implemented when an error is detected. Thus, exception handling provides a method to separate
error handling from the code that may result in errors. It is beneficial in several cases, as it produces
clean executable code.
Programming in JAVA
Caution:The exception class defined by the user must be a subclass of the Exception class.
Example
//Implementation of UncaughtExceptionHandler strategy
class UCEH implements Thread.UncaughtExceptionHandler {
public void uncaughtException(Thread t, Throwable e)
{
System.out.println("And the exception is.. " + e);
}
}
public class ThreadExcExampleN {
public static void main(String[] args)
throws Exception
{
Thread.setDefaultUncaughtExceptionHandler(new UCEH());
throw new Exception("\n language exception is caught");
}
}
Output
PS C:\Users\ OneDrive\Documents\cap615>javac ThreadExcExampleN.java
PS C:\Users\ OneDrive\Documents\cap615> java ThreadExcExampleN
And the exception is..java.lang.Exception:
language exception is caught
Summary
Synchronization is the ability to manage several threads' access to a common resource.
In Java, each object has its monitor, which a thread can lock or unlock. On a display, only
one thread can retain a lock at a time.
An exception is an object that includes information about the type of error that occurred.
Exception handling is based on the concept of universal error processing, wherein the
error correction code is separated from the main body of code and is fed to several
exception handlers.
A checked exception is thrown whenever an error is probable in input-output processing.
The unchecked exception is thrown due to the invalid argument supplied to a method.
These exceptions originate at run-time.
Keywords such as try, catch, and finally are used for implementing user-defined
exceptions.
For creating an exception, just define a subclass of Exception, which is a subclass of Throwable.
Keywords
Exception: An exception is an occurrence that causes the program's normal flow to be disrupted. It's
a type of object that's thrown at runtime.
throws:Exceptions are declared with the "throws" keyword. It specifies that an exception may occur
in the method.
Stack Trace: A series of method calls that brings back the control to the point where the exception
had occurred.
Synchronization: Synchronisation refers to the ability to regulate multiple threads' access to a
shared resource. It's required for thread-to-thread communication to be secure.
Synchronized Block: A synchronized block in Java indicates that a function or a section of code is
synchronized. It can only be executed by one thread at a time.
ArithmeticException: This exception is thrown when the user tries to divide a number by zero.
Error:An Error is a Throwable subclass that signals major problems that a reasonable application
should not attempt to catch.
Self Assessment
1. Thread synchronization in a process will be required when
A. synchronize
B. syn
C. synchronized
D. synch
A. It’s a process of handling situations when two or more threads need access to a shared
resource
B. It’s a process by which many threadscan access the same shared resource simultaneously
C. It’s a process by which a method can access many different threads simultaneously
D. It’s a method that allows too many threads to access any information they require
Programming in JAVA
5. What is the valid syntax for synchronized blocks to get the lock of the current object?
A. synchronized(this)
B. synchronized(super)
C. synchronized(Test.java)
D. None of these
6. If two threads are trying to execute one synchronized method with two different objects, then
their execution order is?
A. One by One
B. Both at time
C. The thread which gets locked first will execute first
D. None of these
8. Assume the following method is properly synchronized and called from a thread A on an
object B:
wait(2000);
After calling this method, when will thread A become a candidate to get another turn at the
CPU?
A. Synchronization is used to coordinate access to objects that are shared among multiple
threads.
B. A synchronized method may be invoked and executed without acquiring an object's lock.
C. A non-synchronized method requires that a thread obtain an object's lock before the method
may be executed.
D. Another word for a lock is monitor.
A. try
B. finally
C. thrown
D. catch
11. Which of these keywords must be used to handle the exception thrown by try block in some
rational manner?
A. try
B. finally
C. throw
D. catch
A. try
B. finally
C. throw
D. catch
13. The methods wait(), notify() and notifyAll() must be called only when they own the monitor
of that object, otherwise they throw __________________.
A. IllegalMonitorException
B. IllegalStateException
C. IllegalMonitorStateException
D. IllegalMonitorOwnStateException
A. Compile error
B. Syntax error
C. Runtime error
D. Not an error
6. B 7. B 8. A 9. D 10. C
Programming in JAVA
Review Questions
1. What do you understand by thread synchronization and why it is required? Give the syntax of
thread synchronization.
2. Explain the different ways used for the implementation of thread synchronization.
3. With the help of a suitable example explain the different types of exceptions?
4. Write a program to implement the concept of thread synchronization.
5. Elucidate the various strategies used for handling exceptions in a multithreaded environment.
6. Define the following:
a. synchronized block
b. finally
c. Exception
d. synchronization
Further Readings
Eckel, B. (2003). Thinking in JAVA. Prentice-Hall Professional.
Horstmann, C. S. (1997). Practical object-oriented development in C++ and Java. John Wiley &
Sons, Inc.
Savitch, W. (2019). Java: An introduction to problem solving & programming. Pearson
Education Limited.
Oaks, S., & Wong, H. (2004). Java Threads: Understanding and Mastering Concurrent
Programming. " O'Reilly Media, Inc.".
Hyde, P. (1999). Java thread programming (p. 528). Sams Pub.
Web Links
https://www.javatpoint.com/synchronization-in-java
https://dotnettutorials.net/lesson/thread-synchronization-in-java/
https://www.tutorialspoint.com/java/java_thread_synchronization.htm
https://programmer.group/java-concurrent-multithreading-exception-handling.html
http://mapoly.co.in/wpcontent/uploads/2020/03/Chapter4MultithreadingandException
Handling.pdf
Objectives
Learn the basic concept of JButton class and its various Constructors.
Understand the working of JRadioButton class and its various implementation methods.
Learn the basic concept of JTextArea Class and its various constructors
Understand the various methods of JTextArea Class and their Implementation
Know the basic concept of JComboBox class, its various constructors, methods, and their
implementation
Analyze the working of Jtable class and its various functions
Introduction
Swing is an important component of the Java language, which is provided in the
javax.swingpackage. Theconcept of swings came into existence to provide a more advanced
collection of GUI(Graphical User Interface) components to Java as compared to the AWT.
Programming in JAVA
8.1 JButton class
The JButton class is used to create a labeled button that has a platform-independent
implementation. The application results in some action when the button is pushed. The buttons are
the classes derived from the AbstractButtonclass. The AbstractButtonclass is a class, which contains
different methods that control the behavior of buttons, checkboxes, and radio buttons. Buttons are
simple buttons, on which a user can click and perform the desired operations.
JButtonsare the swing components that extend the JComponent. The button class in Swings is
similar to the button class found in java.awt.Buttonpackage. The buttons can be arranged and
organized by Actions. Swing buttons are used to display both the text and an image. The letter that
is underlined in the text of each button is the keyboard alternative for each button. The appearance
of the button is auto-generated with the button's disabled appearance. The user can provide an
image as a substitute for the normal image.
Programming in JAVA
JButton b=new JButton(new ImageIcon("C:\\Users\\Harjinder Kaur\\Downloads\\cc.jpg"));
frame.add(b);
frame.setSize(100,100);
frame.setLayout(new FlowLayout());
frame.setVisible(true);
}
}
Output
Example:G.add(Button1);G.add(Button2);
isSelected() : it will return a Boolean value true or false, if a JRadioButton is selected it Will return
true otherwise false.
Example:JRadioButton.isSelected()
Set(…) and Get(…) Methods: Set and get are used to replace directly accessing member variables
from external classes.Instead of accessing class member variables directly, you define get methods
to access these variables, and set methods to modify them.
The RadioButton class can be implemented by one of the following:
Using ActionListener
Programming in JAVA
// Declaration of object of JRadioButton class.
JRadioButton jRadioButton1;
// Declaration of object of JRadioButton class.
JRadioButton jRadioButton2;
// Declaration of object of JButton class.
JButtonjButton;
// Declaration of object of ButtonGroup class.
ButtonGroup G1;
// Declaration of object of JLabel class.
JLabel L1;
// Constructor of Demo class.
public Demo()
{
// Setting layout as null of JFrame.
this.setLayout(null);
// Initialization of object of "JRadioButton" class.
jRadioButton1 = new JRadioButton();
// Initialization of object of "JRadioButton" class.
jRadioButton2 = new JRadioButton();
// Initialization of object of "JButton" class.
jButton = new JButton("Click");
// Initialization of object of "ButtonGroup" class.
G1 = new ButtonGroup();
// Initialization of object of " JLabel" class.
L1 = new JLabel("Qualification");
// setText(...) function is used to set text of radio button.
// Setting text of "jRadioButton2".
jRadioButton1.setText("Under-Graduate");
// Setting text of "jRadioButton4".
jRadioButton2.setText("Graduate");
// Setting Bounds of "jRadioButton2".
jRadioButton1.setBounds(120, 30, 120, 50);
// Setting Bounds of "jRadioButton4".
jRadioButton2.setBounds(250, 30, 80, 50);
// Setting Bounds of "jButton".
jButton.setBounds(125, 90, 80, 30);
// Setting Bounds of JLabel "L2".
L1.setBounds(20, 30, 150, 50);
// "this" keyword in java refers to current object.
// Adding "jRadioButton2" on JFrame.
this.add(jRadioButton1);
Programming in JAVA
// Setting Visible status of frame as true.
f.setVisible(true);
}
}
Output:
Programming in JAVA
// Setting Title of frame.
f.setTitle("RadioButtons");
// Setting Visible status of frame as true.
f.setVisible(true);
}
}
Output:
Constructors of JTextArea
The following constructors are used to create the JTextArea class;
1. JTextArea() : constructs a new blank text area JTextArea(String s): constructs a new text
area with a given initial text.
2. JTextArea(int row, int column): constructs a new text area with a given number of rows
and columns.
3. JTextArea(String s, int row, int column): constructs a new text area with a given number
of rows and columns and a given initial text.
Output:
Programming in JAVA
(a) Displaying the selected text field on the screen.
(b) Exhibiting the display of the list box that is controlled by the button that is present on the
rightside of the text field.
(c) Editing the selected text field.
(d) Displaying icons along with or in the place of the text.
Constructor Description
Methods of JComboBox
Every class is having its own methods which are used for the implementation. The below is the list
of various methods used in JComboBox Class:
Task: Compile a list of constructors used in the JTextArea and JComboBoxclass, along with their
description.
Programming in JAVA
f=new JFrame();
String tab[][]={ {"1","Rahul","6"},
{"2","Kawar","7"},
{"3","Seerat","8"}};
String col[]={"Roll","NAME","CGPA"};
JTablejt=new JTable(tab,col);
jt.setBounds(30,40,200,300);
JScrollPanesp=new JScrollPane(jt);
f.add(sp);
f.setSize(300,400);
f.setVisible(true);
}
public static void main(String[] args) {
newjtExample();
}
}
Output :
Summary
Swing is a part of Java Foundation Class (JFC) and it includes graphical widgets like
checkboxes, radio buttons, menus, and so on.
The AbstractButtonclass is a class, which contains different methods that control the
behavior of buttons, checkboxes, and radio buttons.
A radio button is a Swing component, which is similar to the checkbox component. But in
a group of radio buttons, only one radio button can be selected per click, unlike
checkboxes.
A Radio button is also a Swing component, which is defined as an item that a user can
select or deselect with a single click.
Keywords
java.awt.event: A package in Java that provides interfaces and classes, which are used to deal with
various events that are fired by the AWT components.
javax.swing: A package in Java that provides a collection of lightweight components, that is,
thecomponents working similarly on all platforms.
JTable:TheJTable class is used to display data in tabular form.
JTextArea: The JtextAreacomponent is used to display plain text and is a multi-line text area. This is
a swing text component.
ButtonGroup:ButtonGroup object is used to create a group of the button in which only one button
at a time can be selected.
Self Assessment
1. Which of the following components extends and matches the Frame class in the AWT
package?
A. JFrame
B. JPanel
C. JApplet
D. JDialog
A. ComboBoxes
B. Lists
C. Menu
D. Button
A. JTextArea
B. JTable
C. JPanel
D. JtabbedPane
Programming in JAVA
5. Which of the following objects are created by using the JRadioButton( )and
JRadioButton(Icon icon) constructors?
A. JRadioButton
B. JButton
C. JTextBox
D. JCheckBox
A. methods
B. classes
C. interfaces
D. packages
A. panel.add(button);
B. button.add(panel);
C. frame.add(panel);
D. panel.add(JButton);
A. KeyEvent
B. WindowEvent
C. AdjustmentEvent
D. ActionEvent
A. ActionEvents
B. ChangeEvents
C. WindowEvents
D. MouseEvents
10. Which of the following packages is used to include classes to create the user interface like
Button and Checkbox?
A. java.lang
B. java.net
C. java.awt
D. java.io
11. Which of the following creates an initially unselected radio button with no set text.
A. JRadioButton(Icon icon)
B. JRadioButton()
C. JRadioButton(Action a)
D. All
A. AbstractButton
B. JButton
C. Button
D. JRadioButton
A. Button, Checkbox
B. JCheckBox,JRadioButton
C. Button, MenuItem
D. JCheckBox, TextField
A. JComboBox()
B. JComboBox(Object[] items)
C. JComboBox(Vector<?> items)
D. All
6. B 7. A 8. D 9. A 10. C
Review Questions
1. “A JRadioButtonobject can be created using many constructors.” Discuss these
constructors.
2. “A ComboBoxcontains three components.” Discuss these components.
3. What is the use of JComboBox class? With an example explain the various constructors of
JComboBox class?
Programming in JAVA
4. With an example explain the various constructors and methods of JTextArea class.
5. “JTable class is used to display data in tabular form” justify the statement with the help of
a program.
6. Write a program to show the implementation of the following:
a) JButton class.
b) JComboBox class.
Further Readings
Er. R. Kabilan, (2009), Secrets of JAVA, Firewall Media.
Kim Topley, (2000), Core Swing: advanced programming, Prentice Hall PTR.
Arnold, K., Gosling, J., & Holmes, D. (2005). The Java programming language. Addison
Wesley Professional.
Haggar, P. (2000). Practical Java: programming language guide. Addison-Wesley
Professional.
Web Links
http://java.comsci.us/examples/swing/JTextArea.html
http://www.javabeginner.com/java-swing/java-swing-tutorial
http://zetcode.com/tutorials/javaswingtutorial/basicswingcomponentsII
http://www.devx.com/tips/Tip/12812
http://www.beginner-java-tutorial.com/jbutton.html
https://ocw.mit.edu/courses/civil-and-environmental-engineering/1-00-introduction-
to-computers-and-engineering-problem-solving-spring-2012/lecture-
notes/MIT1_00S12_Lec_17.pdf
Objectives
After this unit you will be able to:
• Learn the basic concept of JColorChooser, JProgressBar, and JSlider Class.
• Understand the various constructors and methods of JColorChooser,JProgressBar, and
JSlider Class.
• Implementation of JColorChooser,JProgressBar and JSlider Class.
Introduction
Swing is a Java GUI widget toolkit. It's part of Oracle's Java Foundation Classes (JFC), which
provides an API for creating graphical user interfaces for Java programs. It was created to give a
more advanced set of graphical user interface components than the previous Abstract Window
Toolkit (AWT). Swing supports a pluggable look and feels that allows applications to have a look
and feel that is unconnected to the underlying platform, as well as a look and feel that emulates the
look and feel of numerous platforms. Its components are more powerful and flexible than those of
AWT.
Swing is a framework developed entirely in Java. The 'javax.swing' package in Java contains the
Swing framework. The javax.swing package contains classes that begin with the letter 'J.'
JProgressBar, JSlider, JColorChooser, and other classes that will be found in the javax.swing
package. Every control is described in the javax.swing package that is included in AWT is available
in the Swing API. As a result, swing serves as a sort of AWT replacement. Swing also supports
several complex components tabbed windows.
Programming in JAVA
new Swing component; no corresponding class exists in AWT. There are five panes in the default
color picker:
Swatches:Swatches are used to select a color from a set of swatches.
HSV:For using the Hue-Saturation-Value color representation to select a color. It was previously
known as HSB (Hue-Saturation-Brightness) until JDK 7.
HSL:HSL stands for Hue-Saturation-Lightness and is used to select a color.
RGB: The Red-Green-Blue color model is used to select a color.
CMYK:CMYK is a color model that uses the process color or four color model to select a color.
Constructors of JColorChooser Class
The following are the commonly used constructors of JColorChooser class:
JColorChooser():Creates a color picker pane with a white background.
JColorChooser(Color initialColor): The specified initial color is used to create a color chooser pane.
JColorChooser(ColorSelectionModel model): Creates a colour picker pane with the
ColorSelectionModel supplied.
JColorChooser Description
Example
//Implementation of JColorChooser to change background color.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.*;
Programming in JAVA
Task: Write a simple Java program to illustrate the concept of JColorChooser Class.
9.2 JProgressBar
The JProgressBar is a Java Swing component. JProgressBar is a visual representation of the progress
of a task. JProgressBar displays the percentage of a task that has been completed. As the work is
completed, the progress bar fills up. It can also display additional text in addition to the percentage
of task completion.
Constructors of JProgressBar
JProgressBar(): This constructor generates a progress bar without any text.
JProgressBar(int orientation):It produces an orientation-specific progress bar. If
SwingConstants.VERTICAL is being passed then a vertical progress bar is created and if
SwingConstants.HORIZONTAL is being passed thena horizontal progress bar is created.
JProgressBar(int min, int max):It generates a progress bar with a minimum and maximum
value supplied.
JProgressBar(int orientation, int min, int max):This constructor generates a progress bar with
a minimum and maximum value, as well as an orientation.
Example
// Program to implement JProgressBar
import javax.swing.*;
public class PBExample extends JFrame{
JProgressBarjb;
int i=0,num=0;
PBExample(){
jb=new JProgressBar(SwingConstants.HORIZONTAL);
jb.setBounds(40,40,160,30);
jb.setValue(0);
jb.setStringPainted(true);
add(jb);
setSize(250,150);
setLayout(null);
}
public void iterate(){
while(i<=100){
jb.setValue(i);
i=i+10;
try{Thread.sleep(150);}catch(Exception e){}
}
}
public static void main(String[] args) {
PBExample pb=new PBExample();
pb.setVisible(true);
pb.iterate();
}
}
Output
Programming in JAVA
PS C:\Users\ OneDrive\Documents\cap615\programs>javac PBExample.java
PS C:\Users\ OneDrive\Documents\cap615\programs> java PBExample
Example
// Java Program to set specific string message on progressbar
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class barprogress extends JFrame {
// create a frame
static JFramejf;
static JProgressBarjb;
public static void main(String args[])
{
// create a frame
jf = new JFrame("ProgressBar with string message");
// create a panel
JPaneljp = new JPanel();
// create a progressbar
jb = new JProgressBar();
// set initial value
jb.setValue(0);
jb.setStringPainted(true);
// add progressbar
jp.add(jb);
jf.add(jp);
jf.setSize(500, 500);
jf.setVisible(true);
//new progress();
fill();
}
// function to increase progress
public static void fill()
{
int i = 0;
Programming in JAVA
Figure 7: Slider
Constructors of JSlider
The following are some of the most common constructors in JSlider:
JSlider(): It produces a slider with a value of 50 as the initial point and a range of 0 to 100 as the
range.
JSlider(BoundedRangeModel b):Using the provided BoundedRangeModel, creates a horizontal
slider.
JSlider(int orientation):It constructs a slider with any JSlider's provided orientation.
JSlider. HORIZONTAL or JSlider.VERTICAL with a range of 0 to 100 and a starting value of 50.
JSlider(int min, int max):Creates a horizontal slider with an initial value equal to the average of
the min and max values, using the provided min and max values.
JSlider(int min, int max, int value):The stated min, max, and value are used to create a
horizontal slider.
JSlider(int orientation, int min, int max, int value):Creates a slider with the supplied
minimum, maximum, and starting values, as well as the specified orientation.
Example
//Implementation of Jslider class without ticks
import javax.swing.*;
We need to know the positions of specific numbers in some instances. In this case, we can add the
positions to the slider and name them.
Example
//Implementation of major and minor ticks
import javax.swing.*;
public class SliderTicks extends JFrame
{
public SliderTicks()
{
JSlidersl=new JSlider(JSlider.VERTICAL,0,80,35);
sl.setMinorTickSpacing(2);
sl.setMajorTickSpacing(10);
sl.setPaintTicks(false);
sl.setPaintLabels(true);
Programming in JAVA
JPanel panel=new JPanel();
panel.add(sl);
add(panel);
}
public static void main(String s[])
{
SliderTicksst=new SliderTicks();
st.pack();
st.setVisible(true);
}
}
Output
PS C:\Users\ OneDrive\Documents\cap615\programs>javac SliderTicks.java
PS C:\Users\ OneDrive\Documents\cap615\programs> java SliderTicks
We can add the change listener to the slider and conduct several operations to make it more
functional.Another panel might be added to show the value of the slider in real-time, for example.
Then we know exactly where the slider is. In the next example, we add a change listener to the
slider and display the slider's value in a panel below the slider.
Example
// java Program to create a vertical slider with min and max value and major and minor ticks
painted and set the font of the slider.
import javax.swing.event.*;
import java.awt.*;
import javax.swing.*;
class slfont extends JFrame implements ChangeListener {
// frame
static JFramejf;
// slider
static JSliderjs;
// label
static JLabeljl;
// main class
Programming in JAVA
Output
PS C:\Users\ OneDrive\Documents\cap615\programs>javac slfont.java
Note: slfont.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
PS C:\Users\ OneDrive\Documents\cap615\programs> java slfont
Summary
In swing the visual appearance is independent of internal representation, swing controls
can be easily adjusted.
JColorChooser is a class that provides a set of controls that allow a user to manipulate and
select a color.
The JSlider component is a swing component that allows the user to choose a value by
moving a knob in a defined interval.
SetMajorTickSpacing and setMinorTickSpacing in JSlider are used to adjust the number of
values between the tick marks.
JProgressBar is a visual representation of the progress of a task. It displays the percentage
of a task that has been completed.
A progress bar shows the progress of an event by displaying its percentage of completion
and, in certain cases, a textual representation of that percentage.
Keywords
GUI: Graphical User Interface
JColorChooser: This component extends JComponent and allows the user to select a color.
getString(): It returns the string representation of the current value in the progress bar.
JSlider(): It produces a slider with a value of 50 as the initial point and a range of 0 to 100 as the
range.
JSlider:A component that allows the user to select a value graphically by sliding a knob in a limited
interval.
JComponent: This component is the root class for all Swing components, but not for the top-level containers.
javax.swing: A package in Java that provides a collection of lightweight components, that is,
thecomponents working similarly on all platforms.
Self Assessment
1. ___________sets the progress bar’s minimum value to the value n.
A. void setMinimum(int n)
B. int setMinimum(int n)
C. void SetMinimum(int n)
D. int SetMinimum(int n)
A. ProgressMonitor
B. JSlider
C. JProgressBar
D. None
4. Which of the following constructor is used to create the progress bar along with the
mentioned orientation in its parameter.
A. JProgressBar(int orientation)
B. JProgressbar(int orientation)
C. JProgressBar(int orientation, int min, int max)
D. JProgressBar(int orientation, int min, int max)
5. Which of the following get the progress bar’s string representation of the current value.
A. String GetString()
B. int getString()
C. Int getString()
D. String getString()
A. JSlider(into)
B. JSlider(int min, int max)
C. JSlider(int min, int max, int value)
D. void setMinimum(int p)
Programming in JAVA
8. To set the extent of the slider, which of the following methods is used?
A. SetExtent()
B. setextent()
C. setExtent()
D. All
9. Which of the following method is used to change the maximum value of a slider?
A. setMaximum()
B. getMaximum()
C. Maximum()
D. useMaximum()
10. JSlider(int min, int max) is used to create a new slider with _____________orientation and
max and min value specified.
A. Vertical
B. Horizontal
C. Mixed
D. None
A. Java.swing
B. javax.swing
C. java.lang
D. java.awt
A. JComponent
B. JContainer
C. JSwing
D. All
13. Which of the followingconstructor creates a color chooser pane with white color as the
default.
A. jcolorchooser()
B. JColorChooser(color white)
C. JColorChooser()
D. ColorChooser()
14. Which of the followingmethod is used to return the current color from the color chooser
dialog box.
A. getColor()
B. setColor()
C. GetColor()
D. All
15. JColorChooser (Color col) is a color chooser pane created with the mentioned initial color
col.
A. False
B. Ture
C. Can’t Say
D. May be
6. A 7. D 8. C 9. A 10. B
Review Questions
1. “JcolorChooser helps in offering a control panel that is considered to allow a user to select a
color”.Comment on the statement with the help of an appropriate example.
2. Explain the various panes and methods used in JColorChooser class?
3. What is the significance of using JSlider? Discuss the various constructors of JSlider.
4. Write a program to show the specific string message on the progressbar.
5. “ SetMajorTickSpacing and setMinorTickSpacing in JSlider are used to adjust the number of
values between the tick marks” Justifying the statement with the help of an appropriate example.
6. Write a program to add a change listener to the slider and display the slider's value in a panel
below the slider.
Further Readings
Loy, M., Eckstein, R., Wood, D., Elliott, J., & Cole, B. (2002). Java swing. " O'Reilly Media,
Inc.".
Cole, B., Eckstein, R., Elliott, J., Loy, M., & Wood, D. (2002). Java Swing. O'Reilly.
Zukowski, J. (2006). The definitive guide to Java Swing. Apress.
Topley, K. (2000). Core Swing: advanced programming. Prentice-Hall Professional.
Robinson, M., &Vorobiev, P. (2004). Swing. Dreamtech Press.
Web Links
https://www.softwaretestinghelp.com/java/java-swing-tutorial/
https://www.geeksforgeeks.org/java-swing-jcolorchooser-class/
https://www.programcreek.com/java-api-examples/?api=javax.swing.JColorChooser
https://examples.javacodegeeks.com/desktop-java/swing/java-swing-slider-example/
Objectives
After this unit you will be able to:
Introduction
The arrangement of components within the container is referred to as layout. In other words, we
can say that the components are placed in a specific location within the container. Layouts are used
to format components on the screen, which is platform-independent. This means thatthe programs
can be executed on multiple platforms.The Layout Manager is in charge of automatically laying out
the controls.
Programming in JAVA
CASE-2: A few components must be displayed in a compact row at their original size.
Consider grouping the components in a JPanel and utilizing the default FlowLayout manager or
the BoxLayout manager. This is when SpringLayout helps a lot.
CASE-3: A few components of the same size must be displayed in rows and columns.
GridLayout is ideal for this task.
CASE-4: You want to show a few components in a row or column, with various amounts
of space between them, configurable alignment, and custom component sizes.
This is when BoxLayout works great.
CASE-5 You need to show aligned columns, such as in a form-like interface where a label
column is used to describe text fields in a neighboring column.
For this, SpringLayout is an obvious choice. The makeCompactGrid function in the SpringUtilities
class, which is used in various Tutorial examples, allows you to simply align several rows and
columns of components.
Caution: When less than five components are placed in a container and BorderLayoutis used,
the empty component regions disappear. The remaining components then expand to fill the
available space.
BorderLayout Constructors
BorderLayout Constructors are commonly used to create new border layouts with or without gaps
between the components. The gap and gap arguments in the border layout constructors are used to
set horizontal and vertical spacing between components. The following are the border layout
constructors:
BorderLayout():It will create a new BorderLayout with no gaps between the components.
BorderLayout(int, int):It creates a border layout with the provided gaps between components.
Methods of BorderLayout
The following are the various methods used in the border Layout:
toString(): It returns a string describing the current state of border layout.
getLayoutAlignmentX(Container parent): This method is used to return the X-axis layout
alignment.
getLayoutAlignmentY(Container parent): This method returns the Y-axis layout alignment.
removeLayoutComponent(Component comp): Used to remove a component from the
BorderLayout.
getVgap(): This method returns the vertical gap between the components.
getHgap(): The horizontal space between the components is returned by getHgap().
setHgap(inthgap): This method is used to adjust the horizontal gap between components.
setVgap(intvgap): This method is used to adjust the vertical gap between components.
Example:
Programming in JAVA
10.3 GridLayout
In Graphic programming, layout managers are used to arranging components in a specified order.
They're used to figure out how big a component is and where it should go in a container. Layout
managers come in a variety of shapes and sizes. One of them is GridLayout.Grid Layout helps in
the arrangement of components in rows and columns. This process of arrangement of components
starts at the first row and column, then moves across the row until it is full, and then continues to
the next row.
Grid Layout Manager allows the user to reposition or resize objects after adding or removing
components. The GridLayout container is divided into rectangles of the same size. Each rectangle
contains one of the components. Because each rectangle cell is the same size, it has a component
that fills the full cell. When the user modifies or adjusts the container's size, the size of each
rectangle adjusts as well.
GridLayout Constructors
GridLayout(): It creates a single-row grid layout with a default of one column per component.
GridLayout(intrw, int cl): It builds a grid layout with the number of rows and columns specified.
GridLayout(intrw, int cl, inthgap, intvgap): This function constructs a grid layout with the
supplied number of rows and columns, as well as a horizontal and vertical gap.
GridLayout Methods
GridLayout is beneficial in Java when you wish to construct grids in a container with one condition:
each of the grid's cells must be of equal size and uniformly distributed. The following are the
various methods used in the GridLayout.
addLayoutComponent(String str, Component cmp): This method adds the supplied component to
the layout with the specified name.
setColumns(int cl): Sets the number of columns in this layout to the specified value.
setHgap(inthgap): Sets the horizontal gap between components to the supplied value.
setRows(intrw):This method increases or decreases the number of rows in this layout.
setVgap(intvgap): Sets the vertical gap between components to the supplied value.
toString(): It returns a string representation of the values in this grid layout.
Example
// Implementation of GridLayout
importjava.awt.*;
importjavax.swing.*;
Programming in JAVA
10.4 FlowLayout
Flow Layout is the default layout of the Panel class. When components are added to the screen,
they flow from left to right based on the order added and the width of the applet. If many
components have to be placed in a window, then they wrap to a new row.
In most cases, flow layouts are used to place buttons in a panel. It will arrange the buttons from left
to right until there are no more buttons that will fit on the same line. Each line is in the middle.
CENTER: This value indicates that the components in each row should be centered.
RIGHT: This value indicates that each component row should be justified to the right.
FlowLayout Constructors
The following table illustrates the various constructors of FlowLayout class along with their
description:
Table 1: Constructors of FlowLayout
Constructor Description
FlowLayout(int align, Creates a flow layout with the supplied alignment and
inthgap, intvgap) horizontal and vertical gaps
Example
//implementation of FlowLayout
importjava.awt.*;
importjavax.swing.*;
public class FlowLayoutExample
{
JFramejf;
FlowLayoutExample()
{
jf=new JFrame();
JButton jb1=new JButton("1");
JButton jb2=new JButton("R");
JButton jb3=new JButton("A");
JButton jb4=new JButton("4");
JButton jb5=new JButton("B");
jf.add(jb1);
jf.add(jb2);
jf.add(jb3);
Programming in JAVA
jf.add(jb4);
jf.add(jb5);
jf.setLayout(new FlowLayout(FlowLayout.RIGHT));
jf.setSize(300,300);
jf.setVisible(true);
}
public static void main(String[] args)
{
newFlowLayoutExample();
}
}
Output
PS C:\Users\\OneDrive\Documents\cap615\programs>javac FlowLayoutExample.java
PS C:\Users\OneDrive\Documents\cap615\programs> java FlowLayoutExample
Task: Write a program to illustrate a flow layout manager in Java AWT. Drag the sides
orcorners of the displayed frame to demonstrate the working of the layout manager.
10.5 BoxLayout
BoxLayout is a common layout manager included with the Java platform. It aids in the horizontal
or vertical arrangement of components within the container. Even if we enlarge the frame, the
component arrangement will remain the same. i.e., even if the frame resizes, the vertical
arrangement remains vertical. To put it another way, the contents of the container will not be
wrapped. BoxLayout constructor, unlike other layout managers, gives the appropriate containers to
the layout manager constructor. The next sections will go over the constructors, methods, and
examples of the BoxLayout Class.
BoxLayout provides four constants to arrange the components either horizontally or vertically.
They are as follows:
public static final int X_AXIS:The components are aligned horizontally from left to right.
public static final int Y_AXIS:The components are vertically aligned from top to bottom
public static final int LINE_AXIS:Component alignment is comparable to how words are
aligned in a line, and it is determined by the container's ComponentOrientation attribute.
The components are positioned horizontally if the container's ComponentOrientation
property is horizontal; otherwise, they are aligned vertically. There are two types of
horizontal orientations: left to right and right to left. Components are rendered from left to
right if the container's ComponentOrientation property is set to left to right, and right to
left if the container's ComponentOrientation property is set to right to left. The
components are always shown from top to bottom in vertical orientations.
public static final int PAGE_AXIS:The ComponentOrientation property of the container
is used to align the components in the same way as text lines are aligned on a page.
Components are positioned vertically if the container's ComponentOrientation attribute is
horizontal; otherwise, components are aligned horizontally. There are two types of
horizontal orientations: left to right and right to left. Components are rendered from left to
right if the container's ComponentOrientation property is also set to left to right, and
components are rendered from right to left if the container's ComponentOrientation
property is set to right to left. The components are always shown from top to bottom in
vertical orientations.
BoxLayout Constructor
The following constructor will be used to implement the BoxLayout class:
BoxLayout(Container c, int axis):It builds a box layout with the provided axis that arranges the
components.Container and axis are the two arguments supplied, which aid in the creation of the
container with the axis specified. The following are the two valid directions:
BoxLayout – from left to right.
X_ AXIS
BoxLayout from top to bottom.
Y_ AXIS
If we call BoxLayout.Y-AXIS we'll get the following output.
If we call BoxLayout.X-AXIS we'll get the followinglayout that looks like (one row).
Programming in JAVA
BoxLayout Methods
addLayoutComponent(Component cmp, Object obj): The goal of this method is to use the
constraint object to add the indicated component to the container.
getLayoutAlignmentX(Container con): The container's alignment in the left to the right direction is
returned by this method. X-Axis, to be precise. The value can range from 0 to 1, with 0 being the
origin alignment, 1 representing the farthest alignment from the origin, and 0.5 representing the
centered alignment.
getLayoutAlignmentY(Container con):The top-to-bottom alignment of the container is returned by
this method. Y-Axis, for example. The value can range from 0 to 1, with 0 being the origin
alignment, 1 representing the farthest alignment from the origin, and 0.5 representing the centered
alignment.
maximumLayoutSize(Container con): This method provides the target container's maximum size
for laying out the containers that are added to it.
minimumLayoutSize(Container con): This function returns the smallest size that the target
container can use to layout any other containers.
removeLayoutComponent(Component cmp): This function removes the specified component from
the layout of the container.
layoutContainer(Container tar): When the Abstract Window Toolkit calls this function, it lays up
the container's layout (AWT).
Example
//BoxLayout example with different BoxLayout alignment settings
importjavax.swing.BorderFactory;
importjavax.swing.BoxLayout;
importjavax.swing.JButton;
importjavax.swing.JFrame;
importjavax.swing.JPanel;
importjava.awt.Component;
importjava.awt.FlowLayout;
public class BoxLayoutAlignExample {
public static void main(String[] args) {
JFrame frame = new JFrame("BoxLayout With Different Alignments");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton jb1 = new JButton("OK");
JButton jb2 = new JButton("SUBMIT");
JButton jb3 = new JButton("DELETE");
JButton jb4 = new JButton("UPDATE");
JButton jb5 = new JButton("CANCEL");
JButton jb6 = new JButton("SAVE");
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
p1.setBorder(BorderFactory.createTitledBorder("LEFT"));
p2.setBorder(BorderFactory.createTitledBorder("CENTER"));
p3.setBorder(BorderFactory.createTitledBorder("RIGHT"));
// Set up the BoxLayout
BoxLayout layout1 = new BoxLayout(p1, BoxLayout.Y_AXIS);
BoxLayout layout2 = new BoxLayout(p2, BoxLayout.Y_AXIS);
BoxLayout layout3 = new BoxLayout(p3, BoxLayout.Y_AXIS);
p1.setLayout(layout1);
p2.setLayout(layout2);
p3.setLayout(layout3);
jb1.setAlignmentX(Component.LEFT_ALIGNMENT);
jb2.setAlignmentX(Component.LEFT_ALIGNMENT);
p1.add(jb1);
p1.add(jb2);
jb3.setAlignmentX(Component.CENTER_ALIGNMENT);
jb4.setAlignmentX(Component.CENTER_ALIGNMENT);
p2.add(jb3);
p2.add(jb4);
jb5.setAlignmentX(Component.RIGHT_ALIGNMENT);
jb6.setAlignmentX(Component.RIGHT_ALIGNMENT);
p3.add(jb5);
p3.add(jb6);
frame.setLayout(new FlowLayout());
frame.add(p1);
frame.add(p2);
frame.add(p3);
frame.pack();
frame.setVisible(true);
}
}
Programming in JAVA
Output
PS C:\Users\ OneDrive\Documents\cap615\programs>javac BoxLayoutAlignExample.java
PS C:\Users\ OneDrive\Documents\cap615\programs> java BoxLayoutAlignExample
10.6 CardLayout
Card Layout, unlike other layouts that display the components of a container one at a time,
functions as a deck of playing cards with only one card visible at a time, i.e. the topmost card. Every
component in a container is treated as a Card, and the container itself is treated as a Stack of cards.
Internally, the order of the cards in a container is determined. It is the initial component existing in
the container that is seen when the container is displayed for the first time.
CardLayoutConstructors
CardLayout is a Java class that has a few constructors. Some of CardLayout's Constructors are
listed below:
CardLayout():This constructor of the Java class CardLayout is used to build a new CardLayout
with gaps between the individual components of size zero (0).
CardLayout(inthorizontalgap, intverticalgap): This Java constructor is used to generate a new
CardLayout with the specified horizontal and vertical gaps between the components in the
arguments. The horizontal gap between the components is denoted by Hgap, whereas the vertical
gap is denoted by vgap.
Methods of CardLayout
next(Container parent):The procedure for advancing to the next card in the container.
previous(Container parent):The way for navigating to the previous card in the container.
first(Container parent):The mechanism for navigating to the first card in the container.
last(Container parent):The process for getting to the last card in the container.
show(Container parent, String name ):The mechanism for navigating to the container with the
supplied name.
getLayoutAlignmentX(Container parent):The alignment along the x-axis is returned by this
method.
getLayoutAlignmentY(Container parent):The y-axis alignment is returned by this method.
getVgap():The method for determining the vertical space between the components.
addLayoutComponent(Component cm, Object cn):The method for adding a component to the
internal table of components for a card layout.
getHgap():The method for determining the horizontal space between the components.
toString():The textual representation of this card arrangement is returned by this method.
removeLayoutComponent(Component cm):This method deletes the specified component
from the card layout.
Example
// Program to show Examples of different methods of CardLayout.
importjava.awt.*;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjavax.swing.*;
public class CardLayoutMethod extends JFrame {
privateintcurrentCard = 1;
privateCardLayout cl;
publicCardLayoutMethod()
{
setTitle("Card Layout Example");
setSize(300, 150);
JPanelcPanel = new JPanel();
cl = new CardLayout();
cPanel.setLayout(cl);
JPanel jp1 = new JPanel();
JPanel jp2 = new JPanel();
JPanel jp3 = new JPanel();
JPanel jp4 = new JPanel();
JLabel jl1 = new JLabel("First");
JLabel jl2 = new JLabel("Second");
JLabel jl3 = new JLabel("Third");
JLabel jl4 = new JLabel("Fourth");
jp1.add(jl1);
jp2.add(jl2);
jp3.add(jl3);
jp4.add(jl4);
cPanel.add(jp1,"1");
cPanel.add(jp2,"2");
cPanel.add(jp3,"3");
cPanel.add(jp4,"4");
JPanelbuttonPanel = new JPanel();
JButtonfBtn = new JButton("First button");
JButtonnBtn = new JButton("Next button");
JButtonpBtn = new JButton("Previous button");
JButtonlBtn = new JButton("Last button");
buttonPanel.add(fBtn);
buttonPanel.add(nBtn);
buttonPanel.add(pBtn);
buttonPanel.add(lBtn);
fBtn.addActionListener(new ActionListener()
{
Programming in JAVA
// value of currentcard is 1
currentCard = 1;
}
});
lBtn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
// used last c1 CardLayout
cl.last(cPanel);
// value of currentcard is 4
currentCard = 4;
}
});
nBtn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
if (currentCard< 4)
{
// increment the value of currentcard by 1
currentCard += 1;
// show the value of currentcard
cl.show(cPanel, "" + (currentCard));
}
}
});
pBtn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
// if condition apply
if (currentCard> 1) {
// decrement the value
// of currentcard by 1
currentCard -= 1;
// show the value of currentcard
cl.show(cPanel, "" + (currentCard));
}
}
});
getContentPane().add(cPanel, BorderLayout.SOUTH);
getContentPane().add(buttonPanel, BorderLayout.NORTH);
}
public static void main(String[] args)
{
CardLayoutMethod cl = new CardLayoutMethod();
// Function to set default operation of JFrame.
cl.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cl.setVisible(true);
}
}
Output
PS C:\Users\ OneDrive\Documents\cap615\programs>javac CardLayoutMethod.java
PS C:\Users\ OneDrive\Documents\cap615\programs> java CardLayoutMethod
Lab Exercise: Write a program to illustrate a grid layout. The grid must contain five grids with
different names.
Summary
Layouts are used to format components on the screen.
A layout manager is assigned to each container and is in charge of arranging the
components within it.
The layout manager arranges the components according to the layout manager's rules,
property settings, and component limitations.
A good appearance, regardless of the platform, screen size, or actions the user might take is
givenby the layout managers.
The different types of layout managers are flow layout, border layout, grid layout, box
layout,and card layout.
The BoxLayout is used to vertically or horizontally organize the components.
Programming in JAVA
If there isn't enough horizontal space to hold all of the components in one row, Flow layout
adds them to the next row, and so on.
The layout manager positions all of the components within the container automatically, and
if youdon't use the layout manager, the default layout manager positions the components.
When we want to arrange the components in five regions, we utilize BorderLayout.
Keywords
LayoutManager:The LayoutManager interface specifies which methods must be implemented by
the class whose object will be used as a layout manager.
GridLayout:It arranges all of the elements in a grid of cells of equal size, adding them from left to
right and top to bottom.
CardLayout: The components are organized in a deck with all of the same-sized cards and just the
top card showing at any given moment.
previous(Container parent):The way for navigating to the previous card in the container.
getHgap(): The horizontal space between the components is returned by getHgap().
LEFT: This value indicates that each component row should be justified to the left.
BoxLayout: It arranges multiple components either vertically or horizontally, but not both.
Self Assessment
1. Positions the components into five regions: east, west, north, south, center
A. BorderLayout
B. CardLayout
C. GridLayout
D. FlowLayout
A. Horizontal only.
B. Horizontal and Vertical.
C. Left aligned and Right aligned.
D. Centered and Justified.
4. What type of object determines where GUI components are placed in a container?
A. FlowLayout
B. GridLayout
C. BorderLayout
D. BoxLayout
A. CENTER
B. TOP
C. HORIZONTAL
D. VERTICAL
A. FlowLayout
B. BorderLayout
C. GridLayout
D. CardLayout
9. The ______________ is used to arrange the components in a line, one after another.
A. BorderLayout
B. GridLayout
C. FlowLayout
D. CardLayout
A. FlowLayout()
B. FlowLayout(int align)
C. FlowLayout(int align, intHorizontalGap, intVerticalGap )
D. All of the above.
A. setTitle(String Text)
B. getAlignment()
C. SetAlignment(int align)
D. setAlignment(int align)
Programming in JAVA
A. BorderLayout
B. CardLayout
C. GridLayout
D. FlowLayout
13. Which layout manager works by positioning components in rows and columns?
A. BorderLayout
B. FlowLayout
C. GridLayout
D. BoxLayout
14. When the user changes or adjusts the size of the container in GridLayout, the size of each
________ changes accordingly.
A. Rectangle
B. Square
C. Circle
D. None
A. BorderLayout
B. CardLayout
C. GridLayout
D. FlowLayout
6. A 7. C 8. A 9. C 10. D
Review Questions
1. "The Java development kit offers five classes and these classes implement the layout
manager interface". Discuss.
2. “Card Layout, unlike other layouts that display the components of a container one at a
time” justify the answer with an appropriate example.
3. Discuss the various scenarios that can help us choose the best layout manager.
4. Elucidate BorderLayout along with its various methods.
5. “BoxLayout provides four constants to arrange the components either horizontally or
vertically” what are they? Explain each component with the help of an example?
6. Enlighten the significance of using GridLayout. Discuss the various constructors and
methods used by GridLayout.
Further Readings
JADHAV, T. (2020). Advance Java.
Arnold, K., Gosling, J., & Holmes, D. (2005). The Java programming language. Addison
Wesley Professional.
Liang, Y. D. (2003). Introduction to Java programming. Pearson Education India.
Sharan, K. (2014). Beginning Java 8 APIs, Extensions, and Libraries: Swing, JavaFX,
JavaScript, JDBC, and Network Programming APIs. Apress.
Sharan, K., Sharan, K., &Anglin. (2018). Java APIs, Extensions, and Libraries. Apress.
Web Links
https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
https://www.tutorialspoint.com/awt/awt_layouts.htm
https://www.c-sharpcorner.com/UploadFile/9a9e6f/layout-managers-in-java-part-1/
https://ecomputernotes.com/java/awt-and-applets/gridlayoutjavaexample
http://www.java2s.com/Tutorial/Java/0240__Swing/WhatistheBorderLayout.htm
Harjinder Kaur, Lovely Professional University Unit 11: Managing data using JDBC
Objectives
Learn the basic concept of JDBC and understand the different types of JDBC drivers.
Know and analyze the different architectural components of JDBC.
Understand the various steps required for database connectivity.
Implement database connectivity and CRUD operations.
Introduction
The JDBC API is a Java API that allows you to access any type of tabular data, including data from
a Relational Database. JDBC enables you to create Java applications that handle the following three
programming tasks:
11.1 JDBC
JDBC stands for Java Database Connectivity and is an Application Programming Interface (API) for
connecting Java applications to databases.It can communicate with a variety of databases, including
Oracle, MS Access, My SQL, and SQL Server.It's also known as a platform-agnostic interface
between a relational database and Java programming.It enables a Java program to execute SQL
statements and obtain database results.
Programming in JAVA
The JDBC API is made up of classes and methods that are used to connect to, read from, write to,
and store data in a database.
Use of JDBC
Enterprise applications built with the JAVA EE platform must communicate with
databases to store application-specific data.
Before JDBC, the ODBC API was the database API for connecting to the database
and running queries.
However, the ODBC API makes use of the ODBC driver, which is written in C.
(i.e. platform-dependent and unsecured).
We can use JDBC API to handle database using Java program and can perform
the following activities:
Connect to the database.
Execute queries and update statements to the database.
Retrieve the result received from the database.
Purpose of JDBC
Enterprise applications built with the JAVA EE platform must communicate with databases to store
application-specific data. As a result, communicating with a database necessitates effective
database connectivity, which can be accomplished with the ODBC (Open database connectivity)
driver. This driver is used in conjunction with JDBC to connect or communicate with a variety of
databases, including Oracle, MS Access, Mysql, and SQL Server.
Example: JDBC drivers, allow you to open database connections and interact with them by
delivering SQL or database commands and then getting the results in Java.
The Java.sql package that comes with JDK has several classes that have their behavior defined but
are implemented by third-party drivers. The java.sql.The driver interface is implemented by third-
party database drivers.
Advantages
It is simple to use.
It's simple to connect to any database.
Disadvantages
Performance suffers as a result of the conversion of JDBC method calls to ODBC function
calls.
On the client's PC, the ODBC driver must be installed.
Native-API driver
The Native API driver makes use of the database's client-side libraries. The driver translates JDBC
method calls to database API native calls. It is not written in Java.
Advantage
Programming in JAVA
The Native driver must be installed on each client machine, which is a disadvantage.
On the client machine, the Vendor client library must be installed.
Advantage
Because the application server can do numerous activities such as auditing, load
balancing, and logging, no client-side libraries are required.
Disadvantages
Thin driver
JDBC calls are converted directly into the vendor-specific database protocol via the thin driver. That
is why it is referred to as a "thin driver." It is entirely written in the Java programming language.
Advantages
Outperforms all other drivers in terms of performance.
There is no software required on either the client or server-side
Disadvantage
Drivers are reliant on the database, which is a disadvantage.
Components of JDBC
The following components are required to interface with the database using JDBC.
DriverManager: The java.sql package's DriverManager class manages many types of JDBC
drivers. This class is responsible for loading the driver classes. Furthermore, once a new connection
is established, it selects and loads the appropriate driver from the previously loaded drivers.
Note: Beginning with JDBC 4.0, the drivers in the CLASSPATH will be automatically loaded.
Statement: To execute SQL statements to the database, you use objects built using this interface. In
addition to performing stored procedures, certainly derived interfaces accept parameters.
Note: When you close a Connection, it automatically closes any open statements or result sets.
Programming in JAVA
ResultSet:You can use the ResultSet interface to get data from a SQL query. The ResultSet
interface is most commonly used to read data, however, as of JDBC version 2.0, you can also update
and delete records. If you merely want to read the results, use the next method to move to the next
row, then use one of the several get methods to receive the data.
These objects store data acquired from a database after utilizing Statement objects to run a SQL
query. It functions as an iterator, allowing you to cycle through the data it contains.
Example:
ResultSet results = stmt.executeQuery(
"select last_name, age from Person);
while (results.next())
{
String lastName = results.getString("last_name");
int age = results.getInt("age");
}
SQLException:This class handles any errors that occur in a database application.
DriverManager
Driver
Connection
Statement
PreparedStatement
CallableStatement
ResultSet
SQL data
DriverManager: It plays an important role in the JDBC architecture.It uses some database-
specific drivers to effectively connect enterprise applications to databases.
JDBC drivers: To communicate with a data source through JDBC, you need a JDBC driver that
intelligently communicates with the respective data source.
Register
Driver Class
Create Close
Connection Connection
Create Execute
Statement queries
Programming in JAVA
Register the driver class:The driver class is registered using the Class class's forName() method.
This technique is used to load the driver class dynamically.
Example: Class.forName(“MySql.jdbc.driver.MySqlDriver");
Example:Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","syst
em","password");
Create the Statement object:To generate a statement, use the Connection interface's
createStatement() method. The statement's object is in charge of doing queries on the database.
Example: con.close();
Operation Description
Creating a Database
Here we are going to discuss how we can create a database using NetBeans. The following steps
you need to follow for the creation of a database.
To create a new database, right-click on Java DB again. From the menu that appears, select Create
Database:
When you click on Create Database, you'll see a dialogue box appear:
Type a name for your database in the first box. Call it DBStudent. Type any User Name and
Password.
Programming in JAVA
When a connection is made, you'll see some default folders for Tables, Views, and Procedures.To
create a new table in your database, right-click the Tables folder. From the menu that appears,
select Create Table:
Here you can give the table name you want to create and add attributes into it using add column
command.
Where The NAME is the name of the column in the table, like ID, First_Name, etc. The TYPE is the
DATA TYPE, Integer, VARCHAR, etc. Click the dropdown list to see more. Then check or uncheck
the CONSTRAINTS boxes as indicated.
Programming in JAVA
Example
// Implementation of CRUD Operations
Database Connectivity
package Empl;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class Works extends javax.swing.JFrame {
Connection con;
Statement stmt;
ResultSetrs;
public Works() {
initComponents();
DoConnect();
Programming in JAVA
}
public void DoConnect( )
{
try
{
String host="jdbc:derby://localhost:1527/DBStudent";
String uname="Shallu";
String pwd="Shallu";
con=DriverManager.getConnection(host, uname, pwd);
}
catch(SQLException e)
{
JOptionPane.showMessageDialog(this, e.getMessage());
}
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jTextField3 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextField1.setText("Name");
jTextField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEventevt) {
jTextField1ActionPerformed(evt);
}
});
jTextField2.setText("Address");
jTextField3.setText("Contact");
jButton1.setText("Insert");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEventevt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Delete");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEventevt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setText("Update");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEventevt) {
jButton3ActionPerformed(evt);
}
});
jButton4.setText("Display");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEventevt) {
jButton4ActionPerformed(evt);
}
});
private void jButton1ActionPerformed(java.awt.event.ActionEventevt) {
// TODO add your handling code here:
try
{
stmt=con.createStatement();
String name=jTextField1.getText();
String mob=jTextField2.getText();
String add=jTextField3.getText();
String sql="Insert into TBSTU values('"+(name)+"','"+(add)+"','"+(mob)+"')";
stmt.executeUpdate(sql);
JOptionPane.showMessageDialog(this, "Record Saved Successfully");
jTextField1.setText("");
jTextField2.setText("");
jTextField2.setText("");
}
catch(SQLException e)
{
JOptionPane.showMessageDialog(this, e.getMessage());
Programming in JAVA
}
private void jButton3ActionPerformed(java.awt.event.ActionEventevt) {
// TODO add your handling code here:
try
{
stmt=con.createStatement();
String name=jTextField1.getText();
String mob=jTextField2.getText();
String add=jTextField3.getText();
String sql="Update TBstu set NAME='" + (name)+ "', ADDRESS='" + (add)+ "'"+ " where Mob = '"
+ (mob) + "'";
stmt.executeUpdate(sql);
JOptionPane.showMessageDialog(this, "Record updated Successfully");
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");
}
catch(SQLException e)
{
JOptionPane.showMessageDialog(this, e.getMessage());
}
}
private void jTextField1ActionPerformed(java.awt.event.ActionEventevt) {
// TODO add your handling code here:
}
/**
* @param argsThe command-line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Works().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
Programming in JAVA
Method Function
public Statement createStatement(int Creates a Statement object that will generate ResultSet
resultSetType,intresultSetConcurrency) objects with the given type and concurrency.
public void setAutoCommit(boolean It is used to set the commit status.By default it is true.
status)
public void commit() It is used to save the changes made since the previous
commit/rollback is permanent.
public void rollback() Drops all changes made since the previous
commit/rollback.
public void close() It closes the connection and Releases JDBC resources
immediately.
Summary
JDBC is a software tool that makes a connection between a standard database and a Java
application that intends to use that database, also known as an application programming
interface.
The first layer of the JDBC architecture is the JDBC driver, which has direct communication
with the data storage devices.
JDBC drivers are client-side adapters that translate Java program requests into a protocol
that the database management system can understand.
The CRUD operation can be defined as user interface conventions that allow view, search,
and modify information through computer-based forms and reports.
A result set is a table of rows and columns that contains the results of executing an SQL
query.
Keywords
JDBC: JDBC stands for Java Database Connectivity, which is a standard Java API for database-
independent connectivity between the Java programming language, and a wide range of databases.
JDBC Drivers:A JDBC driver is a collection of Java classes that enables you to connect to a certain
database.
Statement:A Statement is what you use to execute queries and updates against the database.
ResultSet:When you perform a query against the database you get back a ResultSet.
Application: It is a java applet or a servlet that communicates with a data source.
Driver: This interface handles the communications with the database server.
SQL: Structured Query Language is a standardized language that allows you to perform operations
on a database, such as creating entries, reading content, updating content, and deleting entries
Self Assessment
1. What must be the first characters of a database URL?
A. db,
B. db:
C. jdbc,
D. jdbc:
2. To transfer data between a database and an application written in the Java programming
language, the JDBC API provides which of these methods?
A. Methods on the ResultSet class for retrieving SQL SELECT results as Java types.
B. Methods on the PreparedStatement class for sending Java types as SQL statement
parameters.
C. Methods on the CallableStatement class for retrieving SQL OUT parameters as Java types.
D. All mentioned above
3. The ………………………….. method executes a simple query and returns a single Result Set
object
A. executeUpdate()
B. executeQuery()
C. execute()
D. noexecute()
A. One
B. Two
C. Three
D. Four
5. A Connection is the session between java application and ____________.
Programming in JAVA
A. Table
B. Database
C. Row
D. Column
7. A _______object is used when an application plans to specify parameters to your SQL queries.
A. statement
B. prepared statement
C. data source
D. parameterized statement
A. Connection
B. DataSource
C. Statement
D. CallableStatement
A. executeResult()
B. executeQuery()
C. executeUpdate()
D. execute()
10. How many transaction isolation levels provide the JDBC through the Connection interface?
A. 3
B. 4
C. 7
D. 2
11. The method on the result set that tests whether or not there remains at least one unfetched tuple
in the result set, is said to be
A. Fetch method
B. Current method
C. Next method
D. Access method
12. The__________package contains classes that help in connecting to a database, sending SQL
statements to the database, and processing the query request.
A. connection.sql
B. db.sql
C. pkg.sql
D. java.sql
14. Which of the following is the advantage of using the JDBC connection pool?
A. Slow performance
B. Using more memory
C. Using less memory
D. Better performance
6. C 7. B 8. A 9. C 10. B
Review Questions
1) What are the important components of JDBC?
2) Explain the various JDBC drivers.
3) With the help of an example elucidate the various steps of database connectivity.
4) Describe the JDBC architecture in detail.
5) Explain the significance of using a connection interface along with its various methods.
6) Write down the step-by-step process of creation of the database and table.
7) Write a note on the following:
a) Two-tier Architecture.
b) Three-tier Architecture.
Programming in JAVA
Further Readings
Patel, P., & Moss, K. (1997). Java database programming with JDBC (pp. 5-8). Coriolis Group
Books.
Khannedy, E. K. (2011). MySQL dan Java Database Connectivity. Bandung: StripBandung.
Bales, D. (2002). Java Programming with Oracle JDBC. " O'Reilly Media, Inc.".
Reese, G. (2000). Database Programming with JDBC and JAVA. " O'Reilly Media, Inc.".
Parsian, M. (2006). JDBC Metadata, MySQL, and Oracle recipes: a problem-solution approach.
Apress.
Web Links
https://www.baeldung.com/java-jdbc
https://www.simplilearn.com/tutorials/java-tutorial/java-jdbc
https://www.ibm.com/docs/en/informix-servers/12.10?topic=started-what-is-jdbc
https://docs.oracle.com/javase/tutorial/jdbc/basics/index.html
https://www.codejava.net/java-se/jdbc/jdbc-tutorial-sql-insert-select-update-and-delete-
examples
Objectives
After this unit you will be able to:
• Understand and implement Statement and ResultSet Interface
• Learn and implement Resultset Interface
• Know the concept, methods of DatabaseMetaData Interface and its implementation
Introduction
Java database connectivity (JDBC) specifies interfaces and classes that enable database applications
to be written in Java by establishing database connections. JDBC facilitates SQL statement execution
and provides basic SQL capability. Because thin clients run Java, applets placed in Web sites
provide downloadable JDBC scripts that enable remote database access.When a Java application
needs a database connection, one of the DriverManager.getConnection() methods are used to create
a JDBC connection. The following are the various use cases used in JDBC:
Query the database:Reading data from a database is one of the most prevalent usage cases.
Querying a database is the process of reading data from it.
Query the database metadata:Querying the database metadata is another typical use case. The
database metadata is made up of details about the database.
Example: Data on the tables defined, the columns in each table, the data formats, and so on.
Update the database:Updating the database is another popular JDBC use case. Writing data to the
database is what updating it entails. Adding new records or altering (updating) existing ones, in
other words.
Perform transactions:Another prominent use case is transactions. A transaction is a single action
that combines several updates and perhaps queries. Either all of the activities are carried out, or
none of them are carried out.
Programming in JAVA
Create Statement
Prepared Statement
Callable Statement
Create a Statement: You can create the object for this interface from the connection interface. It's
typically utilized for general–purpose database access and comes in handy when running static
SQL commands.
Syntax:
Statement statement = connection.createStatement();
The required SQL statement is sent as a query, and the Statement object delivers a set of
results.Because we can't construct interface objects, we can utilise the connection object's
createStatement() function to get a Statement object.A single connection object can be used to
produce numerous objects.
Example:
package db_console;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
*
* @author Harjinder Kaur
*/
public class DB_Connect {
/**
* @param argsThe command-line arguments
* @throws java.sql.SQLException
*/
Output
run:
Roll=1
name=Geeta
city=Delhi
BUILD SUCCESSFUL (total time: 0 seconds)
Prepared Statement:The term "prepared statement" refers to a recompiled SQL statement that
can be used several times. This accepts SQL queries with parameters. In this case, "?" is used instead
of the parameter; however, the parameter can be passed dynamically by utilizing the PREPARED
STATEMENT methods at run time.
Callable Statement: Callable Statements are stored procedures, which are a collection of
statements that we compile in the database for a specific task. They are useful when dealing with
multiple tables in a complex scenario and instead of sending multiple queries to the database, we
can send the required data to the stored procedure and reduce the logic that is executed on the
database server. The JDBC API's Callable Statement interface aids in the execution of stored
procedures.
Programming in JAVA
Syntax
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
The data is returned in a result set by SQL statements that read data from a database query. The
conventional technique to select rows from a database and view them in a result set is to use the
SELECT command.
A database query's result set is represented via the ResultSet interface.A cursor is maintained in a
ResultSet object that points to the current row in the result set. The row and column data included
in a ResultSet object are referred to as a "result set."
Caution: If one ResultSet's reading is interleaved with the reading of another, each must have
been generated by different Statements.
The following are the several types of ResultSet interface methods:
Types of ResultSet
The various RSTypes are listed here. If you don't specify a ResultSet type, you'll get one that's
TYPE_ FORWARD_ONLY by default.
ResultSet.TYPE_FORWARD_ONLY: In the result set, the cursor can only move ahead.
ResultSet.TYPE_SCROLL_INSENSITIVE:The cursor can move forward and backward in the result
set, and the result set is unaffected by changes to the database made by others after it was formed.
ResultSet.TYPE_SCROLL_SENSITIVE:The cursor can go forward and backward, and the result set
is sensitive to changes to the database made by others after it was formed.
Method Description
public boolean next() used to move the cursor to the one row next from the
current position.
public boolean previous() used to move the cursor to the one row previous from
the current position.
public boolean first() used to move the cursor to the first row in the result
set object.
public boolean last() used to move the cursor to the last row in the result
set object.
public boolean absolute(int row) used to move the cursor to the specified row number
in the ResultSet object.
public boolean relative(int row) used to move the cursor to the relative row number in
the ResultSet object, it may be positive or negative.
public int getInt(int columnIndex) used to return the data of specified column index of
the current row as int.
public int getInt(String columnName) used to return the data of specified column name of
the current row as int.
public String getString(int used to return the data of specified column index of
columnIndex) the current row as String.
public String getString(String used to return the data of specified column name of
columnName) the current row as String.
Example:
package db_console;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
Programming in JAVA
/**
*
* @author Harjinder Kaur
*/
public class DB_Connect {
city=Bombay
Syntax:
public DatabaseMetaDatagetMetaData()throws SQLException.
Example
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package db_console;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
Programming in JAVA
import java.sql.SQLException;
/**
*
* @author Harjinder Kaur
*/
public class DBMetaExa {
public static void main(String args[]){
try{
//Class.forName("oracle.jdbc.driver.OracleDriver");
Connectioncon=DriverManager.getConnection("jdbc:derby://localhost:1527/DBStudent","Sha
llu","Shallu");
DatabaseMetaDatadbmd=con.getMetaData();
System.out.println("Driver Name: "+dbmd.getDriverName());
System.out.println("Driver Version: "+dbmd.getDriverVersion());
System.out.println("UserName: "+dbmd.getUserName());
System.out.println("Database Product Name: "+dbmd.getDatabaseProductName());
System.out.println("Database Product Version: "+dbmd.getDatabaseProductVersion());
System.out.println("Numeric functions:" +dbmd.getNumericFunctions());
String tab[]={"TABLE"};
ResultSetrs=dbmd.getTables(null,null,null,tab);
while(rs.next()){
System.out.println(rs.getString(3));
}
con.close();
}catch(SQLException e){ System.out.println(e);}
}
}
Output
Driver Name: Apache Derby Network Client JDBC Driver
Driver Version: 10.11.1.2 - (1629631)
UserName: Shallu
Database Product Name: Apache Derby
Database Product Version: 10.10.2.0 - (1582446)
Numeric
functions:ABS,ACOS,ASIN,ATAN,ATAN2,CEILING,COS,COT,DEGREES,EXP,FLOOR,LOG,L
OG10,MOD,PI,RADIANS,RAND,SIGN,SIN,SQRT,TAN
TBSTU
Summary
JDBC stands for Java Database Connectivity, which is a standard Java API for database-
independent connectivity between the Java programming language and a wide range of
databases.
The JDBC API uses a driver manager and database-specific drivers to provide transparent
connectivity to heterogeneous databases.
PreparedStatements have the added benefit of preventing SQL injection attacks.
The DatabaseMetaData interface provides methods for obtaining information about the
database you've connected to.
The row and column data included in a ResultSet object are referred to as a "result set."
The statement interface is a ResultSet factory, which means it provides factory methods for
getting a ResultSet object.
If you don't specify a ResultSet type, you'll get one that's TYPE_ FORWARD_ONLY by
default.
Keywords
Prepared Statement: The term "prepared statement" refers to a recompiled SQL statement that can
be used several times.
Statement: The Statement interface provides methods for executing database queries.
getDriverVersion(): It returns the version number of the JDBC driver.
getInt(String columnName): It is used to return the data of the specified column name of the
current row as int.
ResultSet.TYPE_SCROLL_SENSITIVE: The cursor can go forward and backward, and the result set
is sensitive to changes to the database made by others after it was formed.
Update methods:Update methods are used to update the data in the current row's columns.
Callable Statement: Callable Statements are stored procedures, which are a collection of statements
that we compile in the database for a specific task.
Self Assessment
1. Preparedstatement Object in JDBC is used to execute___________queries.
A. executable
B. simple
C. high level
D. parameterized
2. Which of the following is the statement that permits the storage of large objects in the
database?
A. Callable statement
B. Object statement
C. Prepared statement
D. None
A. Statement
B. Connection
C. Layout
D. Network
Programming in JAVA
A. prepare call
B. prepare statement
C. create statement
D. none of the above
A. setInt(int, int)
B. setString(int, string)
C. setFloat(int, float)
D. setLength(int)
6. ResultSetMetaData interface is useful because it provides methods to get metadata from the
ResultSet object.
A. True
B. False
C. Cant'say
D. May be
A. getcolumnCount()
B. getcolumncount()
C. getColumnCount()
D. getColumncount()
A. createStatement
B. insertStatement
C. updateStatement
D. All of the above
A. execute(String url)
B. executeQuery(String url)
C. executeUpdate(String url)
D. All of the above
A. Column
B. Row
C. Table
D. None of the above
11. The interface ResultSet has a method, getMetaData(), that returns a/an
A. Tuple
B. Value
C. Object
D. Result
12. Which of the following means that the ResultSet can only be read?
A. ResultSet.CONCUR_READ_ONLY
B. ResultSet.CONCUR_UPDATABLE
C. ResultSet.READ_ONLY
D. ResultSet.UPDATABLE
A. Statement
B. Prepared Statement
C. Callable Statement
D. All of the above
A. getuserName()
B. getUserName()
C. getusername()
D. All of the above
6. A 7. C 8. A 9. D 10. B
Review Questions
1. Define the concept of JDBC. Discuss in detail the various types of statements available in
JDBC.
Programming in JAVA
2. How Statement is different from the PreparedStatement interface? What is the benefit of
using PreparedStatement in Java?
3. What is the significance of using DatabaseMetaData interface? Explain the various
methods of DatabaseMetaData interface with the help of an appropriate example.
4. Explain the concept of ResultSet. Discuss the different types of ResultSet by giving the
example of each.
5. What happens if we call resultSet.getInt(0) when Select query result just have one column
of integer type with the help of an appropriate example?
6. With example elucidate the different methods used to view the data using ResultSet.
Explain the various methods of ResultSet?
7. Write a note on the following:
a) PreparedStatement.
b) ResultSet.
c) JDBC
Further Readings
Patel, P., & Moss, K. (1997). Java database programming with JDBC (pp. 5-8). Coriolis
Group Books.
Keogh, J. (2003). J2ME: The complete reference. Osborne.
Reese, G. (2003). Java Database Best Practices: Persistence Models and Techniques for Java
Database Programming. " O'Reilly Media, Inc.".
Reese, G. (2000). Database Programming with JDBC and JAVA. " O'Reilly Media, Inc.".
Thomas, T. M., & Books, M. T. (2002). Java data access: JDBC, JNDI, and JAXP. M & T
Books.
Web Links
https://www.mysqltutorial.org/jdbc-overview/
https://docs.oracle.com/javase/tutorial/jdbc/overview/index.html
http://tutorials.jenkov.com/jdbc/resultset.html
https://www.softwaretestinghelp.com/jdbc-resultset-tutorial/
https://www.geeksforgeeks.org/establishing-jdbc-connection-in-java/
https://www.ibm.com/docs/en/b2b-integrator/5.2?topic=l-java-database-connectivity-
jdbc-adapter-v523-later
Objectives
• Know the basic concept of Java Networking and its various terminologies
• Understand the various classes used in networking
• Learn the concept of Socket, ServerSocketclass, its methods, and applications
Introduction
Java networking refers to the concept of linking two or more computing devices to exchange
resources. At the application layer, Java software communicates via the network. All Java
networking classes and interfaces can be found in the java.net package.
Two protocols are supported by the java.net package. The following are the details:
TCP: TCP (Transmission Control Protocol) is a protocol that allows two programs to communicate
reliably. TCP is most commonly used with TCP/IP, which stands for Transmission Control
Protocol/Internet Protocol.
UDP: The User Datagram Mechanism (UDP) is a connectionless protocol for sending data packets
between applications.
Note: Java networking is mostly used for resource sharing and centralized software
management.
13.1 Networking
Network programming refers to writing programs that execute across multiple devices
(computers), in which the devices are connected via a
network. Java encapsulates classes and interfaces to allow low-level communication details. Java
Networking is a concept of connecting two or more computing devices so that we can share
resources.Java program communicates over the network at the application layer. The java.net
package is useful for all the Java networking classes and interfaces.
Programming in JAVA
Example: TCP,F,TP,Telnet,SMTP
• Port Number: The port number is used to uniquely identify different applications. It acts
as a communication endpoint between applications. The port number is associated with
the IP address for communication between two applications.
• MAC Address: MAC (Media Access Control) address is a unique identifier of NIC
(Network Interface Controller). A network node can have multiple NICs but each with a
unique MAC address.
InetAddress
Inet Address is used to encapsulate both the numerical IP address and the domain name for that
address. It can handle both IPv4 and Ipv6 addresses. The Figure 1 depicts the subclasses of the Inet
Address class.Three commonly used Inet Address factory methods are.
static InetAddress getLocalHost() throws UnknownHostException.
static InetAddressgetByName (String hostname) throws UnknownHostException.
static InetAddress[ ] getAllByName (String
hostname)throws UnknownHostException.
Example
import java.net.*;
class Demo
{
public static void main(String[] args) throws UnknownHostException
{
InetAddress address = InetAddress.getLocalHost();
System.out.println(address);
address = InetAddress.getByName("www.google.com");
System.out.println(address);
}}
Output
PS C:\Users\Harjinder Kaur\OneDrive\Documents\cap615>javac Demo.java
PS C:\Users\Harjinder Kaur\OneDrive\Documents\cap615> java Demo
LAPTOP-QBKBNCCF/192.168.1.4
www.google.com/142.250.206.132
A socket is bound to a port number so that the TCP layer can identify the application that data is
destined to be sent to.An endpoint is a combination of an IP address and a port number. The
package in the Java platform provides a class, Socket that implements one side of a two-way
connection between your Java program and another program on the network.The class sits on top
of a platform-dependent implementation, hiding the details of any particular system from your
Java program. By using the class instead of relying on native code, your Java programs can
communicate over the network in a platform-independent fashion.
Programming in JAVA
Socket Class
The java.net.Socket class allows us to create socket objects that help us in implementing all
fundamental socket operations. We can perform various networking operations such as sending,
reading data, and closing connections.Each Socket object that has been created using with
java.net.Socket class has been associated exactly with 1 remote host.For connecting to another
different host, we must create a new socket object.The syntax for importing Socket class from
java.net package :
import java.net.Socket;
The following are the methods used in socket class:
public InputStreamgetInputStream() :returns the InputStream attached with this socket.
public OutputStreamgetOutputStream() :returns the OutputStream attached with this
socket.
public synchronized void close() : closes this socket
Client-Side Programming
In the case of client-side programming, The client will first wait for the server to start. Once the
server is up and running, it will send the requests to the server. After that, the client will wait for
the response from the server.So, this is the whole logic of client and server communication.
Here, the first argument represents the IP address of the Server. The second argument
represents the TCP Port. (It is a number that represents which application should run on a
server.)
Here, the first argument represents the IP address of the Server.
The second argument represents the TCP Port. (It is a number that represents which
application should run on a server.)
• Communication: To communicate over a socket connection, streams are used for both
input and output the data. After establishing a connection and sending the requests, you
need to close the connection.
• Closing the connection:The socket connection is closed explicitly once the message to the
server is sent.
The Socket class is used for the creation of a socket and connecting to the specified remote
address on the specified remote port in javax.net.
In javax.ssl.net, the Socket class is used to return a socket layered over an existing socket
connected to the named host at a given port.
In java.nio.channels, Socket class is used for retrieving a socket associated with its channel
SocketChannel.socket()
Programming in JAVA
Server-Side Program
Server-side, a two-socket is required for better communication with the client. When a client opens
a new Socket, the first socket is merely used to wait for the client's request ().And there's a simple
old socket for communicating with the client. The remainder of the steps are the same, but we
utilized the getOutputStream() method on the socket side to send the output.
Example
// SimpleServer.java: A simple server program.
import java.net.*;
import java.io.*;
public class SimpleServer {
public static void main(String args[]) throws IOException {
// Register service on port 1254
ServerSocket s = new ServerSocket(1254);
Socket s1=s.accept(); // Wait and accept a connection
// Get a communication stream associated with the socket
OutputStream s1out = s1.getOutputStream();
DataOutputStream dos = new DataOutputStream (s1out);
// Send a string!
dos.writeUTF("Message from Server Side");
// Close the connection, but not the server socket
dos.close();
s1out.close();
s1.close();
}
}
Example
// SimpleClient.java: A simple client program.
import java.net.*;
import java.io.*;
public class SimpleClient {
public static void main(String args[]) throws IOException {
// Open your connection to a server, at port 1254
Socket s1 = new Socket("localhost",1254);
// Get an input file handle from the socket and read the input
InputStream s1In = s1.getInputStream();
DataInputStream dis = new DataInputStream(s1In);
String st = new String (dis.readUTF());
System.out.println(st);
// When done, just close the connection and exit
dis.close();
s1In.close();
s1.close();
}
}
Output
To get the output you have to open two command prompts simultaneously. First, you have to
execute the ServerSocket class then Socket class is only the connection is established between client
and server and you will get the desired output.
Programming in JAVA
Example: https://www.google.com/what-is-java
Protocol — The protocol subpart of the URL specifies the protocol name, which in this case is
HTTPS.
Hostname - The hostname, also known as the IP address or server name, is the name of the
computer or server, as in www.google.com.
Port Number - The URL's port number is an optional component that gives the logical address of
any resource that communicates over the Internet. Because we don't have the port number, each
resource is assigned a 16-bit integer port number. It returns -1 if the port number is not present.
File Name — The pathname to a resource or file on the server is specified by the file name, which in
this case is "what-is-java."
Example
// Java program to demonstrate working of URL
import java.net.MalformedURLException;
import java.net.URL;
public class URLExample
{
public static void main(String[] args)throws MalformedURLException
{
// creates a URL with string representation.
URL url1 =new URL("https://ums.lpu.in/lpuums/home");
Summary
Java Networking is a notion of combining two or more computing devices to share
resources.
Socket classes are used to represent the connection between a client program and a server
program.
ServerSocketclass is used for providing system-independent implementation of the server-
side of a client/server Socket Connection.
The address of a resource on the World Wide Web is specified by the URL. The URL is a
one-of-a-kind way to access things on the Internet.
The java.net package provides two classes--Socket and ServerSocket--that implement the
client-side of the connection and the server-side of the connection, respectively.
When the client creates its socket object, it specifies the address of the server process,
namely, the IP address of the server and the port number of the process.
Keywords
Hostname:The name of the machine or server is specified by the hostname, IP address, or server
name of the URL.
TCP:The Transmission Control System (TCP) is a widely used data transmission protocol that
supports client/server endpoints on a network.
Programming in JAVA
UDP: The User Datagram Mechanism (UDP) is a connectionless protocol for sending data packets
between applications.
Connection-oriented sockets: They operate as a telephone: they must establish a connection and
then hang up. Everything that flows between these two events arrives in the same order it was
sent.
Connectionless sockets: It operates like the mail: delivery is not guaranteed, and multiple pieces of
mail may arrive in a different order than they were sent.
Port Number: The URL's port number is an optional component that gives the logical address of
any resource that communicates over the Internet
Self Assessment
1. Which steps occur when establishing a TCP connection between two computers using
sockets?
A. The server instantiates a ServerSocket object, denoting which port number communication is
to occur on
B. The server invokes the accept() method of the ServerSocket class. This method waits until a
client connects to the server on the given port
C. After the server is waiting, a client instantiates a Socket object, specifying the server name
and port number to connect to
D. All of the above
A. HTML
B. XHTML
C. HTTP
D. All of the mentioned
3. Which of the following method returns the closed state of the socket.
A. closed()
B. isBound()
C. isClosed()
D. None of the above
A. onopen
B. readyState
C. onmessage
D. ready
A. getLocalAddress()
B. getLocalPort()
C. getLocalSocketAddress()
D. None
A. IP Address
B. Protocol
C. MAC Address
D. All mentioned above
7. Which class can be used to create a server socket. This object is used to establish
communication with the clients?
A. ServerSocket
B. Socket
C. Both A & B
D. None of the above
A. Physical Layer
B. Application Layer
C. Data Link Layer
D. All of the above
9. Which of these is a protocol for breaking and sending packets to an address across a network?
A. TCP/IP
B. DNS
C. Socket
D. Proxy Server
10. _______is the Machine that places the request to access the data.
A. Server Machine
B. Request Machine
C. Client Machine
D. None of these
A. InetAddress
B. Socket and ServerSocket Class
C. URL class
D. All of the above
Programming in JAVA
A. getLocalPort()
B. getPort()
C. getRemotePort()
D. None
A. One
B. Zero
C. Multiple
D. None
15. Name the class which is used to create a port where the server will listen?
A. Socket
B. ServerSocket
C. SocketServer
D. Datagram Socket
6. D 7. A 8. B 9. A 10. C
Review Questions
1. “Network programming refers to writing programs that execute across multiple devices, in
which the devices are connected via a network.” Justify the statement with an example.
2. Discuss the significance of using the URL class. Explain the various components and methods of
URL class by giving an example of each.
3. What is the importance of Socket class? Write a program for the implementation of the Socket
class.
4. “ServerSocket Class is used for providing system-independent implementation of the server-side
of a client/server Socket Connection.” Comment on the statement with the help of an appropriate
example.
5. Diagrammatically elaborate on the concept of networking. Elucidate the various networking
terminologies used in java.
6. Differentiate connection-oriented and connection-less sockets by giving the example of each type.
Further Readings
Graba, J. (2006). An introduction to network programming with Java (pp. I-XI).
Springer.
Harold, E. R. (2004). Java network programming. " O'Reilly Media, Inc.".
Web Links
https://docs.oracle.com/javase/tutorial/networking/sockets/index.html
https://www.edureka.co/blog/java-networking/
https://www.geeksforgeeks.org/socket-programming-in-java/
https://www.section.io/engineering-education/socket-programming-in-java/
https://www.baeldung.com/a-guide-to-java-sockets
Objectives
After this unit you will be able to:
• Understand the concept, methods, and implementation of URL and URLConnection
Class.
• Learn the basic concept DatagramSocket Class.
• Know the various constructors, methods, and implementation of DatagramSocket Class.
• Learn the basic concept of Socket programming.
• Understand the process of creating client and server.
• Implementation of Socket Programming.
Introduction
Networking is the process of sharing information and data between computing devices such as
laptops, desktops, servers, smartphones, and tablets, as well as an ever-expanding array of IoT
devices such as cameras, door locks, doorbells, refrigerators, audio/visual systems, thermostats,
and various sensors.
The term "network programming" refers to the creation of programs that run on several devices
(computers), all of which are connected via a network. A socket is one of the two ends of a two-way
communication link between two networked programs. On its end, a client application builds a
socket and attempts to connect it to a server. The server produces a socket object on its end when
the connection is established. Writing to and reading from the socket allows the client and server to
communicate.
14.1 URL
As many of you must be knowing that Uniform Resource Locator-URL is a string of text that
identifies all the resources on the Internet, telling us the address of the resource, how to
communicate with it, and retrieve something from it.
Programming in JAVA
Note: You might think of a URL like a regular postal mail address: the scheme represents the
postal service you want to use, the domain name is the city or town, and the port is like the zip
code; the path represents the building where your mail should be delivered; the parameters
represent extra information such as the number of the apartment in the building; and, finally, the
anchor represents the actual person to whom you've addressed your mail.
Example
// Java program to demonstrate the working of URL
import java.net.MalformedURLException;
import java.net.URL;
public class URLExample
{
public static void main(String[] args)throws MalformedURLException
{
// creates a URL with string representation.
URL url1 =new URL("https://ums.lpu.in/lpuums/home");
// print the string representation of the URL.
System.out.println(url1.toString());
System.out.println();
System.out.println("Different components of the URL");
System.out.println("Protocol:- " + url1.getProtocol());
System.out.println("Hostname:- " + url1.getHost());
System.out.println("Default port:- " + url1.getDefaultPort());
System.out.println("Query:- " + url1.getQuery());
System.out.println("Path:- " + url1.getPath());
System.out.println("File:- " + url1.getFile());
System.out.println("Reference:- " + url1.getRef());
}
}
Output
Programming in JAVA
HttpURLConnection: If we are connecting to any url which uses “http” as its protocol,
then HttpURLConnection class is used.
JarURLConnection: If however, we are trying to establish a connection to a jar file on the
web, then JarURLConnection is used.
Example
// Implementation of URLConnection Class
import java.io.*;
import java.net.*;
public class URLConnectionclass {
public static void main(String[] args){
try{
URL url=new URL("http://mail.google.com/mail/u/0/?ogbl#inbox");
URLConnectionurlcon=url.openConnection();
InputStream stream=urlcon.getInputStream();
int i;
while((i=stream.read())!=-1){
System.out.print((char)i);
}
}catch(Exception e){System.out.println(e);}
}
}
Output
PS C:\Users\Harjinder Kaur\OneDrive\Documents\cap615>javac URLConnectionclass.java
PS C:\Users\Harjinder Kaur\OneDrive\Documents\cap615> java URLConnectionclass
<HTML>
<HEAD>
<TITLE>Moved Permanently</TITLE>
Programming in JAVA
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Moved Permanently</H1>
The document has moved <A HREF="https://mail.google.com/mail/u/0/">here</A>.
</BODY>
</HTML>
• connect(): Connects to the specified address and port. After connecting to the remote host,
this socket can send or receive a packet from this remote host only.
• disconnect(): Disconnects the socket. If the socket is not connected, then this method has
no effect.
• isClosed(): Returns the boolean value indicating if the socket is closed or not.
• getChannel(): Returns a data channel if any associated with this socket.
• close(): Closes this datagram socket. Any pending receive call will throw
SocketException.
• setBroadcast() : Sets the value of SO_BROADCAST socket option.
• getBroadcast(): Returns true if broadcast is enabled, false otherwise.
• setReuseAddress(): Sometimes it may be necessary to bind multiple sockets to the same
address. Enabling this option enables another socket to bind to the same address as this. It
must be set before a call to bind() is made. It sets the value of the SO_REUSEADDR socket
option.
• setReceiveBufferSize(): Used to set a limit to the maximum size of the packet that is
received on this socket.
• getReceiveBufferSize(): Returns the value of SO_RCVBUF option of this socket.
• setSOTimeout(): This is used to set the waiting time for receiving a datagram packet. As a
call to receive() method blocks execution of the program indefinitely until a packet is
received, this method can be used to limit that time.
• getSoTimeout(): This is used to set the waiting time for receiving a datagram packet. As a
call to receive() method blocks execution of the program indefinitely until a packet is
received, this method can be used to limit that time.
• getLocalPort(): Returns the port on a local machine to which this socket is bound.
• getLocalAddress(): Returns the local address to which this socket is bound.
• receive(): It is used to receive the packet from a sender. When a packet is successfully
received, the buffer of the packet is filled with the received message. The packet also
contains valuable information like the sender's address and the port number. This method
waits till a packet is received.
• send(): Sends a datagram packet from this socket. It should be noted that the information
about the data to be sent, the address to which it is sent, etc are all handled by the packet
itself.
Programming in JAVA
Method Description
int getLength() It returns the length of the data to be sent or the length of
the data received.
int getOffset() It returns the offset of the data to be sent or the offset of
the data received.
int getPort() It returns the port number on the remote host to which
the datagram is being sent or from which the datagram
was received.
void setData(byte[] buff) It sets the data buffer for the packet.
void setPort(int iport) It sets the port number on the remote host to which the
datagram is being sent.
Example
//Code for DSender:
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class DSender
{
public static void main(String[] args) throws Exception
{
DatagramSocket ds = new DatagramSocket();
String str = "Implementation of Datagram Socket";
InetAddressia = InetAddress.getByName("127.0.0.1");
DatagramPacketdp = new DatagramPacket(str.getBytes(), str.length(), ia, 3000);
ds.send(dp);
ds.close();
}
}
Example
//Code for DReceiver:
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class DReceiver
{
public static void main(String[] args) throws Exception
{
DatagramSocket ds = new DatagramSocket(3000);
byte[] buf = new byte[1024];
DatagramPacketdp = new DatagramPacket(buf, 1024);
ds.receive(dp);
String strRecv = new String(dp.getData(), 0, dp.getLength());
System.out.println(strRecv);
ds.close();
}
}
Output
PS C:\Users\Harjinder Kaur\OneDrive\Documents\cap615\programs>javac DReceiver.java
PS C:\Users\Harjinder Kaur\OneDrive\Documents\cap615\programs> java DReceiver
Implementation of Datagram Socket
PS C:\Users\Harjinder Kaur\OneDrive\Documents\cap615\programs>javac DSender.java
PS C:\Users\Harjinder Kaur\OneDrive\Documents\cap615\programs> java DSender
– IP Address of Server
– Port number.
Creating Server
To create the server application, we need to create the instance of ServerSocket class. Here, we are
using the 9999 port number for the communication between the client and server. You may also
choose any other port number. The accept() method waits for the client. If the client connects with
the given port number, it returns an instance of Socket.
ServerSocket ss=new ServerSocket(9999);
Programming in JAVA
Here, we are going to make one-way client and server communication. In this application, the client
sends a message to the server, the server reads the message and prints it. Here, two classes are
being used: Socket and ServerSocket. The Socket class is used to communicate client and server.
Through this class, we can read and write a message. The ServerSocket class is used at the server-
side. The accept() method of ServerSocket class blocks the console until the client is connected.
After the successful connection of the client, it returns the instance of Socket at the server-side.
Caution: When developing a proprietary application, the developer must be careful not to use
one of the well-known port numbers defined in the RFCs.
Creating Client
To create the client application, we need to create the instance of the Socket class. Here, we need to
pass the IP address or hostname of the Server and a port number.
Socket s=new Socket("localhost",9999); Here, we are using "localhost" because our server is
running on same system.
Example
// Implementation of socket client side
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6060);
DataOutputStreamdout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Connected to Server");
dout.flush();
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
}
}
Example
//Implementation of socket on server
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6060);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}
}
Output
PS C:\Users\Harjinder Kaur\OneDrive\Documents\cap615\programs>javac MyServer.java
PS C:\Users\Harjinder Kaur\OneDrive\Documents\cap615\programs> java MyServer
PS C:\Users\Harjinder Kaur\OneDrive\Documents\cap615\programs>javac MyClient.java
PS C:\Users\Harjinder Kaur\OneDrive\Documents\cap615\programs> java MyClient
message= Connected to Server
Summary
URLConnection is the superclass of all the classes that represent a communication link
between the application and a URL.
The java.net.URL class represents a URL and has a complete set of methods to manipulate
URLs in Java.
Socket programming is a means of communicating data between two computers across a
network.
Java DatagramSocket and DatagramPacket classes are used for connection-less socket
programming using the UDP instead of TCP.
Programming in JAVA
The DatagramPacket classes and DatagramSocket are used for connection-less socket
programming.
A URL class represents a Uniform Resource Locator, which is a pointer to a “resource”
on the World Wide Web.
Keywords
Socket: One endpoint of a two-way communication link between two programs that are running on
anetwork.
TCP:Transmission Control Protocol (TCP) is a widely used protocol for data transmission on a
network that supports client/server endpoints.
DatagramSocket: A datagram socket is the sending or receiving point for a packet delivery service.
Each packet sent or received on a datagram socket is individually addressed and routed.
URL:URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource
on the Internet.
DatagramPacket: DatagramPacket is a message that can be sent or received. If you send multiple
packets, they may arrive in any order.
Self Assessment
1. Which of these exceptions is thrown by the URL class’s constructors?
A. URLNotFound
B. URLSourceNotFound
C. MalformedURLException
D. URLNotFoundException
A. host()
B. getHost()
C. GetHost()
D. gethost()
3. Which of these transfer protocols must be used so that the URL can be accessed by the
URLConnection class object?
A. http
B. HTTPS
C. Any Protocol can be used
D. None of the mentioned
4. Which of these methods is used to know the type of content used in the URL?
A. ContentType()
B. contentType()
C. getContentType()
D. GetContentType()
5. Which method of URL class represents a URL and has the complete set of methods to
manipulate URL in Java?
A. java.net.URL
B. java.net.URLConnection
C. Both A & B
D. None of the above
6. The URLConnection class can be used to read and write data to the specified resource
referred to by the URL
A. True
B. False
C. Cant'say
D. May be
A. getAuthority()
B. toString()
C. getQuery()
D. All of the above.
A. getContentLength()
B. getDate()
C. getHeaderField(int i)
D. All
A. java.io
B. java.util
C. java.net
D. java.network
10. To create the server application, we need to create the instance of ____________class.
A. ServerSocket
B. Socket
C. Server
D. ServerReader
A. Socket
B. IP Address
C. Protocol
D. MAC Address
Programming in JAVA
A. Socket
B. IP Address
C. Protocol
D. MAC Address
A. InetAddress
B. Address
C. IP Address
D. TCP Address
14. Which constructor of the Datagram Socket class is used to create a datagram socket and
binds it with the given Port Number?
A. Datagram Socket
B. Datagram Packet
C. Both Datagram Socket & Datagram Packet
D. Server Socket
6. A 7. A 8. D 9. C 10. A
Review Questions
1. “The URL class is the gateway to any of the resources available on the internet.” Comment on
the statement by explaining the different components of the URL.
2. Differentiate between DatagramSocket and DatagramPacket class. Write a program to
implement the same.
3. “The URLConnection class represents a communication link between the URL and the
application.” Justify the statement by giving the different types of URLConnection class along with
its various methods.
4. What is the significance of socket programming. How we establish a connection between client
and server using socket programming.
5. With the help of an appropriate example differentiate between URL and URLConnection class.
6. Explain the difference in working of TCP and UDP with the help of an example.
Further Readings
Graba, J. (2006). An introduction to network programming with Java (pp. I-XI).
Springer.
Ciubotaru, B., &Muntean, G. M. (2013). Advanced Network Programming–Principles
and Techniques: Network Application Programming with Java. Springer Science &
Business Media.
Calvert, K. L., &Donahoo, M. J. (2011). TCP/IP sockets in Java: a practical guide for
programmers. Morgan Kaufmann.
Calvert, K. L., &Donahoo, M. J. (2011). TCP/IP sockets in Java: a practical guide for
programmers. Morgan Kaufmann.
Calvert, K. L., &Donahoo, M. J. (2011). TCP/IP sockets in Java. Morgan Kaufmann
Publishers.
Donahoo, M. J., & Calvert, K. L. (2009). TCP/IP sockets in C: a practical guide for
programmers. Morgan Kaufmann.
Web Links
https://codezup.com/socket-programming-client-and-server-in-java-example/
https://www.javatpoint.com/socket-programming
https://www.section.io/engineering-education/socket-programming-in-java/
https://docs.oracle.com/javase/8/docs/api/java/net/URLConnection.html