Applet Life Cycle in Java with Example

Applet in Java

Applet in Java is a special Java program that are primarily used in a internet programming.

Applet Life Cycle is very important to know in Java Applet Programming. 

As we have already seen how to run program from command prompt, but there were no GUI.

To provide Graphical user interface(GUI) Java Applet is used.

Applet program runs on a web browser at client side. Applet program are used to make the web site more dynamic.

1 Life Cycle of Applet Stages

When the applet program is loaded is passes through several stages:

Java Applet Life Cycle
Java Applet Life Cycle

A Applet Born State

Also known as initialization state.  

It is the first state of applet lifecycle.

Applet enters in a born/ initialization state when it is first loaded.  

Applet moves in a born state when init() method of Applet class executes.

Applet initialization occurs once in a  applet lifecycle.

Inside the init() method we initialize all the variables.

Syntax of init() method in Java Applet

B Applet Running State

  Applet enters in a running state from born state when a start() method of Applet class executes.  

Running sates call automatically when the initialization phase completes. 

Applet also comes in a running state from idle state when idle applet again get processor.

Running sates call automatically when the initialization phase completes. 

Applet also comes in a running state from idle state when idle applet again get processor.

Syntax of start()              

C Applet Idle State

A running appletenters in a idle sate from running state when execution of start complete.

In a another words when we leave the page of running applet then automatically it enters in a idle sate from running state.

Applet moves in idle state when  stop() method executes and it moves idle to running state when again start() calls.

Syntax of stop()               

D Applet Dead State

  An applet is moved to dead state when we quit the web browser.  When applet moves in a dead state it removed from memory. 

The Applet will be terminate when destroy () method calls. In a applet lifecycle, applet terminates/destroys ones.

Syntax of destroy()        

E Applet Display State

The Display state executes immediately after when applet enters in a running state.

In this state we display the information on the output screen using paint() method.

2 Applet Life Cycle Program in Java Example

Lets see one program to demonstrate the life cycle of applet.

Compile and Run

>javac AppletLifeCycle.java
>appletviewer AppletLifeCycle.java

Applet Life Cycle in Java Example
Fig: Java Applet Life Cycle Example

Output At Console

On running Applet It will print first 3 line from output.

On closing applet it will call stop and destroy method.

init() method can be used to initialize various values and objects that are going to use in program.

Similarly to release resource we can use destroy().

Example: Write a program to read file and show in java applet.

Output

Fig: Reading File in showing in an applet

Read More

  1. JComboBox in Java Swing
  2. JTable in Java Swing
  3. JTable Pagination in Java JDBC
  4. Registration Form in Java Swing
  5. Login form in Java Swing
  6. Simple Calculator in Java Applet

Sum of two numbers using command line arguments in java

Command line argument is as a way to pass arguments in java while running java program.

1 Sum of two integer numbers using command line arguments in java

Steps to add two integer numbers is below

  1. Read command-line variable array args[0] and args[1].
  2. Convert it to integer value and store it in two variables.
  3. add both variables and store in another variable sum
  4. print the sum.

Run above program from command prompt

>javac CommandLineArguments.java

>java CommandLineArguments 8 5

command line arguments in java
Fig: command line arguments in java

Output

value 8 will pass to args[0] and value 5 will store in args[1].

As we know args is String array.

So to convert value from string we used Integer.parseInt() method.

Lets see another example

2 Sum of two double numbers using command line arguments in java

Output

Similar way we can add long, float values.

You have to know how to convert string to long and string to float and from string to other data types.

This is possible with the use of Java wrapper classes.

Each primitive data type has its own class that is known as wrapper class.

Wrapper class contain methods to convert value from string to specify object type.

Following Classes are sub class of Number class.

You can find details in the Number class also check all its sub-classes.

Number Class in Java
Number Class in Java

3 Conversion from String to number using Wrapper class

Sr NoConvert from string toMethod
1ByteByte.ParseByte()
2ShortShort.valueOf()
3IntegerInteger.shortInt()
4LongLong.parseLong()
5FloatFloat.parseFloat()
6DoubleDouble.parseDouble()

Above programs are very simple.

Lets assume a situation if use does not provide two values or provides values like alphabet then how to deal with it.

4 How to check length of command line argument

Before addition we should check whether user has provided tow numbers or not.

Lets check it.

Output

args is string array so we can use length property to check its length.

if (args.length != 2) then we are showing a message to the user that Please provide two arguments and terminating the execution.

5 Exception handling with command line arguments

