Download as pdf or txt
Download as pdf or txt
You are on page 1of 56

Advanced Java Programming Notes

What is Java?

Java is a popular programming language, created in 1995.

It is owned by Oracle, and more than 3 billion devices run Java.

It is used for:

● Mobile applications (specially Android apps)


● Desktop applications
● Web applications
● Web servers and application servers
● Games
● Database connection
● And much, much more!

Why Use Java?

● Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
● It is one of the most popular programming language in the world
● It has a large demand in the current job market
● It is easy to learn and simple to use
● It is open-source and free
● It is secure, fast and powerful
● It has a huge community support (tens of millions of developers)
● Java is an object oriented language which gives a clear structure to programs and allows
code to be reused, lowering development costs

We created a Java file called Main.java, and we used the following code to print "Hello World"
to the screen:

Main.java

public class Main {


public static void main(String[] args) {
System.out.println("Hello World");
}
}

INHERITANCE
Java, Inheritance is an important pillar of OOP(Object-Oriented Programming). It is the
mechanism in Java by which one class is allowed to inherit the features(fields and methods) of
another class. In Java, Inheritance means creating new classes based on existing ones. A class that
inherits from another class can reuse the methods and fields of that class. In addition, you can add
new fields and methods to your current class as well.
Why Do We Need Java Inheritance?
● Code Reusability: The code written in the Superclass is common to all subclasses.
Child classes can directly use the parent class code.
● Method Overriding: Method Overriding is achievable only through Inheritance. It is
one of the ways by which Java achieves Run Time Polymorphism.
● Abstraction: The concept of abstract where we do not have to provide all details is
achieved through inheritance. Abstraction only shows the functionality to the user.

Important Terminologies Used in Java Inheritance

● Class: Class is a set of objects which shares common characteristics/ behavior and
common properties/ attributes. Class is not a real-world entity. It is just a template or
blueprint or prototype from which objects are created.
● Super Class/Parent Class: The class whose features are inherited is known as a
superclass(or a base class or a parent class).
● Sub Class/Child Class: The class that inherits the other class is known as a
subclass(or a derived class, extended class, or child class). The subclass can add its
own fields and methods in addition to the superclass fields and methods.
● Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to
create a new class and there is already a class that includes some of the code that we
want, we can derive our new class from the existing class. By doing this, we are
reusing the fields and methods of the existing class.

How to Use Inheritance in Java?


The extends keyword is used for inheritance in Java. Using the extends keyword indicates you
are derived from an existing class. In other words, “extends” refers to increased functionality.
Syntax :
class derived-class extends base-class
{
//methods and fields
}

Inheritance in Java Example


Example:
// Java Program to illustrate Inheritance (concise)
import java.io.*;

// Base or Super Class


class Employee {
int salary = 60000;
}

// Inherited or Sub Class


class Engineer extends Employee {
int benefits = 10000;
}

// Driver Class
class Inheritance {
public static void main(String args[])
{
Engineer E1 = new Engineer();
System.out.println("Salary : " + E1.salary
+ "\nBenefits : " + E1.benefits);
}}

Output
Salary : 60000
Benefits : 10000
Java Inheritance Types
Below are the different types of inheritance which are supported by Java.
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance

1. Single Inheritance

In single inheritance, subclasses inherit the features of one superclass. In the image below, class A
serves as a base class for the derived class B.

Single inheritance
/ Java program to illustrate the
// concept of single inheritance
import java.io.*;
import java.lang.*;
import java.util.*;

// Parent class
class One {
public void print_geek()
{
System.out.println("Hi");
}
}

class Two extends One {


public void print_for() { System.out.println("me"); }
}

// Driver class
public class Main {
// Main function
public static void main(String[] args)
{
Two g = new Two();
g.print_geek();
g.print_for();
g.print_geek();
}
}

Output
Hi
me
Hi

2. Multilevel Inheritance

In Multilevel Inheritance, a derived class will be inheriting a base class, and as well as the derived
class also acts as the base class for other classes. In the below image, class A serves as a base class
for the derived class B, which in turn serves as a base class for the derived class C. In Java, a class
cannot directly access the grandparent’s members.

Multilevel Inheritance
// Java program to illustrate the
// concept of Multilevel inheritance
import java.io.*;
import java.lang.*;
import java.util.*;

class One {
public void print_geek()
{
System.out.println("Geeks");
}
}

class Two extends One {


public void print_for() { System.out.println("for"); }
}

class Three extends Two {


public void print_geek()
{
System.out.println("Geeks");
}
}

// Drived class
public class Main {
public static void main(String[] args)
{
Three g = new Three();
g.print_geek();
g.print_for();
g.print_geek();
}
}

3. Hierarchical Inheritance

In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass.
In the below image, class A serves as a base class for the derived classes B, C, and D.
// Java program to illustrate the

// concept of Hierarchical inheritance

