Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Java Notes 2

Uploaded by

meetpandit04
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Java Notes 2

Uploaded by

meetpandit04
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 89

Java String

In Java, string is basically an object that represents sequence of char values.


An array of characters works same as Java string. For example:

1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);
is same as:

1. String s="javatpoint";
Java String class provides a lot of methods to perform operations on strings
such as compare(), concat(), equals(), split(), length(), replace(), compareTo(),
intern(), substring() etc.

The java.lang.String class


implements Serializable, Comparable and CharSequence interfaces.

CharSequence Interface
The CharSequence interface is used to represent the sequence of characters.
String, StringBuffer and StringBuilder classes implement it. It means, we can
create strings in Java by using these three classes.
The Java String is immutable which means it cannot be changed. Whenever we
change any string, a new instance is created. For mutable strings, you can use
StringBuffer and StringBuilder classes.

We will discuss immutable string later. Let's first understand what String in Java
is and how to create the String object.

What is String in Java?


Generally, String is a sequence of characters. But in Java, string is an object that
represents a sequence of characters. The java.lang.String class is used to create
a string object.

How to create a string object?


There are two ways to create String object:

1. By string literal
2. By new keyword

1) String Literal
Java String literal is created by using double quotes. For Example:

1. String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool"
first. If the string already exists in the pool, a reference to the pooled instance is
returned. If the string doesn't exist in the pool, a new string instance is created
and placed in the pool. For example:

1. String s1="Welcome";
2. String s2="Welcome";//It doesn't create a new instance
In the above example, only one object will be created. Firstly, JVM will not find
any string object with the value "Welcome" in string constant pool that is why it
will create a new object. After that it will find the string with the value
"Welcome" in the pool, it will not create a new object but will return the
reference to the same instance.

Note: String objects are stored in a special memory area known as the
"string constant pool".

Why Java uses the concept of String literal?


To make Java more memory efficient (because no new objects are created if it
exists already in the string constant pool).

2) By new keyword
1. String s=new String("Welcome");//creates two objects and one reference var
iable
In such case, JVM will create a new string object in normal (non-pool) heap
memory, and the literal "Welcome" will be placed in the string constant pool.
The variable s will refer to the object in a heap (non-pool).

Interfaces and Classes in Strings in Java


In Java, both String and CharBuffer interact with sequences of characters, but
they are designed with different use cases and underlying mechanisms in mind.
Here's an exploration of their interfaces, classes, and how they fit into the Java
ecosystem.

String
The String class is one of the most fundamental types in Java, designed to
represent immutable sequences of characters. Here's a closer look at its
characteristics and the interfaces it implements:

o Immutability: Once instantiated, a String object cannot be modified.


This immutable design is a deliberate choice to ensure thread safety,
consistency, and efficiency, especially regarding the String pool
mechanism.
o String Pool: Java maintains a pool of string literals to help save
memory. When a new string literal is created, Java checks the Pool for
a matching string. If found, the new variable references the pooled
string. If not, the new string is added to the Pool.
o Implemented Interfaces: The String class implements several
interfaces, including:
o Serializable: Allows string objects to be serialized into byte
streams, facilitating their transmission or storage.
o Comparable<String>: Enables lexical comparison between
two strings, supporting natural ordering within collections.
o CharSequence: Provides a unified read-only interface for
different kinds of char sequences, allowing String objects to be
manipulated and accessed generically.

CharBuffer
CharBuffer, on the other hand, is part of the java.nio package, which provides
a set of classes for non-blocking I/O operations. CharBuffer is a mutable
sequence of characters with more flexibility for manipulation. Here's more
about CharBuffer:

o Mutability and Direct Buffers: Unlike strings, CharBuffer instances


can be modified. They can be either heap-based or direct buffers.
Direct buffers can offer higher performance, especially for I/O
operations, as they are managed outside the Java heap and interact
directly with the operating system's native I/O operations.
o Implemented Interfaces: CharBuffer extends the Buffer class and
implements the CharSequence, Appendable,
Comparable<CharBuffer>, and Readable interfaces, providing a
rich set of functionalities for character sequence manipulation,
comparison, and reading operations.
o Usage Scenarios: It is particularly useful for reading and writing to
channels, regular expressions, and character processing in a more
efficient manner, especially when dealing with large datasets or
requiring fine-grained control over character data.

CharSequence Interface
Java's CharSequence interface provides a unified, read-only view of character
sequences and is a component of the java.lang package. It facilitates consistent
access and manipulation across various types of character sequences, including
String, StringBuilder, StringBuffer, and CharBuffer. Through this interface, key
functionalities for handling character data are defined, enabling actions like
measuring sequence length, accessing particular characters, generating
character subsequences, and transforming into a String format. By providing a
common blueprint for character sequences, `CharSequence` enables flexible
and implementation-independent text processing across the Java platform.

1. String
2. StringBuffer
3. StringBuilder

String
In Java, the String class encapsulates a series of characters. Once instantiated, a
String object's content is fixed and cannot be modified, attributing to its
immutable nature. This immutability ensures that String objects are safe for
concurrent use across threads and are optimally performant in situations where
the textual content remains constant. To enhance memory efficiency, Java
employs a technique called string interning. This approach optimizes the storage
and access of commonly utilized string literals.

Syntax:

Direct assignment using string literals:

1. String str = "Hello, World!";


Using the String constructor:

1. String str = new String("Hello, World!");


Filename: StringExample.java

1. public class StringExample {


2. public static void main(String[] args) {
3. // Creating a String
4. String greeting = "Hello";
5. // Concatenating strings
6. String sentence = greeting + ", World!";
7. // Using a method from the String class
8. int length = sentence.length();
9. System.out.println(sentence); // Output: Hello, World!
10. System.out.println("Length: " + length); // Output: Length: 13
11. }
12. }
Output:

Hello, World!
Length: 13

StringBuffer
StringBuffer represents a mutable sequence of characters that ensures thread
safety, making it suitable for scenarios involving multiple threads that modify a
character sequence. It includes various string manipulation capabilities,
including the ability to insert, delete, and append characters. This design avoids
the necessity of generating new objects with each change, leading to enhanced
efficiency in situations requiring regular adjustments to the string content.

Syntax

1. StringBuffer sb = new StringBuffer();


Filename: StringBufferExample.java

1. public class StringBufferExample {


2. public static void main(String[] args) {
3. // Creating a StringBuffer
4. StringBuffer sb = new StringBuffer("Hello");
5. // Appending to the StringBuffer
6. sb.append(", World!");
7. // Inserting into the StringBuffer
8. sb.insert(5, " Java");
9. // Deleting from the StringBuffer
10. sb.delete(5, 10);
11. System.out.println(sb); // Output: Hello, World!
12. }
13. }
Output:

Hello, World!

StringBuilder
StringBuilder shares similarities with StringBuffer by being a mutable character
sequence. The crucial distinction lies in StringBuilder not being synchronized,
rendering it not suitable for thread-safe operations. This absence of
synchronization, though, contributes to StringBuilder offering superior
performance in environments that are single-threaded or confined to a specific
thread. As a result, StringBuilder becomes the favored option for manipulating
strings in contexts where the safety of concurrent thread access is not an issue.

Syntax

1. StringBuilder sb = new StringBuilder();


Filename: StringBuilderExample.java

1. public class StringBuilderExample {


2. public static void main(String[] args) {
3. // Creating a StringBuilder
4. StringBuilder sb = new StringBuilder("Hello");
5. // Appending to the StringBuilder
6. sb.append(", World!");
7. // Inserting into the StringBuilder
8. sb.insert(5, " Java");
9. // Deleting from the StringBuilder
10. sb.delete(5, 10);
11. System.out.println(sb); // Output: Hello, World!
12. }
13. }
Output:

Hello, World!

StringTokenizer
Java's StringTokenizer class, housed within the java.util package, simplifies the
process of segmenting a string into multiple tokens, utilizing designated
separators. This class is exceptionally beneficial for parsing strings and
navigating through their tokens, especially in scenarios involving user inputs,
file contents, or network transmissions formatted with straightforward
separators such as commas, spaces, or tabs. It offers an efficient means to
dissect and examine the tokenized segments of a string, catering to situations
that demand basic parsing capabilities.

The StringTokenizer class implements the Enumeration<Object> interface,


allowing the tokens of the string to be iterated like other enumeration types in
Java. It offers a straightforward approach to tokenization, avoiding the need for
more complex regular expressions, making it suitable for simple parsing needs.

Syntax:

1. public StringJoiner(CharSequence delimiter)


Filename: StringTokenizer.java

1. import java.util.StringJoiner;
2. public class StringTokenizer {
3. public static void main(String[] args) {
4. // Creating a StringJoiner with a comma (,) as the delimiter
5. StringJoiner joiner = new StringJoiner(", ");
6. // Adding strings to the StringJoiner
7. joiner.add("Apple");
8. joiner.add("Banana");
9. joiner.add("Cherry");
10. // Converting the StringJoiner to a String
11. String result = joiner.toString();
12. // Output the result
13. System.out.println(result); // Output: Apple, Banana, Cherry
14. }
15. }
Output:

Apple, Banana, Cherry

Immutable String in Java


In Java, strings are immutable. It means that its value cannot be changed once a
String object is created. If any operation appears to modify a String, what
happens is the creation of a new String object. The original string remains
unchanged. This immutable characteristic of strings in Java has several
implications for performance, security, and functionality.