A. Handling ArrayIndexOutOfBoundsException

This exception occurs because we tried to access array index that does not exists.

Read More

Exception Handling try catch finally blocks in Java
Exception Handling in Java: Hierarchy Example and Types
User-Defined (Custom) Exceptions in Java with Examples

If user passed only one value and we accessing first tow value then this error can occurs.

To avoid this we already seen above validation problem.

Lets again run our first program and pass only one value

Output

Lets see how to handle with exception

Output

Result

B. Handling NumberFormatException

This exception occurs when method is unable to convert string to a number type.

For example, a user gives “w” as input so the method is unable to convert it to a number.

Then this method will throw NumberFormatException.

Output

To resolve NumberFormatException again we will use try catch block.

Output

C. Handling Multiple Exceptions

try can throw multiple exceptions to handle this we can create multiple catch blocks each for a specific exception.

We can also use one catch block to handle multiple exceptions.

Read More

  1. Duplicate Number between 1 to n numbers
  2. Print vowels in a String
  3. Program to reverse a string
  4. Prime number program in java using while loop
  5. Print vowels in a String
  6. Square Star Pattern

Write a java program to reverse a string

Using StringBuffer or StringBuilder class

Output

Using Loops(Iteration)

Copy and reverse the string

Here getting input from user

converted into character array using toCharArray() of String

Initialize the other character array with same length as c character array.

Loop char array c in reverse order and r in forward order.

this will copy character array c in reverse order to r.

converted char array r to String

print both character array

Output

Read More

  1. Duplicate Number between 1 to n numbers
  2. Print vowels in a String
  3. Sum of two numbers using command line arguments
  4. Prime number program in java using while loop
  5. Print vowels in a String
  6. Square Star Pattern

JLabel in Java Swing with Method Constructors and Examples

JLabel in Java Swing is an object that is used to display text and images in a Frame.

Jlabel uses to display information, show different messages, and make the frame interactive and readable.

JLabel class declaration

JLabel extends JComponent and implements SwingConstants and Accessible Interfaces.

JLabel Constructors

Sr NoConstructor and Description
1JLabel()
Create a Jlabel with no image and empty text
2JLabel​(String text)
Create a Jlabel with specified text
3JLabel​(String text, int horizontalAlignment)
Create a Jlabel with specified text and horizontalAlignment
4JLabel​(String text, Icon icon, int horizontalAlignment)
Create a Jlabel with specified text, image and horizontalAlignment
5JLabel​(Icon image)
Create a Jlabel with specified image
6JLabel​(Icon image, int horizontalAlignment)
Create a Jlabel with specified image and horizontalAlignment

Commonly used JLabel Methods

Sr NoMethod and Description
1String getText()
Get the text of label
2void setText​(String text)
Set the text of label
3Icon getIcon()
Return the Graphic Icon of label
4void setIcon​(Icon icon)
Set the graphic icon for label
5void setHorizontalAlignment​(int alignment)
Set Horizontal alignment of label
6int getHorizontalAlignment()
Get Horizontal alignment of label
5void setVerticalAlignment​(int alignment)
Set Vertical alignment of label
6int getVerticalAlignment()
Get Vertical alignment of label

JLabel contains more methods we have used a few of them here.

jlabel java Examples

jlabel java Examples

Label in java Example- How to change jlabel background color

JLabel Example – Foreground and background color change

Foreground and background color change

Jlabel set font Example Set JLable font Size, Font Height

jlabel set font Example

JLabel Example to getAttributes

How to Show Image in JLabel

Read More

  1. JComboBox in Java Swing
  2. JTable in Java Swing
  3. JTable Pagination in Java JDBC
  4. Registration Form in Java Swing
  5. Login form in Java Swing
  6. Simple Calculator in Java Applet
  7. Applet Life Cycle in Java

Read More

  1. JComboBox in Java Swing
  2. JTable in Java Swing
  3. JTable Pagination in Java JDBC
  4. Registration Form in Java Swing
  5. Login form in Java Swing
  6. Simple Calculator in Java Applet
  7. Applet Life Cycle in Java

double array java- java double array declare initialize access

Double array java is a Java array with double values.

All values are stored in contineous memory location

Declaring double array in Java

General syntax to declare array is

dataType [] arrayName;

dataType: Any primitive or user-defined data types like int, char, float, double. etc

[] : notation to represent an array.

arrayName: name of an array;

double[] d;

double[] price;

here d and price are arrays that can refer to the array of double type.

Initializing and Accessing double array in Java

initialization specifies the size and initial values of an array.