class A {

public void print_A() { System.out.println("Class A"); }

class B extends A {

public void print_B() { System.out.println("Class B"); }

class C extends A {

public void print_C() { System.out.println("Class C"); }

class D extends A {

public void print_D() { System.out.println("Class D"); }

// Driver Class

public class Test {

public static void main(String[] args)

{
B obj_B = new B();

obj_B.print_A();

obj_B.print_B();

C obj_C = new C();

obj_C.print_A();

obj_C.print_C();

D obj_D = new D();

obj_D.print_A();

obj_D.print_D();

Output
Class A
Class B
Class A
Class C
Class A
Class D

Exception handling is one of the most important feature of java


programming that allows us to handle the runtime errors caused by exceptions.
In this guide, you will learn what is an exception, types of it, exception classes
and how to handle exceptions in java with examples.

What is an exception?
An Exception is an unwanted event that interrupts the normal flow of the
program. When an exception occurs program execution gets terminated. In such
cases we get a system generated error message.

The good thing about exceptions is that java developer can handle these
exception in such a way so that the program doesn’t get terminated abruptly and
the user get a meaningful error message.

For example: You are writing a program for division and both the numbers are
entered by user. In the following example, user can enter any number, if user
enters the second number (divisor) as 0 then the program will terminate and
throw an exception because dividing a number by zero gives undefined result. To
get the user input, we are using Scanner class. Notice the output of the program.

import java.util.Scanner;
public class JavaExample {

public static void main(String[] args) {

int num1, num2;


Scanner scan = new Scanner(System.in);
System.out.print("Enter first number(dividend): ");
num1 = scan.nextInt();

System.out.print("Enter second number(divisor): ");


num2 = scan.nextInt();

int div = num1/num2;


System.out.println("Quotient: "+div);
}
}
Output:
As you can see, the user input caused the program to throw Arithmetic exception,
however this is not a good programming practice to leave such exceptions
unhandled. Let’s handle this exception.

Exception Handling in Java


Here, we are trying to handle the exception that is raised in the above program.
You can see that the program ran fine and gave a meaningful error message
which can be understood by the user.

Note: Do not worry about the try and catch blocks as we have covered these
topics in detail in separate tutorials. For now just remember that the code that
can throw exception needs to be inside try block and the catch block follows the
try block, where the exception error message is set.

import java.util.Scanner;
public class JavaExample {

public static void main(String[] args) {

int num1, num2;


Scanner scan = new Scanner(System.in);
System.out.print("Enter first number(dividend): ");
num1 = scan.nextInt();

System.out.print("Enter second number(divisor): ");


num2 = scan.nextInt();
try {
int div = num1 / num2;
System.out.println("Quotient: "+div);
}catch(ArithmeticException e){
System.out.println("Do not enter divisor as zero.");
System.out.println("Error Message: "+e);
}

}
}
Output:
If an exception occurs, which has not been handled by programmer then program
execution gets terminated and a system generated error message is shown to
the user.

These system generated messages are not user friendly so a user will not be
able to understand what went wrong. In order to let them know the reason in
simple language, we handle exceptions. We handle such exceptions and then
prints a user friendly warning message to user, which lets them correct the error
as most of the time exception occurs due to bad data provided by user.

Why we handle the exceptions?


Exception handling ensures that the flow of the program doesn’t break when an
exception occurs. For example, if a program has bunch of statements and an
exception occurs mid way after executing certain statements then the
statements, that occur after the statement that caused the exception will not
execute and the program will terminate abruptly. By handling we make sure that
all the statements execute and the flow of execution of program doesn’t break.

Why an exception occurs?


There can be several reasons that can cause a program to throw exception. For
example: Opening a non-existing file in your program, Network connection
problem, bad input data provided by user etc. Let’s see few scenarios:
1. ArithmeticException:
We have already seen this exception in our example above. This exception
occurs when we divide a number by zero. If we divide any number by zero.

int num = 25/0;//ArithmeticException


2. NullPointerException:
When a variable contains null value and you are performing an operation on the
variable. For example, if a string variable contains null and you are comparing
with another string. Another example is when you are trying to print the length of
the string that contains null.
String str = null;

//NullPointerException
System.out.println(str.length());
3. NumberFormatException:
This exception occurs where there is a type mismatch. Let’s say you are trying to
perform an arithmetic operator on a string variable.

String str = "beginnersbook.com";

//NumberFormatException
int num=Integer.parseInt(str);
4. ArrayIndexOutOfBoundsException:
When you are trying to access the array index which is beyond the size of array.
Here, we are trying to access the index 8 (9th element) but the size of the array is
only 3. This exception occurs when you are accessing index which doesn’t exist.

int arr[]=new int[3];

//ArrayIndexOutOfBoundsException
arr[8]=100;

Difference between error and exception


Errors indicate that something went wrong which is not in the scope of a
programmer to handle. You cannot handle an error. Also, the error doesn’t occur
due to bad data entered by user rather it indicates a system failure, disk crash or
resource unavailability.

Exceptions are events that occurs during runtime due to bad data entered by
user or an error in programming logic. A programmer can handle such conditions
and take necessary corrective actions. Few examples:
NullPointerException – When you try to use a reference that points to null.
ArithmeticException – When bad data is provided by user, for example, when you
try to divide a number by zero this exception occurs because dividing a number
by zero is undefined.
ArrayIndexOutOfBoundsException – When you try to access the elements of an
array out of its bounds, for example array size is 5 (which means it has five
elements) and you are trying to access the 10th element.

Types of exceptions

There are two types of exceptions in Java:


1) Checked exceptions
2) Unchecked exceptions

I have covered these topics in detail in a separate tutorial: Checked and


Unchecked exceptions in Java.
1) Checked exceptions
All exceptions other than Runtime Exceptions are known as Checked exceptions
as the compiler checks them during compilation to see whether the programmer
has handled them or not. If these exceptions are not handled/declared in the
program, you will get compilation error. For example, SQLException, IOException,
ClassNotFoundException etc.

2) Unchecked Exceptions
Runtime Exceptions are also known as Unchecked Exceptions. These exceptions
are not checked at compile-time so compiler does not check whether the
programmer has handled them or not but it’s the responsibility of the
programmer to handle these exceptions and provide a safe exit.

For example, ArithmeticException, NullPointerException,


ArrayIndexOutOfBoundsException etc. The examples that we seen above were
unchecked exceptions.
Note: Compiler doesn’t enforce you to catch such exceptions or ask you to
declare it in the method using throws keyword.

Frequently used terms in Exception handling


try: The code that can cause the exception, is placed inside try block. The try
block detects whether the exception occurs or not, if exception occurs, it transfer
the flow of program to the corresponding catch block or finally block. A try block
is always followed by either a catch block or finally block.

catch: The catch block is where we write the logic to handle the exception, if it
occurs. A catch block only executes if an exception is caught by the try block. A
catch block is always accompanied by a try block.

finally: This block always executes whether an exception is occurred or not.

throw: It is used to explicitly throw an exception. It can be used to throw a


checked or unchecked exception.
throws: It is used in method signature. It indicates that this method might throw
one of the declared exceptions. While calling such methods, we need to handle
the exceptions using try-catch block.

how to use try-catch along with finally block in Java. We will cover various
examples to see, how try catch and finally works together during exception
handling.

Scenario 1: Exception doesn’t occur in try block


If exception doesn’t occur in try block then all the catch blocks are ignored,
however the finally block executes (if it is present) because it executes whether
exception occurs or not.

Case 1: try-catch block with no finally block:

class JavaExample
{
public static void main(String args[])
{
int x = 10;
int y = 10;
try{
int num= x/y;
System.out.println("Remaining statements inside try block");
}
catch(Exception ex)
{
System.out.println("Exception caught in catch block");
}
System.out.println("Statements Outside of try-catch");
}
}
Output:

Remaining statements inside try block


Statements Outside of try-catch
Case 2: Same scenario with try-catch-finally clause:

public class JavaExample {


public static void main(String args[]){
//declared and initialized two variables
int num1 =10, num2 = 5;
try
{
int div = num1/num2;

// if exception occurs in the above statement then this


// statement will not execute else it will execute
System.out.println("num1/num2: "+div);
}
catch(ArithmeticException e)
{
System.out.println("Catch block: ArithmeticException caught");
}
finally{
System.out.println("Finally block: I will always execute");
}

// rest of the code


System.out.println("Outside try-catch-finally");
}
}
Output:

Scenario 2: Exception occurred in try block and


handled in catch block
If exception occurs in try block then the rest of the statements inside try block
are ignored and the corresponding catch block executes. After catch block, the
finally block executes and then the rest of the program.

In the following example, an Arithmetic exception occurred as the number is


divided by zero, there is a catch block to handle Arithmetic exception so the
control got transferred to it. After which the statements inside finally block (if
present) are executed.

Case 1: try-catch without finally:


class JavaExample
{
public static void main(String args[])
{
int x = 10;
int y = 0;
try{
int num= x/y;
System.out.println("Remaining statements inside try block");
}
catch(Exception ex)
{
System.out.println("Exception caught in catch block");
}
System.out.println("Statements Outside of try-catch");
}
}
Output:

Exception caught in catch block


Statements Outside of try-catch
Point to note in above example: There are two statements present inside try
block. Since exception occurred because of first statement, the second
statement didn’t execute. Hence we can say that if an exception occurs then the
rest of the statements in try block don’t execute and control passes to catch
block.

Case 2: try-catch with finally:

public class JavaExample {


public static void main(String args[]){
//now the second variable is initialized with 0 value
int num1 =10, num2 = 0;
try
{
int div = num1/num2;

// if exception occurs in the above statement then this


// statement will not execute else it will execute
System.out.println("num1/num2: "+div);
}
catch(ArithmeticException e)
{
System.out.println("Catch block: ArithmeticException caught");
}
finally{
System.out.println("Finally block: I will always execute");
}

// rest of the code


System.out.println("Outside try-catch-finally");
}
}
Output:

Scenario 3: Exception occurred in try block and not


handled in catch block
If the exception raised in try block is not handled in catch block then the rest of
the statements in try block and the statements after try-catch-finally doesn’t
execute, only the finally block executes and a system generated error message
for the exception that occurred in try block.

In the following example, the ArithmeticException occurred in try block but there
is no catch block that can handle ArithmeticException so after the execution of
finally block, a system generated error message is displayed.

public class JavaExample {


public static void main(String args[]){
//now the second variable is initialized with 0 value
int num1 =10, num2 = 0;
try
{
int div = num1/num2;

// if exception occurs in the above statement then this


// statement will not execute else it will execute
System.out.println("num1/num2: "+div);
}
//this cannot handle ArithmeticException
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Catch block: ArrayIndexOutOfBoundsException caught");
}
finally{
System.out.println("Finally block executed");
}

// rest of the code


System.out.println("Outside try-catch-finally");
}
}
Output:

Flow of control in try catch finally in Java:


To summarise everything we have learned so far:

1. If exception occurs in try block then control immediately


transfers(skipping rest of the statements in try block) to the catch
block. Once catch block finished execution then finally block and
after that rest of the program.
2. If no exception occurs in try block, then try block gets executed
completely and then control gets transferred to finally block (skipping
catch blocks), after which rest of the statements after try-catch-finally
are executed.

Difference between throw and throws in Java


The throw and throws is the concept of exception handling where the throw keyword
throw the exception explicitly from a method or a block of code whereas the throws
keyword is used in signature of the method.

There are many differences between throw and throws keywords. A list of differences
between throw and throws are given below:

Sr. Basis of Differences throw throws


no.

1. Definition Java throw keyword is used Java throws keyword is used in


throw an exception explicitly the method signature to
declare an exception which
in the code, inside the might be thrown by the
function or the block of code. function while the execution
of the code.

2. Type of exception Using throw Using throws keyword, we


keyword, we can only propagate can declare both checked
unchecked exception i.e., the and unchecked exceptions.
checked exception cannot be However, the throws
propagated using throw only. keyword can be used to
propagate checked
exceptions only.

3. Syntax The throw keyword is The throws keyword is


followed by an instance of followed by class names of
Exception to be thrown. Exceptions to be thrown.

4. Declaration throw is used within the throws is used with the


method. method signature.

5. Internal implementation We are allowed to throw only We can declare multiple


one exception at a time i.e. exceptions using throws
we cannot throw multiple keyword that can be thrown
exceptions. by the method. For example,
main() throws IOException,
SQLException.

Java throw Example


TestThrow.java

1. public class TestThrow {


2. //defining a method
3. public static void checkNum(int num) {
4. if (num < 1) {
5. throw new ArithmeticException("\nNumber is negative, cannot calculate
square");
6. }
7. else {
8. System.out.println("Square of " + num + " is " + (num*num));
9. }
10. }
11. //main method
12. public static void main(String[] args) {
13. TestThrow obj = new TestThrow();
14. obj.checkNum(-3);
15. System.out.println("Rest of the code..");
16. }
17. }

Output:

Java throws Example


TestThrows.java

1. public class TestThrows {


2. //defining a method
3. public static int divideNum(int m, int n) throws ArithmeticException {
4. int div = m / n;
5. return div;
6. }
7. //main method
8. public static void main(String[] args) {
9. TestThrows obj = new TestThrows();
10. try {
11. System.out.println(obj.divideNum(45, 0));
12. }
13. catch (ArithmeticException e){
14. System.out.println("\nNumber cannot be divided by 0");
15. }
16.
17. System.out.println("Rest of the code..");
18. }
19. }

Output:

Java throw and throws Example


TestThrowAndThrows.java

1. public class TestThrowAndThrows


2. {
3. // defining a user-defined method
4. // which throws ArithmeticException
5. static void method() throws ArithmeticException
6. {
7. System.out.println("Inside the method()");
8. throw new ArithmeticException("throwing ArithmeticException");
9. }
10. //main method
11. public static void main(String args[])
12. {
13. try
14. {
15. method();
16. }
17. catch(ArithmeticException e)
18. {
19. System.out.println("caught in main() method");
20. }
21. }
22. }

Output:

Multithreading in Java
Multithreading in Java is a process of executing multiple threads simultaneously.

A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing


and multithreading, both are used to achieve multitasking.

However, we use multithreading than multiprocessing because threads use a shared


memory area. They don't allocate separate memory area so saves memory, and context-
switching between the threads takes less time than process.

Java Multithreading is mostly used in games, animation, etc.

Advantages of Java Multithreading


1) It doesn't block the user because threads are independent and you can perform
multiple operations at the same time.

2) You can perform many operations together, so it saves time.