Filename: ImmutableStringExample.java

1. public class ImmutableStringExample {


2. public static void main(String[] args) {
3. // Original string
4. String originalString = "Java";
5. System.out.println("Original string: " + originalString);
6. // Attempt to modify the original string
7. String modifiedString = originalString.concat(" Programming");
8. // Showing that the original string remains unchanged
9. System.out.println("After modification, original string: " + originalString)
;
10. // The result of the modification attempt is stored in a new string
11. System.out.println("Modified string: " + modifiedString);
12. // Demonstrating further that the original string is immutable
13. originalString.toUpperCase(); // This operation does not change th
e original string
14. System.out.println("After calling toUpperCase on original string: "
+ originalString);
15. // Correct way to use the result of a string operation
16. String upperCaseString = originalString.toUpperCase(); // Stores t
he result in a new string
17. System.out.println("Original string in uppercase: " + upperCaseStr
ing);
18. }
19. }
Output:

Original string: Java


After modification, original string: Java
Modified string: Java Programming
After calling toUpperCase on original string: Java
Original string in uppercase: JAVA

Memory Allotment of String


Memory allotment for strings in Java is interesting due to Java's handling of
string immutability and the string pool mechanism. Understanding how strings
are stored can help optimize memory usage in Java applications, especially
those that heavily use string manipulations.
String Literal Storage: When you create a string using string literals, Java
checks the string pool first. The new variable points to the existing string if it
already exists. If it doesn't exist, the new string is added to the Pool, and the
variable points to this new string.

Syntax:

1. String s1 = "Hello"; // String literal


2. String s2 = "Hello"; // Points to the same "Hello" in the Pool as s1
new Keyword and String Pool: Strings created with the new operator do not
use the Pool by default. They are stored in the heap memory outside the Pool,
which means each new operation results in a new object, even if it contains the
same string data.

Syntax:

1. String s3 = new String("Hello"); // A new string object is created in the heap


Interning: We can manually add a string to the Pool or ensure it uses the Pool
by calling the intern() method on a string object. If the Pool already contains an
equal string, the string from the Pool is returned. Otherwise, the string is added
to the Pool.

Syntax:

1. String s4 = new String("Hello").intern(); // Ensures use of the string pool


Filename: StringMemoryAllotment.java

1. public class StringMemoryAllotment {


2. public static void main(String[] args) {
3. // String literals - stored in the string pool
4. String str1 = "Java";
5. String str2 = "Java";
6. // Checking if str1 and str2 point to the same object
7. System.out.println("str1 == str2: " + (str1 == str2)); // true, because bo
th refer to the same string literal in the pool
8. // Strings created with 'new' - stored in heap memory outside the string
pool
9. String str3 = new String("Java");
10. String str4 = new String("Java");
11. // Checking if str3 and str4 point to the same object
12. System.out.println("str3 == str4: " + (str3 == str4)); // false, beca
use 'new' creates a new object each time
13. // Interning str3
14. String str5 = str3.intern();
15. // Checking if str1 and str5 point to the same object
16. System.out.println("str1 == str5: " + (str1 == str5)); // true, str5 i
s interned, so it refers to the string in the pool
17. // Demonstrating the effect of interning on memory allocation
18. String str6 = new String("Java").intern();
19. // Checking if str6 is the same as str1
20. System.out.println("str1 == str6: " + (str1 == str6)); // true, str6 i
s interned and points to the pooled instance
21. }
22. }
Output:

str1 == str2: true


str3 == str4: false
str1 == str5: true
str1 == str6: true

Why did the String pool move from PermGen to the normal
heap area?
Java 8 introduced a notable shift in memory management within the Java Virtual
Machine (JVM) by moving the String Pool from the Permanent Generation
(PermGen) to the general heap space. This adjustment was a key element of a
wider effort to improve memory utilization, ease the management and
configuration of memory, and boost the efficiency and scalability of Java-based
applications. To fully comprehend the significance of this change, it's important
to understand both the constraints associated with PermGen and the
advantages that stem from transferring the String Pool and additional metadata
to the heap area.

Syntax:

1. String demoString = new String("Javatpoint").intern();


Filename: StringInternExample.java

1. public class StringInternExample {


2. public static void main(String[] args) {
3. // Creating a string using the new keyword, so it's not in the String Pool i
nitially
4. String demoString = new String("Javatpoint");
5. // Interning the string, which adds it to the String Pool if it's not already t
here
6. // and returns a reference to the string from the Pool
7. String internedString = demoString.intern();
8. // Creating a string literal that is automatically added to the String Pool
9. String literalString = "Javatpoint";
10. // Checking if the interned string and the literal string refer to the
same object in the String Pool
11. System.out.println("Interned String and Literal String refer to the s
ame object: " + (internedString == literalString));
12. }
13. }
Output:

Interned String and Literal String refer to the same object: true

Construct String from a subset of the char array


In Java, creating a String based on a portion of a char array is achievable
through a specific constructor in the String class. This constructor requires three
parameters: the char array to be used, an index indicating the starting point of
the desired subset, and the count of characters to encompass in the subset.
Here's the syntax and an example:

Syntax:

1. String(char[] value, int offset, int count)

o value: The char array.


o offset: The initial offset into the array.
o count: The number of characters to use from the array.
Filename: CharArrayToString.java

1. public class CharArrayToString {


2. public static void main(String[] args) {
3. // Define a char array
4. char[] charArray = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'};
5. // Construct a string from a subset of the char array
6. // Here, we start at index 6 (the space character) and use the next 5 cha
racters
7. String resultString = new String(charArray, 6, 5);
8. // Output the result
9. System.out.println(resultString);
10. }
11. }
Output:
World

Java String Example


StringExample.java

1. public class StringExample{


2. public static void main(String args[]){
3. String s1="java";//creating string by Java string literal
4. char ch[]={'s','t','r','i','n','g','s'};
5. String s2=new String(ch);//converting char array to string
6. String s3=new String("example");//creating Java string by new keyword
7. System.out.println(s1);
8. System.out.println(s2);
9. System.out.println(s3);
10. }}
Test it Now
Output:

java
strings
example

The above code, converts a char array into a String object. And displays the
String objects s1, s2, and s3 on console using println() method.

Java String class methods


The java.lang.String class provides many useful methods to perform operations
on sequence of char values.

No. Method Description

It returns char value for


1 char charAt(int index)
the particular index

2 int length() It returns string length


static String format(String It returns a formatted
3
format, Object... args) string.

static String format(Locale


It returns formatted string
4 l, String format, Object...
with given locale.
args)

String substring(int It returns substring for


5
beginIndex) given begin index.

It returns substring for


String substring(int
6 given begin index and end
beginIndex, int endIndex)
index.

It returns true or false


boolean
7 after matching the
contains(CharSequence s)
sequence of char value.

static String
join(CharSequence
8 It returns a joined string.
delimiter, CharSequence...
elements)

static String
join(CharSequence
9 delimiter, Iterable<? It returns a joined string.
extends CharSequence>
elements)

It checks the equality of


boolean equals(Object
10 string with the given
another)
object.

11 boolean isEmpty() It checks if string is empty.

12 String concat(String str) It concatenates the


specified string.

String replace(char old, It replaces all occurrences


13
char new) of the specified char value.

String It replaces all occurrences


14 replace(CharSequence old, of the specified
CharSequence new) CharSequence.

static String
It compares another string.
15 equalsIgnoreCase(String
It doesn't check case.
another)

It returns a split string


16 String[] split(String regex)
matching regex.

String[] split(String regex, It returns a split string


17
int limit) matching regex and limit.

It returns an interned
18 String intern()
string.

It returns the specified


19 int indexOf(int ch)
char value index.

It returns the specified


int indexOf(int ch, int
20 char value index starting
fromIndex)
with given index.

int indexOf(String It returns the specified


21
substring) substring index.

22 int indexOf(String It returns the specified


substring, int fromIndex) substring index starting
with given index.

It returns a string in
23 String toLowerCase()
lowercase.

It returns a string in
String toLowerCase(Locale
24 lowercase using specified
l)
locale.

It returns a string in
25 String toUpperCase()
uppercase.

It returns a string in
String toUpperCase(Locale
26 uppercase using specified
l)
locale.

It removes beginning and


27 String trim() ending spaces of this
string.

It converts given type into


static String valueOf(int
28 string. It is an overloaded
value)
method.

Exception Handling in Java


1. Exception Handling
2. Advantage of Exception Handling
3. Hierarchy of Exception classes
4. Types of Exception
5. Exception Example
6. Scenarios where an exception may occur

The Exception Handling in Java is one of the powerful mechanism to handle


the runtime errors so that the normal flow of the application can be maintained.
In this tutorial, we will learn about Java exceptions, it's types, and the difference
between checked and unchecked exceptions.

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.

PlayNext
Mute

Current Time 0:00

Duration 18:10
Loaded: 0.37%

Fullscreen
Backward Skip 10sPlay VideoForward Skip 10s

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?
o What is the difference between checked and unchecked exceptions?
o What happens behind the code int data=50/0;?
o Why use multiple catch block?
o Is there any possibility when the finally block is not executed?
o What is exception propagation?
o What is the difference between the throw and throws keyword?
o What are the 4 rules for using exception handling with method overriding?

Hierarchy of Java Exception classes


The java.lang.Throwable class is the root class of Java Exception hierarchy
inherited by two subclasses: Exception and Error. The hierarchy of Java
Exception classes is given below:
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. An error is
considered as the unchecked exception. However, according to Oracle, there are
three types of exceptions namely:

1. Checked Exception
2. Unchecked Exception
3. Error
Difference between Checked and Unchecked Exceptions

1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException
and Error are known as checked exceptions. For example, IOException,
SQLException, etc. Checked exceptions are checked at compile-time.

2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked
exceptions. For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked
at compile-time, but they are checked at runtime.

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

Java Exception Keywords


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

Keyword Description

The "try" keyword is used to specify a


block where we should place an
try exception code. It means we can't use try
block alone. The try block must be
followed by either catch or finally.

The "catch" block is used to handle the


exception. It must be preceded by try
catch block which means we can't use catch
block alone. It can be followed by finally
block later.

The "finally" block is used to execute the


necessary code of the program. It is
finally
executed whether an exception is
handled or not.

The "throw" keyword is used to throw an


throw
exception.

The "throws" keyword is used to declare


exceptions. It specifies that there may
throws occur an exception in the method. It
doesn't throw an exception. It is always
used with method signature.

Java Exception Handling Example


Let's see an example of Java Exception Handling in which we are using a try-
catch statement to handle the exception.

JavaExceptionExample.java

1. public class JavaExceptionExample{


2. public static void main(String args[]){
3. try{
4. //code that may raise exception
5. int data=100/0;
6. }catch(ArithmeticException e){System.out.println(e);}
7. //rest code of the program
8. System.out.println("rest of the code...");
9. }
10. }
Test it Now
Output:

Exception in thread main java.lang.ArithmeticException:/ by zero


rest of the code...

In the above example, 100/0 raises an ArithmeticException which is handled by


a try-catch block.

Common Scenarios of Java Exceptions


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

1) A scenario where ArithmeticException occurs