Syntax of initialization is

dataType [] arrayName=new dataType[SIZE];

or

dataType [] arrayName=new dataType[]{value1, value2, …. ,value n};

double[] d=new double[5];

double[] price=new double[4];

above two statements will allocate memory for two array that are pointed by d and price.

Initialize both arrays by value 0.0 (the default value of double data type).

We can also provide some initial value to the array as follows

double[] d=new double[]{2.3,5.4,7.6,8.9,9.9};

another way to initialize array is

double[] d={2.3,5.4,7.6,8.9,9.9};

Java Array Loop Initialization

Initializing Array using Arrays.fill()

Some times we need to fill array using same value that we can use fill method as below.

double[] d=new double[5];
Arrays.fill(d,4.4);

It will fill all array elements with 4.4

double[] d={2.3,4.5,5.6,7.8,9.8};
Arrays.fill(d,1,3,5.5);

Initializing Array using Arrays.setAll()

import java.util.Arrays;

DoubleStream to double Array in Java

DoubleStream is a sequence of double values that supports sequential and parallel aggregation operations.

DoubleStreams of() can be used to create a double stream of specified values.

toArray() of DoubleStream can use to convert it to an array.

double array Java length

The length of an array can be found using the length property.

double to double array copy

To copy one array in to another we can use

  1. clone()
  2. System.arraycopy()
  3. Arrays.copyOf()

there are other methods also we discuss above three here

double array copy using clone()

array copy using System.arraycopy()

double array copy using Arrays.copyOf()

Above all will copy double array d to e.

Sorting double Array

Arrays class provides a method sort() to sort any type of array.

example to sort double array is as below.

output of above program is here

There are different ways to sort and array we discussed only one.

One dimensional array in java with examples

What is One dimensional (Single dimensional) array in java

An array is a collection of similar elements. All array elements are stored in the contiguous memory location.

One dimensional or single dimensional array is an array with one dimension.

One dimensional array declaration in java

Syntax

Example

In above declaration age is a reference variable which will hold reference of array same for price and for names.

One dimensional array construction

Array uses new operator to dynamically allocating memory locations.
Syntax

Example

new operator will dynamically allocate memory for 5 integer values that is 5*4=20 bytes continuously.

Array uses zero based indexing where first element is stored in zero location. Last element is stored in array size-1 location.

We can assign values in array element one by one as below

Single dimensional array initialization in java

Array declaration and initialization can be done in one statement
syntax

Example

Accessing array element: array element can be accessed by its index value.

Syntax

Example age[0] access all first value of array we can use loop
We can print all values is age below

One dimensional array in java examples

Array programs in java

Result

We can also use for each loop to show array elements

Java array programs

Output

Array input in java

Scanner class is used here to get Input in the array.

Static array in java

To create an static array add keyword static before an array.

Length of array in java

length property of an array is used to find the length of an array

How to store string in array in java

String to integer array in java

This program is taking a string as an argument converting it to StringTokenizer based on delimiter [,] and space.

String tokenizer contains a set of string tokens these tokens are converted to an integer using Integer.parseInt().

above program can handle the following strings

String s1 = “1 2 3 4 5 6 7 8 9”; or

String s1 = “1,2,3,4,5,6,7,8,9”;

String s1 = “[1,2,3,4,5,6,7,8,9]”;

Anonymous array in java

anonymous array in java are arrays without name

like

new Integer[]{1, 2, 3, 4, 5, 6, 7}

new String[]{“Ram”,”Mohan”,”Sohan”};

How to get the length of the 2D array in Java

Two dimensional array in java

To declare an 2D array in java we use the following syntax

Datatype [][] arrayName=new Datatype[rows][cols]

If you want to declare any primitive 2D array.

int [][] ages=new int[3][4];

double [][] prices=new double[4][4]

Array ages is a two-dimensional int array, it can store 3 rows and each row can contain 4 values (columns) total of 3*4=12 values.

similar price is a two-dimensional double array, it can store 4 rows and 4 columns total (4*4) 20 elements.

Two-dimensional array initialization

above are the two-dimension array declared and initialized.

Length of an array in Java

Java array provides a variable length to find the length of a variable.4

to find the length of one dimension array we use following code

One dimension array length is number of elements in array

Length of the 2D array in Java

In a two-dimensional array, java length is the number of rows in 2D array.

To access each row length we can use the following code

Exception Handling try catch finally blocks in Java

What is try block

A try block is used to surround a set of statements where exceptions may occur.

A try block used with catch and finally block

