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

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

User Defined Exception in Java with Examples

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.

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

Thread Life Cycle in Java

Thread Life Cycle in Java tells the various information of thread form born to terminate.

Thread life cycle contains the several stages and at a time any thread can be present  in a single state.

States of Thread life cycle

  1. Born
  2. Ready
  3. Running
  4. Blocked
  5. Sleep
  6. Wait
  7. Dead
Java Thread Life Cycle
Java Thread Life Cycle

Ready:  In this state thread is ready to execute but not running. 

When the start() method calls thread enters from born to ready state.

Running:  When a run() method executes highest priority ready thread assigned a processor and enter in a running state for execution.

Thread can visit more than ones in a running state.

Blocked: When a running thread has a input-output issue it enters in a blocked state from running state and when input-output issue solves it again comes in a running thread.

Sleep : A running thread enter in a sleep state for a specified number of milliseconds when a sleep() method calls.

When sleep time expires then thread moves to ready state.

Wait : When a low priority thread executing and high priority thread comes then high priority thread get preference and enter in a running state. Then low priority thread leaves a running state and moves to wait state for indefinite time.

When a high priority thread execution completes it calls waiting thread for execution by notify () & notifyall () method.

Dead: A running thread is enter in a dead state when its execution completes (run() method completes)   or terminate for any reason.

Multithreading in java example programs

  1. Created a class Thread1 that extends Thread class
  2. main() creates two thread t1 and t2.
  3. To start thread start method is called t1.start() and t2.start()
  4. Start method calls the run method to execute the work
  5. Thread.sleep() send thread to sleep state for 500 milliseconds
  6. From sleep state thread come back to ready then running state
  7. After completing work thread get dead.

Read More

Multithreading in Java

Multithreading in Java Thread Creation Method Use Example

Multithreading in Java

1 What is a Thread in Java

A thread is light weight process that can execute simultaneously. Multithreading in java allows multiple threads to run simultaneously.

  • A program can be divided into two or more parts that can run concurrently and each part of such program is known as thread.
  • In a simple word, thread is a lightweight sub-process.
  •  It is a smallest unit of processing.
  • When these threads execute concurrently for accomplishing a task is known multithreading.
  • In multithreading, each thread defines a separate path of execution. 
  • In multithreading, every thread has a priority between 1 to 10. Thread with highest priority get preference over lower priority thread for execution.
Java Process and Thread Diagram
Fig: Java Process and Thread Diagram

 In a java programming, Thread is a predefined class within a java.lang package.

Operating system (OS) can contain multiple process, in the above figure, there are three process  P1,P2 & P3, within OS and within P3 process there are three threads T1, T2& T3. There is context-switching between the threads.  

2 Difference between Process and Thread

Difference between Process and Thread
ProcessThread
A process has their own virtual address space.Threads are entities within a process it uses its virtual address space of process.
Two processes running on the same system at the same time do not uses address space.Two threads running within a process uses the same address space.
Every process has its own data segmentAll threads within the process uses the same data segment of process.
In multiprocessing, processes use inter process communication techniques to interact with other processes.In multithreading, threads do not uses inter process communication techniques because they not uses separate address spaces. They share the same address space therefore, they can communicate directly with other threads within process.
Processes have considerable overhead.Threads have almost no overhead;
Process is heavy weight.Threads are light weight process (LWP).
Process contains much information about system, resource.Threads carry less state information than process
When we create a child process from a parent process then it requires duplication of the resources of parent process.No duplication of resources is required when we create a child thread from main thread.

3 How to create a thread in Java

We can create a thread by two ways:

  1. By extending Thread
  2. By implementing Runnable interface
How to create a thread in Java
Fig: How to create a thread in Java

Lets see multithreading in java with example

A Creating Thread By Implementing Runnable Interface

  1. We can create a thread by creating a class that implements the Runnable interface.
  2. To implement Runnable, a class only need to implement a single method called run().
  3. Inside run () we will define the code that constitute the new thread.    
  4. When a new thread creates, it do not executes until we call its start () method. When start () method executes it call to run() method.  

Below is the multithreading program in java with implementing runnable interface

Example: Print hello to illustrate multithreading example in java

Output

Creating more than one thread in java :- multithreading in java example

Output

Another Example of Thread is

Result

Description:

Passing “this” as a argument, “DemoThread” is the name of the thread.  

In this program, main thread fineshes last because the main thread sleeps for 1000 milliseconds (1 seconds) between iteration, but the child thread sleeps for only 500 milliseconds.

This cause the child thread terminates earlier than main thread.

B Creating Thread By extending Thread class in java

  1. To create a thread we will create a thread a class that extends Thread class.
  2. To extend Thread class, a class only needs to implement a single method called run (). This extending class must override the run() method
  3. Inside run () we will define the code that constitute the new thread.                                                                                 
  4. When a new thread creates, it do not executes until we call its start () method. When start () method executes it call to run() method.

Simple Thread example in java

Example: Write a thread program in java by extending thread class.

Multithreading in Java example programs

Example: Write a program to show multithreading in java by extending thread class

Multithreading in java example using Thread class

Result

4 Thread Methods in Java

Commonly used methods of Thread class are as follows

Sr NoMethod and Description
1void run()
Work execute as a thread is defined in this method .
2void start()
Used to start a thred which Calls the run() method of the thread or child class.
3static void sleep(long miliseconds)
Suspend the thread for specified amount of time.
4static void sleep(long miliseconds,int nanos)
Suspend the thread for specified amount of time.
5void join()
This method is used to pause the ececution of current thread until it die. void join().
6 void join(long miliseconds)
Pause the execution of current thread for the pecified miliseconds.
7void join(long miliseconds,int nanos)
Pause the execution of current thread for the pecified miliseconds and nano seconds.
8 boolean isAlive()
To checks a thread is alive or not.
9 String getName()
Returns the name of the thread.
10 setName(String name)
Used to set the name of thread.
11 int getPriority()
Get the priority of the thread.
12 void setPriority(int priority)
Set the priority of thread.
13 static Thread currentThread()
Returns the reference of currently executing thread
14 long getId()
Returns the id of the thread.
15 static void yield()
Temporarily pause the currently executing thread and allow other threads to execute.
16 void suspend()
Used to suspend the thread.
17 void resume()
Used to resume the suspended thread.
18 void stop()
Used to stop the thread.
19 void interrupt()
Interrupts the thread.
20 boolead isInterrupted()
Check whether the thead is interrupted or not

Use of thread in java

  1. To Reduce the time of execution of a program
  2. To achieve parallel execution

Read More

Thread Life Cycle in Java

How many ways to create thread in java

There are two ways to create thread in java

  1. By Extending Thread class
  2. By Implementing runnable Interface.

Types of thread in java

  1. Daemon thread provide services to other threads
  2. User defined threads Created by User

How to perform two tasks by two threads ?

Real time example of multithreading in java

  1. When two or more I/O operations are not dependent of each other then we can perform them by different threads.
  2. When tow or more Database read/write operations are not dependent then we can perform using multithreads.
  3. Sending OTP on mobile and email id at same time.
  4. Adding post on social media (fb, twitter, pintrest etc) on one click using publisher software.
  5. Servers are multithreaded they create separate thread to handle each request.

Java multithreading programming exercises

  1. Create Two threads using Thread class.
  2. Create Two threads using runnable Interface.
  3. Implement Produces consumer problem in Java.

Packages in Java -Types Sub Packages and Examples

Packages in Java is one of the important concept. All Java classes and interfaces are arranged in package structure.

What is package in java

Packages is a namespace which contains related classes and Interfaces.

The methods and field of class define inside the package can be accessible in package outside package and in child classes based on access specifier.  

Packages are stored in a hierarchical manner and explicitly imported into a new class definition.

Types of packages in java

Java packages are classified into two types

  1. Predefined or Built-in package
  2. User defined package

1 Java API(Application Programming Interface) packages or Predefined packages or Built-in packages

These packages are defined by the system. Some example of system defined packages are

  1. java.lang: It contains fundamental classes like System, String Math, Number etc. This is the default package in java.
  2. java.util: This package contains collections framework, legacy collection classes, event model and other features.
  3. java.io: Provides system input output with stream classes and files
  4. java.awt: Contain classes for creating user interface graphic and Image classes.
  5. java.net: Contains classes related to networking and sockets
    The Java 1.3 contains nearly 60 predefined packages

Importing packages in Java with Example

import java.util.Scanner; -To import Scanner class