If we divide any number by zero, there occurs an ArithmeticException.

1. int a=50/0;//ArithmeticException

2) A scenario where NullPointerException occurs


If we have a null value in any variable, performing any operation on the variable
throws a NullPointerException.

1. String s=null;
2. System.out.println(s.length());//NullPointerException

3) A scenario where NumberFormatException occurs


If the formatting of any variable or number is mismatched, it may result into
NumberFormatException. Suppose we have a string variable that has
characters; converting this variable into digit will cause
NumberFormatException.
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException

4) A scenario where ArrayIndexOutOfBoundsException occurs


When an array exceeds to it's size, the ArrayIndexOutOfBoundsException
occurs. there may be other reasons to occur ArrayIndexOutOfBoundsException.
Consider the following statements.

1. int a[]=new int[5];


2. a[10]=50; //ArrayIndexOutOfBoundsException

Java try-catch block


Java try block
Java try block is used to enclose the code that might throw an exception. It
must be used within the method.

If an exception occurs at the particular statement in the try block, the rest of the
block code will not execute. So, it is recommended not to keep the code in try
block that will not throw an exception.

Java try block must be followed by either catch or finally block.

Syntax of Java try-catch


1. try{
2. //code that may throw an exception
3. }catch(Exception_class_Name ref){}

Syntax of try-finally block


1. try{
2. //code that may throw an exception
3. }finally{}

Java catch block


Java catch block is used to handle the Exception by declaring the type of
exception within the parameter. The declared exception must be the parent
class exception ( i.e., Exception) or the generated exception type. However, the
good approach is to declare the generated type of exception.
The catch block must be used after the try block only. You can use multiple
catch block with a single try block.

Internal Working of 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.


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
TryCatchExample1.java
1. public class TryCatchExample1 {
2.
3. public static void main(String[] args) {
4.
5. int data=50/0; //may throw exception
6.
7. System.out.println("rest of the code");
8.
9. }
10.
11. }
Test it Now
Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero

As displayed in the above example, the rest of the code is not executed (in
such case, the rest of the code statement is not printed).

There might be 100 lines of code after the exception. If the exception is not
handled, all the code below the exception won't be executed.

Solution by exception handling


Let's see the solution of the above problem by a java try-catch block.

Example 2
TryCatchExample2.java

1. public class TryCatchExample2 {


2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7. }
8. //handling the exception
9. catch(ArithmeticException e)
10. {
11. System.out.println(e);
12. }
13. System.out.println("rest of the code");
14. }
15.
16. }
Test it Now
Output:

java.lang.ArithmeticException: / by zero
rest of the code

As displayed in the above example, the rest of the code is executed, i.e.,
the rest of the code statement is printed.

Example 3
In this example, we also kept the code in a try block that will not throw an
exception.

TryCatchExample3.java

1. public class TryCatchExample3 {


2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7. // if exception occurs, the remaining statement will not exceu
te
8. System.out.println("rest of the code");
9. }
10. // handling the exception
11. catch(ArithmeticException e)
12. {
13. System.out.println(e);
14. }
15.
16. }
17.
18. }
Test it Now
Output:
java.lang.ArithmeticException: / by zero

Here, we can see that if an exception occurs in the try block, the rest of the
block code will not execute.

Example 4
Here, we handle the exception using the parent class exception.

TryCatchExample4.java

1. public class TryCatchExample4 {


2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7. }
8. // handling the exception by using Exception class
9. catch(Exception e)
10. {
11. System.out.println(e);
12. }
13. System.out.println("rest of the code");
14. }
15.
16. }
Test it Now
Output:

java.lang.ArithmeticException: / by zero
rest of the code

Example 5
Let's see an example to print a custom message on exception.

TryCatchExample5.java

1. public class TryCatchExample5 {


2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7. }
8. // handling the exception
9. catch(Exception e)
10. {
11. // displaying the custom message
12. System.out.println("Can't divided by zero");
13. }
14. }
15.
16. }
Test it Now
Output:

Can't divided by zero

Example 6
Let's see an example to resolve the exception in a catch block.

TryCatchExample6.java

1. public class TryCatchExample6 {


2.
3. public static void main(String[] args) {
4. int i=50;
5. int j=0;
6. int data;
7. try
8. {
9. data=i/j; //may throw exception
10. }
11. // handling the exception
12. catch(Exception e)
13. {
14. // resolving the exception in catch block
15. System.out.println(i/(j+2));
16. }
17. }
18. }
Test it Now
Output:

25

Example 7
In this example, along with try block, we also enclose exception code in a catch
block.

TryCatchExample7.java

1. public class TryCatchExample7 {


2.
3. public static void main(String[] args) {
4.
5. try
6. {
7. int data1=50/0; //may throw exception
8.
9. }
10. // handling the exception
11. catch(Exception e)
12. {
13. // generating the exception in catch block
14. int data2=50/0; //may throw exception
15.
16. }
17. System.out.println("rest of the code");
18. }
19. }
Test it Now
Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero

Here, we can see that the catch block didn't contain the exception code. So,
enclose exception code within a try block and use catch block only to handle the
exceptions.
Example 8
In this example, we handle the generated exception (Arithmetic Exception) with
a different type of exception class (ArrayIndexOutOfBoundsException).

TryCatchExample8.java

1. public class TryCatchExample8 {


2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7.
8. }
9. // try to handle the ArithmeticException using ArrayIndexOutOfBound
sException
10. catch(ArrayIndexOutOfBoundsException e)
11. {
12. System.out.println(e);
13. }
14. System.out.println("rest of the code");
15. }
16.
17. }
Test it Now
Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero

Example 9
Let's see an example to handle another unchecked exception.

TryCatchExample9.java

1. public class TryCatchExample9 {


2.
3. public static void main(String[] args) {
4. try
5. {
6. int arr[]= {1,3,5,7};
7. System.out.println(arr[10]); //may throw exception
8. }
9. // handling the array exception
10. catch(ArrayIndexOutOfBoundsException e)
11. {
12. System.out.println(e);
13. }
14. System.out.println("rest of the code");
15. }
16.
17. }
Test it Now
Output:

java.lang.ArrayIndexOutOfBoundsException: 10
rest of the code

Example 10
Let's see an example to handle checked exception.

TryCatchExample10.java

Advertisement

1. import java.io.FileNotFoundException;
2. import java.io.PrintWriter;
3.
4. public class TryCatchExample10 {
5.
6. public static void main(String[] args) {
7.
8.
9. PrintWriter pw;
10. try {
11. pw = new PrintWriter("jtp.txt"); //may throw exception
12. pw.println("saved");
13. }
14. // providing the checked exception handler
15. catch (FileNotFoundException e) {
16.
17. System.out.println(e);
18. }
19. System.out.println("File saved successfully");
20. }
21. }
Test it Now
Output:

File saved successfully

Java Catch Multiple Exceptions


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

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

Flowchart of Multi-catch Block


Example 1
Let's see a simple example of java multi-catch block.

MultipleCatchBlock1.java