Also Read

Exception Handling in Java: Hierarchy Example and Types

What is a catch block

A catch block is created followed by a try block.

Whenever an exception is thrown from try block it catches in the appropriate catch block

There can be more than one catch block for a try block.

Syntax of try catch block

Java finally block

Java finally block is also associated with a try block.

Finally block is used to release resources that are used in a try block.

like closing a file. closing database connection

Finally block gets always executed when there is exception or not in try block.

We can use try and finally or try catch and finally.

Syntax of try-catch and finally

1 try and finally

2 try catch and finally

try catch java examples

ArithmeticException Example in Java

Output

Exception occurs at the line “a = 42 / d; “ , then this exception is thrown, program control transfer from  try block to catch block.

Once  catch block has executed program control continue with the next line in a program following entire try/catch statement.

In the line “catch (ArithmeticException e) “  e is a reference of exception “ArithmeticException”.

When we print the value of “e “ it will print  ( java.lang.ArithmeticException:/by zero                                                                    at  Test.main(Test.java:6) )

  • ArithmeticException is an exception class which resides in java.lang package.
  • “/by zero”  is a type of arithmetic exception (divided by zero).
  • “Test” is the name of the class.
  • “main” is a method in which an exception occurs.
  • 6 is line number in which exception occured.

Java try catch multiple exceptions

1 Try and multiple catch blocks

In java programming, when within a try block multiple exceptions occur then for handling those multiple exceptions we use multiple catches with a single try block.

When we pass no command line argument (during run time) than the length of command line argument (args.length) is zero means value of variable “a” is 0.

Than the output is:

When we pass one or more command line argument ( in this program one command line argument is passed “test” during run time) than the length of command line argument (args.length) is one means value of variable “a” is  1.

Than the output is:

2 Java try catch multiple exceptions

Unreachable Code in Exception Handling

In Java programming, in a sequence of catch statement exception subclass must come before its super class.

In a series, if exception super class comes before  its subclass than exception sub class would never be reached.

It is known as unreachable code. In Java programming, unreachable code is an compile-time error.    

Example unreachable code in Exception Handling

If we will try to compile this program we will receive an error message stating that the second catch statement is unreachable because ArithmeticException is a subclass of the Exception class. 

     Then the first catch statement will handle all exception-based errors, including Arithmetic Exception therefore second catch statement will never execute.

 To solve the problem, reverse the order of the catch statement.  

Nested try catch Java statements

In java programming, it is possible to create a try block within another try block. Such try block is known as nested try.

Nested try catch Example

If there is no command line argument present then the output.

If there is no command line argument present then the output.

Read More

User-Defined Exception in Java with Examples

Q : When a statement within a try block causes an exception, the remaining statements in the try block

Ans: Will Not be executed

Q: In a try/catch construct, after the catch statement is executed:

Ans: Statement just after the catch is executed

Q: Can you have multiple catch blocks on a try statement

Ans: Yes, as per the need we can have multiple catch blocks on a try statement

Q: To catch an exception, the code that might throw the exception must be enclosed in a ____________

Ans: try block

Q: If an exception occurs in a try-catch block, the code in the finally clause ________.

Ans: Get Executed. If with try block finally is associated then it always gets executed no matter it throws an exception or not.

Q: A try block may be followed by a finally block, without a catch block (Java try without catch).

Ans: Yes we can use try and finally without a catch block.

Q: Exceptions can be thrown by ________.

Ans: Throw statement is used to throw an Exception

Q: When is the code within a catch block executed?

Ans: If an exception occurs within the code in the try block then matched exception in the catch block gets executed.

Java unreported exception How to Handle it

The unreported exception is due to you have checked exception in your program and you are not handling it.

You can handle it

  1. By using try catch block
  2. By using throws keyword in method

unreported exception

Which of the following Throwables needs to be declared?

  1. Error
  2. RuntimeException
  3. CheckedException 
  4. Exception

Answer is 3

More MCQ

Read More

  1. Exception Handling in Java: Hierarchy Example and Types
  2. Exception Handling in Java with Examples
  3. Throw and Throws Keywords in Java
  4. How To Fix Internal Exception: java.io.ioexception In Minecraft

Throw and Throws Keywords in Java

In java programming, If the exception occurs within the try block it is thrown.

a throw keyword is used to throw an exception

A system-generated exception is automatically thrown by the java run time system but if we want to manually throw an exception, we can do so by using the throw keyword. 

Exception Handling try catch finally blocks in Java

Syntax of throw

           throw    ThrowableInstance;

