## Java Training (104)

Friday, 07 December 2018 07:50

Written by

## Spy Number

A number is a Spy number, if sum and product of all digits are equal.

Example:

Number 123 is a Spy number, sum of its digits is 6 (1+2+3 =6) and product of its digits is 6 (1x2x3 = 6), sum and product are same, thus, 123 is a spy number.

```import java.util.Scanner;

public class SpyNumber
{
public static void main(String[] args)
{
int n,product=1,sum=0;
int ld;

// create object of scanner.
Scanner sc = new Scanner(System.in);

// you have to enter number here.
System.out.print("Enter the number :" );

// read entered number and store it in "n".
n=sc.nextInt();

// calculate sum and product of the number here.
while(n>0)
{
ld=n%10;
sum=sum+ld;
product=product*ld;
n=n/10;
}

// compare the sum and product.
if(sum==product)
System.out.println("Given number is spy number");
else
System.out.println("Given number is not spy number");
}
}Output```
```First run:
Enter the number :1124
Given number is spy number

Second run:
Enter the number :1123
Given number is not spy number```

### Program to check Spy number in java

Friday, 07 December 2018 07:44

### Program to check if number is Neon Number in java

Written by

This program checks if a number entered is a Neon Number or not, in JAVA.

A number is said to be a Neon Number if the sum of digits of the square of the number is equal to the number itself.

Example- 9 is a Neon Number. 9*9=81 and 8+1=9.Hence it is a Neon Number.

Program -

import java.util.*;
public class NeonNumber
{
public static void main(String args[])
{
Scanner ob=new Scanner(System.in);
System.out.println("Enter the number to be checked.");
int num=ob.nextInt();
int square=num*num;
int sum=0;
while(square!=0)//Loop to find the sum of digits.
{
int a=square%10;
sum=sum+a;
square=square/10;
}
if(sum==num)
{
System.out.println(num+" is a Neon Number.");
}
else
{
System.out.println(num+" is not a Neon Number.");
}
}
}

Description -

The number is entered through Scanner class and then its square is taken by multiplying the number 2 times.After that we find the sum of digits of the square and check if the number is equal to the sum of digits of square of the number.

Friday, 07 December 2018 07:30

### Classify Abundant, deficient and perfect number (integers) between 1 to 10,000

Written by

Write a Java program to classify Abundant, deficient and perfect number (integers) between 1 to 10,000.

In number theory, an abundant number is a number for which the sum of its proper divisors is greater than the number itself.
Example :
The first few abundant numbers are:
12, 18, 20, 24, 30, 36, 40, 42, 48, 54, 56, 60, 66, 70, 72, 78, 80, 84, 88, 90, 96, 100, 102,…
The integer 12 is the first abundant number. Its proper divisors are 1, 2, 3, 4 and 6 for a total of 16.
Deficient number: In number theory, a deficient number is a number n for which the sum of divisors σ(n)<2n, or, equivalently, the sum of proper divisors (or aliquot sum) s(n)<n. The value 2n − σ(n) (or n − s(n)) is called the number's deficiency.
As an example, divisors of 21 are 1, 3 and 7, and their sum is 11. Because 11 is less than 21, the number 21 is deficient. Its deficiency is 2 × 21 − 32 = 10.
The first few deficient numbers are:
1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 19, 21, 22, 23, 25, 26, 27, 29, 31, 32, 33, …….
Perfect number: In number system, a perfect number is a positive integer that is equal to the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself) i.e. σ1(n) = 2n.
The first perfect number is 6. Its proper divisors are 1, 2, and 3, and 1 + 2 + 3 = 6. Equivalently, the number 6 is equal to half the sum of all its positive divisors: ( 1 + 2 + 3 + 6 ) / 2 = 6. The next perfect number is 28 = 1 + 2 + 4 + 7 + 14. This is followed by the perfect numbers 496 and 8128.

Sample Solution:

Java Code:

import static java.util.stream.LongStream.rangeClosed;
public class Exercise2 {

public static void main(String[] args) {
int count_Deficient_no = 0;
int count_Perfect_no = 0;
int count_Abundant_no = 0;

for (long i = 1; i <= 10_000L; i++) {
long sum = proper_Divs_Sum(i);
if (sum < i)
count_Deficient_no++;
else if (sum == i)
count_Perfect_no++;
else
count_Abundant_no++;
}
System.out.println("Number Counting [(integers) between 1 to 10,000]: ");
System.out.println("Deficient number: " + count_Deficient_no);
System.out.println("Perfect number: " + count_Perfect_no);
System.out.println("Abundant number: " + count_Abundant_no);
}
public static Long proper_Divs_Sum(long num) {
return rangeClosed(1, (num + 1) / 2).filter(i -> num % i == 0 && num != i).sum();
}
}

Sample Output:
`Number Counting [(integers) between 1 to 10,000]:`
`Deficient number: 7508 `
`Perfect number: 4   `
`Abundant number: 2488`

Tuesday, 08 August 2017 04:35

### Java Interview Questions

Written by

Q) What is polymorphism ?

Ans) The ability to define a function in multiple forms is called Polymorphism. In java, c++ there are two types of polymorphism: compile time polymorphism (overloading) and runtime polymorphism (overriding).

Method overriding: happens when a child class implements the method with same signature as a method in a parent class. When you override methods, JVM determines the proper methods to call at the program’s runtime, not at the compile time.

Method overloading: happens when several methods have same names but different number or type of parameters. Overloading is determined at the compile time.

• Different method signature and different number or type of parameters.
• Same method signature but different number of parameters.
• Same method signature and same number of parameters but of different type
``````int add(int a,int b)
``````
``````class BookDetails {
String title;
setBook(String title){}
}
class ScienceBook extends BookDetails {
setBook(String title){} //overriding
}
``````

Q) What is use of serialVersionUID?

Ans) The default Java serialization mechanism writes the metadata about the object, which includes the class name, field names and types, and superclass. This class definition is stored as a part of the serialized object. This stored metadata enables the deserialization process to reconstitute the objects and map the stream data into the class attributes with the appropriate type
Everytime an object is serialized the java serialization mechanism automatically computes a hash value. ObjectStreamClass's computeSerialVersionUID() method passes the class name, sorted member names, modifiers, and interfaces to the secure hash algorithm (SHA), which returns a hash value.The serialVersionUID is also called suid.
So when the serilaize object is retrieved , the JVM first evaluates the suid of the serialized class and compares the suid value with the one of the object. If the suid values match then the object is said to be compatible with the class and hence it is de-serialized. If not InvalidClassException exception is thrown.

Changes to a serializable class can be compatible or incompatible. Following is the list of changes which are compatible:

• Change a field from static to non-static
• Change a field from transient to non-transient
• Add classes to the object tree

List of incompatible changes:

• Delete fields
• Change class hierarchy
• Change non-static to static
• Change non-transient to transient
• Change type of a primitive field

So, if no suid is present, inspite of making compatible changes, jvm generates new suid thus resulting in an exception if prior release version object is used .

The only way to get rid of the exception is to recompile and deploy the application again.

If we explicitly mention the suid using the statement:
``private final static long serialVersionUID = <integer value>``

then if any of the metioned compatible changes are made the class need not to be recompiled. But for incompatible changes there is no other way than to compile again.

Q) What is the difference between final, finally and finalize() in Java?

Ans) final - A final variable acts as a constant, a final class is immutable and a final method cannot be override in a child class.

finally - finally keyword is used with try-catch block for handling exception. The finally block is optional in try-catch block. The finally code block is always executed after try or catch block is completed. The general use case for finally block is to close the resources or clean up objects used in try block. For e.g. Closing a FileStream, I/O stream objects, Database connections, HTTP connections are generally closed in a finally block.