3) Threads are independent, so it doesn't affect other threads if an exception occurs in a
single thread.

Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking
to utilize the CPU. Multitasking can be achieved in two ways:

o Process-based Multitasking (Multiprocessing)


o Thread-based Multitasking (Multithreading)

1) Process-based Multitasking (Multiprocessing)


o Each process has an address in memory. In other words, each process allocates a separate
memory area.
o A process is heavyweight.
o Cost of communication between the process is high.
o Switching from one process to another requires some time for saving and
loading registers, memory maps, updating lists, etc.

AD

2) Thread-based Multitasking (Multithreading)


o Threads share the same address space.
o A thread is lightweight.
o Cost of communication between the thread is low.

Note: At least one process is required for each thread.

What is Thread in java


A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path
of execution.

Threads are independent. If there occurs exception in one thread, it doesn't affect other
threads. It uses a shared memory area.

Life Cycle of a Thread in Java Multithreading

A thread goes through various stages in its life cycle. For example,
a thread is born, started, runs, and then dies. The following diagram
shows the complete life cycle of a thread.
Following are the stages of the life cycle −

• New − A new thread begins its life cycle in the new state. It
remains in this state until the program starts the thread. It is
also referred to as a born thread.
• Runnable − After a newly born thread is started, the thread
becomes runnable. A thread in this state is considered to be
executing its task.
• Waiting − Sometimes, a thread transitions to the waiting state
while the thread waits for another thread to perform a task. A
thread transitions back to the runnable state only when another
thread signals the waiting thread to continue executing.
• Timed Waiting − A runnable thread can enter the timed waiting
state for a specified interval of time. A thread in this state
transitions back to the runnable state when that time interval
expires or when the event it is waiting for occurs.
• Terminated (Dead) − A runnable thread enters the terminated
state when it completes its task or otherwise terminates.