1. public class MultipleCatchBlock1 {


2.
3. public static void main(String[] args) {
4.
5. try{
6. int a[]=new int[5];
7. a[5]=30/0;
8. }
9. catch(ArithmeticException e)
10. {
11. System.out.println("Arithmetic Exception occurs");
12. }
13. catch(ArrayIndexOutOfBoundsException e)
14. {
15. System.out.println("ArrayIndexOutOfBounds Exception occ
urs");
16. }
17. catch(Exception e)
18. {
19. System.out.println("Parent Exception occurs");
20. }
21. System.out.println("rest of the code");
22. }
23. }
Test it Now
Output:

Arithmetic Exception occurs


rest of the code

Example 2
MultipleCatchBlock2.java

1. public class MultipleCatchBlock2 {


2.
3. public static void main(String[] args) {
4.
5. try{
6. int a[]=new int[5];
7.
8. System.out.println(a[10]);
9. }
10. catch(ArithmeticException e)
11. {
12. System.out.println("Arithmetic Exception occurs");
13. }
14. catch(ArrayIndexOutOfBoundsException e)
15. {
16. System.out.println("ArrayIndexOutOfBounds Exception occ
urs");
17. }
18. catch(Exception e)
19. {
20. System.out.println("Parent Exception occurs");
21. }
22. System.out.println("rest of the code");
23. }
24. }
Test it Now
Output:

ArrayIndexOutOfBounds Exception occurs


rest of the code

In this example, try block contains two exceptions. But at a time only one
exception occurs and its corresponding catch block is executed.

MultipleCatchBlock3.java

1. public class MultipleCatchBlock3 {


2.
3. public static void main(String[] args) {
4.
5. try{
6. int a[]=new int[5];
7. a[5]=30/0;
8. System.out.println(a[10]);
9. }
10. catch(ArithmeticException e)
11. {
12. System.out.println("Arithmetic Exception occurs");
13. }
14. catch(ArrayIndexOutOfBoundsException e)
15. {
16. System.out.println("ArrayIndexOutOfBounds Exception occ
urs");
17. }
18. catch(Exception e)
19. {
20. System.out.println("Parent Exception occurs");
21. }
22. System.out.println("rest of the code");
23. }
24. }
Test it Now
Output:

Arithmetic Exception occurs


rest of the code
Example 4
In this example, we generate NullPointerException, but didn't provide the
corresponding exception type. In such case, the catch block containing the
parent exception class Exception will invoked.

MultipleCatchBlock4.java

1. public class MultipleCatchBlock4 {


2.
3. public static void main(String[] args) {
4.
5. try{
6. String s=null;
7. System.out.println(s.length());
8. }
9. catch(ArithmeticException e)
10. {
11. System.out.println("Arithmetic Exception occurs");
12. }
13. catch(ArrayIndexOutOfBoundsException e)
14. {
15. System.out.println("ArrayIndexOutOfBounds Exception occ
urs");
16. }
17. catch(Exception e)
18. {
19. System.out.println("Parent Exception occurs");
20. }
21. System.out.println("rest of the code");
22. }
23. }
Test it Now
Output:

Parent Exception occurs


rest of the code

Example 5
Let's see an example, to handle the exception without maintaining the order of
exceptions (i.e. from most specific to most general).
MultipleCatchBlock5.java

1. class MultipleCatchBlock5{
2. public static void main(String args[]){
3. try{
4. int a[]=new int[5];
5. a[5]=30/0;
6. }
7. catch(Exception e){System.out.println("common task completed");}
8. catch(ArithmeticException e){System.out.println("task1 is completed");}
9. catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 co
mpleted");}
10. System.out.println("rest of the code...");
11. }
12. }
Test it Now
Output:

Compile-time error

Java finally block


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

Java finally block is always executed whether an exception is handled or not.


Therefore, it contains all the necessary statements that need to be printed
regardless of the exception occurs or not.

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.

Usage of Java finally


Let's see the different cases where Java finally block can be used.

Case 1: When an exception does not occur


Let's see the below example where the Java program does not throw any
exception, and the finally block is executed after the try block.

TestFinallyBlock.java
1. class TestFinallyBlock {
2. public static void main(String args[]){
3. try{
4. //below code do not throw any exception
5. int data=25/5;
6. System.out.println(data);
7. }
8. //catch won't be executed
9. catch(NullPointerException e){
10. System.out.println(e);
11. }
12. //executed regardless of exception occurred or not
13. finally {
14. System.out.println("finally block is always executed");
15. }
16.
17. System.out.println("rest of phe code...");
18. }
19. }
Output:

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.

TestFinallyBlock1.java

1. public class TestFinallyBlock1{


2. public static void main(String args[]){
3.
4. try {
5.
6. System.out.println("Inside the try block");
7.
8. //below code throws divide by zero exception
9. int data=25/0;
10. System.out.println(data);
11. }
12. //cannot handle Arithmetic type exception
13. //can only accept Null Pointer type exception
14. catch(NullPointerException e){
15. System.out.println(e);
16. }
17.
18. //executes regardless of exception occured or not
19. finally {
20. System.out.println("finally block is always executed");
21. }
22.
23. System.out.println("rest of the code...");
24. }
25. }
Output:

Case 3: When an exception occurs and is handled by the


catch block
Example:

Let's see the following example where the Java code throws an exception and
the catch block handles the exception. Later the finally block is executed after
the try-catch block. Further, the rest of the code is also executed normally.

TestFinallyBlock2.java

1. public class TestFinallyBlock2{


2. public static void main(String args[]){
3.
4. try {
5.
6. System.out.println("Inside try block");
7.
8. //below code throws divide by zero exception
9. int data=25/0;
10. System.out.println(data);
11. }
12.
13. //handles the Arithmetic Exception / Divide by zero exception
14. catch(ArithmeticException e){
15. System.out.println("Exception handled");
16. System.out.println(e);
17. }
18.
19. //executes regardless of exception occured or not
20. finally {
21. System.out.println("finally block is always executed");
22. }
23.
24. System.out.println("rest of the code...");
25. }
26. }
Output:

Rule: For each try block there can be zero or more catch blocks, but only one
finally block.
Note: The finally block will not be executed if the program exits (either by
calling System.exit() or by causing a fatal error that causes the process to
abort).

Java throw Exception


In Java, exceptions allows us to write good quality codes where the errors are
checked at the compile time instead of runtime and we can create custom
exceptions making the code recovery and debugging easier.

Java throw keyword


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

We specify the exception object which is to be thrown. The Exception has some
message with it that provides the error description. These exceptions may be
related to user inputs, server, etc.

We can throw either checked or unchecked exceptions in Java by throw


keyword. It is mainly used to throw a custom exception. We will discuss custom
exceptions later in this section.

We can also define our own set of conditions and throw an exception explicitly
using throw keyword. For example, we can throw ArithmeticException if we
divide a number by another number. Here, we just need to set the condition and
throw exception using throw keyword.

The syntax of the Java throw keyword is given below.

throw Instance i.e.,

1. throw new exception_class("error message");


Let's see the example of throw IOException.

1. throw new IOException("sorry device error");


Where the Instance must be of type Throwable or subclass of Throwable. For
example, Exception is the sub class of Throwable and the user-defined
exceptions usually extend the Exception class.

Java throw keyword Example

Example 1: Throwing Unchecked Exception


In this example, we have created a method named validate() that accepts an
integer as a parameter. If the age is less than 18, we are throwing the
ArithmeticException otherwise print a message welcome to vote.

TestThrow1.java

In this example, we have created the validate method that takes integer value
as a parameter. If the age is less than 18, we are throwing the
ArithmeticException otherwise print a message welcome to vote.

1. public class TestThrow1 {


2. //function to check if person is eligible to vote or not
3. public static void validate(int age) {
4. if(age<18) {
5. //throw Arithmetic exception if not eligible to vote
6. throw new ArithmeticException("Person is not eligible to vote");
7. }
8. else {
9. System.out.println("Person is eligible to vote!!");
10. }
11. }
12. //main method
13. public static void main(String args[]){
14. //calling the function
15. validate(13);
16. System.out.println("rest of the code...");
17. }
18. }
Output:

The above code throw an unchecked exception. Similarly, we can also throw
unchecked and user defined exceptions.

Note: If we throw unchecked exception from a method, it is must to handle


the exception or declare in throws clause.
If we throw a checked exception using throw keyword, it is must to handle the
exception using catch block or the method must declare it using throws
declaration.

Example 2: Throwing Checked Exception


Note: Every subclass of Error and RuntimeException is an unchecked
exception in Java. A checked exception is everything else under the
Throwable class.
TestThrow2.java

1. import java.io.*;
2.
3. public class TestThrow2 {
4.
5. //function to check if person is eligible to vote or not
6. public static void method() throws FileNotFoundException {
7.
8. FileReader file = new FileReader("C:\\Users\\Anurati\\Desktop\\abc.txt");

9. BufferedReader fileInput = new BufferedReader(file);


10.
11.
12. throw new FileNotFoundException();
13.
14. }
15. //main method
16. public static void main(String args[]){
17. try
18. {
19. method();
20. }
21. catch (FileNotFoundException e)
22. {
23. e.printStackTrace();
24. }
25. System.out.println("rest of the code...");
26. }
27. }
Output:

Example 3: Throwing User-defined Exception


exception is everything else under the Throwable class.
TestThrow3.java

1. // class represents user-defined exception


2. class UserDefinedException extends Exception
3. {
4. public UserDefinedException(String str)
5. {
6. // Calling constructor of parent Exception
7. super(str);
8. }
9. }
10. // Class that uses above MyException
11. public class TestThrow3
12. {
13. public static void main(String args[])
14. {
15. try
16. {
17. // throw an object of user defined exception
18. throw new UserDefinedException("This is user-defined excepti
on");
19. }
20. catch (UserDefinedException ude)
21. {
22. System.out.println("Caught the exception");
23. // Print the message from MyException object
24. System.out.println(ude.getMessage());
25. }
26. }
27. }
Output:

Java throws keyword


The Java throws keyword is used to declare an exception. It gives an
information to the programmer that there may occur an exception. So, it is
better for the programmer to provide the exception handling code so that the
normal flow of the program can be maintained.

Exception Handling is mainly used to handle the checked exceptions. If there


occurs any unchecked exception such as NullPointerException, it is
programmers' fault that he is not checking the code before it being used.

Syntax of Java throws


1. return_type method_name() throws exception_class_name{
2. //method code
3. }

Which exception should be declared?


Ans: Checked exception only, because:

o unchecked exception: under our control so we can correct our code.


o error: beyond our control. For example, we are unable to do anything
if there occurs VirtualMachineError or StackOverflowError.

Advantage of Java throws keyword


Now Checked Exception can be propagated (forwarded in call stack).

It provides information to the caller of the method about the exception.

Java throws Example


Let's see the example of Java throws clause which describes that checked
exceptions can be propagated by throws keyword.

Testthrows1.java

1. import java.io.IOException;
2. class Testthrows1{
3. void m()throws IOException{
4. throw new IOException("device error");//checked exception
5. }
6. void n()throws IOException{
7. m();
8. }
9. void p(){
10. try{
11. n();
12. }catch(Exception e){System.out.println("exception handled");}
13. }
14. public static void main(String args[]){
15. Testthrows1 obj=new Testthrows1();
16. obj.p();
17. System.out.println("normal flow...");
18. }
19. }
Test it Now
Output:

exception handled
normal flow...

Rule: If we are calling a method that declares an exception, we must either


caught or declare the exception.
There are two cases:

1. Case 1: We have caught the exception i.e. we have handled the exception using
try/catch block.
2. Case 2: We have declared the exception i.e. specified throws keyword with the
method.

Case 1: Handle Exception Using try-catch block


In case we handle the exception, the code will be executed fine whether
exception occurs during the program or not.

Testthrows2.java

1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. }
6. }
7. public class Testthrows2{
8. public static void main(String args[]){
9. try{
10. M m=new M();
11. m.method();
12. }catch(Exception e){System.out.println("exception handled");}
13.
14. System.out.println("normal flow...");
15. }
16. }
Test it Now
Output:
exception handled
normal flow...

Case 2: Declare Exception


o In case we declare the exception, if exception does not occur, the code
will be executed fine.
o In case we declare the exception and the exception occurs, it will be
thrown at runtime because throws does not handle the exception.
Let's see examples for both the scenario.

A) If exception does not occur

Testthrows3.java

1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. System.out.println("device operation performed");
5. }
6. }
7. class Testthrows3{
8. public static void main(String args[])throws IOException{//declare exce
ption
9. M m=new M();
10. m.method();
11.
12. System.out.println("normal flow...");
13. }
14. }
Test it Now
Output:

device operation performed


normal flow...

B) If exception occurs

Testthrows4.java

1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. }
6. }
7. class Testthrows4{
8. public static void main(String args[])throws IOException{//declare exce
ption
9. M m=new M();
10. m.method();
11.
12. System.out.println("normal flow...");
13. }
14. }
Test it Now
Output:

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.

Advantage of Java Networking


1. Sharing resources
2. Centralize software management

Do You Know ?

o How to perform connection-oriented Socket Programming in networking ?


o How to display the data of any online web page ?
o How to get the IP address of any host name e.g. www.google.com ?
o How to perform connection-less socket programming in networking ?
The java.net package supports two protocols,
1. TCP: Transmission Control Protocol provides reliable communication between the
sender and receiver. TCP is used along with the Internet Protocol referred as
TCP/IP.
2. UDP: User Datagram Protocol provides a connection-less protocol service by
allowing packet of data to be transferred along two or more nodes

Java Networking Terminology


The widely used Java networking terminologies are given below:

Backward Skip 10sPlay VideoForward Skip 10s

1. IP Address
2. Protocol
3. Port Number
4. MAC Address
5. Connection-oriented and connection-less protocol
6. Socket

1) IP Address
IP address is a unique number assigned to a node of a network e.g.
192.168.0.1 . It is composed of octets that range from 0 to 255.

It is a logical address that can be changed.

2) Protocol
A protocol is a set of rules basically that is followed for communication. For
example:

o TCP
o FTP
o Telnet
o SMTP
o POP etc.

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.

java.net package
The java.net 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.

Java Socket Programming


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.

The client in socket programming must know two information:


1. IP Address of Server, and
2. Port number.

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

returns the InputStream attached with


1) public InputStream getInputStream()
this socket.

2) public OutputStream returns the OutputStream attached with


getOutputStream() this socket.

3) public synchronized void close() closes this socket

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

returns the socket and establish a


1) public Socket accept()
connection between server and client.

2) public synchronized void close() closes the server socket.

Example of Java Socket Programming


Creating Server:

To create the server application, we need to create the instance of ServerSocket


class. Here, we are using 6666 port number for the communication between the
client and server. You may also choose any other port number. The accept()
method waits for the client. If clients connects with the given port number, it
returns an instance of Socket.

1. ServerSocket ss=new ServerSocket(6666);


2. Socket s=ss.accept();//establishes connection and waits for the client
Creating Client:

To create the client application, we need to create the instance of Socket class.
Here, we need to pass the IP address or hostname of the Server and a port
number. Here, we are using "localhost" because our server is running on same
system.

1. Socket s=new Socket("localhost",6666);


Let's see a simple of Java socket programming where client sends a text and
server receives and prints it.

File: MyServer.java

1. import java.io.*;
2. import java.net.*;
3. public class MyServer {
4. public static void main(String[] args){
5. try{
6. ServerSocket ss=new ServerSocket(6666);
7. Socket s=ss.accept();//establishes connection
8. DataInputStream dis=new DataInputStream(s.getInputStream());
9. String str=(String)dis.readUTF();
10. System.out.println("message= "+str);
11. ss.close();
12. }catch(Exception e){System.out.println(e);}
13. }
14. }
File: MyClient.java

1. import java.io.*;
2. import java.net.*;
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(s.getOutputStream());
8. dout.writeUTF("Hello Server");
9. dout.flush();
10. dout.close();
11. s.close();
12. }catch(Exception e){System.out.println(e);}
13. }
14. }
download this example
To execute this program open two command prompts and execute each
program at each command prompt as displayed in the below figure.

After running the client application, a message will be displayed on the server
console.

Example of Java Socket Programming (Read-Write both side)


In this example, client will write first to the server then server will receive and
print the text. Then server will write to the client and client will receive and print
the text. The step goes on.

File: MyServer.java

1. import java.net.*;
2. import java.io.*;
3. class MyServer{
4. public static void main(String args[])throws Exception{
5. ServerSocket ss=new ServerSocket(3333);
6. Socket s=ss.accept();
7. DataInputStream din=new DataInputStream(s.getInputStream());
8. DataOutputStream dout=new DataOutputStream(s.getOutputStream());
9. BufferedReader br=new BufferedReader(new InputStreamReader(System.in
));
10.
11. String str="",str2="";
12. while(!str.equals("stop")){
13. str=din.readUTF();
14. System.out.println("client says: "+str);
15. str2=br.readLine();
16. dout.writeUTF(str2);
17. dout.flush();
18. }
19. din.close();
20. s.close();
21. ss.close();
22. }}
File: MyClient.java

1. import java.net.*;
2. import java.io.*;
3. class MyClient{
4. public static void main(String args[])throws Exception{
5. Socket s=new Socket("localhost",3333);
6. DataInputStream din=new DataInputStream(s.getInputStream());
7. DataOutputStream dout=new DataOutputStream(s.getOutputStream());
8. BufferedReader br=new BufferedReader(new InputStreamReader(System.in
));
9.
10. String str="",str2="";
11. while(!str.equals("stop")){
12. str=br.readLine();
13. dout.writeUTF(str);
14. dout.flush();
15. str2=din.readUTF();
16. System.out.println("Server says: "+str2);
17. }
18.
19. dout.close();
20. s.close();
21. }}

Java URL
The Java URL class represents an URL. URL is an acronym for Uniform Resource
Locator. It points to a resource on the World Wide Web. For example:

1. https://www.javatpoint.com/java-tutorial

A URL contains many information:

1. Protocol: In this case, http is the protocol.


2. Server name or IP Address: In this case, www.javatpoint.com is the
server name.
3. Port Number: It is an optional attribute. If we write
http//ww.javatpoint.com:80/sonoojaiswal/ , 80 is the port number. If
port number is not mentioned in the URL, it returns -1.
4. File Name or directory name: In this case, index.jsp is the file
name.

Constructors of Java URL class


URL(String spec)

Creates an instance of a URL from the String representation.

URL(String protocol, String host, int port, String file)

Creates an instance of a URL from the given protocol, host, port number, and
file.

URL(String protocol, String host, int port, String file,


URLStreamHandler handler)