finalize() - This is the method of Object class.It is invoked before an object is discarded by the garbage collector, allowing it to clean up its state. Should not be used to release non-memory resources like file handles, sockets, database connections etc because Java has only a finite number of these resources and you do not know when the garbage collection is going to kick in to release these non-memory resources through the finalize() method.

Q4)What is difference between HashMap and HashTable?

Ans) Both collections implements Map. Both collections store value as key-value pairs. The key differences between the two are:

1. Hashmap is not synchronized in nature but hashtable is(thread-safe). This means that in a multithreaded application, only one thread can gets access to a hashtable object and do an operation on it. Hashmap doesn't gurantee such behavior and is not used in multithreaded environment.
2. Hashmap is traveresed using an iterator, hashtable can be traversed by enumerator or iterator.
3. Iterator in hashmap is fail-fast, enumerator in hashtable is not fail-fast
4. HashMap permits null values and only one null key, while Hashtable doesn't allow key or value as null.
5. Since hashtable is synchornized, it is relatively slower in performance than hashmap

Q) What is difference between abstract class and interface ?

Ans) A class is called abstract when it is declared with keyword`abstract`. Abstract class contains atleast one abstract method. It can also contain n numbers of concrete method. Interface can only contain abstract methods.

• Interface can have only abstract methods. Abstract class can have concerete and abstract methods.
• The abstract class can have public, private, protected or default variables and also constants. In interface the variable is by default public final. In nutshell the interface doesnt have any variables it only has constants.
• A class can extend only one abstract class but a class can implement multiple interfaces. Abstract class doesn't support multiple inheritance whereas abstract class does.
• If an interface is implemented its mandatory to implement all of its methods but if an abstract class is extended its mandatory to implement all abstract methods.
• The problem with an interface is, if you want to add a new feature (method) in its contract, then you MUST implement those method in all of the classes which implement that interface. However, in the case of an abstract class, the method can be simply implemented in the abstract class and the same can be called by its subclass.

Q) What is the difference between equals() and == ?

Ans) == operator is used to compare the references of the objects.
public bollean equals(Object o) is the method provided by the Object class. The default implementation uses == operator to compare two objects. But since the method can be overriden like for String class. equals() method can be used to compare the values of two objects.

``````String str1 = "MyName";
String str2 = "MyName";
String str3 = new String(str2);

if (str1 == str2) {
System.out.println("Objects are equal")
}else{
System.out.println("Objects are not equal")
}
if(str1.equals(str2)) {
System.out.println("Objects are equal")
} else {
System.out.println("Objects are not equal")
}

Output:
Objects are not equal
Objects are equal
``````
``````String str2 = "MyName";
String str3 = str2;
if (str2 == str3) {
System.out.println("Objects are equal")
}else{
System.out.println("Objects are not equal")
}
if (str3.equals(str2)) {
System.out.println("Objects are equal")
} else {
System.out.println("Objects are not equal")
}

Output:
Objects are equal
Objects are equal``````

Q) What is difference between a thread and a process?

Ans)

• Threads share the address space of the process that created it; process has it's own address space.
• Threads have direct access to the data segment of its process; processes have their own copy of the data segment of the parent process.
• Threads can directly communicate with other threads of its process; processes must use interprocess communication to communicate with sibling processes.
• New threads are easily created; new processes require duplication of the parent process.
• Threads can exercise considerable control over threads of the same process; processes can only exercise control over child processes.
• Changes to the main thread (cancellation, priority change etc.) may affect the behavior of the other threads of the process; changes to the parent process do not affect child processes.

Q) What is use of synchronized keyword?

Ans) synchronized keyword can be applied to static/non-static methods or a block of code. Only one thread at a time can access synchronized methods and if there are multiple threads trying to access the same method then other threads have to wait for the execution of method by one thread. Synchronized keyword provides a lock on the object and thus prevents race condition. E.g.