here, ThrowableInstance must be an object of type Throwable or subclass of Throwable.

Example of throw keyword

In this program new is used to create an instance of NullPointerException and we get two chance to deal with the same error.

In the line  “throw new NullPointerException(“demo”);” 

throw keyword is used to throw  NullPointerException(“demo”). Here we set “demo” is a name of exception.

This NullPointerException(“demo”) catch by catch() method which resides in a demo() method.

 Line “throw e;”  re-throw the exception which is catch by catch() method which resides in a main() method.

Throws Keyword in Java

In a java programming, throws keyword list the type of exception that a method might throw.

throws keyword inform that method throws mentioned exceptions

In the throws clause, we declare all the exceptions that a method can throw.

  Syntax of throws:         

                                               

Here, exception1, exception2 are comma, list of the exception that a method can throw.

Example of throws

Explaination: We throws NullPointerException in the line “throw new NullPointerException(“demo”);” .

Here we set “demo” is a name of thread.

This line “throw new NullPointerException(“demo”);” throw the exception which is handled by catch block associated with try within main().

Difference between throw and throws in Java (throw vs throws)

throw keyword is used to throw an exception from method or from a block

throw is used inside method

throw new NullPointerException("demo");

throws keyword is used to inform that a method throws exception(s)

thorws keyword i s used in method header

public Scanner​(File source) throws FileNotFoundException

What is the purpose of the throw statement?

Throw is used to throw an exception from a method or from block of code

what is the difference between throwing an exception and catching an exception?

Throwing an exception can use to throw an exception using the throw keyword.

this can be implicit or explicit

45/0 <- throw ArithmeticException 

throw ArithmeticException(“Denominator can not be zero”);

To catch an exception one or more catch blocks can be used so that program executes properly.

The ______ keyword is used to manually throw an exception in java

The Throw keyword is used to manually throw an exception.

Read More

  1. Exception Handling in Java: Hierarchy Example and Types
  2. Exception Handling in Java with Examples
  3. Exception Handling try catch finally blocks in Java

Reference

How to Throw Exceptions

            

User Defined (Custom) Exceptions in Java with Examples

In Java programming, it is possible to create our own exception and such exception are called user defined exception in Java.

Exception class is a predefined class. Any user defined exception created by us must be a subclass of the predefine Exception class and created by extending the Exception class.

Read More

  1. Exception Handling in Java: Hierarchy Example and Types
  2. Exception Handling in Java with Examples
  3. Exception Handling try catch finally blocks in Java
  4. Throw and Throws Keywords in Java

What is user defined (custom) exception in java

An Exception that is defined by the user/ programmer is known as user defined or custom exception.

example

  1. Checking user age if not valid age throw an exception
  2. If not in a specified time period then throw an exception
  3. If the user name and password is incorrect then throw an exception

All above exceptions are created by the user and throw when required.

How to throw user defined exception in java

 The throw and throws keyword are used for implementing user defined exception. 

throw: throw keyword is used to throw an exception explicitly from a method or from a block.   

for instance

 Here new NumberIsGreaterException();

is creating new exception and throwing it.

throws: throws keyword is used with method signature that informs that the method can throw mentioned exception.   

Here Scanner is class and above mentioned Scanner represents the constructor call, On the constructor call of above we have to handle File not found Exception.

how to create user defined exception in java

  1. Create a class
  2. Extend the Exception class
  3. Create a String argument constructor to pass custom message.

Examples of User Defined Exception in Java

Example1:   write a program to take a number from user by using command line argument during run time. if user will enter  more than 100 then grnerate user defined exception MyException.

Explaination: In the above program, name of user define exception is NumberIsGreaterException. 

In the above program user enter  the number 111 during run time using command line argument.

Here value of “m” is greter than 100 therefore  “throw  newNumberIsGreaterException ();” this throw statement throw the exception and catch by catch block, but before thorw “NumberIsGreaterException ()” constructer will call.

User defined exception in java program to check age is valid or not

InvalidAgeException.java

CheckAge.java

Output

user defined exception in java example to check a time is in range or not, if time is not in range then throw custom exception

InvalidTimeException.java

CheckTime.java

Output

Example: Write a program to create user defined exception in Java to check a given name exists or not. If name doesn’t exists then throw a custom exception.

InvalidNameException.java

CheckName.java

Output

How to write custom exception in java?

or

How to create custom exception in java?

or

How to create your own exception in java?

  1. Create a class
  2. Extend Exception class
  3. Create a constructor to show/pass custom message