Thread Priorities

Every Java thread has a priority that helps the operating system
determine the order in which threads are scheduled.
Java thread priorities are in the range between MIN_PRIORITY (a
constant of 1) and MAX_PRIORITY (a constant of 10). By default,
every thread is given priority NORM_PRIORITY (a constant of 5).

Threads with higher priority are more important to a program and


should be allocated processor time before lower-priority threads.
However, thread priorities cannot guarantee the order in which
threads execute and are very much platform dependent.

Create a Thread by Implementing a Runnable Interface

If your class is intended to be executed as a thread then you can


achieve this by implementing a Runnable interface. You will need to
follow three basic steps −

Step 1: Implement run() Method

As a first step, you need to implement a run() method provided by


a Runnable interface. This method provides an entry point for the
thread and you will put your complete business logic inside this
method. Following is a simple syntax of the run() method −

public void run( )

Step 2: Instantiate a Thread Object

As a second step, you will instantiate a Thread object using the


following constructor −

Thread(Runnable threadObj, String threadName);

Where, threadObj is an instance of a class that implements


the Runnable interface and threadName is the name given to the new
thread.
Step 3: Call Thread using start() Method

Once a Thread object is created, you can start it by


calling start() method, which executes a call to run( ) method.
Following is a simple syntax of start() method −