``````public void synchronized method(){}
public void synchronized staticmethod(){}
public void myMethod(){
synchronized (this){
//synchronized keyword on block of code
}
}``````

Q)Is garbage collector a dameon thread?

Ans) Yes GC is a dameon thread. A dameon thread runs behind the application. It is started by JVM. The thread stops when all non-dameon threads stop.

Q)How is Garbage Collection managed?

Ans)The JVM controls the Garbage Collector; it decides when to run the Garbage Collector. JVM runs the Garbage Collector when it realizes that the memory is running low. The behavior of GC can be tuned by passing parameters to JVM. One can request the Garbage Collection to happen from within the java program but there is no guarantee that this request will be taken care of by jvm.

Saturday, 05 August 2017 08:10

### Java JButton

Written by

The JButton class is used to create a labeled button that has platform independent implementation. The application result in some action when the button is pushed. It inherits AbstractButton class.

## JButton class declaration

Let's see the declaration for javax.swing.JButton class.

1. public class JButton extends AbstractButton implements Accessible

### Commonly used Constructors:

Constructor Description
JButton() It creates a button with no text and icon.
JButton(String s) It creates a button with the specified text.
JButton(Icon i) It creates a button with the specified icon object.

### Commonly used Methods of AbstractButton class:

Methods Description
void setText(String s) It is used to set specified text on button
String getText() It is used to return the text of the button.
void setEnabled(boolean b) It is used to enable or disable the button.
void setIcon(Icon b) It is used to set the specified Icon on the button.
Icon getIcon() It is used to get the Icon of the button.
void setMnemonic(int a) It is used to set the mnemonic on the button.
void addActionListener(ActionListener a) It is used to add the action listener to this object.

## Java JButton Example

1. import javax.swing.*;
2. public class ButtonExample {
3. public static void main(String[] args) {
4.     JFrame f=new JFrame("Button Example");
5.     JButton b=new JButton("Click Here");
6.     b.setBounds(50,100,95,30);
8.     f.setSize(400,400);
9.     f.setLayout(null);
10.     f.setVisible(true);
11. }
12. }

Output:

## Java JButton Example with ActionListener

1. import java.awt.event.*;
2. import javax.swing.*;
3. public class ButtonExample {
4. public static void main(String[] args) {
5.     JFrame f=new JFrame("Button Example");
6.     final JTextField tf=new JTextField();
7.     tf.setBounds(50,50150,20);
8.     JButton b=new JButton("Click Here");
9.     b.setBounds(50,100,95,30);
11. public void actionPerformed(ActionEvent e){
12.             tf.setText("Welcome to Javatpoint.");
13.         }
14.     });
16.     f.setSize(400,400);
17.     f.setLayout(null);
18.     f.setVisible(true);
19. }
20. }

Output:

## Example of displaying image on the button:

1. import javax.swing.*;
2. public class ButtonExample{
3. ButtonExample(){
4. JFrame f=new JFrame("Button Example");
5. JButton b=new JButton(new ImageIcon("D:\\icon.png"));
6. b.setBounds(100,100,10040);
8. f.setSize(300,400);
9. f.setLayout(null);
10. f.setVisible(true);
11. f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
12.     }
13. public static void main(String[] args) {
14.     new ButtonExample();
15. }
16. }

Output:

Saturday, 05 August 2017 08:04

### Java Swing

Written by

Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create window-based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written in java.

Unlike AWT, Java Swing provides platform-independent and lightweight components.

The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.

### Difference between AWT and Swing

There are many differences between java awt and swing that are given below.

No. Java AWT Java Swing
1) AWT components are platform-dependent. Java swing components are platform-independent.
2) AWT components are heavyweight. Swing components are lightweight.
3) AWT doesn't support pluggable look and feel. Swing supports pluggable look and feel.
4) AWT provides less components than Swing. Swing provides more powerful components such as tables, lists, scrollpanes, colorchooser, tabbedpane etc.
5) AWT doesn't follows MVC(Model View Controller) where model represents data, view represents presentation and controller acts as an interface between model and view. Swing follows MVC.