Creates an instance of a URL from the given protocol, host, port number, file,
and handler.

URL(String protocol, String host, String file)


Creates an instance of a URL from the given protocol name, host name, and file
name.

URL(URL context, String spec)

Creates an instance of a URL by parsing the given spec within a specified


context.

URL(URL context, String spec, URLStreamHandler handler)

Creates an instance of a URL by parsing the given spec with the specified
handler within a given context.

Commonly used methods of Java URL class


The java.net.URL class provides many methods. The important methods of URL
class are given below.

Method Description

public String getProtocol() it returns the protocol of the URL.

public String getHost() it returns the host name of the URL.

public String getPort() it returns the Port Number of the URL.

public String getFile() it returns the file name of the URL.

public String getAuthority() it returns the authority of the URL.

it returns the string representation of the


public String toString()
URL.

public String getQuery() it returns the query string of the URL.

public String getDefaultPort() it returns the default port of the URL.


it returns the instance of URLConnection
public URLConnection openConnection()
i.e. associated with this URL.

it compares the URL with the given


public boolean equals(Object obj)
object.

public Object getContent() it returns the content of the URL.

it returns the anchor or reference of the


public String getRef()
URL.

public URI toURI() it returns a URI of the URL.

Example of Java URL class


1. //URLDemo.java
2. import java.net.*;
3. public class URLDemo{
4. public static void main(String[] args){
5. try{
6. URL url=new URL("http://www.javatpoint.com/java-tutorial");
7.
8. System.out.println("Protocol: "+url.getProtocol());
9. System.out.println("Host Name: "+url.getHost());
10. System.out.println("Port Number: "+url.getPort());
11. System.out.println("File Name: "+url.getFile());
12.
13. }catch(Exception e){System.out.println(e);}
14. }
15. }
Test it Now
Output:

Protocol: http
Host Name: www.javatpoint.com
Port Number: -1
File Name: /java-tutorial

Let us see another example URL class in Java.

1. //URLDemo.java
2. import java.net.*;
3. public class URLDemo{
4. public static void main(String[] args){
5. try{
6. URL url=new URL("https://www.google.com/search?
q=javatpoint&oq=javatpoint&sourceid=chrome&ie=UTF-8");
7.
8. System.out.println("Protocol: "+url.getProtocol());
9. System.out.println("Host Name: "+url.getHost());
10. System.out.println("Port Number: "+url.getPort());
11. System.out.println("Default Port Number: "+url.getDefaultPort());
12. System.out.println("Query String: "+url.getQuery());
13. System.out.println("Path: "+url.getPath());
14. System.out.println("File: "+url.getFile());
15.
16. }catch(Exception e){System.out.println(e);}
17. }
18. }
Output:

Protocol: https
Host Name: www.google.com
Port Number: -1
Default Port Number: 443
Query String: q=javatpoint&oq=javatpoint&sourceid=chrome&ie=UTF-8
Path: /search
File: /search?q=javatpoint&oq=javatpoint&sourceid=chrome&ie=UTF-8

Java Applet
Applet is a special type of program that is embedded in the webpage to
generate the dynamic content. It runs inside the browser and works at client
side.
Advantage of Applet
There are many advantages of applet. They are as follows:

o It works at client side so less response time.


o Secured
o It can be executed by browsers running under many plateforms,
including Linux, Windows, Mac Os etc.

Drawback of Applet
 Plugin is required at client browser to execute applet.

Do You Know

o Who is responsible to manage the life cycle of an applet ?


o How to perform animation in applet ?
o How to paint like paint brush in applet ?
o How to display digital clock in applet ?
o How to display analog clock in applet ?
o How to communicate two applets ?

Hierarchy of Applet
As displayed in the above diagram, Applet class extends Panel. Panel class extends
Container which is the subclass of Component.

Lifecycle of Java Applet


1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
Lifecycle methods for Applet:
The java.applet.Applet class 4 life cycle methods and java.awt.Component class
provides 1 life cycle methods for an applet.

java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4
life cycle methods of applet.

1. public void init(): is used to initialized the Applet. It is invoked only


once.
2. public void start(): is invoked after the init() method or browser is
maximized. It is used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when
Applet is stop or browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked
only once.

java.awt.Component class
The Component class provides 1 life cycle method of applet.
1. public void paint(Graphics g): is used to paint the Applet. It
provides Graphics class object that can be used for drawing oval,
rectangle, arc etc.

Who is responsible to manage the life cycle of an applet?


Java Plug-in software.

How to run an Applet?


There are two ways to run an applet

1. By html file.
2. By appletViewer tool (for testing purpose).

Simple example of Applet by html file:


To execute the applet by html file, create an applet and compile it. After that
create an html file and place the applet code in html file. Now click the html file.

1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5.
6. public void paint(Graphics g){
7. g.drawString("welcome",150,150);
8. }
9.
10. }
Note: class must be public because its object is created by Java Plugin
software that resides on the browser.

myapplet.html
1. <html>
2. <body>
3. <applet code="First.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>

Simple example of Applet by appletviewer tool:


To execute the applet by appletviewer tool, create an applet that contains
applet tag in comment and compile it. After that run it by: appletviewer
First.java. Now Html file is not required but it is for testing purpose only.

1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5.
6. public void paint(Graphics g){
7. g.drawString("welcome to applet",150,150);
8. }
9.
10. }
11. /*
12. <applet code="First.class" width="300" height="300">
13. </applet>
14. */
To execute the applet by appletviewer tool, write in command prompt:

c:\>javac First.java
c:\>appletviewer First.java

Displaying Graphics in Applet


java.awt.Graphics class provides many methods for graphics programming.

Commonly used methods of Graphics class:


1. public abstract void drawString(String str, int x, int y): is used
to draw the specified string.
2. public void drawRect(int x, int y, int width, int height): draws a
rectangle with the specified width and height.
3. public abstract void fillRect(int x, int y, int width, int height): is
used to fill rectangle with the default color and specified width and
height.
4. public abstract void drawOval(int x, int y, int width, int
height): is used to draw oval with the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is
used to fill oval with the default color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is
used to draw line between the points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y,
ImageObserver observer): is used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height,
int startAngle, int arcAngle): is used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int
startAngle, int arcAngle): is used to fill a circular or elliptical arc.
10. public abstract void setColor(Color c): is used to set the
graphics current color to the specified color.
11. public abstract void setFont(Font font): is used to set the
graphics current font to the specified font.

Example of Graphics in applet:

1. import java.applet.Applet;
2. import java.awt.*;
3.
4. public class GraphicsDemo extends Applet{
5.
6. public void paint(Graphics g){
7. g.setColor(Color.red);
8. g.drawString("Welcome",50, 50);
9. g.drawLine(20,30,20,300);
10. g.drawRect(70,100,30,30);
11. g.fillRect(170,100,30,30);
12. g.drawOval(70,200,30,30);
13.
14. g.setColor(Color.pink);
15. g.fillOval(170,200,30,30);
16. g.drawArc(90,150,30,30,30,270);
17. g.fillArc(270,150,30,30,0,180);
18.
19. }
20. }

myapplet.html
1. <html>
2. <body>
3. <applet code="GraphicsDemo.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>

Displaying Image in Applet


Applet is mostly used in games and animation. For this purpose image is
required to be displayed. The java.awt.Graphics class provide a method
drawImage() to display the image.

Syntax of drawImage() method:


1. public abstract boolean drawImage(Image img, int x, int y,
ImageObserver observer): is used draw the specified image.

How to get the object of Image:


The java.applet.Applet class provides getImage() method that returns the object of
Image. Syntax:
1. public Image getImage(URL u, String image){}

Other required methods of Applet class to display image:


1. public URL getDocumentBase(): is used to return the URL of the document in
which applet is embedded.
2. public URL getCodeBase(): is used to return the base URL.

Example of displaying image in applet:

1. import java.awt.*;
2. import java.applet.*;
3.
4.
5. public class DisplayImage extends Applet {
6.
7. Image picture;
8.
9. public void init() {
10. picture = getImage(getDocumentBase(),"sonoo.jpg");
11. }
12.
13. public void paint(Graphics g) {
14. g.drawImage(picture, 30,30, this);
15. }
16.
17. }
In the above example, drawImage() method of Graphics class is used to display the
image. The 4th argument of drawImage() method of is ImageObserver object. The
Component class implements ImageObserver interface. So current class object would
also be treated as ImageObserver because Applet class indirectly extends the
Component class.

myapplet.html
1. <html>
2. <body>
3. <applet code="DisplayImage.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>

Animation in Applet
Applet is mostly used in games and animation. For this purpose image is required to be
moved.

Example of animation in applet:


1. import java.awt.*;
2. import java.applet.*;
3. public class AnimationExample extends Applet {
4.
5. Image picture;
6.
7. public void init() {
8. picture =getImage(getDocumentBase(),"bike_1.gif");
9. }
10.
11. public void paint(Graphics g) {
12. for(int i=0;i<500;i++){
13. g.drawImage(picture, i,30, this);
14.
15. try{Thread.sleep(100);}catch(Exception e){}
16. }
17. }
18. }
In the above example, drawImage() method of Graphics class is used to display the
image. The 4th argument of drawImage() method of is ImageObserver object. The
Component class implements ImageObserver interface. So current class object would
also be treated as ImageObserver because Applet class indirectly extends the
Component class.

