Java Notes
Java Notes
Variables - primitive data types – identifiers - naming conventions – keywords – literals – operators –
binary - unary and ternary – expression - precedence rules and associativity - primitive type conversion
and casting - flow of control – arrays- command line arguments.
UNIT-IV MULTITHREADING 9
The main thread - creation of new threads - thread priority – multithreading - using is Alive () and join
() – Synchronization - suspending and resuming threads - communication between threads - reading
and writing data.
Threads – Thread states – Interrupting threads – Thread communication - Networking basics – Java
and the Net - InetAddress –- TCP/IP Server Sockets – Remote Method Invocation – A simple
client/server application using RMI.
TEXT BOOK :
REFERENCES:
2 Peter Haggar, “Practical Java Programming Language Guide”, Addison Wesley, 2000.
3 Daniel Liang Y, “An Introduction to Java Programming”, PHI pvt ltd, 2003.
UNIT - 1
Introduction to OOPS :
OOP stands for Object-Oriented Programming. In Java, everything is based on the object. Java
has a root class called Object from which the entire functionality of Java is derived.
OOP language supports the following features:
• Classes
• Encapsulation
• Abstraction
• Inheritance
• Polymorphism
Abstraction: OOP allows developers to abstract complex real-world concepts into simpler,
more manageable objects. This allows for a more modular and flexible software design, where
individual objects can be modified and updated independently of the rest of the system.
Encapsulation: OOP allows developers to encapsulate data and behaviour within an object.
This protects the internal state of an object from outside interference, ensuring that the object
operates correctly and consistently.
Inheritance: OOP supports inheritance, which allows developers to create new classes that
inherit properties and behaviour from existing classes. This saves time and effort when creating
new classes, as developers can reuse code that has already been written.
Polymorphism: OOP supports polymorphism, which allows developers to create objects that
can take on multiple forms. This means that a single method can be used to operate on different
objects, simplifying code and making it more reusable.
What is Java?
Java is a programming language and a platform. Java is a high level, robust, object-oriented
and secure programming language.
Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year
1995. James Gosling is known as the father of Java. Before Java, its name was Oak. Since Oak
was already a registered company, so James Gosling and his team changed the name from Oak
to Java.
Platform: Any hardware or software environment in which a program runs, is known as a
platform. Since Java has a runtime environment (JRE) and API, it is called a platform.
Application
According to Sun, 3 billion devices run Java. There are many devices where Java is currently
used. Some of them are as follows:
1. Desktop Applications such as acrobat reader, media player, antivirus, etc.
2. Web Applications such as [Link], [Link], etc.
19CS14403 : JAVA PROGRAMMING 4
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games, etc.
History of Java :
Java is a general-purpose, high-level programming language that was created by James Gosling
at Sun Microsystems (later acquired by Oracle) in the mid-1990s. Here is a brief history of
Java:
• Creation: In 1991, James Gosling, Mike Sheridan, and Patrick Naughton created a new
programming language called "Oak" for use in small consumer electronics devices. Oak was
later renamed "Java" and was released publicly in 1995.
• Early years: In the mid-1990s, Java gained popularity as a programming language for building
interactive web applications. The introduction of the Java applet allowed developers to create
rich, interactive content for the web.
• Standardization: In 1997, Sun Microsystems released the first version of the Java
Development Kit (JDK), which included the Java Virtual Machine (JVM) and a set of core
libraries. This enabled developers to write programs in Java that could run on any platform
with a JVM.
19CS14403 : JAVA PROGRAMMING 5
• Today, Java remains one of the most popular programming languages in the world, with a
large and active developer community. It is widely used for building enterprise applications,
mobile apps, games, and web applications, among other things.
JVM :
Java Virtual Machine (JVM) is a software that provides a runtime environment for Java
programs. It is a virtual machine that runs on top of the physical machine (computer hardware)
and is responsible for executing Java bytecode, which is compiled from Java source code.
Java Features :
The primary objective of Java programming language creation was to make it portable, simple
and secure programming language. Apart from this, there are also some excellent features
which play an important role in the popularity of this language. The features of Java are also
known as Java buzzwords.
A list of the most important features of the Java language is given below.
• Simple
• Object-Oriented
• Portable
• Platform independent
• Secured
• Robust
• Architecture neutral
• Interpreted
• High Performance
• Multithreaded
• Distributed
• Dynamic
Structured programming:
It is a programming paradigm aimed at improving the clarity, quality, and development time
of a computer program by making extensive use of the structured control flow constructs of
selection (if/then/else) and repetition (while and for), block structures, and subroutines.
First Java Program | Hello World Example
19CS14403 : JAVA PROGRAMMING 6
In this section, we will learn how to write the simple program of Java. We can write a simple
hello Java program easily after installing the JDK.
To create a simple Java program, you need to create a class that contains the main method.
Let's understand the requirement first.
The requirement for Java Hello World Example
For executing any Java program, the following software or application must be properly
installed.
o Install the JDK if you don't have installed it, download the JDK and install it.
o Set path of the jdk/bin directory. Create the Java program
o Compile and run the Java program
Output:
Hello Java
Compilation Flow:
When we compile Java program using javac tool, the Java compiler converts the source code
into byte code.
Parameters used in First Java Program
Let's see what is the meaning of class, public, static, void, main, String[], [Link]().
o class keyword is used to declare a class in Java.
o public keyword is an access modifier that represents visibility. It means it is visible to
all.
o static is a keyword. If we declare any method as static, it is known as the static method.
The core advantage of the static method is that there is no need to create an object to
invoke the static method. The main() method is executed by the JVM, so it doesn't
require creating an object to invoke the main() method. So, it saves memory.
o void is the return type of the method. It means it doesn't return any value.
o main represents the starting point of the program.
19CS14403 : JAVA PROGRAMMING 7
o String[] args or String args[] is used for command line argument. We will discuss it
in coming section.
o [Link]() is used to print statement. Here, System is a class, out is an object
of the PrintStream class, println() is a method of the PrintStream class. We will discuss
the internal working of [Link]() statement in the coming section.
UNIT - 2
Variables and data types:
19CS14403 : JAVA PROGRAMMING 8
Variables are containers for storing data values.
In Java, there are different types of data types for storing the variables, for example:
• int - stores integers (whole numbers), without decimals, such as 123 or -123
• float - stores floating point numbers, with decimals, such as 19.99 or -19.99
• char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
• String - stores text, such as "Hello". String values are surrounded by double quotes
• boolean - stores values with two states: true or false
Identifiers :
All Java variables must be identified with unique names.
These unique names are called identifiers.
Identifiers can be short names (like x and y) or more descriptive names (age, sum, total
Volume).
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware that the
variable exists.
But, it is not forced to follow. So, it is known as convention not rule. These conventions are
suggested by several Java communities such as Sun Microsystems and Netscape.
All the classes, interfaces, packages, methods and fields of Java programming language are
given according to the Java naming convention. If you fail to follow these conventions, it may
generate confusion or erroneous code.
Literal:
Any constant value which can be assigned to the variable is called literal/constant.
In simple words, Literals in Java is a synthetic representation of boolean, numeric, character,
or string data.
Java Operators:
Operators are used to perform operations on variables and values.
Java divides the operators into the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Bitwise operators
Unary Operators:
A unary operator is an operator that operates on a single operand. An operand can be a value
or an expression.
19CS14403 : JAVA PROGRAMMING 11
For example: a++
Binary Operators
Binary operator operates on two operands. Arithmetic operators are examples of binary
operators.
Operator precedence defines the order in which a given mathematical expression is evaluated.
When an expression includes multiple operators then every single part of the given expression
is evaluated in a certain order following some rules defined as per operator precedence. The
higher precedence is evaluated first and the lowest precedence is evaluated last.
Java Operator Associativity:
With the same precedence follow operator associativity defined for their operator group. In
Java, operators can either follow left-associative, right-associative, or have no associativity.
Operators with left-associative are evaluated from the left to right, operators with right-
associative are evaluated from right to the left, and with no associativity, do not follow any
predefined order.
1) Simple if statement:
It is the most basic statement among all control flow statements in Java. It evaluates a Boolean
expression and enables the program to enter a block of code if the expression evaluates to true.
Syntax of if statement is given below.
1. if(condition) {
2. statement 1; //executes when condition is true
3. }
Consider the following example in which we have used the if statement in the java code.
[Link]
[Link]
1. public class Student {
2. public static void main(String[] args) {
3. int x = 10;
4. int y = 12;
5. if(x+y > 20) {
6. [Link]("x + y is greater than 20");
7. }
8. }
9. }
Output:
x + y is greater than 20
2) if-else statement
The if-else statement is an extension to the if-statement, which uses another block of code, i.e.,
else block. The else block is executed if the condition of the if-block is evaluated as false.
19CS14403 : JAVA PROGRAMMING 13
Syntax:
1. if(condition) {
2. statement 1; //executes when condition is true
3. }
4. else{
5. statement 2; //executes when condition is false
6. }
Consider the following example.
[Link]
1. public class Student {
2. public static void main(String[] args) {
3. int x = 10;
4. int y = 12;
5. if(x+y < 10) {
6. [Link]("x + y is less than 10");
7. } else {
8. [Link]("x + y is greater than 20");
9. }
10. }
11. }
Output:
x + y is greater than 20
3) if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements. In
other words, we can say that it is the chain of if-else statements that create a decision tree where
the program may enter in the block of code where the condition is true. We can also define an
else statement at the end of the chain.
Syntax of if-else-if statement is given below.
1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. }
4. else if(condition 2) {
5. statement 2; //executes when condition 2 is true
6. }
7. else {
8. statement 2; //executes when all the conditions are false
9. }
Consider the following example.
[Link]
1. public class Student {
2. public static void main(String[] args) {
3. String city = "Delhi";
4. if(city == "Meerut") {
19CS14403 : JAVA PROGRAMMING 14
5. [Link]("city is meerut");
6. }else if (city == "Noida") {
7. [Link]("city is noida");
8. }else if(city == "Agra") {
9. [Link]("city is agra");
10. }else {
11. [Link](city);
12. }
13. }
14. }
Output:
Delhi
4. Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement inside another if or
else-if statement.
1. switch (expression){
2. case value1:
3. statement1;
4. break;
5. .
6. .
7. .
8. case valueN:
9. statementN;
10. break;
11. default:
12. default statement;
13. }
Consider the following example to understand the flow of the switch statement.
[Link]
Consider the following example to understand the proper functioning of the for loop in java.
19CS14403 : JAVA PROGRAMMING 17
[Link]
1. public class Calculattion {
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int sum = 0;
5. for(int j = 1; j<=10; j++) {
6. sum = sum + j;
7. }
8. [Link]("The sum of first 10 natural numbers is " + sum);
9. }
10. }
Output:
The sum of first 10 natural numbers is 55
Java for-each loop
Java provides an enhanced for loop to traverse the data structures like array or collection. In
the for-each loop, we don't need to update the loop variable. The syntax to use the for-each
loop in java is given below.
1. for(data_type var : array_name/collection_name){
2. //statements
3. }
Consider the following example to understand the functioning of the for-each loop in Java.
[Link]
1. public class Calculation {
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. String[] names = {"Java","C","C++","Python","JavaScript"};
5. [Link]("Printing the content of the array names:\n");
6. for(String name:names) {
7. [Link](name);
8. }
9. }
10. }
Output:
Printing the content of the array names:
Java
C
C++
Python
JavaScript
0
2
4
6
8
10
Java do-while loop
The do-while loop checks the condition at the end of the loop after executing the loop
statements. When the number of iteration is not known and we have to execute the loop at least
once, we can use do-while loop.
It is also known as the exit-controlled loop since the condition is not checked in advance. The
syntax of the do-while loop is given below.
1. do
2. {
3. //statements
4. } while (condition);
The flow chart of the do-while loop is given in the following image.
Consider the following example to understand the functioning of the do-while loop in Java.
[Link]
19CS14403 : JAVA PROGRAMMING 20
1. public class Calculation {
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int i = 0;
5. [Link]("Printing the list of first 10 even numbers \n");
6. do {
7. [Link](i);
8. i = i + 2;
9. }while(i<=10);
10. }
11. }
Output:
Printing the list of first 10 even numbers
0
2
4
6
8
10
Jump Statements
Jump statements are used to transfer the control of the program to the specific statements. In
other words, jump statements transfer the execution control to the other part of the program.
There are two types of jump statements in Java, i.e., break and continue.
Java break statement
As the name suggests, the break statement is used to break the current flow of the program and
transfer the control to the next statement outside a loop or switch statement. However, it breaks
only the inner loop in the case of the nested loop.
The break statement cannot be used independently in the Java program, i.e., it can only be
written inside the loop or switch statement.
The break statement example with for loop
Consider the following example in which we have used the break statement with the for loop.
[Link]
1. public class BreakExample {
2.
3. public static void main(String[] args) {
4. // TODO Auto-generated method stub
5. for(int i = 0; i<= 10; i++) {
6. [Link](i);
7. if(i==6) {
8. break;
9. }
10. }
11. }
12. }
19CS14403 : JAVA PROGRAMMING 21
Output:
0
1
2
3
4
5
6
break statement example with labeled for loop
[Link]
Arrays:
Normally, an array is a collection of similar type of elements which has contiguous memory
location.
Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure where
we store similar elements. We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element
is stored on 1st index and so on.
Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need
to use the sizeof operator.
19CS14403 : JAVA PROGRAMMING 23
Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
o Random access: We can get any data located at an index position.
Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It doesn't grow
its size at runtime. To solve this problem, collection framework is used in Java which
grows automatically.
33
3
4
5
For-each Loop for Java Array
We can also print the Java array using for-each loop. The Java for-each loop prints the array
elements one by one. It holds an array element in a variable, then executes the body of the loop.
The syntax of the for-each loop is given below:
1. for(data_type variable:array){
2. //body of the loop
3. }
Let us see the example of print the elements of Java array using the for-each loop.
1. //Java Program to print the array elements using for-each loop
2. class Testarray1{
3. public static void main(String args[]){
4. int arr[]={33,3,4,5};
5. //printing array using for-each loop
6. for(int i:arr)
7. [Link](i);
8. }}
Output:
33
19CS14403 : JAVA PROGRAMMING 25
3
4
5
Output:
3
Anonymous Array in Java
Java supports the feature of an anonymous array, so you don't need to declare the array while
passing an array to the method.
1. arr[0][0]=1;
2. arr[0][1]=2;
3. arr[0][2]=3;
4. arr[1][0]=4;
5. arr[1][1]=5;
6. arr[1][2]=6;
7. arr[2][0]=7;
8. arr[2][1]=8;
9. arr[2][2]=9;
Example of Multidimensional Java Array
Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.
1. //Java Program to illustrate the use of multidimensional array
2. class Testarray3{
3. public static void main(String args[]){
4. //declaring and initializing 2D array
5. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
6. //printing 2D array
7. for(int i=0;i<3;i++){
8. for(int j=0;j<3;j++){
9. [Link](arr[i][j]+" ");
10. }
11. [Link]();
12. }
13. }}
Test it Now
Output:
123
245
19CS14403 : JAVA PROGRAMMING 28
445
Jagged Array in Java
If we are creating odd number of columns in a 2D array, it is known as a jagged array. In other
words, it is an array of arrays with different number of columns.
1. //Java Program to illustrate the jagged array
2. class TestJaggedArray{
3. public static void main(String[] args){
4. //declaring a 2D array with odd columns
5. int arr[][] = new int[3][];
6. arr[0] = new int[3];
7. arr[1] = new int[4];
8. arr[2] = new int[2];
9. //initializing a jagged array
10. int count = 0;
11. for (int i=0; i<[Link]; i++)
12. for(int j=0; j<arr[i].length; j++)
13. arr[i][j] = count++;
14.
15. //printing the data of a jagged array
16. for (int i=0; i<[Link]; i++){
17. for (int j=0; j<arr[i].length; j++){
18. [Link](arr[i][j]+" ");
19. }
20. [Link]();//new line
21. }
22. }
23. }
Test it Now
Output:
012
3456
78
Java command-line argument is an argument i.e. passed at the time of running the Java
program. In the command line, the arguments passed from the console can be received in the
java program and they can be used as input. The users can pass the arguments during the
execution bypassing the command-line arguments inside the main() method.
We need to pass the arguments as space-separated values. We can pass both strings and
primitive data types(int, double, float, char, etc) as command-line arguments. These arguments
convert into a string array and are provided to the main() function as a string array argument.
19CS14403 : JAVA PROGRAMMING 29
When command-line arguments are supplied to JVM, JVM wraps these and supplies them to
args[]. It can be confirmed that they are wrapped up in an args array by checking the length of
args using [Link].
Internally, JVM wraps up these command-line arguments into the args[ ] array that we pass
into the main() function. We can check these arguments using [Link] method. JVM stores
the first command-line argument at args[0], the second at args[1], the third at args[2], and so
on.
Simple example of command-line argument in java
In this example, we are receiving only one argument and printing it. To run this java program, you
must pass at least one argument from the command prompt.
1. class CommandLineExample{
2. public static void main(String args[]){
3. [Link]("Your first argument is: "+args[0]);
4. }
5. }
1. compile by > javac [Link]
2. run by > java CommandLineExample sonoo
Example of command-line argument that prints all the values
In this example, we are printing all the
arguments passed from the command-line. For
this purpose, we have traversed the array using
for loop.
1. class A{
2. public static void main(String args[]){
3.
4. for(int i=0;i<[Link];i++)
5. [Link](args[i]);
6.
7. }
8. }
1. compile by > javac [Link]
2. run by > java A sonoo jaiswal 1 3 abc
Output: sonoo
jaiswal
1
3
abc
19CS14403 : JAVA PROGRAMMING 30
UNIT-III
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviours of a parent object. It is an important part of OOPs (Object Oriented programming
system).
The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields of
the parent class. Moreover, you can add new methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-
child relationship.
As displayed in the above figure, Programmer is the subclass and Employee is the superclass.
The relationship between the two classes is Programmer IS-A Employee. It means that
Programmer is a type of Employee.
1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. [Link]("Programmer salary is:"+[Link]);
9. [Link]("Bonus of Programmer is:"+[Link]);
10. }
11. }
Test it Now
Programmer salary is:40000.0
Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.
barking...
eating...
Multilevel Inheritance Example
When there is a chain of inheritance, it is known as multilevel inheritance. 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.
File: [Link]
1. class Animal{
2. void eat(){[Link]("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){[Link]("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){[Link]("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. [Link]();
14. [Link]();
15. [Link]();
16. }}
Output:
weeping...
barking...
eating...
Hierarchical Inheritance Example
When two or more classes inherits a single class, it is known as hierarchical inheritance. In
the example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical
inheritance.
File: [Link]
1. class Animal{
2. void eat(){[Link]("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){[Link]("barking...");}
6. }
7. class Cat extends Animal{
19CS14403 : JAVA PROGRAMMING 34
8. void meow(){[Link]("meowing...");}
9. }
10. class TestInheritance3{
11. public static void main(String args[]){
12. Cat c=new Cat();
13. [Link]();
14. [Link]();
15. //[Link]();//[Link]
16. }}
Output:
meowing...
eating...
An interface in Java is a blueprint of a class. It has static constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body. It is used to achieve abstraction and
multiple inheritance in Java.
19CS14403 : JAVA PROGRAMMING 35
In other words, you can say that interfaces can have abstract methods and variables. It cannot
have a method body.
Java Interface also represents the IS-A relationship.
It cannot be instantiated just like the abstract class.
Since Java 8, we can have default and static methods in an interface.
Output:
Hello
Java Interface Example: Drawable
In this example, the Drawable interface has only one method. Its implementation is provided
by Rectangle and Circle classes. In a real scenario, an interface is defined by someone else, but
its implementation is provided by different implementation providers. Moreover, it is used by
someone else. The implementation part is hidden by the user who uses the interface.
File: [Link]
19CS14403 : JAVA PROGRAMMING 37
1. //Interface declaration: by first user
2. interface Drawable{
3. void draw();
4. }
5. //Implementation: by second user
6. class Rectangle implements Drawable{
7. public void draw(){[Link]("drawing rectangle");}
8. }
9. class Circle implements Drawable{
10. public void draw(){[Link]("drawing circle");}
11. }
12. //Using interface: by third user
13. class TestInterface1{
14. public static void main(String args[]){
15. Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawable()
16. [Link]();
17. }}
Test it Now
Output:
drawing circle
Java Interface Example: Bank
Let's see another example of java interface which provides the implementation of Bank
interface.
File: [Link]
1. interface Bank{
2. float rateOfInterest();
3. }
4. class SBI implements Bank{
5. public float rateOfInterest(){return 9.15f;}
6. }
7. class PNB implements Bank{
8. public float rateOfInterest(){return 9.7f;}
9. }
10. class TestInterface2{
11. public static void main(String[] args){
12. Bank b=new SBI();
13. [Link]("ROI: "+[Link]());
14. }}
Test it Now
Output:
ROI: 9.15
19CS14403 : JAVA PROGRAMMING 38
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known
as multiple inheritance.
1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void show();
6. }
7. class A7 implements Printable,Showable{
8. public void print(){[Link]("Hello");}
9. public void show(){[Link]("Welcome");}
10.
11. public static void main(String args[]){
12. A7 obj = new A7();
13. [Link]();
14. [Link]();
15. }
16. }
Test it Now
Output:Hello
Welcome
Q) Multiple inheritance is not supported through class in java, but it is possible by an interface,
why?
As we have explained in the inheritance chapter, multiple inheritance is not supported in the
case of class because of ambiguity. However, it is supported in case of an interface because
there is no ambiguity. It is because its implementation is provided by the implementation class.
For example:
1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void print();
19CS14403 : JAVA PROGRAMMING 39
6. }
7.
8. class TestInterface3 implements Printable, Showable{
9. public void print(){[Link]("Hello");}
10. public static void main(String args[]){
11. TestInterface3 obj = new TestInterface3();
12. [Link]();
13. }
14. }
Test it Now
Output:
Hello
As you can see in the above example, Printable and Showable interface have same methods
but its implementation is provided by class TestTnterface1, so there is no ambiguity.
Interface inheritance
A class implements an interface, but one interface extends another interface.
1. interface Printable{
2. void print();
3. }
4. interface Showable extends Printable{
5. void show();
6. }
7. class TestInterface4 implements Showable{
8. public void print(){[Link]("Hello");}
9. public void show(){[Link]("Welcome");}
10.
11. public static void main(String args[]){
12. TestInterface4 obj = new TestInterface4();
13. [Link]();
14. [Link]();
15. }
16. }
Test it Now
Output:
Hello
Welcome
Java 8 Default Method in Interface
Since Java 8, we can have method body in interface. But we need to make it default method.
Let's see an example:
File: [Link]
1. interface Drawable{
19CS14403 : JAVA PROGRAMMING 40
2. void draw();
3. default void msg(){[Link]("default method");}
4. }
5. class Rectangle implements Drawable{
6. public void draw(){[Link]("drawing rectangle");}
7. }
8. class TestInterfaceDefault{
9. public static void main(String args[]){
10. Drawable d=new Rectangle();
11. [Link]();
12. [Link]();
13. }}
A class which is declared with the abstract keyword is known as an abstract class in Java. It
can have abstract and non-abstract methods (method with the body).
Before learning the Java abstract class, let's understand the abstraction in Java first.
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality
to the user.
Another way, it shows only essential things to the user and hides the internal details, for
example, sending SMS where you type the text and send the message. You don't know the
internal processing about the message delivery. instead of how it does it.
Ways to achieve Abstraction
There are two ways to achieve abstraction in java
Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the
method.
19CS14403 : JAVA PROGRAMMING 41
Example of abstract class
1. abstract class A{}
A factory method is a method that returns the instance of the class. We will learn about the
factory method later.
In this example, if you create the instance of Rectangle class, draw() method of Rectangle class
will be invoked.
File: [Link]
Abstract class and interface both are used to achieve abstraction where we can declare the
abstract methods. Abstract class and interface both can't be instantiated.
But there are many differences between abstract class and interface that are given below.
19CS14403 : JAVA PROGRAMMING 43
Abstract class Interface
1) Abstract class Interface can have only
can have abstract and abstract methods. Since
non-abstract methods. Java 8, it can have default
and static methods also.
2) Abstract class doesn't Interface supports
support multiple multiple inheritance.
inheritance.
3) Abstract class can Interface has only static
have final, non-final, and final variables.
static and non-static
variables.
4) Abstract class can Interface can't provide
provide the the implementation of
implementation of abstract class.
interface.
5) The abstract The interface keyword is
keyword is used to used to declare interface.
declare abstract class.
6) An abstract class can An interface can extend
extend another Java class another Java interface only.
and implement multiple
Java interfaces.
7) An abstract class can An interface can be
be extended using implemented using
keyword "extends". keyword "implements".
8) A Java abstract Members of a Java
class can have class interface are public by
members like private, default.
protected, etc.
9)Example: Example:
public abstract class public interface Drawable{
Shape{ void draw();
public abstract void }
draw();
}
Java Package
1. javac -d . [Link]
The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to
keep the package within the same directory, you can use . (dot).
19CS14403 : JAVA PROGRAMMING 45
How to run java package program
You need to use fully qualified name e.g. [Link] etc to run the class.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but
not subpackages.
The import keyword is used to make the classes and interface of another package accessible to
the current package.
Example of package that import the packagename.*
1. //save by [Link]
2. package pack;
3. public class A{
4. public void msg(){[Link]("Hello");}
5. }
1. //save by [Link]
2. package mypack;
3. import pack.*;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. [Link]();
9. }
10. }
Output:Hello
2) Using [Link]
If you import [Link] then only declared class of this package will be accessible.
Subpackage in java
Package inside the package is called the subpackage. It should be created to categorize the
package further.
Let's take an example, Sun Microsystem has definded a package named java that contains many
classes like System, String, Reader, Writer, Socket etc. These classes represent a particular
group e.g. Reader and Writer classes are for Input/Output operation, Socket and ServerSocket
classes are for networking etc and so on. So, Sun has subcategorized the java package into
subpackages such as lang, net, io etc. and put the Input/Output related classes in io package,
Server and ServerSocket classes in net packages and so on.
The standard of defining package is [Link] e.g. [Link] or
[Link].
Example of Subpackage
1. package [Link];
2. class Simple{
3. public static void main(String args[]){
4. [Link]("Hello subpackage");
5. }
6. }
To Compile: javac -d . [Link]
Output:Hello subpackage
1. //save as [Link]
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. [Link]("Welcome to package");
6. }
7. }
To Compile:
e:\sources> javac -d c:\classes [Link]
To Run:
To run this program from e:\source directory, you need
to set classpath of the directory where the class file
resides.
o Temporary
o By setting the classpath in the command prompt
o By -classpath switch
o Permanent
o By setting the classpath in the environment variables
o By creating the jar file, that contains all the class files, and copying the jar file
in the jre/lib/ext folder.
Rule: There can be only one public class in a java source file and it must be saved by the public
class name.
1. //save as [Link] otherwise Compilte Time Error
2.
3. class A{}
4. class B{}
5. public class C{}
1. //save as [Link]
2.
3. package javat;
4. public class A{}
1. //save as [Link]
2.
3. package javat;
4. public class B{}
There are two types of modifiers in Java: access modifiers and non-access modifiers.
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor,
or class. We can change the access level of fields, constructors, methods, and class by applying
the access modifier on it.
There are four types of Java access modifiers:
19CS14403 : JAVA PROGRAMMING 50
1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
3. Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be accessed
from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
There are many non-access modifiers, such as static, abstract, synchronized, native, volatile,
transient, etc. Here, we are going to learn the access modifiers only.
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
1) Private
The private access modifier is accessible only within the class.
Simple example of private access modifier
In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the class,
so there is a compile-time error.
1. class A{
2. private int data=40;
3. private void msg(){[Link]("Hello java");}
4. }
5.
6. public class Simple{
19CS14403 : JAVA PROGRAMMING 51
7. public static void main(String args[]){
8. A obj=new A();
9. [Link]([Link]);//Compile Time Error
10. [Link]();//Compile Time Error
11. }
12. }
Role of Private Constructor
If you make any class constructor private, you cannot create the instance of that class from
outside the class. For example:
1. class A{
2. private A(){}//private constructor
3. void msg(){[Link]("Hello java");}
4. }
5. public class Simple{
6. public static void main(String args[]){
7. A obj=new A();//Compile Time Error
8. }
9. }
Note: A class cannot be private or protected except nested class.
2) Default
If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package. It cannot be accessed from outside the package. It provides
more accessibility than private. But, it is more restrictive than protected, and public.
Example of default access modifier
In this example, we have created two packages pack and mypack. We are accessing the A class
from outside its package, since A class is not public, so it cannot be accessed from outside the
package.
1. //save by [Link]
2. package pack;
3. class A{
4. void msg(){[Link]("Hello");}
5. }
1. //save by [Link]
2. package mypack;
3. import pack.*;
4. class B{
5. public static void main(String args[]){
6. A obj = new A();//Compile Time Error
7. [Link]();//Compile Time Error
8. }
9. }
In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.
19CS14403 : JAVA PROGRAMMING 52
3) Protected
The protected access modifier is accessible within package and outside the package but
through inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It
can't be applied on the class.
It provides more accessibility than the default modifer.
Example of protected access modifier
In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this
package is declared as protected, so it can be accessed from outside the class only through
inheritance.
1. //save by [Link]
2. package pack;
3. public class A{
4. protected void msg(){[Link]("Hello");}
5. }
1. //save by [Link]
2. package mypack;
3. import pack.*;
4.
5. class B extends A{
6. public static void main(String args[]){
7. B obj = new B();
8. [Link]();
9. }
10. }
Output:Hello
4) Public
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
Example of public access modifier
1. //save by [Link]
2.
3. package pack;
4. public class A{
5. public void msg(){[Link]("Hello");}
6. }
1. //save by [Link]
2.
3. package mypack;
4. import pack.*;
19CS14403 : JAVA PROGRAMMING 53
5.
6. class B{
7. public static void main(String args[]){
8. A obj = new A();
9. [Link]();
10. }
11. }
Output:Hello
The classes String, StringBuffer, and StringBuilder similarly provide commonly used
operations on character strings.
Class Throwable encompasses objects that may be thrown by the throw statement. Subclasses
of Throwable represent errors and exceptions.
Following are a list of classes under [Link] package. I explained all the methods with lots
of examples from each class. Our suggestion is to do lots of hands experience using this
tutorial.
The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that the normal flow of the application can be maintained.
19CS14403 : JAVA PROGRAMMING 56
In this tutorial, we will learn about Java exceptions, it's types, and the difference between
checked and unchecked exceptions.
What is Exception in Java?
Dictionary Meaning: Exception is an abnormal condition.
In Java, an exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.
What is Exception Handling?
Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException,
IOException, SQLException, RemoteException, etc.
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal flow of the application.
An exception normally disrupts the normal flow of the application; that is why we need to
handle exceptions. Let's consider a scenario:
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
Suppose there are 10 statements in a Java program and an exception occurs at statement 5; the
rest of the code will not be executed, i.e., statements 6 to 10 will not be executed. However,
when we perform exception handling, the rest of the statements will be executed. That is why
we use exception handling in Java.
Do You Know?
Keyword Description
1. String s=null;
2. [Link]([Link]());//NullPointerException
3) A scenario where NumberFormatException occurs
If the formatting of any variable or number is mismatched, it may result into
NumberFormatException. Suppose we have a string variable that has characters; converting
this variable into digit will cause NumberFormatException.
1. String s="abc";
2. int i=[Link](s);//NumberFormatException
4) A scenario where ArrayIndexOutOfBoundsException occurs
When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may
be other reasons to occur ArrayIndexOutOfBoundsException. Consider the following
statements.
1. int a[]=new int[5];
2. a[10]=50; //ArrayIndexOutOfBoundsException
Java try-catch block
The JVM firstly checks whether the exception is handled or not. If exception is not handled,
JVM provides a default exception handler that performs the following tasks:
o Prints out exception description.
19CS14403 : JAVA PROGRAMMING 61
o Prints the stack trace (Hierarchy of methods where the exception occurred).
o Causes the program to terminate.
But if the application programmer handles the exception, the normal flow of the application is
maintained, i.e., rest of the code is executed.
Problem without exception handling
Let's try to understand the problem if we don't use a try-catch block.
Example 1
[Link]
1. public class TryCatchExample1 {
2.
3. public static void main(String[] args) {
4.
5. int data=50/0; //may throw exception
6.
7. [Link]("rest of the code");
8.
9. }
10.
11. }
Test it Now
Output:
Exception in thread "main" [Link]: / by zero
Java Nested try block
In Java, using a try block inside another try block is permitted. It is called as nested try block.
Every statement that we enter a statement in try block, context of that exception is pushed onto
the stack.
For example, the inner try block can be used to handle Array Index Out Of Bounds
Exception while the outer try block can handle the Arithemetic Exception (division by
zero).
Why use nested try block
Sometimes a situation may arise where a part of a block may cause one error and the entire
block itself may cause another error. In such cases, exception handlers have to be nested.
Syntax:
1. ....
2. //main try block
3. try
4. {
5. statement 1;
6. statement 2;
7. //try catch block within another try block
8. try
9. {
19CS14403 : JAVA PROGRAMMING 62
10. statement 3;
11. statement 4;
12. //try catch block within nested try block
13. try
14. {
15. statement 5;
16. statement 6;
17. }
18. catch(Exception e2)
19. {
20. //exception message
21. }
22.
23. }
24. catch(Exception e1)
25. {
26. //exception message
27. }
28. }
29. //catch block of parent (outer) try block
30. catch(Exception e3)
31. {
32. //exception message
33. }
34. ....
When any try block does not have a catch block for a particular exception, then the catch block
of the outer (parent) try block are checked for that exception, and if it matches, the catch block
of outer try block is executed.
If none of the catch block specified in the code is unable to handle the exception, then the Java
runtime system will handle the exception. Then it displays the system generated message for
that exception.
Example 2
Let's consider the following example. Here the try block within nested try block (inner try block
2) do not handle the exception. The control is then transferred to its parent try block (inner try
block 1). If it does not handle the exception, then the control is transferred to the main try block
(outer try block) where the appropriate catch block handles the exception. It is termed as
nesting.
19CS14403 : JAVA PROGRAMMING 64
[Link]
1. public class NestedTryBlock2 {
2.
3. public static void main(String args[])
4. {
5. // outer (main) try block
6. try {
7.
8. //inner try block 1
9. try {
10.
11. // inner try block 2
12. try {
13. int arr[] = { 1, 2, 3, 4 };
14.
15. //printing the array element out of its bounds
16. [Link](arr[10]);
17. }
18.
19. // to handles ArithmeticException
20. catch (ArithmeticException e) {
21. [Link]("Arithmetic exception");
22. [Link](" inner try block 2");
23. }
24. }
25.
26. // to handle ArithmeticException
27. catch (ArithmeticException e) {
28. [Link]("Arithmetic exception");
29. [Link]("inner try block 1");
30. }
31. }
32.
33. // to handle ArrayIndexOutOfBoundsException
34. catch (ArrayIndexOutOfBoundsException e4) {
35. [Link](e4);
36. [Link](" outer (main) try block");
37. }
38. catch (Exception e5) {
39. [Link]("Exception");
40. [Link](" handled in main try-block");
41. }
42. }
43. }
Java finally block
Java finally block is a block used to execute important code such as closing the connection,
etc.
19CS14403 : JAVA PROGRAMMING 65
Java finally block is always executed whether an exception is handled or not. Therefore, it
contains all the necessary statements that need to be printed regardless of the exception occurs
or not.
The finally block follows the try-catch block.
Flowchart of finally block
Note: If you don't handle the exception, before terminating the program, JVM executes finally
block (if any).
Why use Java finally block?
o finally block in Java can be used to put "cleanup" code such as closing a file, closing
connection, etc.
o The important statements to be printed can be placed in the finally block.
Case 2: When an exception occurr but not handled by the catch block
Let's see the the fillowing example. Here, the code throws an exception however the catch
block cannot handle it. Despite this, the finally block is executed after the try block and then
the program terminates abnormally.
[Link]
1. public class TestFinallyBlock1{
2. public static void main(String args[]){
3.
4. try {
5.
6. [Link]("Inside the try block");
7.
8. //below code throws divide by zero exception
9. int data=25/0;
10. [Link](data);
11. }
12. //cannot handle Arithmetic type exception
13. //can only accept Null Pointer type exception
14. catch(NullPointerException e){
15. [Link](e);
16. }
17.
19CS14403 : JAVA PROGRAMMING 67
18. //executes regardless of exception occured or not
19. finally {
20. [Link]("finally block is always executed");
21. }
22.
23. [Link]("rest of the code...");
24. }
25. }
Java Custom Exception
In Java, we can create our own exceptions that are derived classes of the Exception class.
Creating our own Exception is known as custom exception or user-defined exception.
Basically, Java custom exceptions are used to customize the exception according to user need.
Consider the example 1 in which InvalidAgeException class extends the Exception class.
Using the custom exception, we can have your own exception and message. Here, we have
passed a string to the constructor of superclass i.e. Exception class that can be obtained using
getMessage() method on the object we have created.
In this section, we will learn how custom exceptions are implemented and used in Java
programs.
In order to create custom exception, we need to extend Exception class that belongs to [Link]
package.
Consider the following example, where we create a custom exception named
WrongFileNameException:
Note: We need to write the constructor that takes the String as the error message and it is
called parent class constructor.
Example 1:
Let's see a simple example of Java custom exception. In the following code, constructor of
InvalidAgeException takes a string as an argument. This string is passed to constructor of
19CS14403 : JAVA PROGRAMMING 68
parent class Exception using the super() method. Also the constructor of Exception class can
be called without using a parameter and calling super() method is not mandatory.
[Link]
1. // class representing custom exception
2. class InvalidAgeException extends Exception
3. {
4. public InvalidAgeException (String str)
5. {
6. // calling the constructor of parent Exception
7. super(str);
8. }
9. }
10.
11. // class that uses custom exception InvalidAgeException
12. public class TestCustomException1
13. {
14.
15. // method to check the age
16. static void validate (int age) throws InvalidAgeException{
17. if(age < 18){
18.
19. // throw an object of user defined exception
20. throw new InvalidAgeException("age is not valid to vote");
21. }
22. else {
23. [Link]("welcome to vote");
24. }
25. }
26.
27. // main method
28. public static void main(String args[])
29. {
30. try
31. {
32. // calling the method
33. validate(13);
34. }
35. catch (InvalidAgeException ex)
36. {
37. [Link]("Caught the exception");
38.
39. // printing the message from InvalidAgeException object
40. [Link]("Exception occured: " + ex);
41. }
42.
43. [Link]("rest of the code...");
44. }
45. }
19CS14403 : JAVA PROGRAMMING 69
Output:
Example 2:
[Link]
1. // class representing custom exception
2. class MyCustomException extends Exception
3. {
4.
5. }
6.
7. // class that uses custom exception MyCustomException
8. public class TestCustomException2
9. {
10. // main method
11. public static void main(String args[])
12. {
13. try
14. {
15. // throw an object of user defined exception
16. throw new MyCustomException();
17. }
18. catch (MyCustomException ex)
19. {
20. [Link]("Caught the exception");
21. [Link]([Link]());
22. }
23.
24. [Link]("rest of the code...");
25. }
26. }
Encapsulation in Java
Encapsulation in Java is a process of wrapping code and data together into a single unit, for
example, a capsule which is mixed of several medicines.
19CS14403 : JAVA PROGRAMMING 70
We can create a fully encapsulated class in Java by making all the data members of the class
private. Now we can use setter and getter methods to set and get the data in it.
The Java Bean class is the example of a fully encapsulated class.
Advantage of Encapsulation in Java
By providing only a setter or getter method, you can make the class read-only or write-only.
In other words, you can skip the getter or setter methods.
It provides you the control over the data. Suppose you want to set the value of id which should
be greater than 100 only, you can write the logic inside the setter method. You can write the
logic not to store the negative numbers in the setter methods.
It is a way to achieve data hiding in Java because other class will not be able to access the data
through the private data members.
The encapsulate class is easy to test. So, it is better for unit testing.
The standard IDE's are providing the facility to generate the getters and setters. So, it is easy
and fast to create an encapsulated class in Java.
Simple Example of Encapsulation in Java
Let's see the simple example of encapsulation that has only one field with its setter and getter
methods.
File: [Link]
1. //A Java class which is a fully encapsulated class.
2. //It has a private data member and getter and setter methods.
3. package [Link];
4. public class Student{
5. //private data member
6. private String name;
7. //getter method for name
8. public String getName(){
9. return name;
10. }
11. //setter method for name
12. public void setName(String name){
13. [Link]=name
14. }
15. }
File: [Link]
1. //A Java class to test the encapsulated class.
2. package [Link];
3. class Test{
4. public static void main(String[] args){
5. //creating instance of the encapsulated class
6. Student s=new Student();
7. //setting value in the name member
8. [Link]("vijay");
19CS14403 : JAVA PROGRAMMING 71
9. //getting value of the name member
10. [Link]([Link]());
11. }
12. }
Compile By: javac -d . [Link]
Run By: java [Link]
Output:
vijay
Read-Only class
1. //A Java class which has only getter methods.
2. public class Student{
3. //private data member
4. private String college="AKG";
5. //getter method for college
6. public String getCollege(){
7. return college;
8. }
9. }
Now, you can't change the value of the college data member which is "AKG".
1. [Link]("KITE");//will render compile time error
Write-Only class
1. //A Java class which has only setter methods.
2. public class Student{
3. //private data member
4. private String college;
5. //getter method for college
6. public void setCollege(String college){
7. [Link]=college;
8. }
9. }
Now, you can't get the value of the college, you can only change the value of college data
member.
1. [Link]([Link]());//Compile Time Error, because there is no such method
2. [Link]([Link]);//Compile Time Error, because the college data member is priva
te.
3. //So, it can't be accessed from outside the class
Another Example of Encapsulation in Java
Let's see another example of encapsulation that has only four fields with its setter and getter
methods.
File: [Link]
Create an event policy with a Java method enrichment action to run a Java method and enrich
an event based on the method output values. The Java method must return a comma-separated
list of properties and returned values as follows for the enrichment to work:
propertyname
,
value
,
propertyname
,
value
...
19CS14403 : JAVA PROGRAMMING 73
Java method enrichments require the following information:
The method must exist on the SA Manager and on every connector system to which you want
to deploy the event policy.
Follow these steps:
1. Create an event policy based on a search pattern, and select Enrich Event as the action
type.
2. Select Java method in the Type drop-down list and enter information in the following
fields:
The text at the bottom of the page indicates if any required information is missing.
Defines the full class path and jar file of the method to use for the enrichment.
Example:
<C:\Program Files\CA\SOI\lib\ivy\[Link]>
● Class Name
Defines the class name of the Java method, including the package, to use for the
enrichment.
Example:
[Link]
● User
(Optional) Defines the user name to run the Java method, if necessary.
● Password
(Optional) Defines the password for the specified Java method user name, if
necessary.
If the method requires user authentication in its parameters, enter the credentials
here and reference them on the following page to ensure that the data is
protected.
19CS14403 : JAVA PROGRAMMING 74
● Method
Defines the name of the Java method to run from the referenced class.
Example:
performCMDBEnrichment_v2
The Java method connection is verified. The Configuration Test Result dialog indicates
whether the connection was successful.
If you have to change this information after deploying the policy, restart the CA SAM
Integration Services service on the connector system to ensure that the change takes
effect. For information about how to configure enrichment value caching, see Configure
Enrichment Cache Timeout.
Click Next.
The Enrichment Policy page opens. Right-click each column on this page for additional
help information.
Enter the following in the Parameter Configuration table to determine how the input parameters
to the enrichment process are assigned according to method parameter values and event
properties:
● Input Parameter
Defines placeholder names for each required method input parameter. The
enrichment always reads the parameters sequentially; therefore, the names that
you enter for each parameter can be anything (param1, param2, and so on).
Create an entry for each required input parameter to ensure that the method runs
successfully.
● Assigned Value
Defines the event property or other value to use for the corresponding method
parameter value. Use the right-click menu to assign the value of a property from
any matching event pattern. The value for each method parameter can take any
of the following forms:
${user}
${password}
The Preview cell displays the result of the entered value based on the selected event in the
Event Log table. You must run an event search before creating the policy to get its results in
the Event Log table for previewing enrichment values based on existing event content.
Include all required parameters for the method to run. If the Java method does not run
successfully based on the entered parameters or does not return a comma-separated list of
properties and values, the enrichment does not occur for that event.
Enter the following in the Enrichment Property Assignment table to specify how enrichment
output values are assigned to event properties, and click Next:
● Assigned Value
Defines the Java method output property values to assign to the event properties
in the Event Property column. This value determines the property value to use
for the enrichment from the comma-separated list of properties and values that
the method returns.
propertyname
value
,role,
value
,department,
value
', ${role} uses the returned value from the role output property for the
enrichment. Any values entered without this format appear directly in the event
as written. You can add enrichments to as many event properties as necessary.
19CS14403 : JAVA PROGRAMMING 76
You can change the names of the User Attribute properties if you want them to
accurately represent the enrichment properties that you assign to them.
However, these properties appear under their original names in the Event Policy
dialog, even if you renamed them. Assigning values to these original names
properly displays the values under the renamed properties in the Operations
Console.
Only the properties that support enrichment value assignment appear in the
Event Property column.
The enrichments use .jar files that are only available with the Mid-tier connector. Deploy these
provided enrichments on the Mid-tier connector only.
Example: Enrich events with location information from CA CMDB
This example enriches events with location information stored in CA CMDB. The information
could help you create alert queues by location or add location-based criteria to escalation
policy.
● Select Java Method on the Enrichment Configuration page, and select CMDB in the
Templates drop-down list.
● Use the User and Password fields to enter valid credentials for the CA CMDB server,
and leave the default values in all other fields.
● Do the following on the Enrichment Policy Configuration page:
o Enter values for the provided method parameters in the Input Parameter column
in the Assigned Values column:
1. endpointref:
[Link]
19CS14403 : JAVA PROGRAMMING 77
2. userid: ${user}
3. password: ${password}
4. propertylist: [Link],[Link]
Note:
This parameter configuration queries the defined CA CMDB instance for CIs
with a dns_name property that matches the event AlertedMdrProdInstance
property value and returns the [Link] and [Link] properties of
the matching CI. It uses substitution strings for the required CA CMDB
credentials (referencing the credentials entered on the previous page) to avoid
entering the information unencrypted.
Assertion:
Assertion is a statement in java. It can be used to test your assumptions about the program.
While executing assertion, it is believed to be true. If it fails, JVM will throw an error named
AssertionError. It is mainly used for testing purpose.
Advantage of Assertion:
It provides an effective way to detect and correct programming errors.
1. According to Sun Specification, assertion should not be used to check arguments in the
public methods because it should result in appropriate runtime exception e.g.
IllegalArgumentException, NullPointerException etc.
2. Do not use assertion, if you don't want any error in any situation.
UNIT - 4
Multithreading in Java
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to
utilize the CPU. Multitasking can be achieved in two ways:
o Process-based Multitasking (Multiprocessing)
o Thread-based Multitasking (Multithreading)
Threads are independent. If there occurs exception in one thread, it doesn't affect other threads.
It uses a shared memory area.
As shown in the above figure, a thread is executed inside the process. There is context-
switching between the threads. There can be multiple processes inside the OS, and one process
can have multiple threads.
19CS14403 : JAVA PROGRAMMING 80
Note: At a time one thread is executed only.
Java Thread class
Java provides Thread class to achieve thread programming. Thread class
provides constructors and methods to create and perform operations on a thread. Thread class
extends Object class and implements Runnable interface.
19CS14403 : JAVA PROGRAMMING 81
Java Thread Methods
19CS14403 : JAVA PROGRAMMING 82
S.N Modifier Method Description
. and Type
In Java, a thread always exists in any one of the following states. These states are:
1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated
Blocked or Waiting: Whenever a thread is inactive for a span of time (not permanently) then,
either the thread is in the blocked state or is in the waiting state.
For example, a thread (let's say its name is A) may want to print some data from the printer.
However, at the same time, the other thread (let's say its name is B) is using the printer to print
some data. Therefore, thread A has to wait for thread B to use the printer. Thus, thread A is in
the blocked state. A thread in the blocked state is unable to perform any execution and thus
never consume any cycle of the Central Processing Unit (CPU). Hence, we can say that thread
A remains idle until the thread scheduler reactivates thread A, which is in the waiting or
blocked state.
When the main thread invokes the join() method then, it is said that the main thread is in the
waiting state. The main thread then waits for the child threads to complete their tasks. When
the child threads complete their job, a notification is sent to the main thread, which again moves
the thread from waiting to the active state.
If there are a lot of threads in the waiting or blocked state, then it is the duty of the thread
scheduler to determine which thread to choose and which one to reject, and the chosen thread
is then given the opportunity to run.
Timed Waiting: Sometimes, waiting for leads to starvation. For example, a thread (its name
is A) has entered the critical section of a code and is not willing to leave that critical section.
In such a scenario, another thread (its name is B) has to wait forever, which leads to starvation.
To avoid such scenario, a timed waiting state is given to thread B. Thus, thread lies in the
waiting state for a specific span of time, and not forever. A real example of timed waiting is
when we invoke the sleep() method on a specific thread. The sleep() method puts the thread in
the timed wait state. After the time runs out, the thread wakes up and start its execution from
when it has left earlier.
Terminated: A thread reaches the termination state because of the following reasons:
o When a thread has finished its job, then it exists or terminates normally.
o Abnormal termination: It occurs when some unusual events such as an unhandled
exception or segmentation fault.
A terminated thread means the thread is no more in the system. In other words, the thread is
dead, and there is no way one can respawn (active after kill) the dead thread.
The following diagram shows the different states involved in the life cycle of a thread.
Thread class:
Thread class provide constructors and methods to create and perform operations on a
[Link] class extends Object class and implements Runnable interface.
Commonly used Constructors of Thread class:
o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to
be executed by a thread. Runnable interface have only one method named run().
1. public void run(): is used to perform action for a thread.
Starting a thread:
The start() method of Thread class is used to start a newly created thread. It performs the
following tasks:
The Java Thread class provides the two variant of the sleep() method. First one accepts only an
arguments, whereas the other variant accepts two arguments. The method sleep() is being used
to halt the working of a thread for a given amount of time. The time up to which the thread
remains in the sleeping state is known as the sleeping time of the thread. After the sleeping
time is over, the thread starts its execution from where it has left.
The sleep() Method Syntax:
Following are the syntax of the sleep() method.
1. public static void sleep(long mls) throws InterruptedException
2. public static void sleep(long mls, int n) throws InterruptedException
The method sleep() with the one parameter is the native method, and the implementation of the
native method is accomplished in another programming language. The other methods having
the two parameters are not the native method. That is, its implementation is accomplished in
Java. We can access the sleep() methods with the help of the Thread class, as the signature of
the sleep() methods contain the static keyword. The native, as well as the non-native method,
throw a checked Exception. Therefore, either try-catch block or the throws keyword can work
here.
The [Link]() method can be used with any thread. It means any other thread or the main
thread can invoke the sleep() method.
Parameters:
The following are the parameters used in the sleep() method.
mls: The time in milliseconds is represented by the parameter mls. The duration for which the
thread will sleep is given by the method sleep().
n: It shows the additional time up to which the programmer or developer wants the thread to
be in the sleeping state. The range of n is from 0 to 999999.
The method does not return anything.
19CS14403 : JAVA PROGRAMMING 89
Important Points to Remember About the Sleep() Method
Whenever the [Link]() methods execute, it always halts the execution of the current
thread.
Whenever another thread does interruption while the current thread is already in the sleep
mode, then the InterruptedException is thrown.
If the system that is executing the threads is busy, then the actual sleeping time of the thread is
generally more as compared to the time passed in arguments. However, if the system executing
the sleep() method has less load, then the actual sleeping time of the thread is almost equal to
the time passed in the argument.
Example of the sleep() method in Java : on the custom thread
The following example shows how one can use the sleep() method on the custom thread.
FileName: [Link]
1. class TestSleepMethod1 extends Thread{
2. public void run(){
3. for(int i=1;i<5;i++){
4. // the thread will sleep for the 500 milli seconds
5. try{[Link](500);}catch(InterruptedException e){[Link](e);}
6. [Link](i);
7. }
8. }
9. public static void main(String args[]){
10. TestSleepMethod1 t1=new TestSleepMethod1();
11. TestSleepMethod1 t2=new TestSleepMethod1();
12.
13. [Link]();
14. [Link]();
15. }
16. }
The join() method in Java is provided by the [Link] class that permits one thread to
wait until the other thread to finish its execution. Suppose th be the object the class Thread
whose thread is doing its execution currently, then the [Link](); statement ensures that th is
finished before the program does the execution of the next statement.
Syntax:
1. public final synchronized void join(long mls, int nanos) throws InterruptedException, wher
e mls is in milliseconds.
Example of join() Method in Java
The following program shows the usage of the join() method.
FileName: [Link]
19CS14403 : JAVA PROGRAMMING 90
1. // A Java program for understanding
2. // the joining of threads
3.
4. // import statement
5. import [Link].*;
6.
7. // The ThreadJoin class is the child class of the class Thread
8. class ThreadJoin extends Thread
9. {
10. // overriding the run method
11. public void run()
12. {
13. for (int j = 0; j < 2; j++)
14. {
15. try
16. {
17. // sleeping the thread for 300 milli seconds
18. [Link](300);
19. [Link]("The current thread name is: " + [Link]().getName());
20. }
21. // catch block for catching the raised exception
22. catch(Exception e)
23. {
24. [Link]("The exception has been caught: " + e);
25. }
26. [Link]( j );
27. }
28. }
29. }
30.
31. public class ThreadJoinExample
32. {
33. // main method
34. public static void main (String argvs[])
35. {
36.
37. // creating 3 threads
38. ThreadJoin th1 = new ThreadJoin();
39. ThreadJoin th2 = new ThreadJoin();
40. ThreadJoin th3 = new ThreadJoin();
41.
42. // thread th1 starts
43. [Link]();
44.
45. // starting the second thread after when
46. // the first thread th1 has ended or died.
47. try
48. {
49. [Link]("The current thread name is: "+ [Link]().getName());
50.
19CS14403 : JAVA PROGRAMMING 91
51. // invoking the join() method
52. [Link]();
53. }
54.
55. // catch block for catching the raised exception
56. catch(Exception e)
57. {
58. [Link]("The exception has been caught " + e);
59. }
60.
61. // thread th2 starts
62. [Link]();
63.
64. // starting the th3 thread after when the thread th2 has ended or died.
65. try
66. {
67. [Link]("The current thread name is: " + [Link]().getName());
68. [Link]();
69. }
70.
71. // catch block for catching the raised exception
72. catch(Exception e)
73. {
74. [Link]("The exception has been caught " + e);
75. }
76.
77. // thread th3 starts
78. [Link]();
79. }
80. }
Output:
The current thread name is: main
The current thread name is: Thread - 0
0
The current thread name is: Thread - 0
1
The current thread name is: main
The current thread name is: Thread - 1
0
The current thread name is: Thread - 1
1
The current thread name is: Thread - 2
0
The current thread name is: Thread - 2
1
Explanation: The above program sh
ava Thread isAlive() method
19CS14403 : JAVA PROGRAMMING 92
The isAlive() method of thread class tests if the thread is alive. A thread is considered alive
when the start() method of thread class has been called and the thread is not yet dead. This
method returns true if the thread is still running and not finished.
Syntax
1. public final boolean isAlive()
Return
This method will return true if the thread is alive otherwise returns false.
Example
1. public class JavaIsAliveExp extends Thread
2. {
3. public void run()
4. {
5. try
6. {
7. [Link](300);
8. [Link]("is run() method isAlive "+[Link]().isAlive());
9. }
10. catch (InterruptedException ie) {
11. }
12. }
13. public static void main(String[] args)
14. {
15. JavaIsAliveExp t1 = new JavaIsAliveExp();
16. [Link]("before starting thread isAlive: "+[Link]());
17. [Link]();
18. [Link]("after starting thread isAlive: "+[Link]());
19. }
20. }
Test it Now
Output:
Synchronization in Java is the capability to control the access of multiple threads to any shared
resource.
Java Synchronization is better option where we want to allow only one thread to access the
shared resource.
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data. It
can be achieved by using the following three ways:
1. By Using Synchronized Method
2. By Using Synchronized Block
3. By Using Static Synchronization
5
100
10
200
15
300
20
400
25
500
Deadlock in Java
Deadlock in Java is a part of multithreading. Deadlock can occur in a situation when a thread
is waiting for an object lock, that is acquired by another thread and second thread is waiting for
an object lock that is acquired by first thread. Since, both threads are waiting for each other to
release the lock, the condition is called deadlock.
Thread 1 waits for thread 2, thread 2 waits for thread 3, thread 3 waits for thread 4, and thread
4 waits for thread 1.
How to avoid deadlock?
A solution for a problem is found at its roots. In deadlock it is the pattern of accessing the
resources A and B, is the main issue. To solve the issue we will have to simply re-order the
statements where the code is accessing shared resources.
[Link]
1. public class DeadlockSolved {
2.
3. public static void main(String ar[]) {
4. DeadlockSolved test = new DeadlockSolved();
5.
6. final resource1 a = [Link] resource1();
7. final resource2 b = [Link] resource2();
8.
9. // Thread-1
10. Runnable b1 = new Runnable() {
19CS14403 : JAVA PROGRAMMING 98
11. public void run() {
12. synchronized (b) {
13. try {
14. /* Adding delay so that both threads can start trying to lock resources */
15. [Link](100);
16. } catch (InterruptedException e) {
17. [Link]();
18. }
19. // Thread-1 have resource1 but need resource2 also
20. synchronized (a) {
21. [Link]("In block 1");
22. }
23. }
24. }
25. };
26.
27. // Thread-2
28. Runnable b2 = new Runnable() {
29. public void run() {
30. synchronized (b) {
31. // Thread-2 have resource2 but need resource1 also
32. synchronized (a) {
33. [Link]("In block 2");
34. }
35. }
36. }
37. };
38.
39.
40. new Thread(b1).start();
41. new Thread(b2).start();
42. }
43.
44. // resource1
45. private class resource1 {
46. private int i = 10;
47.
48. public int getI() {
49. return i;
50. }
51.
52. public void setI(int i) {
53. this.i = i;
54. }
55. }
56.
57. // resource2
58. private class resource2 {
59. private int i = 20;
60.
19CS14403 : JAVA PROGRAMMING 99
61. public int getI() {
62. return i;
63. }
64.
65. public void setI(int i) {
66. this.i = i;
67. }
68. }
69. }
Output:
In block 1
In block 2
In the above code, class DeadlockSolved solves the deadlock kind of situation. It will help in
avoiding deadlocks, and if encountered, in resolving them.
How to Avoid Deadlock in Java?
Deadlocks cannot be completely resolved. But we can avoid them by following basic rules
mentioned below:
1. Avoid Nested Locks: We must avoid giving locks to multiple threads, this is the main
reason for a deadlock condition. It normally happens when you give locks to multiple
threads.
2. Avoid Unnecessary Locks: The locks should be given to the important threads. Giving
locks to the unnecessary threads that cause the deadlock condition.
3. Using Thread Join: A deadlock usually happens when one thread is waiting for the
other to finish. In this case, we can use join with a maximum time that a thread will
take.
1) wait() method
The wait() method causes current thread to release the lock and wait until either another thread
invokes the notify() method or the notifyAll() method for this object, or a specified amount of
time has elapsed.
The current thread must own this object's monitor, so it must be called from the synchronized
method only otherwise it will throw exception.
19CS14403 : JAVA PROGRAMMING 100
Method Description
2) notify() method
The notify() method wakes up a single thread that is waiting on this object's monitor. If any
threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary
and occurs at the discretion of the implementation.
Syntax:
1. public final void notify()
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.
Syntax:
1. public final void notifyAll()
Understanding the process of inter-thread communication
Why wait(), notify() and notifyAll() methods are defined in Object class not Thread class?
It is because they are related to lock and object has a lock.
Difference between wait and sleep?
Let's see the important differences between wait and sleep methods.
wait() sleep()
The suspend() method of thread class puts the thread from running to waiting state. This
method is used if you want to stop the thread execution and start it again when a certain event
occurs. This method allows a thread to temporarily cease execution. The suspended thread can
be resumed using the resume() method.
Syntax
1. public final void suspend()
Return
This method does not return any value.
Exception
SecurityException: If the current thread cannot modify the thread.
Example
1. public class JavaSuspendExp extends Thread
2. {
3. public void run()
4. {
5. for(int i=1; i<5; i++)
6. {
7. try
8. {
9. // thread to sleep for 500 milliseconds
10. sleep(500);
11. [Link]([Link]().getName());
12. }catch(InterruptedException e){[Link](e);}
13. [Link](i);
14. }
15. }
16. public static void main(String args[])
19CS14403 : JAVA PROGRAMMING 103
17. {
18. // creating three threads
19. JavaSuspendExp t1=new JavaSuspendExp ();
20. JavaSuspendExp t2=new JavaSuspendExp ();
21. JavaSuspendExp t3=new JavaSuspendExp ();
22. // call run() method
23. [Link]();
24. [Link]();
25. // suspend t2 thread
26. [Link]();
27. // call run() method
28. [Link]();
29. }
30. }
Test it Now
Output:
Thread-0
1
Thread-2
1
Thread-0
2
Thread-2
2
Thread-0
3
Thread-2
3
Thread-0
4
Thread-2
4
The resume() method of thread class is only used with suspend() method. This method is used
to resume a thread which was suspended using suspend() method. This method allows the
suspended thread to start again.
Syntax
1. public final void resume()
Return value
This method does not return any value.
Exception
SecurityException: If the current thread cannot modify the thread.
19CS14403 : JAVA PROGRAMMING 104
Example
1. public class JavaResumeExp extends Thread
2. {
3. public void run()
4. {
5. for(int i=1; i<5; i++)
6. {
7. try
8. {
9. // thread to sleep for 500 milliseconds
10. sleep(500);
11. [Link]([Link]().getName());
12. }catch(InterruptedException e){[Link](e);}
13. [Link](i);
14. }
15. }
16. public static void main(String args[])
17. {
18. // creating three threads
19. JavaResumeExp t1=new JavaResumeExp ();
20. JavaResumeExp t2=new JavaResumeExp ();
21. JavaResumeExp t3=new JavaResumeExp ();
22. // call run() method
23. [Link]();
24. [Link]();
25. [Link](); // suspend t2 thread
26. // call run() method
27. [Link]();
28. [Link](); // resume t2 thread
29. }
30. }
Test it Now
Output:
Thread-0
1
Thread-2
1
Thread-1
1
Thread-0
2
Thread-2
2
Thread-1
2
Thread-0
3
Thread-2
19CS14403 : JAVA PROGRAMMING 105
3
Thread-1
3
Thread-0
4
Thread-2
4
Thread-1
4
Writing and reading elements in an array is a small problem where each element is first added
to the array and then the entire array is read element by element and printed on the console.
But when the number of elements is too large, it could take a lot of time. But this could be
solved by dividing the writing and reading tasks into parts.
This could be done by using multi-threading where each core of the processor is used. In this
case, two threads are used, where one thread is responsible for writing to the array and the other
thread is responsible for reading the array. In this way, the performance of a program can be
improved as well as the cores of the processor can be utilized. It is better to use one thread for
each core. Although one can create as many threads as required for a better understanding of
multi-threading.
This article focuses on writing and reading the elements of the array using the concept of
multithreading.
Approach: This section states the algorithm that is followed to design a program to writing
and read elements of an array using multithreading:
● In the first step, two threads will be created.
● One for writing operation and one for reading operation.
● Here the synchronized keyword is used with the array so that only one thread can access the
array at a time.
● First, the write operation will be performed on the array.
● Then, the read operation is performed on the array.
Below is the Java program to implement the above approach-
● C++14
● Java
● Python3
● C#
● Javascript
19CS14403 : JAVA PROGRAMMING 106
#include <iostream>
#include <thread>
using namespace std;
int main()
{
// Array created for 5 elements
int a[5];
return 0;
}
Output:
Explanation: Here, firstly the write thread is started and at that time read thread will not
interfere as the array is synchronized. Similarly, during reading, write thread will not interfere.
19CS14403 : JAVA PROGRAMMING 108
UNIT – 5
Java Threads
Threads allows a program to operate more efficiently by doing multiple things at the same time.
Threads can be used to perform complicated tasks in the background without interrupting the
main program.
A thread is a program in execution created to perform a specific task. Life cycle of a Java thread
starts with its birth and ends on its death.
The start() method of the Thread class is used to initiate the execution of a thread and it goes
into runnable state and the sleep() and wait() methods of the Thread class sends the thread into
non runnable state.
After non runnable state, thread again comes into runnable state and starts its execution. The
run() method of thread is very much important. After executing the run() method, the lifecycle
of thread is completed.
Interrupting a Thread:
19CS14403 : JAVA PROGRAMMING 109
If any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the
interrupt() method on the thread, breaks out the sleeping or waiting state throwing
InterruptedException. If the thread is not in the sleeping or waiting state, calling the interrupt()
method performs normal behaviour and doesn't interrupt the thread but sets the interrupt flag
to true. Let's first see the methods provided by the Thread class for thread interruption.
Inter-Thread communication:
Java Networking:
Java Networking is a concept of connecting two or more computing devices together so that
we can share resources.
Java socket programming provides facility to share data between different computing devices.
3) 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.
4) MAC Address
MAC (Media Access Control) address is a unique identifier of NIC (Network Interface
Controller). A network node can have multiple NIC but each with unique MAC address.
For example, an ethernet card may have a MAC address of 00:0d:83::b1:c0:8e.
5) Connection-oriented and connection-less protocol
In connection-oriented protocol, acknowledgement is sent by the receiver. So it is reliable but
slow. The example of connection-oriented protocol is TCP.
But, in connection-less protocol, acknowledgement is not sent by the receiver. So it is not
reliable but fast. The example of connection-less protocol is UDP.
6) Socket
A socket is an endpoint between two way communications.
Visit next page for Java socket programming.
[Link] package
The [Link] package can be divided into two sections:
1. A Low-Level API: It deals with the abstractions of addresses i.e. networking
identifiers, Sockets i.e. bidirectional data communication mechanism and Interfaces i.e.
network interfaces.
2. A High Level API: It deals with the abstraction of URIs i.e. Universal Resource
Identifier, URLs i.e. Universal Resource Locator, and Connections i.e. connections to
the resource pointed by URLs.
The [Link] package provides many classes to deal with networking applications in Java. A
list of these classes is given below:
19CS14403 : JAVA PROGRAMMING 111
o Authenticator
o CacheRequest
o CacheResponse
o ContentHandler
o CookieHandler
o CookieManager
o DatagramPacket
o DatagramSocket
o DatagramSocketImpl
o InterfaceAddress
o JarURLConnection
o MulticastSocket
o InetSocketAddress
o InetAddress
o Inet4Address
o Inet6Address
o IDN
o HttpURLConnection
o HttpCookie
o NetPermission
o NetworkInterface
o PasswordAuthentication
o Proxy
o ProxySelector
o ResponseCache
o SecureCacheResponse
o ServerSocket
o Socket
o SocketAddress
o SocketImpl
o SocketPermission
o StandardSocketOptions
Java Socket programming is used for communication between the applications running on
different JRE.
Java Socket programming can be connection-oriented or connection-less.
Socket and ServerSocket classes are used for connection-oriented socket programming and
DatagramSocket and DatagramPacket classes are used for connection-less socket
programming.
Here, we are going to make one-way client and server communication. In this application,
client sends a message to the server, 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 message. The ServerSocket class is used at
server-side. The accept() method of ServerSocket class blocks the console until the client is
connected. After the successful connection of client, it returns the instance of Socket at server-
side.
Socket class
A socket is simply an endpoint for communications between the machines. The Socket class
can be used to create a socket.
Important methods
Method Description
ServerSocket class
The ServerSocket class can be used to create a server socket. This object is used to establish
communication with the clients.
Important methods
Method Description
File: [Link]
1. import [Link].*;
2. import [Link].*;
3. public class MyServer {
4. public static void main(String[] args){
5. try{
6. ServerSocket ss=new ServerSocket(6666);
7. Socket s=[Link]();//establishes connection
8. DataInputStream dis=new DataInputStream([Link]());
9. String str=(String)[Link]();
10. [Link]("message= "+str);
11. [Link]();
12. }catch(Exception e){[Link](e);}
13. }
14. }
File: [Link]
1. import [Link].*;
2. import [Link].*;
3. public class MyClient {
4. public static void main(String[] args) {
5. try{
6. Socket s=new Socket("localhost",6666);
7. DataOutputStream dout=new DataOutputStream([Link]());
8. [Link]("Hello Server");
9. [Link]();
10. [Link]();
11. [Link]();
12. }catch(Exception e){[Link](e);}
13. }
14. }
19CS14403 : JAVA PROGRAMMING 114
ava InetAddress class
2. IPv6
IPv6 is the latest version of Internet protocol. It aims at fulfilling the need of more internet
addresses. It provides solutions for the problems present in IPv4. It provides 128-bit address
space that can be used to form a network of 340 undecillion unique IP addresses. IPv6 is also
identified with a name IPng (Internet Protocol next generation).
Features of IPv6:
o It has a stateful and stateless both configurations.
o It provides support for quality of service (QoS).
o It has a hierarchical addressing and routing infrastructure.
TCP/IP Protocol
o TCP/IP is a communication protocol model used connect devices over a network via
internet.
19CS14403 : JAVA PROGRAMMING 115
o TCP/IP helps in the process of addressing, transmitting, routing and receiving the data
packets over the internet.
o The two main protocols used in this communication model are:
1. TCP i.e. Transmission Control Protocol. TCP provides the way to create a
communication channel across the network. It also helps in transmission of
packets at sender end as well as receiver end.
2. IP i.e. Internet Protocol. IP provides the address to the nodes connected on the
internet. It uses a gateway computer to check whether the IP address is correct
and the message is forwarded correctly or not.
One for the server and one for the client. The ServerSocket class is designed as a "listener",
waiting for a client to connect before doing anything. So ServerSocket is for servers. The
Socket class is for clients. It is designed to connect to a server socket and initiate a protocol
exchange. This is because client sockets are most commonly used in Java applications. Creating
a Socket object implicitly establishes a connection between the client and server. There is no
method or constructor that explicitly exposes details about setting up this connection.
Here are the two constructors used to create a client socket:
1. Socket(String hostName, int port) throws UnknownHostException,
IOException: Creates a socket connected to the specified host and port.
2. Socket(InetAddress ipAddress, int port) throws IOException: Creates a socket
using a pre-existing InetAddress object and a port.
Socket defines multiple instance methods. For example, a Socket can always check for
associated address and port information using the following methods:
1. InetAddress getInetAddress( ): It returns the InetAddress associated with the Socket
object. It returns null if the socket is not connected.
2. int getPort( ): It returns the remote port to which the invoking Socket object is
connected. It returns 0 if the socket is not connected.
3. int getLocalPort( ): Returns the local port to which the invoking Socket object is
bound. It returns -1 if the socket is not bound.
4. InputStream getInputStream( ) throws IOException: Returns the InputStream
associated with the invoking socket.
5. OutputStream getOutputStream( ) throws IOException: Returns the OutputStream
associated with the invoking socket.
6. connect( ): Allows you to specify a new connection
7. isConnected( ): Returns true if the socket is connected to a server
8. isBound( ): Returns true if the socket is bound to an address
9. isClosed( ): Returns true if the socket is closed.
The following program provides a simple socket example. Opens a connection to a "whois"
port (port 43) of the InterNIC server, sends command-line argument to the socket, and prints
the returned data. The InterNIC will try find the argument by the registered Internet domain
name, and then send back the IP address and contact information for that site.
19CS14403 : JAVA PROGRAMMING 117
Example of Stream Socket
[Link]
1. import [Link].*;
2. import [Link].*;
3. public class WhoisClient {
4. public static void main(String[] args) {
5. // no arguments passed, simply return
6. if ([Link] < 1)
7. return;
8. // initializing domainName with the name passed in the argument
9. String domainName = args[0];
10. // specifying the host name
11. String hostname = "[Link]";
12. int port = 43;
13. try (Socket socket = new Socket(hostname, port)) {
14. // getOutputStream( ) returns the OutputStream
15. // associated with the invoking socket
16. OutputStream output = [Link]();
17. PrintWriter writer = new PrintWriter(output, true);
18. // print the domain name
19. [Link](domainName);
20. // getInputStream( ) returns the InputStream
21. // associated with the invoking socket
22. InputStream input = [Link]();
23. BufferedReader reader = new BufferedReader(new InputStreamReader(input));
24. String line;
25. while ((line = [Link]()) != null) {
26. [Link](line);
27. }
28. }
29. catch (UnknownHostException ex) {
30. [Link]("Server not found: " + [Link]());
31. }
32. catch (IOException ex) {
33. [Link]("I/O error: " + [Link]());
34. }
35. }
36. }
Output:
19CS14403 : JAVA PROGRAMMING 118
RMI Example
In this example, we have followed all the 6 steps to create and run the rmi application. The
client application need only two files, remote interface and client application. In the rmi
application, both client and server interacts with the remote interface. The client application
invokes methods on the proxy object, RMI sends the request to the remote JVM. The return
value is sent back to the proxy object and then to the client application.
19CS14403 : JAVA PROGRAMMING 119
In case, you extend the UnicastRemoteObject class, you must define a constructor that declares
RemoteException.
1. import [Link].*;
2. import [Link].*;
3. public class AdderRemote extends UnicastRemoteObject implements Adder{
4. AdderRemote()throws RemoteException{
5. super();
6. }
7. public int add(int x,int y){return x+y;}
8. }
19CS14403 : JAVA PROGRAMMING 120
3) create the stub and skeleton objects using the rmic tool.
Next step is to create stub and skeleton objects using the rmi compiler. The rmic tool invokes
the RMI compiler and creates stub and skeleton objects.
1. rmic AdderRemote
public static void It binds the remote object with the given name.
bind([Link],
[Link]) throws
[Link],
[Link],
[Link];
public static void It destroys the remote object which is bound with the
unbind([Link]) throws given name.
[Link],
[Link],
[Link];
public static void It binds the remote object to the new name.
rebind([Link],
[Link]) throws
[Link],
[Link];
public static [Link][] It returns an array of the names of the remote objects
list([Link]) throws bound in the registry.
[Link],
[Link];
In this example, we are binding the remote object by the name sonoo.
19CS14403 : JAVA PROGRAMMING 121
1. import [Link].*;
2. import [Link].*;
3. public class MyServer{
4. public static void main(String args[]){
5. try{
6. Adder stub=new AdderRemote();
7. [Link]("rmi://localhost:5000/sonoo",stub);
8. }catch(Exception e){[Link](e);}
9. }
10. }
Another Example
Creating a Simple RMI application involves following steps
import [Link].*;
public interface AddServerInterface extends Remote
{
public int sum(int a,int b);
}
Copy
import [Link].*;
import [Link].*;
public class Adder extends UnicastRemoteObject implements AddServerInterface
{
Adder()throws RemoteException{
super();
}
public int sum(int a,int b)
{
19CS14403 : JAVA PROGRAMMING 123
return a+b;
}
}
Copy
import [Link].*;
import [Link].*;
public class AddServer {
public static void main(String args[]) {
try {
AddServerInterface addService=new Adder();
[Link]("AddService",addService); //addService
object is hosted with name AddService
}
catch(Exception e) {
[Link](e);
}
}
}
Copy
import [Link].*;
public class Client {
19CS14403 : JAVA PROGRAMMING 124
public static void main(String args[]) {
try{
AddServerInterface st =
(AddServerInterface)[Link]("rmi://"+args[0]+"/AddService");
[Link]([Link](25,8));
}
catch(Exception e) {
[Link](e);
}
}
}
Copy
Example:
Program: [Link]
import [Link].*;
public interface Power extends Remote
{
public int power1()throwsRemoteException;
}
Copy
Program: [Link]
import [Link].*;
import [Link].*;
19CS14403 : JAVA PROGRAMMING 127
import [Link];
public class PowerRemote extends UnicastRemoteObject implements Power
{
PowerRemote()throws RemoteException
{
super();
}
public int power1(int z)
{
int z;
Scanner sc = new Scanner([Link]);
[Link]("Enter the base number ::");
int x = [Link]();
[Link]("Enter the exponent number ::");
int y = [Link]();
z=y^x;
[Link](z);
}
}
Copy
[Link]
import [Link].*;
import [Link].*;
public class MyServer
{
public static void main(String args[])
{
try
{
19CS14403 : JAVA PROGRAMMING 128
Power stub=new PowerRemote();
[Link]("rmi://localhost:1995/shristee",stub);
}
catch(Exception e)
{
[Link](e);
}
}
}
Copy
[Link]
import [Link].*;
public class MyClient
{
public static void main(String args[])
{
try
{
Power stub=(Power)[Link]("rmi://localhost:1995/shristee");
[Link](stub.power1());
}
catch(Exception e){}
}
}
Copy
19CS14403 : JAVA PROGRAMMING 129
19CS14403 : JAVA PROGRAMMING 130
Output of this RMI example
19CS14403 : JAVA PROGRAMMING 131