### What is JFC

The Java Foundation Classes (JFC) are a set of GUI components which simplify the development of desktop applications.

### Hierarchy of Java Swing classes

The hierarchy of java swing API is given below.

### Commonly used Methods of Component class

The methods of Component class are widely used in java swing that are given below.

Method Description
public void setSize(int width,int height) sets size of the component.
public void setLayout(LayoutManager m) sets the layout manager for the component.
public void setVisible(boolean b) sets the visibility of the component. It is by default false.

## Java Swing Examples

There are two ways to create a frame:

• By creating the object of Frame class (association)
• By extending Frame class (inheritance)

We can write the code of swing inside the main(), constructor or any other method.

### Simple Java Swing Example

Let's see a simple swing example where we are creating one button and adding it on the JFrame object inside the main() method.

File: FirstSwingExample.java

1. import javax.swing.*;
2. public class FirstSwingExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame();//creating instance of JFrame
5.
6. JButton b=new JButton("click");//creating instance of JButton
7. b.setBounds(130,100,10040);//x axis, y axis, width, height
8.
10.
11. f.setSize(400,500);//400 width and 500 height
12. f.setLayout(null);//using no layout managers
13. f.setVisible(true);//making the frame visible
14. }
15. }

### Example of Swing by Association inside constructor

We can also write all the codes of creating JFrame, JButton and method call inside the java constructor.

File: Simple.java

1. import javax.swing.*;
2. public class Simple {
3. JFrame f;
4. Simple(){
5. f=new JFrame();//creating instance of JFrame
6.
7. JButton b=new JButton("click");//creating instance of JButton
8. b.setBounds(130,100,10040);
9.
11.
12. f.setSize(400,500);//400 width and 500 height
13. f.setLayout(null);//using no layout managers
14. f.setVisible(true);//making the frame visible
15. }
16.
17. public static void main(String[] args) {
18. new Simple();
19. }
20. }

The setBounds(int xaxis, int yaxis, int width, int height)is used in the above example that sets the position of the button.

### Simple example of Swing by inheritance

We can also inherit the JFrame class, so there is no need to create the instance of JFrame class explicitly.

File: Simple2.java

1. import javax.swing.*;
2. public class Simple2 extends JFrame{//inheriting JFrame
3. JFrame f;
4. Simple2(){
5. JButton b=new JButton("click");//create button
6. b.setBounds(130,100,10040);
7.
9. setSize(400,500);
10. setLayout(null);
11. setVisible(true);
12. }
13. public static void main(String[] args) {
14. new Simple2();
15. }}
What we will learn in Swing Tutorial
• JButton class
• JTextArea class
• JComboBox class
• JTable class
• JColorChooser class
• JProgressBar class
• JSlider class
• Digital Watch
• Graphics in swing
• Displaying image
• OpenDialog Box
• Puzzle Game
• Pic Puzzle Game
• Tic Tac Toe Game
• BorderLayout
• GridLayout
• FlowLayout
• CardLayout
Tuesday, 01 August 2017 06:18

### Java AWT Label

Written by

The object of Label class is a component for placing text in a container. It is used to display a single line of read only text. The text can be changed by an application but a user cannot edit it directly.

## AWT Label Class Declaration

1. public class Label extends Component implements Accessible

## Java Label Example

1. import java.awt.*;
2. class LabelExample{
3. public static void main(String args[]){
4.     Frame f= new Frame("Label Example");
5.     Label l1,l2;
6.     l1=new Label("First Label.");
7.     l1.setBounds(50,100100,30);
8.     l2=new Label("Second Label.");
9.     l2.setBounds(50,150100,30);
11.     f.setSize(400,400);
12.     f.setLayout(null);
13.     f.setVisible(true);
14. }
15. }