void start();

Example: Create Thread by Implementing Runnable


Interface

Here is an example that creates a new thread and starts running it


class RunnableDemo implements Runnable {


private Thread t;
private String threadName;

RunnableDemo( String name) {


threadName = name;
System.out.println("Creating " + threadName );
}

public void run() {


System.out.println("Running " + threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}
public void start () {
System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
}

public class TestThread {

public static void main(String args[]) {


RunnableDemo R1 = new RunnableDemo( "Thread-1");
R1.start();

RunnableDemo R2 = new RunnableDemo( "Thread-2");


R2.start();
}
}

Output
Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.
AD

What Is Applet In Java?

A Java applet is a special kind of Java program that a browser enabled with Java technology can download from
the internet and run. An applet is typically embedded inside a web page and runs in the context of a browser. An
applet must be a subclass of the java.applet.Applet class. The Applet class provides the standard
interface between the applet and the browser environment.

A Java application that is integrated into a webpage is called an applet. It functions as a


front-end and is run within the web computer. It makes a page more interactive and
dynamic by operating inside the web browser. Applets are hosted on web servers and
inserted into HTML pages via the OBJECT or APPLET tags.

It can be compared to a tiny application that runs on the address bar. In addition to
updating content in real-time and responding to human input, it may also play basic
puzzles or graphics.

The Life Cycle Of An Applet


The process by which an object is developed, launched, halted, and demolished
throughout an application's implementation is known as the applet life cycle in Java. In
essence, it has five main methods: paint(), destroy(), stop(), init(), and start().The
browser calls these methods in order to perform their

It is important to understand the order in which the various methods shown in


the above image are called. When an applet begins, the following methods are
called, in this sequence:
1. init( )
2. start( )
3. paint( )
When an applet is terminated, the following sequence of method calls takes
place:
1. stop( )
2. destroy( )

actions.

1. Init()- The init() function is the first to be executed and is responsible for initializing
the applet. It can only be called once throughout the startup process. The initialized
objects are created by the web browser, which executes the init() function located
inside the applet after confirming the authentication setting.
2. Start()- This function launches the applet and includes the applet's real code. It
begins directly following the call to the init() function. The start() function is called each
time the browser loads or refreshes. Additionally, it is triggered when the applet is
relaunched, improved, or switched across tabs in the web interface. Until the init()
function is used, it is in an idle state.

3. Stop()- The applet's execution is terminated by using the stop() function. Every time
the applet is minimized, paused, or switched between tabs on the web page, the stop()
function is triggered. Again, the start() function is called when we return to that page.

4. Destroy()- Once the applet completes its task, the destroy() function terminates it.
When the webpage-containing tab closes, or the applet window closes, it is triggered. It
is performed just once and expunges the applet data from RAM. We can't restart the
applet after it's been deleted.

5. Paint()- The Java Graphics class contains the paint() function. It is employed in the
applet to draw forms like squares, circles, trapeziums, and so on. It runs following the
call to the start() function and whenever the web page or applet display resizes.

Types of Applets

Java applets can be classified as either local or remote, depending on where they are
stored and how easily they can be accessed.

1. Local Applet

We will write the Local Applet ourselves and then integrate it into websites. A local
applet is created locally and kept on the local machine. When a web page detects a
local applet in the Java system's memory, it does not need to obtain data directly from
the internet in order to function. It is defined or provided by the pathname or folder
name. When constructing an applet, two properties are used: the source folder, which
defines the path name, and the code itself, which defines the filename containing the
applet's programming.

2. Remote Applet

The remote applet is stored or accessible on another computer that is linked to the
world over the internet. We must have internet access on the system to be able to
obtain and use the applet that resides on the other machine. We need to be familiar with
a remote applet's Uniform Resource Locator (URL) or web location in order to find and
download it.

Simple Applet Program In Java

"Hello, World" is a well-known illustration of a basic applet program in Java. The code is
as follows:

Java

import java. applet.*;


import java. awt.*;
public class HelloWorld extends
Applet
{
public
void
init()
{
setBackground(Color.white);
}
public
void
paint(Graphics g)
{
g.setColor(Color.black);
g.drawString("Hello, world!", 50, 50);
}
}

Advantages Of Java Applets

1. Interaction With Browsers

Through a smooth integration with online sites, applets let viewers engage with
dynamic information without exiting the browser. This results in improved customer
service while eliminating the need to obtain and set up separate programs.

2. Diminished Server Traffic

Local execution of the applet's code allows functionality to occur on the front end or the
user's workstation. In doing so, the server's workload is lessened, and it can process
more inquiries and users at once.

3. Availability

Applets may adjust to changing frequency bands and computing power. They can be
compact and quick to load for users with poorer interactions while providing more
capability for those with greater capabilities.
Disadvantages Of Java Applets

1. Utilizing Excessive Performance And Resources

A common complaint about Java applets is their resource use, particularly with
complicated ones. In certain situations, they can even cause crashes, hinder browser
performance, and deplete the gadget's batteries. This slowness and waste of resources
are not acceptable in today's performance-driven online environment.

How to Run the HelloWorld Applet :


After you enter the source code for HelloWorld.java, compile in the same way
that you have been compiling java programs(using javac command). However,
running HelloWorld with the java command will generate an error because it
is not an application.
java HelloWorld

Error: Main method not found in class HelloWorld,


please define the main method as:
public static void main(String[] args)
There are two standard ways in which you can run an applet :
1. Executing the applet within a Java-compatible web browser.
2. Using an applet viewer, such as the standard tool, applet-viewer. An
applet viewer executes your applet in a window. This is generally the
fastest and easiest way to test your applet.
Each of these methods is described next.
1. Using java enabled web browser : To execute an applet in a web browser
we have to write a short HTML text file that contains a tag that loads the
applet. We can use APPLET or OBJECT tag for this purpose. Using APPLET,
here is the HTML file that executes HelloWorld :
<applet code="HelloWorld" width=200 height=60>
</applet>
The width and height statements specify the dimensions of the display area
used by the applet. The APPLET tag contains several other options. After you
create this html file, you can use it to execute the applet.
NOTE : Chrome and Firefox no longer supports NPAPI (technology required
for Java applets). Refer here
2. Using appletviewer : This is the easiest way to run an applet. To execute
HelloWorld with an applet viewer, you may also execute the HTML file shown
earlier. For example, if the preceding HTML file is saved with
RunHelloWorld.html, then the following command line will run HelloWorld :
appletviewer RunHelloWorld.html

3. appletviewer with java source file : If you include a comment at the head of
your Java source code file that contains the APPLET tag then your code is
documented with a prototype of the necessary HTML statements, and you can
run your compiled applet merely by starting the applet viewer with your Java
source code file. If you use this method, the HelloWorld source file looks like
this :

• Java

//code to illustrate paint


//method gets called again
//and again

import java.applet.*;// used


//to access showStatus()
import java.awt.*;//Graphic
//class is available in this package
import java.util.Date;// used
//to access Date object
public class GFG extends Applet
{
public void paint(Graphics g)
{
Date dt = new Date();
super.showStatus("Today is" + dt);
//in this line, super keyword is
// avoidable too.
}
}

>
With this approach, first compile HelloWorld.java file and then simply run the
below command to run applet :
appletviewer HelloWorld
To prove above mentioned point,i.e paint is called again and again.
To prove this, let’s first study what is “Status Bar” in Applet:
“Status Bar” is available in the left bottom window of an applet. To use the
status bar and write something in it, we use method showStatus() whose
prototype is
public void showStatus(String)
By default status bar shows “Applet Started”
By default background color is white.
To prove paint() method is called again and again, here is the code:
Note: This code is with respect to Netbeans IDE.

• Java

//code to illustrate paint


//method gets called again
//and again

import java.applet.*;// used


//to access showStatus()
import java.awt.*;//Graphic
//class is available in this package
import java.util.Date;// used
//to access Date object
public class GFG extends Applet
{
public void paint(Graphics g)
{
Date dt = new Date();
super.showStatus("Today is" + dt);
//in this line, super keyword is
// avoidable too.
}
}

Note:- Here we can see that if the screen is maximized or minimized we will
get an updated time. This shows that paint() is called again and again.
Features of Applets over HTML
• Displaying dynamic web pages of a web application.
• Playing sound files.
• Displaying documents
• Playing animations
Restrictions imposed on Java applets
Due to security reasons, the following restrictions are imposed on Java applets:
1. An applet cannot load libraries or define native methods.
2. An applet cannot ordinarily read or write files on the execution host.
3. An applet cannot read certain system properties.
4. An applet cannot make network connections except to the host that it
came from.
5. An applet cannot start any program on the host that’s executing it.

Java URLConnection Class


The Java URLConnection class represents a communication link between the URL and
the application. It can be used to read and write data to the specified resource referred
by the URL.
Components of a URL
A URL can have many forms. The most general however follows a three-
components system as proposed below:
1. Protocol: HTTP is the protocol here
2. Hostname: Name of the machine on which the resource lives.
3. File Name: The pathname to the file on the machine.
4. Port Number: Port number to which to connect (typically optional).

URL Class

The URL class is the gateway to any of the resources available on the internet.
A Class URL represents a Uniform Resource Locator, which is a pointer to a
“resource” on the World Wide Web. A resource can point to a simple file or
directory, or it can refer to a more complicated object, such as a query to a
database or to a search engine.

Constructors of the URL class

1. URL(String address) throws MalformedURLException: It creates a


URL object from the specified String.
2. URL(String protocol, String host, String file): Creates a URL object
from the specified protocol, host, and file name.
3. URL(String protocol, String host, int port, String file): Creates a
URL object from protocol, host, port, and file name.
4. URL(URL context, String spec): Creates a URL object by parsing the
given spec in the given context.
5. URL(String protocol, String host, int port, String file,
URLStreamHandler handler):
Creates a URL object from the specified protocol, host, port number,
file, and handler.
6. URL(URL context, String spec, URLStreamHandler handler):
Creates a URL by parsing the given spec with the specified handler
within a specified context.
What is the URL?
o URL is an abbreviation for Uniform Resource Locator. An URL is a form of string that helps
to find a resource on the World Wide Web (WWW).
o URL has two components:

1. The protocol required to access the resource.


2. The location of the resource.

Features of URLConnection class


1. URLConnection is an abstract class. The two subclasses HttpURLConnection and
JarURLConnection makes the connetion between the client Java program and URL
resource on the internet.
2. With the help of URLConnection class, a user can read and write to and from any resource
referenced by an URL object.
3. Once a connection is established and the Java program has an URLConnection object, we
can use it to read or write or get further information like content length, etc.

Constructors
Constructor Description
1) protected URLConnection(URL url) It constructs a URL connection to the specified URL.

URLConnection Class Methods


Method Description

void addRequestProperty(String key, String value) It adds a general request property specified by
a key-value pair

void connect() It opens a communications link to the resource


referenced by this URL, if such a connection
has not already been established.

boolean getAllowUserInteraction() It returns the value of the allowUserInteraction


field for the object.

int getConnectionTimeout() It returns setting for connect timeout.

Object getContent() It retrieves the contents of the URL connection.

Object getContent(Class[] classes) It retrieves the contents of the URL connection.

String getContentEncoding() It returns the value of the content-encoding


header field.

int getContentLength() It returns the value of the content-length


header field.

long getContentLengthLong() It returns the value of the content-length


header field as long.

String getContentType() It returns the value of the date header field.

long getDate() It returns the value of the date header field.

static boolean getDefaultAllowUserInteraction() It returns the default value of the


allowUserInteraction field.

boolean getDefaultUseCaches() It returns the default value of an


URLConnetion's useCaches flag.
boolean getDoInput() It returns the value of the URLConnection's
doInput flag.

boolean getDoInput() It returns the value of the URLConnection's


doOutput flag.

long getExpiration() It returns the value of the expires header files.

static FileNameMap getFilenameMap() It loads the filename map from a data file.

String getHeaderField(int n) It returns the value of nth header field

String getHeaderField(String name) It returns the value of the named header field.

long getHeaderFieldDate(String name, long Default) It returns the value of the named field parsed
as a number.

int getHeaderFieldInt(String name, int Default) It returns the value of the named field parsed
as a number.

String getHeaderFieldKey(int n) It returns the key for the nth header field.

long getHeaderFieldLong(String name, long Default) It returns the value of the named field parsed
as a number.

Map<String, List<String>> getHeaderFields() It returns the unmodifiable Map of the header


field.

long getIfModifiedSince() It returns the value of the object's


ifModifiedSince field.

InputStream getInputStream() It returns an input stream that reads from the


open condition.

long getLastModified() It returns the value of the last-modified header


field.

OutputStream getOutputStream() It returns an output stream that writes to the


connection.
Permission getPermission() It returns a permission object representing the
permission necessary to make the connection
represented by the object.

int getReadTimeout() It returns setting for read timeout.

Map<String, List<String>> getRequestProperties() It returns the value of the named general


request property for the connection.

URL getURL() It returns the value of the URLConnection's


URL field.

boolean getUseCaches() It returns the value of the URLConnection's


useCaches field.

Static String guessContentTypeFromName(String fname) It tries to determine the content type of an


object, based on the specified file component
of a URL.

static String guessContentTypeFromStream(InputStream It tries to determine the type of an input


is) stream based on the characters at the
beginning of the input stream.

void setAllowUserInteraction(boolean It sets the value of the allowUserInteraction


allowuserinteraction) field of this URLConnection.

static void It sets the ContentHandlerFactory of an


setContentHandlerFactory(ContentHandlerFactory fac) application.

static void setDefaultAllowUserInteraction(boolean It sets the default value of the


defaultallowuserinteraction) allowUserInteraction field for all future
URLConnection objects to the specified value.

void steDafaultUseCaches(boolean defaultusecaches) It sets the default value of the useCaches field
to the specified value.

void setDoInput(boolean doinput) It sets the value of the doInput field for this
URLConnection to the specified value.
void setDoOutput(boolean dooutput) It sets the value of the doOutput field for the
URLConnection to the specified value.

How to get the object of URLConnection Class


The openConnection() method of the URL class returns the object of URLConnection class.

Syntax:

1. public URLConnection openConnection()throws IOException{}

Displaying Source Code of a Webpage by


URLConnecton Class
The URLConnection class provides many methods. We can display all the data of a
webpage by using the getInputStream() method. It returns all the data of the specified
URL in the stream that can be read and displayed.

Example of Java URLConnection Class


1. import java.io.*;
2. import java.net.*;
3. public class URLConnectionExample {
4. public static void main(String[] args){
5. try{
6. URL url=new URL("http://www.javatpoint.com/java-tutorial");
7. URLConnection urlcon=url.openConnection();
8. InputStream stream=urlcon.getInputStream();
9. int i;
10. while((i=stream.read())!=-1){
11. System.out.print((char)i);
12. }
13. }catch(Exception e){System.out.println(e);}
14. }
15. }
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.

This client program is straightforward and simple because the echo server implements a simple protocol. The
client sends text to the server, and the server echoes it back. When your client programs are talking to a more
complicated server such as an HTTP server, your client program will also be more complicated. However, the
basics are much the same as they are in this program:

1. Open a socket.
2. Open an input stream and output stream to the socket.
3. Read from and write to the stream according to the server's protocol.
4. Close the streams.
5. Close the socket.

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

1) public InputStream getInputStream() returns the InputStream attached with this socket.
2) public OutputStream getOutputStream() returns the OutputStream attached with 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