myapplet.html
1. <html>
2. <body>
3. <applet code="DisplayImage.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>

EventHandling in Applet
As we perform event handling in AWT or Swing, we can perform it in applet also. Let's
see the simple example of event handling in applet that prints a message by click on
the button.

Example of EventHandling in applet:

1. import java.applet.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. public class EventApplet extends Applet implements ActionListener{
5. Button b;
6. TextField tf;
7.
8. public void init(){
9. tf=new TextField();
10. tf.setBounds(30,40,150,20);
11.
12. b=new Button("Click");
13. b.setBounds(80,150,60,50);
14.
15. add(b);add(tf);
16. b.addActionListener(this);
17.
18. setLayout(null);
19. }
20.
21. public void actionPerformed(ActionEvent e){
22. tf.setText("Welcome");
23. }
24. }
In the above example, we have created all the controls in init() method because it is
invoked only once.

myapplet.html
1. <html>
2. <body>
3. <applet code="EventApplet.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
<<prevnext>>

JApplet class in Applet


As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of
swing. The JApplet class extends the Applet class.

Example of EventHandling in JApplet:

1. import java.applet.*;
2. import javax.swing.*;
3. import java.awt.event.*;
4. public class EventJApplet extends JApplet implements ActionListener{
5. JButton b;
6. JTextField tf;
7. public void init(){
8.
9. tf=new JTextField();
10. tf.setBounds(30,40,150,20);
11.
12. b=new JButton("Click");
13. b.setBounds(80,150,70,40);
14.
15. add(b);add(tf);
16. b.addActionListener(this);
17.
18. setLayout(null);
19. }
20.
21. public void actionPerformed(ActionEvent e){
22. tf.setText("Welcome");
23. }
24. }
In the above example, we have created all the controls in init() method because it is
invoked only once.

myapplet.html
1. <html>
2. <body>
3. <applet code="EventJApplet.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>

Servlets | Servlet Tutorial


Servlet technology is used to create a web application (resides at server side
and generates a dynamic web page).

Servlet technology is robust and scalable because of java language. Before


Servlet, CGI (Common Gateway Interface) scripting language was common as a
server-side programming language. However, there were many disadvantages
to this technology. We have discussed these disadvantages below.

There are many interfaces and classes in the Servlet API such as Servlet,
GenericServlet, HttpServlet, ServletRequest, ServletResponse, etc.

What is a Servlet?
Servlet can be described in many ways, depending on the context.

o Servlet is a technology which is used to create a web application.


o Servlet is an API that provides many interfaces and classes including
documentation.
o Servlet is an interface that must be implemented for creating any
Servlet.
o Servlet is a class that extends the capabilities of the servers and
responds to the incoming requests. It can respond to any requests.
o Servlet is a web component that is deployed on the server to create a
dynamic web page.
What is a web application?
A web application is an application accessible from the web. A web application is
composed of web components like Servlet, JSP, Filter, etc. and other elements
such as HTML, CSS, and JavaScript. The web components typically execute in
Web Server and respond to the HTTP request.

CGI (Common Gateway Interface)


CGI technology enables the web server to call an external program and pass
HTTP request information to the external program to process the request. For
each request, it starts a new process.
Disadvantages of CGI
There are many problems in CGI technology:

1. If the number of clients increases, it takes more time for sending the response.
2. For each request, it starts a process, and the web server is limited to start
processes.
3. It uses platform dependent language e.g. C, C++, perl.

Advantages of Servlet

There are many advantages of Servlet over CGI. The web container creates
threads for handling the multiple requests to the Servlet. Threads have many
benefits over the Processes such as they share a common memory area,
lightweight, cost of communication between the threads are low. The
advantages of Servlet are as follows:

1. Better performance: because it creates a thread for each request, not process.
2. Portability: because it uses Java language.
3. Robust: JVM manages Servlets, so we don't need to worry about the memory
leak, garbage collection, etc.
4. Secure: because it uses java language.

Servlet Interface
1. Servlet Interface
2. Methods of Servlet interface

Servlet interface provides commonbehaviorto all the servlets.Servlet


interface defines methods that all servlets must implement.

Servlet interface needs to be implemented for creating any servlet (either


directly or indirectly). It provides 3 life cycle methods that are used to initialize
the servlet, to service the requests, and to destroy the servlet and 2 non-life
cycle methods.

Methods of Servlet interface


There are 5 methods in Servlet interface. The init, service and destroy are the
life cycle methods of servlet. These are invoked by the web container.

Method Description

initializes the servlet. It is the life cycle


public void init(ServletConfig config) method of servlet and invoked by the
web container only once.

provides response for the incoming


public void service(ServletRequest
request. It is invoked at each request by
request,ServletResponse response)
the web container.

public void destroy() is invoked only once and indicates that


servlet is being destroyed.

public ServletConfig
returns the object of ServletConfig.
getServletConfig()

returns information about servlet such as


public String getServletInfo()
writer, copyright, version etc.

Servlet Example by implementing Servlet interface


Let's see the simple example of servlet by implementing the servlet interface.

It will be better if you learn it after visiting steps to create a servlet.


File: First.java
1. import java.io.*;
2. import javax.servlet.*;
3.
4. public class First implements Servlet{
5. ServletConfig config=null;
6.
7. public void init(ServletConfig config){
8. this.config=config;
9. System.out.println("servlet is initialized");
10. }
11.
12. public void service(ServletRequest req,ServletResponse res)
13. throws IOException,ServletException{
14.
15. res.setContentType("text/html");
16.
17. PrintWriter out=res.getWriter();
18. out.print("<html><body>");
19. out.print("<b>hello simple servlet</b>");
20. out.print("</body></html>");
21.
22. }
23. public void destroy(){System.out.println("servlet is destroyed");}
24. public ServletConfig getServletConfig(){return config;}
25. public String getServletInfo(){return "copyright 2007-1010";}
26.
27. }

GenericServlet class
1. GenericServlet class
2. Methods of GenericServlet class
3. Example of GenericServlet class

GenericServlet class
implements Servlet, ServletConfig and Serializable interfaces. It provides
the implementation of all the methods of these interfaces except the service
method.

GenericServlet class can handle any type of request so it is protocol-


independent.

You may create a generic servlet by inheriting the GenericServlet class and
providing the implementation of the service method.

Methods of GenericServlet class


There are many methods in GenericServlet class. They are as follows:

1. public void init(ServletConfig config) is used to initialize the servlet.


2. public abstract void service(ServletRequest request, ServletResponse
response) provides service for the incoming request. It is invoked at each time
when user requests for a servlet.
3. public void destroy() is invoked only once throughout the life cycle and
indicates that servlet is being destroyed.
4. public ServletConfig getServletConfig() returns the object of ServletConfig.
5. public String getServletInfo() returns information about servlet such as
writer, copyright, version etc.
6. public void init() it is a convenient method for the servlet programmers, now
there is no need to call super.init(config)
7. public ServletContext getServletContext() returns the object of
ServletContext.
8. public String getInitParameter(String name) returns the parameter value
for the given parameter name.
9. public Enumeration getInitParameterNames() returns all the parameters
defined in the web.xml file.
10. public String getServletName() returns the name of the servlet object.
11. public void log(String msg) writes the given message in the servlet log file.
12. public void log(String msg,Throwable t) writes the explanatory message in
the servlet log file and a stack trace.

Servlet Example by inheriting the GenericServlet class


Let's see the simple example of servlet by inheriting the GenericServlet class.

It will be better if you learn it after visiting steps to create a servlet.


File: First.java
1. import java.io.*;
2. import javax.servlet.*;
3.
4. public class First extends GenericServlet{
5. public void service(ServletRequest req,ServletResponse res)
6. throws IOException,ServletException{
7.
8. res.setContentType("text/html");
9.
10. PrintWriter out=res.getWriter();
11. out.print("<html><body>");
12. out.print("<b>hello generic servlet</b>");
13. out.print("</body></html>");
14.
15. }
16. }

HttpServlet class
1. HttpServlet class
2. Methods of HttpServlet class

The HttpServlet class extends the GenericServlet class and implements Serializable
interface. It provides http specific methods such as doGet, doPost, doHead, doTrace
etc.

Methods of HttpServlet class


There are many methods in HttpServlet class. They are as follows:
1. public void service(ServletRequest req,ServletResponse res) dispatches
the request to the protected service method by converting the request and
response object into http type.
2. protected void service(HttpServletRequest req, HttpServletResponse
res) receives the request from the service method, and dispatches the request
to the doXXX() method depending on the incoming http request type.
3. protected void doGet(HttpServletRequest req, HttpServletResponse
res) handles the GET request. It is invoked by the web container.
4. protected void doPost(HttpServletRequest req, HttpServletResponse
res) handles the POST request. It is invoked by the web container.
5. protected void doHead(HttpServletRequest req, HttpServletResponse
res) handles the HEAD request. It is invoked by the web container.
6. protected void doOptions(HttpServletRequest req, HttpServletResponse
res) handles the OPTIONS request. It is invoked by the web container.
7. protected void doPut(HttpServletRequest req, HttpServletResponse
res) handles the PUT request. It is invoked by the web container.
8. protected void doTrace(HttpServletRequest req, HttpServletResponse
res) handles the TRACE request. It is invoked by the web container.
9. protected void doDelete(HttpServletRequest req, HttpServletResponse
res) handles the DELETE request. It is invoked by the web container.
10. protected long getLastModified(HttpServletRequest req) returns the time
when HttpServletRequest was last modified since midnight January 1, 1970 GMT.