Output:

## Java AWT Label Example with ActionListener

1. import java.awt.*;
2. import java.awt.event.*;
3. public class LabelExample extends Frame implements ActionListener{
4.     TextField tf; Label l; Button b;
5.     LabelExample(){
6.         tf=new TextField();
7.         tf.setBounds(50,50150,20);
8.         l=new Label();
9.         l.setBounds(50,100250,20);
10.         b=new Button("Find IP");
11.         b.setBounds(50,150,60,30);
14.         setSize(400,400);
15.         setLayout(null);
16.         setVisible(true);
17.     }
18.     public void actionPerformed(ActionEvent e) {
19.         try{
20.         String host=tf.getText();
22.         l.setText("IP of "+host+" is: "+ip);
23.         }catch(Exception ex){System.out.println(ex);}
24.     }
25.     public static void main(String[] args) {
26.         new LabelExample();
27.     }
28. }

Output:

TextField: www.toshiyas.in

IP Of www.toshiyas.in is 144.18.16.18

Button : Find IP

Tuesday, 01 August 2017 06:09

### Java AWT Button

Written by

The button class is used to create a labeled button that has platform independent implementation. The application result in some action when the button is pushed.

## AWT Button Class declaration

1. public class Button extends Component implements Accessible

## Java AWT Button Example

1. import java.awt.*;
2. public class ButtonExample {
3. public static void main(String[] args) {
4.     Frame f=new Frame("Button Example");
5.     Button b=new Button("Click Here");
6.     b.setBounds(50,100,80,30);
8.     f.setSize(400,400);
9.     f.setLayout(null);
10.     f.setVisible(true);
11. }
12. }

Output:

## Java AWT Button Example with ActionListener

1. import java.awt.*;
2. import java.awt.event.*;
3. public class ButtonExample {
4. public static void main(String[] args) {
5.     Frame f=new Frame("Button Example");
6.     final TextField tf=new TextField();
7.     tf.setBounds(50,50150,20);
8.     Button b=new Button("Click Here");
9.     b.setBounds(50,100,60,30);
11.     public void actionPerformed(ActionEvent e){
12.             tf.setText("Welcome to Toshiyas IT");
13.         }
14.     });
16.     f.setSize(400,400);
17.     f.setLayout(null);
18.     f.setVisible(true);
19. }
20. }

Output:

welcome to Toshiyas IT

Tuesday, 01 August 2017 05:27

### Event and Listener (Java Event Handling)

Written by
 Changing the state of an object is known as an event. For example, click on button, dragging mouse etc. The java.awt.event package provides many event classes and Listener interfaces for event handling.

## Java Event classes and Listener interfaces

Event Classes Listener Interfaces
ActionEvent ActionListener
MouseEvent MouseListener and MouseMotionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener

## Steps to perform Event Handling

Following steps are required to perform event handling:

1. Register the component with the Listener

## Registration Methods

For registering the component with the Listener, many classes provide the registration methods. For example:

• Button
• TextField
• TextArea
• Checkbox
• Choice
• List

### Java Event Handling Code

We can put the event handling code into one of the following places:

1. Within class
2. Other class
3. Anonymous class

### Java event handling by implementing ActionListener

1. import java.awt.*;
2. import java.awt.event.*;
3. class AEvent extends Frame implements ActionListener{
4. TextField tf;
5. AEvent(){
6.
7. //create components
8. tf=new TextField();
9. tf.setBounds(60,50,170,20);
10. Button b=new Button("click me");
11. b.setBounds(100,120,80,30);
12.
13. //register listener
15.
16. //add components and set size, layout and visibility
18. setSize(300,300);
19. setLayout(null);
20. setVisible(true);
21. }
22. public void actionPerformed(ActionEvent e){
23. tf.setText("Welcome");
24. }
25. public static void main(String args[]){
26. new AEvent();
27. }
28. }