1) public Socket accept() returns the socket and establish a connection between server and
client.

2) public synchronized void closes the server socket.


close()

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. }
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.

Getting Connected to the Web Server


There are certain steps to be followed to get connected with a web server as
mentioned below:
Step 1: Define the URL
Before we can connect to a web server, we need to specify the URL of the
server we want to interact with. This URL should point to the resource we
want to access, such as a website, API endpoint, or web service. In our
example, we’ll use “https://www.example.com” as a placeholder URL, but you
should replace it with the URL of your choice.
Step 2: Create a URL Object
In Java, we use the URL class to work with URLs. We create a URL object by
passing the URL string as a parameter to the URL constructor. This object
represents the URL we want to connect to.
Step 3: Open a Connection
To establish a connection to the web server, we use
the ‘HttpURLConnection’ class, which provides HTTP-specific functionality.
We call the ‘openConnection()‘ method on our URL object to open a
connection. We then cast the returned connection to ‘HttpURLConnection’ for
HTTP-related operations.
Step 4: Set the Request Method
HTTP requests have different methods, such as GET, POST, PUT, and DELETE.
In this example, we’re making a GET request to retrieve data from the server.
We set the request method to “GET” using
the ‘setRequestMethod(“GET”)’ method on the ‘HttpURLConnection’ object.
Step 5: Get the Response Code
To check the status of our request, we obtain the HTTP response code using
the ‘getResponseCode()’ method. The response code indicates whether the
request was successful or if there were any issues.
Step 6: Read and Display Response Content
To retrieve and display the content returned by the web server, we create
a ‘BufferedReader’ to read the response content line by line. We append each
line to a ‘StringBuilder’ to construct the complete response content. Finally, we
print the response content to the console.

