Java Notes 2
Java Notes 2
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.
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.
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".
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).
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:
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:
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:
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
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
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.
Syntax:
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:
Filename: ImmutableStringExample.java
Syntax:
Syntax:
Syntax:
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:
Interned String and Literal String refer to the same object: true
Syntax:
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.
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)
static String
It compares another string.
15 equalsIgnoreCase(String
It doesn't check case.
another)
It returns an interned
18 String intern()
string.
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.
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
Duration 18:10
Loaded: 0.37%
Fullscreen
Backward Skip 10sPlay VideoForward Skip 10s
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?
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.
Keyword Description
JavaExceptionExample.java
1. int a=50/0;//ArithmeticException
1. String s=null;
2. System.out.println(s.length());//NullPointerException
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.
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:
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:
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.
Example 2
TryCatchExample2.java
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
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
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
Example 6
Let's see an example to resolve the exception in a catch block.
TryCatchExample6.java
25
Example 7
In this example, along with try block, we also enclose exception code in a catch
block.
TryCatchExample7.java
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
Example 9
Let's see an example to handle another unchecked exception.
TryCatchExample9.java
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:
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.
MultipleCatchBlock1.java
Example 2
MultipleCatchBlock2.java
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
MultipleCatchBlock4.java
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
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:
TestFinallyBlock1.java
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
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).
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 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.
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.
The above code throw an unchecked exception. Similarly, we can also throw
unchecked and user defined exceptions.
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");
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...
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.
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...
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:
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.
Do You Know ?
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.
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.
6) Socket
A socket is an endpoint between two way communications.
java.net package
The java.net package can be divided into two sections:
Here, we are going to make one-way client and server communication. In this
application, client sends a message to the server, server reads the message and
prints it. Here, two classes are being used: Socket and ServerSocket. The Socket
class is used to communicate client and server. Through this class, we can read
and write message. The ServerSocket class is used at server-side. The accept()
method of ServerSocket class blocks the console until the client is connected.
After the successful connection of client, it returns the instance of Socket at
server-side.
Socket class
A socket is simply an endpoint for communications between the machines. The
Socket class can be used to create a socket.
Important methods
Method Description
ServerSocket class
The ServerSocket class can be used to create a server socket. This object is
used to establish communication with the clients.
Important methods
Method Description
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.
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.
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
Creates an instance of a URL from the given protocol, host, port number, and
file.
Creates an instance of a URL from the given protocol, host, port number, file,
and handler.
Creates an instance of a URL by parsing the given spec with the specified
handler within a given context.
Method Description
Protocol: http
Host Name: www.javatpoint.com
Port Number: -1
File Name: /java-tutorial
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:
Drawback of Applet
Plugin is required at client browser to execute applet.
Do You Know
Hierarchy of Applet
As displayed in the above diagram, Applet class extends Panel. Panel class extends
Container which is the subclass of Component.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4
life cycle methods of applet.
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.
1. By html file.
2. By appletViewer tool (for testing purpose).
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>
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
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>
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.
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.
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>>
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>
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.
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
Method Description
public ServletConfig
returns the object of ServletConfig.
getServletConfig()
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.
You may create a generic servlet by inheriting the GenericServlet class and
providing the implementation of the service method.
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.
The web container maintains the life cycle of a servlet instance. Let's see the life
cycle of the servlet:
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.
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.
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.
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.
In JSP, java code can be written inside the jsp page using the scriptlet tag. Let's
see what are the scripting elements first.
o scriptlet tag
o expression tag
o declaration tag
1. <html>
2. <body>
3. <% out.print("welcome to jsp"); %>
4. </body>
5. </html>
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.
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.
index.jsp
Advertisement
1. <html>
2. <body>
3. Current Time: <%= java.util.Calendar.getInstance().getTime() %>
4. </body>
5. </html>
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>
The code written inside the jsp declaration tag is placed outside the service()
method of auto generated servlet.
The declaration of scriptlet tag is placed The declaration of jsp declaration tag is
inside the _jspService() method. placed outside the _jspService() method.
index.jsp
1. <html>
2. <body>
3. <%! int data=50; %>
4. <%= "Value of the variable is:"+data %>
5. </body>
6. </html>
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>