public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the above example that sets the position of the component it may be button, textfield etc.

### 2) Java event handling by outer class

1. import java.awt.*;
2. import java.awt.event.*;
3. class AEvent2 extends Frame{
4. TextField tf;
5. AEvent2(){
6. //create components
7. tf=new TextField();
8. tf.setBounds(60,50,170,20);
9. Button b=new Button("click me");
10. b.setBounds(100,120,80,30);
11. //register listener
12. Outer o=new Outer(this);
14. //add components and set size, layout and visibility
16. setSize(300,300);
17. setLayout(null);
18. setVisible(true);
19. }
20. public static void main(String args[]){
21. new AEvent2();
22. }
23. }

1. import java.awt.event.*;
2. class Outer implements ActionListener{
3. AEvent2 obj;
4. Outer(AEvent2 obj){
5. this.obj=obj;
6. }
7. public void actionPerformed(ActionEvent e){
8. obj.tf.setText("welcome");
9. }
10. }

### 3) Java event handling by anonymous class

1. import java.awt.*;
2. import java.awt.event.*;
3. class AEvent3 extends Frame{
4. TextField tf;
5. AEvent3(){
6. tf=new TextField();
7. tf.setBounds(60,50,170,20);
8. Button b=new Button("click me");
9. b.setBounds(50,120,80,30);
10.
12. public void actionPerformed(){
13. tf.setText("hello");
14. }
15. });
17. setSize(300,300);
18. setLayout(null);
19. setVisible(true);
20. }
21. public static void main(String args[]){
22. new AEvent3();
23. }
24. }

Tuesday, 01 August 2017 05:22

### Java AWT Tutorial

Written by

Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based applications in java.

Java AWT components are platform-dependent i.e. components are displayed according to the view of operating system. AWT is heavyweight i.e. its components are using the resources of OS.

The java.awt package provides classes for AWT api such as TextField, Label, TextArea, RadioButton, CheckBox, Choice, List etc.

### Java AWT Hierarchy

The hierarchy of Java AWT classes are given below.

### Container

The Container is a component in AWT that can contain another components like buttons, textfields, labels etc. The classes that extends Container class are known as container such as Frame, Dialog and Panel.

### Window

The window is the container that have no borders and menu bars. You must use frame, dialog or another window for creating a window.

### Panel

The Panel is the container that doesn't contain title bar and menu bars. It can have other components like button, textfield etc.

### Frame

The Frame is the container that contain title bar and can have menu bars. It can have other components like button, textfield etc.

### Useful Methods of Component class

Method Description
public void add(Component c) inserts a component on this component.
public void setSize(int width,int height) sets the size (width and height) of the component.
public void setLayout(LayoutManager m) defines the layout manager for the component.
public void setVisible(boolean status) changes the visibility of the component, by default false.

### Java AWT Example

To create simple awt example, you need a frame. There are two ways to create a frame in AWT.

• By extending Frame class (inheritance)
• By creating the object of Frame class (association)

## AWT Example by Inheritance

Let's see a simple example of AWT where we are inheriting Frame class. Here, we are showing Button component on the Frame.

1. import java.awt.*;
2. class First extends Frame{
3. First(){
4. Button b=new Button("click me");
5. b.setBounds(30,100,80,30);// setting button position
7. setSize(300,300);//frame size 300 width and 300 height
8. setLayout(null);//no layout manager
9. setVisible(true);//now frame will be visible, by default not visible
10. }
11. public static void main(String args[]){
12. First f=new First();
13. }}

The setBounds(int xaxis, int yaxis, int width, int height) method is used in the above example that sets the position of the awt button.

## AWT Example by Association

Let's see a simple example of AWT where we are creating instance of Frame class. Here, we are showing Button component on the Frame.

1. import java.awt.*;
2. class First2{
3. First2(){
4. Frame f=new Frame();
5. Button b=new Button("click me");
6. b.setBounds(30,50,80,30);