Java programs
[Link] of java
Sol:
public class sai { //class name shouls be file name
public static void main(String[] args) {
[Link]("Hello world");
Output:
Hello world
[Link] types
Sol:
public class sai {
public static void main(String[] args) {
byte age = 20;
short year = 2025;
int salary = 50000;
long population = 7896541230L;
float price = 99.9f;
double height = 5.9;
char grade = 'A';
boolean isPass = true;
[Link]("Age: " + age);
[Link]("Year: " + year);
[Link]("Salary: " + salary);
[Link]( "population:" +population);
[Link]("Price: " + price);
[Link]("Height: " + height);
Java programs
[Link]("Grade: " + grade);
[Link]("Passed: " + isPass);
Output:
Age: 20
Year: 2025
Salary: 50000
population:7896541230
Price: 99.9
Height: 5.9
Grade: A
Passed: true
3. type conversion and type casting:
Sol: implicit convertion:
public class sai {
public static void main(String[] args) {
int num=10;
double value=num;
[Link](value);
Output:
10.0
Explicit convertion:
public class sai {
public static void main(String[] args) {
int a=126;
double b= (double)a;
Java programs
[Link](b);
4. operators examples:
Sol:
public class sai {
public static void main(String[] args) {
int a = 10, b = 5;
[Link]("Arithmetic: " + (a + b));
[Link]("Relational: " + (a > b));
[Link]("Logical: " + ((a > b) && (a < 20)));
a += 5;
[Link]("Assignment (a += 5): " + a);
[Link]("Unary (++a): " + (++a));
[Link]("Ternary: " + ((a > b) ? "True" : "False"));
Output:
Arithmetic: 15
Relational: true
Logical: true
Assignment (a += 5): 15
Unary (++a): 16
Ternary: True
[Link] satements
Sol:
[Link] making statements:
Java programs
a) if statement
public class sai {
public static void main(String[] args) {
int x=10, y=12;
if( x+y > 20){
[Link]("x+y is greater than 20");
Output:
x+y is greater than 20
b) if-else
public class sai {
public static void main(String[] args) {
int x=10, y=11;
if (x+y >=25) {
[Link]("x+y is greter than 25");
}else{
[Link]("x+y is less than 25");
Output:
x+y is less than 25
c) if-else-if
public class sai {
public static void main(String[] args) {
int marks= 80;
if (marks>=90) {
[Link]("A grade");
}else if (marks>=75) {
Java programs
[Link]("B grade");
}else{
[Link]("C grade");
Output:
B grade
D) switch statement:
public class sai {
public static void main(String[] args) {
String fruit= "apple";
switch(fruit){
case "mango":
[Link]("king of fruits");
break;
case "apple":
[Link]("keeps doctor away");
break;
case "banana":
[Link]("energy booster");
break;
default:
[Link]("unknown fruit");
Output:
Java programs
Keeps the doctor away
2. looping statements:
a) for loop
public class sai {
public static void main(String[] args) {
for(int i=1; i<=10; i++){
[Link](i);
Output:
10
B) while loop
public class sai {
public static void main(String[] args) {
int i=1;
while (i<=10) {
[Link](i);
i++;
}
Java programs
Output:
10
c) do- while loop
public class sai {
public static void main(String[] args) {
int i=1;
do{
[Link](i);
}while(i<=10);
Output:
6
Java programs
10
6. classes and objects example:
Ans:
// Class definition
class Student {
// Data members (variables)
String name;
int age;
// Method to display student details
void display() {
[Link]("Student Name: " + name);
[Link]("Student Age: " + age);
// Main class
public class Main {
public static void main(String[] args) {
// Creating an object of Student class
Student s1 = new Student();
// Assigning values to object variables
[Link] = "Ganesh";
[Link] = 20;
// Calling method to display the details
[Link]();
Output:
Java programs
Student Name: Ganesh
Student Age: 19
[Link] with multiple classes and objects:
Sol: a)
class student{
// data members
String name;
int age;
double marks;
// method to set details
void setdetails(String n, int a, double m){
name=n;
age=a;
marks=m;
// method to display details
void display(){
[Link]("name:"+name);
[Link]("age:"+age);
[Link]("marks:"+marks);
public class sai{
public static void main(String[] args){
// creating objects
student s1= new student();
student s2=new student();
[Link]("sai",19,75.6);
[Link]();
Java programs
[Link]("ganesh",20,85.6);
[Link]();
Output:
name:sai
age:19
marks:75.6
name:ganesh
age:20
marks:85.6
b) Example with Parameters and Return Type
sol:
class Calculator {
// method with parameters and return type
int add(int a, int b) {
return a + b;
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator(); // create object
int result = [Link](10, 20); // call method
[Link]("Sum = " + result);
Output:
12
Java programs
8)method overloading (Compile-Time polymorphism)
Sol:
class calculator{
public int add(int n1, int n2, int n3){
return n1+n2+n3;
//there are same methods(add) but with differ parameters
public int add(int n1, int n2){
return n1+n2;
public double add(double n1, int n2){
return n1+n2;
public class sai{
public static void main(String[] args){
calculator obj= new calculator();
double r2=[Link](2.0,1,2);
int r1= [Link](1,21,3); //based on the [Link] values passed output will execute
[Link](r1);
[Link](r2);
Output:
25
3.0
9) Arryas:
sol:
1dimensional array:
Java programs
public class sai{
public static void main(String[] args){
int a[]=new int[5];
a[0]=10;
a[1]=20;
a[2]=30;
a[3]=40;
a[4]=50;
for(int i=0; i<5; i++)
[Link](a[i]);
Output:
10
20
20
40
50
b) 2d or multi dimensional arrays
sol:
public class sai{
public static void main(String[] args){
int a[][]=new int[3][4]; //3 rows four columns`
for(int i=0; i<3; i++) //outer for loop for 3 rows
for(int j=0; j<4; j++){ //outer loop for columns
[Link](a[i][j] + " ");
Java programs
[Link](); // for matrix shape
Output :
0000
0000
0000
10) strings:
Sol:
a)String methods example:
public class StringMethodsExample {
public static void main(String[] args) {
// Original string
String name = "Sai Ganesh";
[Link]("Original String: " + name);
[Link]("----------------------------------");
// 1. length()
[Link]("Length of string: " + [Link]());
// 2. charAt()
[Link]("Character at index 4: " + [Link](4));
// 3. toUpperCase() and toLowerCase()
[Link]("Uppercase: " + [Link]());
[Link]("Lowercase: " + [Link]());
// 4. substring()
[Link]("Substring from index 4: " + [Link](4));
Java programs
[Link]("Substring (0,3): " + [Link](0, 3));
// 5. equals() and equalsIgnoreCase()
String name2 = "sai ganesh";
[Link]("Equals (case-sensitive): " + [Link](name2));
[Link]("Equals (ignore case): " + [Link](name2));
// 6. concat()
[Link]("After concatenation: " + [Link](" is learning Java"));
// 7. replace()
[Link]("After replacing 'a' with 'o': " + [Link]('a', 'o'));
// 8. trim()
String spaced = " Sai Ganesh ";
[Link]("Before trim: [" + spaced + "]");
[Link]("After trim: [" + [Link]() + "]");
Output:
Original String: Sai Ganesh
----------------------------------
Length of string: 10
Character at index 4: G
Uppercase: SAI GANESH
Lowercase: sai ganesh
Substring from index 4: Ganesh
Substring (0,3): Sai
Equals (case-sensitive): false
Equals (ignore case): true
After concatenation: Sai Ganesh is learning Java
Java programs
After replacing 'a' with 'o': Soi Gonesh
Before trim: [ Sai Ganesh ]
After trim: [Sai Ganesh]
b)String duffer methods:
public class StringBufferDemo {
public static void main(String[] args) {
// Create a StringBuffer object with some text
StringBuffer sb = new StringBuffer("Hello");
// 1. append() → Add text at the end
[Link](" World");
[Link]("After append: " + sb); // Hello World
// 2. insert() → Insert text at a specific position
[Link](6, "Java ");
[Link]("After insert: " + sb); // Hello Java World
// 3. replace() → Replace a part of the text
[Link](6, 10, "Python");
[Link]("After replace: " + sb); // Hello Python World
// 4. delete() → Delete characters between index 5 and 12
[Link](5, 12);
[Link]("After delete: " + sb); // HelloWorld
// 5. length() → Get number of characters in the buffer
[Link]("Length: " + [Link]()); // Number of characters
// 6. capacity() → Get total capacity of buffer (default 16 + string length)
[Link]("Capacity: " + [Link]());
Java programs
Output:
After append: Hello World
After insert: Hello Java World
After replace: Hello Python World
After delete: HelloWorld
Length: 10
Capacity: 34
11)constructors
a) default constructor:
class student {
String name;
int id;
student() { //non-parameterized constructor
[Link]("default constructor");
name = "sai ganesh";
id = 71;
void display() {
[Link]("name: " + name);
[Link]("student id: " + id);
public static void main(String[] args) {
student s1 = new student();
[Link]();
Output:
Java programs
default constructor
name: sai ganesh
student id: 71
b) parameterized constructor
sol:
class Student {
int id;
String name;
// Parameterized constructor
Student(int i, String n){
id=i;
name=n;
void display(){
[Link]("id:"+id);
[Link]("name:"+name);
public static void main(String[] args) {
Student s1= new Student(101,"sai");
Student s2=new Student(71,"Ganesh");
[Link]();
[Link]();
Output:
id:101
name:sai
id:71
name:Ganesh
Java programs
c) copy constructor
sol)
class Student {
int id;
String name;
// 1. Parameterized constructor
Student(int id, String name) {
[Link] = id;
[Link] = name;
// 2. Copy constructor
Student(Student s) {
id = [Link];
name = [Link];
void display() {
[Link]("ID: " + id + ", Name: " + name);
public static void main(String[] args) {
// Create first object
Student s1 = new Student(101, "Sai");
// Create second object using copy constructor
Student s2 = new Student(s1);
// Display both
[Link]();
Java programs
[Link]();
Output:
ID: 101, Name: Sai
ID: 101, Name: Sai
d) constructor overloading
sol:
class Student {
String name;
int age;
//conatructor 1 with no parameters(default constructor)
Student(){
name="unknown";
age=0;
//constructor 2 with 1 parameters
Student(String n){
name=n;
age=0;
//constructor 3 with 2 parameters
Student(String n, int a){
name=n;
age=a;
void display(){
[Link]("name:"+name +" , Age:"+age);
}
Java programs
public class Main {
public static void main(String[] args) {
Student s1= new Student(); //calls constructor 1
Student s2= new Student("sai"); //calls constructor 2
Student s3= new Student("sai ganehs",19); //calls constructor 3
[Link]();
[Link]();
[Link]();
Output:
name:unknown , Age:0
name:sai , Age:0
name:sai ganehs , Age:19
12) this keyword:
Sol:
class Student {
String name;
int age;
Student() {
this("Unknown", 0); // Calls parameterized constructor
Student(String name, int age) {
[Link] = name; // Distinguish instance variables
[Link] = age;
Student setName(String name) {
[Link] = name; // Return current object for method chaining
Java programs
return this;
Student setAge(int age) {
[Link] = age;
return this;
void display() {
[Link]("Name: " + [Link] + ", Age: " + [Link]);
public class Main {
public static void main(String[] args) {
Student s = new Student();
[Link]("Sai").setAge(20).display();
// Output: Name: Sai, Age: 20
Output:
Name: Sai, Age: 20
13) static keyword
Sol:
class mobile {
String brand;
int price;
static String name;
public void display(){
[Link](brand + ":"+ price + ":" +name );
public static void main(String[] args) {
Java programs
mobile m1= new mobile();
mobile m2= new mobile();
[Link]="apple";
[Link]=100000;
[Link]="iqoo";
[Link]=10000;
[Link]="smart phone"; // static variable always define with class name
[Link]();
[Link]();
Output:
apple:100000:smart phone
iqoo:10000:smart phone
14) Final keyword
Sol:
class Student {
final int id = 101; // final variable
void display() {
[Link]("ID: " + id);
public class Main {
public static void main(String[] args) {
Student s = new Student();
Java programs
[Link](); // Output: ID: 101
// [Link] = 102; // Error! Cannot change final variable
15)encapsulation:
Sol:
class Student {
//private instance variables
private int age=19;
private String name="sai";
//can be accesesd throgh methods in the same class
public int getage(){
return age;
public String getname(){
return name;
public class Main {
public static void main(String[] args) {
Student obj=new Student();
// [Link]=19;
// [Link]="sai";
[Link]([Link]()); //calling methods
[Link]([Link]());
}
Java programs
Output:
Sai
19
16)super class
Sol:
class A { //super class
public A(){
[Link]("default constructor of A");
public A(int n){
[Link]("parameterized constructor of A");
class B extends A //sub class
public B()
[Link]("default constructor of B");
public B(int n){
super(5); //super used to call parameterized constructor i.e super class A
[Link]("parameterized constructor of B");
public class Main {
public static void main(String[] args) {
B obj= new B(5);
Java programs
Output:
parameterized constructor of A
parameterized constructor of B
17)inheritance:
Sol:
a)single inheritance
class Student {
String name;
String departement;
void getinfo(){
[Link]("name:"+name);
[Link]("departement:"+departement );
class Teacher extends Student{ //inherits properties from super class i.e Student class
String subjetc;
int salary;
void display(){
[Link]( "name:"+name);
[Link]("departement:"+departement );
[Link]( "subject:"+subjetc);
[Link]("salary:"+salary );
Java programs
public class Main {
public static void main(String[] args) {
Student s1= new Student();
Teacher T1=new Teacher();
[Link]="sai";
[Link]="bca";
[Link]="kavitha";
[Link]="bca";
[Link]="java";
[Link]=19000;
[Link](); //calling super class(parent class)
[Link](); //calling sub class(child class)
Output:
name:sai //parent class
departement:bca //””””
name:avitha //child class
departement:bca // “”””
subject:java //inherited from parent class
salary:19000 // “”””
b) multi-level inheritance
sol:
class Student {
Java programs
String name;
String departement;
void getinfo(){
[Link]("name:"+name);
[Link]("departement:"+departement );
class Teacher extends Student{ //inherits properties from super class i.e Student class
String subjetc;
int salary;
void display(){
[Link]( "name:"+name);
[Link]("departement:"+departement );
[Link]( "subject:"+subjetc);
[Link]("salary:"+salary );
class Jl extends Teacher {
String section;
void information(){
[Link]( "name:"+name);
[Link]("departement:"+departement );
[Link]( "subject:"+subjetc);
[Link]("salary:"+salary );
[Link]("section:"+section);
}
Java programs
public class Main {
public static void main(String[] args) {
Student s1= new Student();
Teacher T1=new Teacher();
Jl j= new Jl();
//student class
[Link]="sai";
[Link]="bca";
//Teacher class
[Link]="kavitha";
[Link]="bca";
[Link]="java";
[Link]=19000;
//Jl class
[Link]="ganesh";
[Link]="informatics";
[Link]=15000;
[Link]="all in one";
[Link]= "A section";
[Link](); //calling super class(parent class)
[Link](); //calling sub class(child class)
[Link]();
Output:
name:sai
departement:bca
name:kavitha
departement:bca
subject:java
Java programs
salary:19000
name:ganesh
departement:informatics
subject:all in one
salary:15000
section:A section
c) hierarchical inheritance
sol:
class vehicle {
void displayType(){
[Link]("This is a vehicle");
class car extends vehicle{
void getinfo(){
[Link]("this is a four wheeler vehicle");
class bike extends vehicle{
void getinfo(){
[Link]("This is a two wheeler vehice");
class Truck extends vehicle{
void getinfo(){
[Link]("This vehicle is used to carry heavy loads");
}
Java programs
public class Main {
public static void main(String[] args) {
vehicle V= new vehicle();
car C= new car();
bike B=new bike();
Truck T=new Truck();
[Link](); // child class 1
[Link]();
[Link](); // child class 2
[Link]();
[Link](); // child class 3
[Link]();
Output:
This is a vehicle
this is a four wheeler vehicle
This is a vehicle
This is a two wheeler vehice
This is a vehicle
This vehicle is used to carry heavy loads
18)method overriding:(Run-time polymorphism)
Sol:
class Vehicle {
void run() {
Java programs
[Link]("Vehicle is running");
class Bike extends Vehicle {
@Override //keyword(annotation, optional)
void run() {
[Link]("Bike is running safely");
class Car extends Vehicle {
@Override //keyword(annotation, optional)
void run() {
[Link]("Car is running smoothly");
public class Main {
public static void main(String[] args) {
Vehicle v1 = new Bike();
Vehicle v2 = new Car();
[Link](); // calls Bike's run()
[Link](); // calls Car's run()
output:
Bike is running safely
Car is running smoothly
Java programs
19)Acess modifiers(public, protected, private, default):
Sol:
class Student {
public String name = "Sai";
protected int age = 21;
int rollNumber = 71; // default access modifier
private String password = "abc123"; // private access modifier
public void showPublic() {
[Link]("Public Method: Accessible Everywhere");
protected void showProtected() {
[Link]("Protected Method: Accessible in same package and subclass");
void showDefault() {
[Link]("Default Method: Accessible only in same package");
private void showPrivate() {
[Link]("Private Method: Accessible only within this class");
void showAll() {
[Link]("\n--- Inside the Same Class ---");
[Link]("Name (public): " + name);
[Link]("Age (protected): " + age);
[Link]("Roll Number (default): " + rollNumber);
[Link]("Password (private): " + password);
showPublic();
showProtected();
showDefault();
showPrivate();
}
Java programs
class Teacher extends Student {
void display() {
[Link]("\n--- Inside Subclass (Same Package) ---");
[Link]("Name (public): " + name);
[Link]("Age (protected): " + age);
[Link]("Roll Number (default): " + rollNumber);
// [Link]("Password (private): " + password); // Not accessible
showPublic();
showProtected();
showDefault();
// showPrivate(); // Not accessible
public class AccessModifiersExample {
public static void main(String[] args) {
Student s = new Student();
Teacher t = new Teacher();
[Link](); // accessing all inside Student class
[Link](); // accessing from subclass
[Link]("\n--- Inside Main Class (Same Package) ---");
[Link]("Name (public): " + [Link]);
[Link]("Age (protected): " + [Link]);
[Link]("Roll Number (default): " + [Link]);
// [Link]("Password (private): " + [Link]); // Not accessible
[Link]();
[Link]();
[Link]();
// [Link](); // Not accessible
}
Java programs
Output:
--- Inside the Same Class ---
Name (public): Sai
Age (protected): 21
Roll Number (default): 71
Password (private): abc123
Public Method: Accessible Everywhere
Protected Method: Accessible in same package and subclass
Default Method: Accessible only in same package
Private Method: Accessible only within this class
--- Inside Subclass (Same Package) ---
Name (public): Sai
Age (protected): 21
Roll Number (default): 71
Public Method: Accessible Everywhere
Protected Method: Accessible in same package and subclass
Default Method: Accessible only in same package
--- Inside Main Class (Same Package) ---
Name (public): Sai
Age (protected): 21
Roll Number (default): 71
Public Method: Accessible Everywhere
Protected Method: Accessible in same package and subclass
Default Method: Accessible only in same package
20)Abstract class:
Sol:
abstract class Car {
public abstract void drive();
Java programs
public void Playmusic(){
[Link]("music is playing");
class WagnoR extends Car{
public void drive(){
[Link]("Driving");
public class Main {
public static void main(String[] args) {
Car c1= new WagnoR(); //we can't create a object of an abstract
//class instead we have create reference object i.e is WagnoR
[Link]();
[Link]();
Output:
Driving
music is playing
21. interface:
Sol:
interface A {
//creating variables
int type=4; //variables are static and by final default in interfaces
String Brand= "Alto";
//methods
public void car(); //in interface methods are initially public
Java programs
public void playmusic();
class B implements A
public void car(){
[Link]("the car has 4 wheels");
public void playmusic(){
[Link]("the music is playing ");
public class Main {
public static void main(String[] args) {
A obj;
obj=new B(); // we cant create object directly instead we can create like below
[Link]();
[Link]();
[Link]([Link]); //calling variable
[Link]([Link]);
Output:
the car has 4 wheels
the music is playing
Java programs
Alto
22. exception-handling:
Sol: using try, catch(with multiple catches)
public class Main {
public static void main(String[] args) {
int i=0;
int j=0;
int arr[]= new int[5]; //the arr limit is upto 4 index
String str=null;
try
j=18/i;
[Link]([Link]()); //null value passed in length nullpointer exception
[Link](arr[5]);
} // if no exception occurs it will skip try block
catch(ArithmeticException e){ //arithmetic exception
[Link]("can't divide by zero" +e);
catch(ArrayIndexOutOfBoundsException e){ //ArrayIndexOutOfBoundsException i.e we are
[Link]("stay in yur limit"+ e); //crossing [Link] indexes arr limit
catch(NullPointerException e){ //nullpointerexception exception
[Link]("no values passed" +e);
Finally{
[Link]("always executes”); //finally block always excecute either exception there or not
[Link](j);
Java programs
[Link]("bye");
Output:
can't divide by [Link]: / by zero //exception will give ouput only once
Bye
always executes
23)multi-threading:
Sol:
class Task1 extends Thread {
public void run() { //runs the thread
for(int i = 1; i <= 5; i++) {
[Link]("Task1: " + i);
class Task2 extends Thread {
public void run() { //runs the thread
for(int i = 1; i <= 5; i++) {
[Link]("Task2: " + i);
public class Main {
public static void main(String[] args) {
Task1 t1 = new Task1();
Task2 t2 = new Task2();
Java programs
[Link](); //starts the thread
[Link]();
Output:
Task1: 1
Task2: 1
Task1: 2
Task2: 2
Task1: 3
Task2: 3
b)multi threading using exception handlind(output will not enough to show)
sol
class A extends Thread
public void run(){
for(int i=1; i<=10; i++){
[Link]("hii");
try{
[Link](10);
} catch(InterruptedException e){
[Link]();
}
Java programs
class B extends Thread
public void run(){
for(int i=1; i<=10; i++){
[Link]("hii bro");
try{
[Link](10); //tells os to stop 10 milli seconds execute other thread
} catch(InterruptedException e){
[Link]();
public class Example{
public static void main(String[] args) {
A obj1=new A();
B obj2=new B();
[Link](1); //sets priority for obj1
[Link]();
[Link]();
24) Threads
a) creating with extending Thread class:
// Creating a thread by extending Thread class
class MyThread extends Thread {
public void run() {
[Link]("Thread is running using Thread class!");
Java programs
public static void main(String[] args) {
MyThread t1 = new MyThread(); // Create object
[Link](); // Start the thread
Output:
Thread is running using Thread class!
b)creating a Thread by implementing runnable interface
// Creating a thread by implementing Runnable interface
class MyRunnable implements Runnable {
public void run() {
[Link]("Thread is running using Runnable interface!");
public static void main(String[] args) {
MyRunnable obj = new MyRunnable(); // Create object
Thread t1 = new Thread(obj); // Pass to Thread
[Link](); // Start the thread
Output:
Thread is running using Runnable interface!
25) AWT buttons, labels,textfields,checkboxes
Sol:
import [Link].*; //importing AWT packages
import [Link]; //importing methods
import [Link];
Java programs
public class AWT {
AWT(){ //constructor
//creating frame
Frame frame=new Frame("firts frame");
//creating a text field
TextField textfield=new TextField("textfield");
[Link](20,120,150,30);
//creating label
Label label=new Label("this is a label");
[Link](20,90,150,30); //dimensions of label
// creating button
Button button=new Button("click me");
[Link](20,40,80,30); //settings height width and-
dimensions of buttons i.e x and y-axis
//creating a checkBox
Checkbox checkbox=new Checkbox("java");
[Link](20, 160, 80, 30);
//creating a checkBox2
Checkbox checkbox1=new Checkbox("python");
[Link](20,200,50,30);
//adding label into frame
[Link](label);
[Link]([Link] ); //setting background color;
//adding button into frame
[Link](button);
//adding textfield
Java programs
[Link](textfield);
//adding checkbox
[Link](checkbox);
[Link](checkbox1);
[Link](300,400); //setting size of a frame
[Link](null); //setting layout of a button null=default
[Link](true); //setting visibility of frame
//closing method for created frame when clicked on X
[Link](new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e){
[Link]();
});
public static void main(String[] args) {
AWT obj1= new AWT(); //object creation of constructor
Output:
Java programs
26) swings(similar program as AWT but using with swings)
Sol:
import [Link].*; // Import Swing package
import [Link].*; // For color
import [Link].*; // For window events
public class SwingProgram {
SwingProgram() { // Constructor
// Creating frame
JFrame frame = new JFrame("First Frame");
// Creating a text field
JTextField textfield = new JTextField("textfield");
[Link](20, 120, 150, 30);
// Creating label
JLabel label = new JLabel("this is a label");
[Link](20, 90, 150, 30);
[Link](true); // needed to show background color
[Link]([Link]);
// Creating button
JButton button = new JButton("click me");
[Link](20, 40, 80, 30);
// Creating checkboxes
JCheckBox checkbox = new JCheckBox("java");
[Link](20, 160, 80, 30);
JCheckBox checkbox1 = new JCheckBox("python");
Java programs
[Link](20, 200, 80, 30);
// Adding components to frame
[Link](label);
[Link](button);
[Link](textfield);
[Link](checkbox);
[Link](checkbox1);
// Frame settings
[Link](300, 400);
[Link](null);
[Link](true);
// Closing the frame when clicked on "X"
[Link](JFrame.DISPOSE_ON_CLOSE);
public static void main(String[] args) {
new SwingProgram(); // object creation calls constructor
Output:
Java programs
27) event-handling:
Sol:
import [Link].*;
import [Link].*; // For ActionListener
class AEvent extends Frame implements ActionListener {
TextField tf;
AEvent() {
tf = new TextField();
[Link](60, 50, 170, 20);
Button b = new Button("Click me");
[Link](100, 120, 80, 30);
[Link](this); // Register listener
add(b);
add(tf);
setSize(300, 300);
setLayout(null);
setVisible(true);
// Implementing abstract method
public void actionPerformed(ActionEvent e) {
[Link]("Welcome");
public static void main(String[] args) {
Java programs
new AEvent();
Output:
28) AWT Applets example:
Sol:
import [Link];
import [Link].*;
// <applet code="[Link]" width="300" height="200"></applet>
public class MyApplet extends Applet {
String message = "";
// 1. Initialization
public void init() {
message = "Applet Initialized!";
// 2. Start
public void start() {
message = "Applet Started!";
// 3. Paint (Display Output)
public void paint(Graphics g) {
[Link](message, 100, 100);
}
Java programs
// 4. Stop
public void stop() {
message = "Applet Stopped!";
// 5. Destroy
public void destroy() {
message = "Applet Destroyed!";
How to Execute an Applet
Compile the Applet
Open terminal or VS Code terminal:
javac [Link]
Create an HTML File
Create a file named [Link]:
<html>
<body>
<applet code="[Link]" width="300" height="200">
</applet>
</body>
</html>
Run the Applet
Use the applet viewer:
appletviewer [Link]
Output: You’ll see a small window displaying “Applet Started!”
Java programs