Implementing a Server
The server is the program that starts first and waits for incoming connections. Implementing a server consists
of six basic steps:

1. Create a ServerSocket object.


2. Create a Socket object from the ServerSocket.

3. Create an input stream to read input from the client.

4. Create an output stream that can be used to send information back to the client.

5. Do I/O with input and output streams.

6. Close the Socket when done.


Each of these steps is described in more detail in the following sections. As with the client, note that most of the
methods described throw an IOException, so they need to be wrapped inside a try/catch block in an

actual implementation.
Create a ServerSocket object.

With a client socket, you actively go out and connect to a particular system. With a server, however, you
passively sit and wait for someone to come to you. So, creation requires only a port number, not a host, as
follows:

ServerSocket listenSocket = Å@

new ServerSocket(portNumber);

On Unix, if you are a nonprivileged user, this port number must be greater than 1023 (lower numbers are
reserved) and should be greater than 5000 (numbers from 1024 to 5000 are more likely to already be in use).
In addition, you should check /etc/services to make sure your selected port doesn't conflict with other
services running on the same port number. If you try to listen on a socket that is already in use,
an IOException will be thrown.
Create a Socket object from the ServerSocket.

Many servers allow multiple connections, continuing to accept connections until some termination condition is
reached. The ServerSocket accept method blocks until a connection is established, then returns a
normal Socket object. Here is the basic idea:

while(someCondition) {

Socket server = listenSocket.accept();

doSomethingWith(server);

}
If you want to allow multiple simultaneous connections to the socket, you should pass this socket to a separate
thread to create the input/output streams. In the next section, we give an example of creating a separate thread
for each connection.

Create an input stream to read input from the client.

Once you have a Socket, you can use the socket in the same way as with the client code shown in Section

17.1. The example here shows the creation of an input stream before an output stream, assuming that most
servers will read data before transmitting a reply. You can switch the order of this step and the next if you send
data before reading, and even omit this step if your server only transmits information.
As was also discussed in the client section, a BufferedReader is more efficient to use underneath
the InputStreamReader, as follows:

BufferedReader in =

new BufferedReader

(new InputStreamReader(server.getInputStream()));

Java also lets you use ObjectInputStream to receive complex objects from another Java program.
An ObjectInputStream connected to the network is used in exactly the same way as one connected to a
file; simply use readObject and cast the result to the appropriate type. See Section 13.9 (Serializing
Windows) for more details and an example. Also see Section 17.9 (RMI: Remote Method Invocation) for a high-
level interface that uses serialization to let you distribute Java objects across networks.
Create an output stream that can be used to send information back to the client.

You can use a generic OutputStream if you want to send binary data. If you want to use the
familiar print and println commands, create a Print_Writer. Here is an example of creating
a PrintWriter:
PrintWriter out = new PrintWriter(server.getOutputStream());
In Java, you can use an ObjectOutputStream if the client is written in the Java programming language and
is expecting complex Java objects.
Do I/O with input and output streams.
The BufferedReader, DataInputStream, and PrintWriter classes can be used in the same ways as

discussed in the client section earlier in this


chapter. BufferedReader provides read and readLine methods for reading characters or
strings. DataInputStream has readByte and readFully methods for reading a single byte or a byte
array. Use print and println for sending high-level data through a PrintWriter; use write to send a

byte or byte array.


Close the Socket when done.

When finished, close the socket:

server.close();

This method closes the associated input and output streams but does not terminate any loop that listens for
additional incoming connections.

You might also like