import java.util.*; To import all classes in util package

Here we import is used to import java.util.Scanner;

2 User defined packages in java

These packages are defined by the user.

How to create package in java

Defining as packages: To define a package, place “package” command as the first statement in the source file.

The syntax of packages creation :-

  • The class that is defined in the package must be public. So that is can be accessible by any another of them.
  • Java uses the file system file directories to store packages. We save the program with number.java and compile the package is as javac_d/number.java. Due to this compilation Mypackage directory is automatically created and .class file is stores in that directory.

Once the package creation has completed. Then the package information is including with the help of “import” keyword.  import keyword links the package with our program.

Java Package Example

It is place before the class definition:

Java Package
Java Package Example
  • In this program, package is within x folder and main program is within y folder in c drive.
  • Package name in this program is x.
  • File name and package class name must be same ex: (number.java- source file).

How to compile package in java

c:\> javac folder/filename.java

c:\>java package.filename

Note: If we want to access all the classes of information then the classes are stored in different files with the same package name.

Sub Packages

In Java, it is possible to create a sub packages for the main packages.

Syntax

                 package  pack1.pack2;  

Where pack1 is the main package and pack2 is the sub package.

Java packages sub package example

Result

How many predefined packages in java

As per different java versions there are different packages and classes this SO question is also helpful.

We Inspected javase 14 and find there are 225 predefined packages / sub packages in java.

Which Package is default package in java

The package which is not required to import explicitly is known as default package.

If we write simple program to print hello then there we use System, String class we don’t need to import that. These are defined in java.lang package.

Default Package in Java is java.lang

Which keyword is used for accessing the features of a package

The import keyword is used for accessing the features of a package.

We can import classes and interfaces in our current file using import.

What is Import in Java

Import in a keyword in java. We use import statement to import class or all classes from a package.

How to import a package in java

import java.util.Date; or
import java.util.*;

How to create a package in java (Steps to create package in java with example)

  1. Create a folder with package name
  2. Create java files inside folder
  3. each java files include package definition package packagename;

packages in java with example program 

How to run package program in java (How to execute package in java)

compile d:\>javac foldername/filename.java
run d:\>java packagename.filename

What is java lang package in java

java lang (java.lang) is default package in Java. It contains fundamental classes.

Use of packages in java

  1. Group related classes and interfaces
  2. To avoid Naming conflicts
  3. To provide Access Control

Example of predefined packages in java

Predefined packages are defend by Java Team like

  1. java.lang (default package)
  2. java.util
  3. java.io
  4. java.net
  5. java.math
  6. java.sql
  7. java.time
  8. java.awt
  9. java.text

view all

The package which should be created to categorize the package further

The package which should be created to categorize the package further is sub package

java package java.

sub packages java.land, java.util etc.

Which of the following is used to avoid naming conflicts?

  1. class
  2. Interface
  3. package
  4. templet

Answer is package

Reference

Java Package


Login page in awt applet Java

Creating Login page in awt applet is easy.

Here we are not using any layout.

Login page contains two label, one textfield , one password field and two buttons.

Steps by step process to develop this program is as below

  1. Declare Label, JTextField, JPasswordField and Button
  2. Inside init() create object for JLabel, JTextField and JPasswordField and Button
  3. setBounds() to show elements in specific position.
  4. set Container layout to null setLayout(null);
  5. add all elements to container using add()
  6. set size of container setSize(400, 300);
  7. addActionListener() to login and reset button
  8. override actionPerformed() for login and reset
  9. on click on login button if username is Bond007 and password in James007 then show message Dialog Successfully Login
  10. if username and password is incorrect then show message Dialog Opps username/ password is incorrect
  11. on click on reset button reset the values of username and password field

Login page in awt applet Example

Elements are placed in specific position using setBound().

Buttons click events are bind using ActionListener and handled by actionPerformed.

We handled events like below.

You can handle actionPerformed() separately for that you have to implement ActionListener in your class.

You can run and check Program output

Login page in awt applet
Fig: Login page in awt applet failure
Login page in awt applet success
Fig: Login page in awt applet success

Hope you Got this.

Read More

Login form in Java Swing and MySql Database with source code

Registration Form in Java Swing with MySql Database

JTable in Java Swing with Examples
JTable Pagination in Java JDBC and MySQL Database