Life Cycle of a Servlet (Servlet Life Cycle)


1. Life Cycle of a Servlet
1. Servlet class is loaded
2. Servlet instance is created
3. init method is invoked
4. service method is invoked
5. destroy method is invoked

The web container maintains the life cycle of a servlet instance. Let's see the life
cycle of the servlet:

1. Servlet class is loaded.


2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.
As displayed in the above diagram, there are three states of a servlet: new,
ready and end. The servlet is in new state if servlet instance is created. After
invoking the init() method, Servlet comes in the ready state. In the ready state,
servlet performs all the tasks. When the web container invokes the destroy()
method, it shifts to the end state.

1) Servlet class is loaded


The classloader is responsible to load the servlet class. The servlet class is
loaded when the first request for the servlet is received by the web container.

2) Servlet instance is created


The web container creates the instance of a servlet after loading the servlet
class. The servlet instance is created only once in the servlet life cycle.
3) init method is invoked
The web container calls the init method only once after creating the servlet instance.
The init method is used to initialize the servlet. It is the life cycle method of the
javax.servlet.Servlet interface. Syntax of the init method is given below:
1. public void init(ServletConfig config) throws ServletException

4) service method is invoked


The web container calls the service method each time when request for the
servlet is received. If servlet is not initialized, it follows the first three steps as
described above then calls the service method. If servlet is initialized, it calls the
service method. Notice that servlet is initialized only once. The syntax of the
service method of the Servlet interface is given below:

1. public void service(ServletRequest request, ServletResponse response)


2. throws ServletException, IOException

5) destroy method is invoked


The web container calls the destroy method before removing the servlet
instance from the service. It gives the servlet an opportunity to clean up any
resource for example memory, thread etc. The syntax of the destroy method of
the Servlet interface is given below:

1. public void destroy()

JSP Tutorial

JSP technology is used to create web application just like Servlet technology. It
can be thought of as an extension to Servlet because it provides more
functionality than servlet such as expression language, JSTL, etc.
A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to
maintain than Servlet because we can separate designing and development. It
provides some additional features such as Expression Language, Custom Tags,
etc.

Advantages of JSP over Servlet


There are many advantages of JSP over the Servlet. They are as follows:

1) Extension to Servlet
JSP technology is the extension to Servlet technology. We can use all the
features of the Servlet in JSP. In addition to, we can use implicit objects,
predefined tags, expression language and Custom tags in JSP, that makes JSP
development easy.

2) Easy to maintain
JSP can be easily managed because we can easily separate our business logic
with presentation logic. In Servlet technology, we mix our business logic with
the presentation logic.

3) Fast Development: No need to recompile and redeploy


If JSP page is modified, we don't need to recompile and redeploy the project. The
Servlet code needs to be updated and recompiled if we have to change the look
and feel of the application.

4) Less code than Servlet


In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that
reduces the code. Moreover, we can use EL, implicit objects, etc.

The Lifecycle of a JSP Page


The JSP pages follow these phases:

o Translation of JSP Page


o Compilation of JSP Page
o Classloading (the classloader loads class file)
o Instantiation (Object of the Generated Servlet is created).
o Initialization ( the container invokes jspInit() method).
o Request processing ( the container invokes _jspService() method).
o Destroy ( the container invokes jspDestroy() method).

Note: jspInit(), _jspService() and jspDestroy() are the life cycle methods of
JSP.

As depicted in the above diagram, JSP page is translated into Servlet by the help
of JSP translator. The JSP translator is a part of the web server which is
responsible for translating the JSP page into Servlet. After that, Servlet page is
compiled by the compiler and gets converted into the class file. Moreover, all
the processes that happen in Servlet are performed on JSP later like
initialization, committing response to the browser and destroy.

Creating a simple JSP Page


To create the first JSP page, write some HTML code as given below, and save it
by .jsp extension. We have saved this file as index.jsp. Put it in a folder and
paste the folder in the web-apps directory in apache tomcat to run the JSP page.

index.jsp
Let's see the simple example of JSP where we are using the scriptlet tag to put
Java code in the JSP page. We will learn scriptlet tag later.

1. <html>
2. <body>
3. <% out.print(2*5); %>
4. </body>
5. </html>
It will print 10 on the browser.

How to run a simple JSP Page?


Follow the following steps to execute this JSP page:

o Start the server


o Put the JSP file in a folder and deploy on the server
o Visit the browser by the URL http://localhost:portno/contextRoot/jspfile,
for example, http://localhost:8888/myapplication/index.jsp

Do I need to follow the directory structure to run a simple


JSP?
No, there is no need of directory structure if you don't have class files or TLD
files. For example, put JSP files in a folder directly and deploy that folder. It will
be running fine. However, if you are using Bean class, Servlet or TLD file, the
directory structure is required.

The Directory structure of JSP


The directory structure of JSP page is same as Servlet. We contain the JSP page
outside the WEB-INF folder or in any directory.
JSP Scriptlet tag (Scripting elements)
1. Scripting elements
2. JSP scriptlet tag
3. Simple Example of JSP scriptlet tag
4. Example of JSP scriptlet tag that prints the user name

In JSP, java code can be written inside the jsp page using the scriptlet tag. Let's
see what are the scripting elements first.

JSP Scripting elements


The scripting elements provides the ability to insert java code inside the jsp.
There are three types of scripting elements:

o scriptlet tag
o expression tag
o declaration tag

JSP scriptlet tag


A scriptlet tag is used to execute java source code in JSP. Syntax is as follows:
1. <% java source code %>

Example of JSP scriptlet tag


In this example, we are displaying a welcome message.

1. <html>
2. <body>
3. <% out.print("welcome to jsp"); %>
4. </body>
5. </html>

Example of JSP scriptlet tag that prints the user


name
In this example, we have created two files index.html and welcome.jsp. The
index.html file gets the username from the user and the welcome.jsp file prints
the username with the welcome message.

File: index.html

1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname">
5. <input type="submit" value="go"><br/>
6. </form>
7. </body>
8. </html>
File: welcome.jsp

1. <html>
2. <body>
3. <%
4. String name=request.getParameter("uname");
5. out.print("welcome "+name);
6. %>
7. </form>
8. </body>
9. </html>
JSP expression tag
The code placed within JSP expression tag is written to the output stream of
the response. So you need not write out.print() to write data. It is mainly used to
print the values of variable or method.

Syntax of JSP expression tag


1. <%= statement %>

Example of JSP expression tag


In this example of jsp expression tag, we are simply displaying a welcome
message.

1. <html>
2. <body>
3. <%= "welcome to jsp" %>
4. </body>
5. </html>
Note: Do not end your statement with semicolon in case of expression tag.

Example of JSP expression tag that prints current time


To display the current time, we have used the getTime() method of Calendar
class. The getTime() is an instance method of Calendar class, so we have called
it after getting the instance of Calendar class by the getInstance() method.

index.jsp

Advertisement

1. <html>
2. <body>
3. Current Time: <%= java.util.Calendar.getInstance().getTime() %>
4. </body>
5. </html>

Example of JSP expression tag that prints the user


name
In this example, we are printing the username using the expression tag. The
index.html file gets the username and sends the request to the welcome.jsp file,
which displays the username.
File: index.jsp

1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname"><br/>
5. <input type="submit" value="go">
6. </form>
7. </body>
8. </html>
File: welcome.jsp

1. <html>
2. <body>
3. <%= "Welcome "+request.getParameter("uname") %>
4. </body>
5. </html>

JSP Declaration Tag


1. JSP declaration tag
2. Difference between JSP scriptlet tag and JSP declaration tag
3. Example of JSP declaration tag that declares field
4. Example of JSP declaration tag that declares method

The JSP declaration tag is used to declare fields and methods.

The code written inside the jsp declaration tag is placed outside the service()
method of auto generated servlet.

So it doesn't get memory at each request.

Syntax of JSP declaration tag


The syntax of the declaration tag is as follows:

1. <%! field or method declaration %>

Difference between JSP Scriptlet tag and Declaration tag

Jsp Scriptlet Tag Jsp Declaration Tag


The jsp scriptlet tag can only declare The jsp declaration tag can declare
variables not methods. variables as well as methods.

The declaration of scriptlet tag is placed The declaration of jsp declaration tag is
inside the _jspService() method. placed outside the _jspService() method.

Example of JSP declaration tag that declares field


In this example of JSP declaration tag, we are declaring the field and printing the
value of the declared field using the jsp expression tag.

index.jsp
1. <html>
2. <body>
3. <%! int data=50; %>
4. <%= "Value of the variable is:"+data %>
5. </body>
6. </html>

Example of JSP declaration tag that declares


method
In this example of JSP declaration tag, we are defining the method which returns
the cube of given number and calling this method from the jsp expression tag.
But we can also use jsp scriptlet tag to call the declared method.

index.jsp
1. <html>
2. <body>
3. <%!
4. int cube(int n){
5. return n*n*n*;
6. }
7. %>
8. <%= "Cube of 3 is:"+cube(3) %>
9. </body>
10. </html>

You might also like