Java IMP
Java IMP
The Adapter classes with their corresponding listener interfaces are given below.
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
2. Explain List Collection with Example?
The list() method of Java Collections class is used to get an array list containing
the elements returned by the specified enumeration in the order in which they are
returned by the enumeration.
import java.util.*;
public class CollectionsListExample1 {
public static void main(String[] args) {
//Create vector and array list
List<String> arrlist = new ArrayList<String>();
Vector v = new Vector();
//Populate the vector
v.add("A");
v.add("B");
v.add("C");
v.add("D");
v.add("E");
//Create enumeration
Enumeration e = v.elements();
//Get the list
arrlist = Collections.list(e);
System.out.println("Value of returned list: "+arrlist);
}
}
As you can see, we are passing parameter (?) for the values. Its value will be set
by calling the setter methods of PreparedStatement.
Why use PreparedStatement?
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");
stmt.setInt(1,101);//1 specifies the first parameter in the query
stmt.setString(2,"Ratan");
int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
init(); //This HttpServlet has 2 init() one which is parameterized and the other
one is non
//parameterized.But this non parameterized version of init() has a blank
body.
//So this call is useless.
}
Now see the coding of our class
public void init(ServletConfig con) throws ServletException
{
super.init(con); //Since,our class init() will run first,but to run HttpServlet init()
we
// have used super keyword.And Database connectivity code will be
their
}
NOTE:- As we can see, total 3 init() calls we have to make.First init() gets
called of our class then of HttpServlet class then non parameterized version of
HttpServlet class.
But now, we will achieve the same thing with less number of calls:
APPROACH 2
Coding of HttpServlet parametrized and non parameterized versions of init()
will remain the same. But in our class instead of overriding parameterized
version of init(), we will override non parameterized version of init().
Let’s see the coding of our class non parameterized version of init():
public void init() throws ServletException
{
//database connectivity code
}
NOTE: Since this method public void init() throws ServletException ,we have
override from HttpServlet class whose coding is like:
public void init() throws ServletException
{
//empty body
}
Since it’s body is blank, therefore it is known as “Helper method” as it is used
for overriding purpose.
Now, as the servlet starts executing its methods, it will call the parameterized
version of init(). Since we have not to override the parameterized version,
therefore it will give a call to the HttpServlet parameterized version of init().
Since coding of a parameterized version of init() of HttpServlet is as same as
above, therefore, from there on it will call init() (i.e non parameterized version
of init). It will give a call to our class non parameterized version of init() and
the code continues.
Now, as you can see, total number of init() calls are 2 which is less than the
first approach. Therefore, execution time is less in 2nd approach and less
headache for CPU for maintaining stack and it’s speed increases as
compared to 1st approach.
Therefore, it is highly recommended to override non parameterized version of
init().Although both will run but due to efficiency first approach is rarely used
and also in first approach we have to use super keyword too.Therefore in below
mentioned program,we have override non parameterized version of init().
service() method :
1. The service() method is the most important method to perform that provides
the connection between client and server.
2. The web server calls the service() method to handle requests coming from the
client( web browsers) and to send response back to the client.
3. This method determines the type of Http request (GET, POST, PUT,
DELETE, etc.) .
4. This method also calls various other methods such as doGet(), doPost(),
doPut(), doDelete(), etc. as required.
5. This method accepts two parameters.
6. The prototype for this method:
7. public void service(ServletRequest req, ServletResponse resp)
throws ServletException, IOException { }
where
req is the ServletRequest object which encapsulates the connection from
client to server
resp is the ServletResponse object which encapsulates the connection from
server back to the client
destroy() method :
8. The destroy() method is called only once.
9. It is called at the end of the life cycle of the servlet.
10. This method performs various tasks such as closing connection with
the database, releasing memory allocated to the servlet, releasing
resources that are allocated to the servlet and other cleanup activities.
11. When this method is called, the garbage collector comes into action.
12. The prototype for this method is:
public void destroy() { // Finalization code...}
Below is a sample program to illustrate Servlet in Java:
// Initializing servlet
public void init() throws ServletException
{
output = "Advance Java Concepts";
}
// Requesting and printing the output
public void doGet(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException
{
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.println(output);
}
If a class has multiple methods having same name but different in parameters, it
is known as Method Overloading.
If we have to perform only one operation, having same name of the methods
increases the readability of the program.
Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the method such as a(int,int) for two
parameters, and b(int,int,int) for three parameters then it may be difficult for you
as well as other programmers to understand the behavior of the method because
its name differs.
In Java, Method Overloading is not possible by changing the return type of the
method only.
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
Output:
22
33
// driver class
public class Test {
public static void main(String args[])
{
Output:
No of gears are 3
speed of bicycle is 100
seat height is 25
in the above program, when an object of MountainBike class is created, a copy
of all methods and fields of the superclass acquires memory in this object. That
is why by using the object of the subclass we can also access the members of a
superclass.
9. Explain Interface with Example?
An Interface in Java programming language is defined as an abstract type used
to specify the behavior of a class. An interface in Java is a blueprint of a
behavior. A Java interface contains static constants and abstract methods.
What are Interfaces in Java?
The interface in Java is a mechanism to achieve abstraction. There can be only
abstract methods in the Java interface, not the method body. It is used to
achieve abstraction and multiple inheritances in Java using Interface . In other
words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body. Java Interface also represents the IS-A
relationship.
When we decide on a type of entity by its behavior and not via attribute we
should define it as an interface.
// Java program to demonstrate the
// real-world example of Interfaces
import java.io.*;
interface Vehicle {
// all are the abstract methods.
void changeGear(int a);
void speedUp(int a);
void applyBrakes(int a);
}
int speed;
int gear;
// to change gear
@Override
public void changeGear(int newGear){
gear = newGear;
}
// to increase speed
@Override
public void speedUp(int increment){
// to decrease speed
@Override
public void applyBrakes(int decrement){
// to change gear
@Override
public void changeGear(int newGear){
gear = newGear;
}
// to increase speed
@Override
public void speedUp(int increment){
// to decrease speed
@Override
public void applyBrakes(int decrement){
}
class GFG {
Abstract Class.
Concrete Class.
Singleton Class.
POJO Class.
Inner Class.
1. Static Class
We can declare a class as static if and only if it is a nested class. We can declare
an inner class with the static modifier, such types of inner classes are called
static nested classes.
2. Final Class
The class can be declared as final by using the keyword ‘final’. If a class is
declared as final we can’t extend the functionality of that class i.e we can’t
create a child class for that class, i.e inheritance is not possible for final classes.
Every method present inside the ultimate class is usually final by default, but
every variable present inside the ultimate class needn’t be final.
3. Abstract Class
We can declare a class as abstract by using the keyword ‘abstract’. For any java
class if we are not allowed to create an object such type of class, we should
declare with the abstract modifier, i.e for abstract classes instantiation is not
possible. If a class contains at least one abstract method then compulsory we
should declare a class as abstract otherwise we get a compilation error.
4. Concrete Class
A concrete class is nothing but a normal or regular class in java. A concrete
class is a class that extends another class or implements an interface.
5. Singleton Class
For any java class if we are allowed to make just one object such sort of class is
claimed to be a singleton class.
6. POJO Class
POJO stands for Plain Old Java Object. If we write a category, then it got to
follow some rules referred to as POJO rules. it’s wont to java to extend
readability and reusability. It provides Encapsulation.
7. Inner Class
Sometimes we can declare a class inside another class such types of classes is
called inner classes. Inner classes concept is introduced to fix GUI bugs as a
part of event handling but because of powerful features and benefits of inner
classes slowly programmers are started using in regular coding also. Without
existing one type of object there is no chance of executing another type of
object then we should go for inner classes.
Anonymous Inner classes:
Sometimes we declare inner classes without a name such types of inner classes
are called anonymous inner classes. The main purpose of anonymous inner
classes is just for instant use. Based on declaration and behavior there are three
types of anonymous inner classes
1. Anonymous inner class that extends a class
2. Anonymous inner class that implements an interface
3. Anonymous inner class that defines the inside argument
Here are two types of modifiers in Java: access modifiers and non-access
modifiers.
The access modifiers in Java specifies the accessibility or scope of a field,
method, constructor, or class. We can change the access level of fields,
constructors, methods, and class by applying the access modifier on it.
1. Private: The access level of a private modifier is only within the class. It
cannot be accessed from outside the class.
2. Default: The access level of a default modifier is only within the package.
It cannot be accessed from outside the package. If you do not specify any
access level, it will be the default.
3. Protected: The access level of a protected modifier is within the package
and outside the package through child class. If you do not make the child
class, it cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be
accessed from within the class, outside the class, within the package and
outside the package.
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
In this example, we are creating two classes Bike and Splendor. Splendor class
extends Bike class and overrides its run() method. We are calling the run method
by the reference variable of Parent class. Since it refers to the subclass object and
subclass method overrides the Parent class method, the subclass method is
invoked at runtime.
1. class Bike{
2. void run(){System.out.println("running");}
3. }
4. class Splendor extends Bike{
5. void run(){System.out.println("running safely with 60km");}
6.
7. public static void main(String args[]){
8. Bike b = new Splendor();//upcasting
9. b.run();
10. }
11. }
Output:
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}
Output:
animal is created
dog is created
}
}
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
3) Error
Keyword Description
19. Explain Arrays In Java, What are the types of array In java ?
Array in Java is index-based, the first element of the array is stored at the 0th
index, 2nd element is stored on 1st index and so on.
Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort
the data efficiently.
o Random access: We can get any data located at an index position.
Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It
doesn't grow its size at runtime. To solve this problem, collection
framework is used in Java which grows automatically.
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
We can also print the Java array using for-each loop. The Java for-each loop
prints the array elements one by one. It holds an array element in a variable, then
executes the body of the loop
class Testarray1{
public static void main(String args[]){
int arr[]={33,3,4,5};
//printing array using for-each loop
for(int i:arr)
System.out.println(i);
}}
Example of Multidimensional Java Array
//Java Program to illustrate the use of multidimensional array
class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}
20. Explain Regular Expressions In Java With Example?
It is widely used to define the constraint on strings such as password and email
validation. After learning Java regex tutorial, you will be able to test your regular
expressions by the Java Regex Tester Tool.
import java.util.regex.*;
class RegexExample2{
public static void main(String args[]){
System.out.println(Pattern.matches(".s", "as"));//true (2nd char is s)
System.out.println(Pattern.matches(".s", "mk"));//false (2nd char is not s)
System.out.println(Pattern.matches(".s", "mst"));//false (has more than 2 char)
System.out.println(Pattern.matches(".s", "amms"));//false (has more than 2 char)
System.out.println(Pattern.matches("..s", "mas"));//true (3rd char is s)
}}
Types of Streams:
1. Input Stream: These streams are used to read data that must be taken as an
input from a source array or file or any peripheral device. For eg.,
FileInputStream, BufferedInputStream, ByteArrayInputStream etc.
2. Output Stream: These streams are used to write data as outputs into an array
or file or any output peripheral device. For eg., FileOutputStream,
BufferedOutputStream, ByteArrayOutputStream etc.
3. ByteStream: This is used to process data byte by byte (8 bits). Though it has
many classes, the FileInputStream and the FileOutputStream are the most
popular ones. The FileInputStream is used to read from the source and
FileOutputStream is used to write to the destination. Here is the list of
various ByteStream Classes:
Stream class Description
Stream class Description
BufferedReader It is used to handle buffered input stream.
BufferedInputStream It is used for Buffered Input Stream.
FileReader This is an input stream that reads from file.
It contains method for reading java standard
DataInputStream
datatypes.
InputStreamReader This input stream is used to translate byte to character.
panel.add(new JLabel("Course:"));
JTextField courseField = new JTextField(20);
panel.add(courseField);
panel.add(submitButton);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
23. Explain Architecture Of Web Application with Challenges?
24. Major Difference Between Developing and Deployment
Servelet?
25. What Is JSP With Example?
Java Server Pages technology (JSP) is a server-side programming language used
to create a dynamic web page in the form of HyperText Markup Language
(HTML). It is an extension to the servlet technology.
A JSP page is internally converted into the servlet. JSP has access to the entire
family of the Java API including JDBC API to access enterprise database. Hence,
Java language syntax has been used in the java server pages (JSP). The JSP pages
are more accessible to maintain than Servlet because we can separate designing
and development. It provides some additional features such as Expression
Language, Custom Tags, etc.
Thread(ThreadGroup group,
Allocates a new Thread object.
Runnable target)
Thread(ThreadGroup group,
Allocates a new Thread object.
String name)
Now let us do discuss all the methods of this class are illustrated as follows:
Methods Action Performed
Throws
CloneNotSupportedException as a
clone()
Thread can not be meaningfully
cloned
Java inner class or nested class is a class that is declared inside the class or
interface.
We use inner classes to logically group classes and interfaces in one place to be
more readable and maintainable.
Additionally, it can access all the members of the outer class, including private
data members and methods.
class Outer_Demo {
int num;
// inner class
private class Inner_Demo {
public void print() {
System.out.println("This is an inner class");
}
}
// Accessing he inner class from the method within
void display_Inner() {
Inner_Demo inner = new Inner_Demo();
inner.print();
}
}
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while
sharing data. There are three types of Mutual Exclusive mentioned below:
Synchronized method.
Synchronized block.
Static synchronization.
Example of Synchronization
Below is the implementation of the Java Synchronization:
Java
// A Java program to demonstrate working of
// synchronized.
import java.io.*;
import java.util.*;
// Driver class
class SyncDemo {
public static void main(String args[])
{
Sender send = new Sender();
ThreadedSend S1 = new ThreadedSend(" Hi ", send);
ThreadedSend S2 = new ThreadedSend(" Bye ", send);
Output
Sending Hi
Hi Sent
Sending Bye
Bye Sent
The output is the same every time we run the program.
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
Autoboxing
The automatic conversion of primitive data type into its corresponding wrapper
class is known as autoboxing, for example, byte to Byte, char to Character
Output:
20 20 20
Unboxing
The automatic conversion of wrapper type into its corresponding primitive type
is known as unboxing. It is the reverse process of autoboxing.
public class WrapperExample2{
public static void main(String args[]){
//Converting Integer to int
Integer a=new Integer(3);
int i=a.intValue();//converting Integer to int explicitly
int j=a;//unboxing, now compiler will write a.intValue() internally
Output:
333
1. java.awt.BorderLayout
import java.awt.*;
import javax.swing.*;
// creating buttons
JButton b1 = new JButton("NORTH");; // the button will be labeled as NORTH
JButton b2 = new JButton("SOUTH");; // the button will be labeled as SOUTH
JButton b3 = new JButton("EAST");; // the button will be labeled as EAST
JButton b4 = new JButton("WEST");; // the button will be labeled as WEST
JButton b5 = new JButton("CENTER");; // the button will be labeled as CENTER
f.setSize(300, 300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
}
Output:: 3.30%Fullscreen
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.
33. Explain Action Listener class
The Java ActionListener is notified whenever you click on the button or menu
item. It is notified against ActionEvent. The ActionListener interface is found
in java.awt.event package. It has only one method: actionPerformed().
example
import java.awt.*;
import java.awt.event.*;
//1st step
public class ActionListenerExample implements ActionListener{
public static void main(String[] args) {
Frame f=new Frame("ActionListener Example");
final TextField tf=new TextField();
tf.setBounds(50,50, 150,20);
Button b=new Button("Click Here");
b.setBounds(50,100,60,30);
//2nd step
b.addActionListener(this);
f.add(b);f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
//3rd step
public void actionPerformed(ActionEvent e){
tf.setText("Welcome to Javatpoint.");
}
}
Output:
34. What is Request Dispatcher?
The RequestDispatcher interface provides the facility of dispatching the request
to another resource it may be html, servlet or jsp. This interface can also be
used to include the content of another resource also. It is one of the way of
servlet collaboration.
There are two methods defined in the RequestDispatcher interface.The
RequestDispatcher interface provides two methods. They are:
1. public void forward(ServletRequest request,ServletResponse
response)throws ServletException,java.io.IOException:Forwards a request
from a servlet to another resource (servlet, JSP file, or HTML file) on the
server.
2. public void include(ServletRequest request,ServletResponse
response)throws ServletException,java.io.IOException:Includes the
content of a resource (servlet, JSP page, or HTML file) in the response.
in the above figure, response of second servlet is sent to the client. Response
of the first servlet is not displayed to the user.
As you can see in the above figure, response of second servlet is included in
the response of the first servlet that is being sent to the client.
35. Write servlet to accept student information from HTML page, and
store the details in a database. [Note: Take suitable fields.]
CREATE TABLE "REGISTERUSER"
( "NAME" VARCHAR2(4000),
"PASS" VARCHAR2(4000),
"EMAIL" VARCHAR2(4000),
"COUNTRY" VARCHAR2(4000)
)
/
To create the registration page in servlet, we can separate the database logic
from the servlet. But here, we are mixing the database logic in the servlet only
for simplicity of the program. We will develop this page in JSP following
DAO, DTO and Singleton design pattern later.
o register.html
o Register.java
o web.xml
register.html
In this page, we have getting input from the user using text fields and combobox.
The information entered by the user is forwarded to Register servlet, which is
responsible to store the data into the database.
<html>
<body>
<form action="servlet/Register" method="post">
<br/><br/>
<input type="submit" value="register"/>
</form>
</body>
</html>
Register.java
This servlet class receives all the data entered by user and stores it into the
database. Here, we are performing the database logic. But you may separate it,
which will be better for the web application.
import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
String p=request.getParameter("userPass");
String e=request.getParameter("userEmail");
String c=request.getParameter("userCountry");
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
PreparedStatement ps=con.prepareStatement(
"insert into registeruser values(?,?,?,?)");
ps.setString(1,n);
ps.setString(2,p);
ps.setString(3,e);
ps.setString(4,c);
int i=ps.executeUpdate();
if(i>0)
out.print("You are successfully registered...");
out.close();
}
web.xml file
<web-app>
<servlet>
<servlet-name>Register</servlet-name>
<servlet-class>Register</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Register</servlet-name>
<url-pattern>/servlet/Register</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>register.html</welcome-file>
</welcome-file-list>
</web-app>
36. Explain servlet life - cycle.
1. Servlet instance is created.
2. init method is invoked.
3. service method is invoked.
4. 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.
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.
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.Backward Skip
10sPlay VideoForward Skip 10s
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:
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:
public void destroy()
Iterator Enumeration
Constructors Methods
A class can have many Constructors A class can have many methods but
but must not have the same parameters. must not have the same parameters.
Iterator ListIterator
There can be a lot of usage of Java this keyword. In Java, this is a reference
variable that refers to the current object.
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Output:
In Java, a thread always exists in any one of the following states. These states
are:
1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated
New: Whenever a new thread is created, it is always in the new state. For a
thread in the new state, the code has not been run yet and thus has not begun its
execution.
Active: When a thread invokes the start() method, it moves from the new state to
the active state. The active state contains two states within it: one is runnable,
and the other is running.
o Running: When the thread gets the CPU, it moves from the runnable to the
running state. Generally, the most common change in the state of a thread is
from runnable to running and again back to runnable.
For example, a thread (let's say its name is A) may want to print some data from
the printer. However, at the same time, the other thread (let's say its name is B) is
using the printer to print some data. Therefore, thread A has to wait for thread B
to use the printer. Thus, thread A is in the blocked state. A thread in the blocked
state is unable to perform any execution and thus never consume any cycle of the
Central Processing Unit (CPU). Hence, we can say that thread A remains idle
until the thread scheduler reactivates thread A, which is in the waiting or blocked
state.
When the main thread invokes the join() method then, it is said that the main
thread is in the waiting state. The main thread then waits for the child threads to
complete their tasks. When the child threads complete their job, a notification is
sent to the main thread, which again moves the thread from waiting to the active
state.
If there are a lot of threads in the waiting or blocked state, then it is the duty of
the thread scheduler to determine which thread to choose and which one to reject,
and the chosen thread is then given the opportunity to run.
o When a thread has finished its job, then it exists or terminates normally.
o Abnormal termination: It occurs when some unusual events such as an
unhandled exception or segmentation fault.
A terminated thread means the thread is no more in the system. In other words,
the thread is dead, and there is no way one can respawn (active after kill) the
dead thread.
The following diagram shows the different states involved in the life cycle of a
thread.
1) Abstract class can have abstract Interface can have only abstract methods.
and non-abstract methods. Since Java 8, it can have default and
static methods also.
Output:
I love my country
try {
OutputStream outputStream = new FileOutputStream("output.txt");
Writer outputStreamWriter = new OutputStreamWriter(outputStream);
outputStreamWriter.write("Hello World");
outputStreamWriter.close();
} catch (Exception e) {
e.getMessage();
}
}
}