0% found this document useful (0 votes)
2 views78 pages

Java Record

This document is a certificate template for B. Tech II year II Semester students at J.N.T.U.H College of Engineering, certifying completion of the Java Programming Lab for the academic year 2023-2024. It includes a list of experiments conducted over several weeks, covering various Java programming concepts such as class creation, arrays, exception handling, and GUI development. Additionally, it provides sample code and outputs for some of the programs developed during the lab sessions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views78 pages

Java Record

This document is a certificate template for B. Tech II year II Semester students at J.N.T.U.H College of Engineering, certifying completion of the Java Programming Lab for the academic year 2023-2024. It includes a list of experiments conducted over several weeks, covering various Java programming concepts such as class creation, arrays, exception handling, and GUI development. Additionally, it provides sample code and outputs for some of the programs developed during the lab sessions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 78

J.N.T.U.

H COLLEGE OF ENGINEERING
KUKATPALLY, HYDERABAD – 500 085

CERTIFICATE
This is to certify that __________________of B. TECH II year II Semester
bearing Hall-ticket number ___________________ has fulfilled his/her Java
Programming Lab record for the academic year 2023-2024.

Signature of the Head of the Department Signature of the staff member

Date of Examination

Internal Examiner External Examiner

1
J.N.T.U UNIVERSITY COLLEGE OF ENGINEERING HYDERABAD
(Autonomous)
Name: Roll Number:

Class: Year: Laboratory:

List of Experiments

Sno. Name of the Program Pg No.

1 WEEK 1
1. Java program to create class and print Student Details

2. Java program to print elements of lower triangle

3. Java program to calculate salary of an employee

4. Java program to display sum of each rows and sum of


columns of matrix

2. WEEK 2
1. Java program to print the area of a rectangle by creating a
class named 'Area' having two methods. First method
named as 'setDim' takes length and breadth of rectangle as
parameters and the second method named as 'getArea'
returns the area of the rectangle. Length and breadth of
rectangle are entered through keyboard.

2. Write a Java program to create a class called "Employee"


with a name, job title, and salary attributes, and methods to
calculate and update salary.

3. Write a Java program to create a class called "Person" with


a name and age attribute. Create two instances of the
"Person" class, set their attributes using the constructor,
and print their name and age.

4. Write a Java program to create a class called "Airplane"


with a flight number, destination, and departure time
attributes, and methods to check flight status and delay.

2
3. WEEK 3
1. Write a Java program to test if an array contains a specific
value.

2. Write a Java program to remove a specific element from an


array and move remaining elements up

3. Write a Java program to insert an element (specific


position) into an array

4. Write a Java program to find common elements between


two integer arrays

5. Write a Java program to remove duplicate elements from a


given array and return the updated array length. Sample
array: [20, 20, 30, 40, 50, 50, 50] After removing the
duplicate elements the program should return 4 as the new
length of the array.

6. Write a Java recursive method to calculate the factorial of a


given positive integer.

7. Write a java program to illustrate the concept


(a) static variable
(b) static method
(c) static block
(d) static inner class

4. WEEK 4
1. Write a Java program to create an abstract class Shape with
abstract methods calculateArea() and calculatePerimeter().
Create subclasses Circle and Triangle that extend the Shape
class and implement the respective methods to calculate the
area and perimeter of each shape.

2. Write a Java program to create an abstract class


BankAccount with abstract methods deposit() and
withdraw(). Create subclasses: SavingsAccount and
CurrentAccount that extend the BankAccount class and
implement the respective methods to handle deposits and
withdrawals for each account type.

3. Write a Java program to create an abstract class Employee


with abstract methods calculateSalary() and displayInfo().
Create subclasses Manager and Programmer that extend the

3
Employee class and implement the respective methods to
calculate salary and display information for each role.

4. Write a Java program to create a base class Animal with


methods eat() and sound(). Create three subclasses: Lion,
Tiger, and Panther. Override the eat() method in each
subclass to describe what each animal eats. In addition,
override the sound() method to make a specific sound for
each animal.

5. Write JAVA program to illustrate all the uses of final


keyword(before variable, before method, before class)

WEEK 5
5.
1. Write a Java program to create a method that takes an
integer as a parameter and throws an exception if the
number is odd.

2. Write a Java program that reads a list of integers from the


user and throws an exception if any numbers are duplicates.
(use user defined exception Duplicate)

3. Write a Java program to create a method that takes a string


as input and throws an exception if the string does not
contain vowels (use user defined exception NoVowels)

4. Write a JAVA program to change the properties of main


thread and print on screen along with it has to print primary
numbers between 1 to 50

5. Write a JAVA program to print 1 to 10 with 1000msec


duration by one thread and another thread has to print 10 to
1 with 500msec duration

6. Write a JAVA program to print odd numbers by one thread


and vowels by another thread

7. Write a Java program to create and start multiple threads


that increment a shared counter variable concurrently.

8. Write a Java program to create a producer-consumer


scenario using the wait() and notify() methods for thread
synchronization.

6. WEEK 6

4
1. Write a program in Java such that it demonstrates the event
actions associated with the keyboard. The program should
demonstrate various keyboard events such as key typed
event, key pressed event and key released event by using
alphabets, digits and non aplha numeric keys.

2. Write a program in Java such that it demonstrates the event


actions associated with a mouse. The program should
demonstrate various mouse events such as mouse clicked
event, mouse pressed event, mouse released event, mouse
entered event and mouse exited event.

3. Write a program in Java such that it creates a menu bar


with menu items and the label of the menu item is
displayed in the frame.

4. Write a program in Java such that it creates a choice menu


consisting of 5 languages (C, C++, Java, Python, R), and
the selected language from the choice menu is displayed in
the frame.

5. Write a program in Java such that it creates two input fields


for two numbers, and contains four buttons for the
operations – Addition, Subtraction, Multiplication and
Division. When the user clicks on any button after entering
the value in the two input field, the respective operation is
performed and the value is displayed in an output text field.

6. Write a program in JAVA that it creates three scroll bars


represents Red, Green, Blue color. If value of scroll bars
changes applet foreground color must change accordingly

7. Write a program in JAVA that it creates username and


password screen and give functionality accordingly

8. write a program in Java such that it creates a frame


containing a smiling face using Graphics class.

9. Write a program in Java such that it creates a applet


containing a cylinder using Graphics class.

7. WEEK 7
1. Write a Java program that creates a GUI with a text field
and three checkboxes using Swing. The text field should
display a sample text. The checkboxes should be labeled
"Monospaced", "Bold", and "Italic". When a checkbox is

5
selected or deselected, the font of the text in the text field
should update accordingly.

2. Dynamic Image Display with JComboBox

3. Write a Java Program to demonstrate Scroll Plane

4. Write a program to demonstrate JTabbed Plane

5. Write a program to demonstrate JTable

6. Write a program to demonstrate JTextField

7. Write a program to demonstrate JRadio

8. Write a program to demonstrate JTree

9. Write a program to demonstrate JCheck

6
WEEK 1
PROGRAM 1
Write a Java Program to create class and print Student Details.

CODE
import java.util.*;

public class StudentDetails{

String name;

String roll;

double phn;

String branch;

float cgpa;

StudentDetails(String name, String rollno, double phn, String branch,float cgpa){

this.name = name;

this.roll = rollno;

this.phn = phn;

this.branch = branch;

this.cgpa = cgpa;

void print(){

System.out.println("Name :" + name);

System.out.println("Roll :" + roll);

System.out.println("Branch" + branch);

System.out.println("Phone :" + phn);

System.out.println("cgpa :" + cgpa);

7
public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Name:");

String name = sc.next();

System.out.println("Roll Number :");

String roll = sc.next();

System.out.println("Branch :");

String branch = sc.next();

System.out.println("Phone number :");

double phn = sc.nextDouble();

System.out.println("CGPA :");

float cgpa = sc.nextFloat();

StudentDetails s = new StudentDetails(name, roll, phn,branch, cgpa);

s.print();

OUTPUT:

PROGRAM 2
Develop a Java Program to display lower triangle elements of the matrix

8
CODE
import java.util.*;
public class A{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number :");
int n = sc.nextInt();
int [][]arr = new int[n][n];
System.out.println("Enter the elements :");
for(int i = 0; i <n ; i++){
for(int j = 0; j < n; j++){
arr[i][j] = sc.nextInt();
}
}
System.out.println("The pattern :");
for(int i = 0; i <n ; i++){
for(int j = 0; j <= i; j++){
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
OUTPUT

PROGRAM 3
Write a Java Program to calculate the row sum and column sum

9
CODE
import java.util.*;

public class SumOf {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of rows :");
int row = sc.nextInt();
System.out.println("Enter the number of columns :");
int col = sc.nextInt();

int [][]arr = new int [row][col];


int i, j;
for(i = 0 ; i < row ; i++){
for(j = 0; j < col ; j++){
arr[i][j] = sc.nextInt();
}
}
int rowsum ;
for(i = 0; i < row; i++){
rowsum = 0;
for(j = 0; j < col; j++){
rowsum += arr[i][j];
}
System.out.println("Rowsum : " + rowsum);
}
int colsum = 0;
for(i = 0; i < col; i++){
colsum = 0;
for(j = 0; j < row; j++){
colsum += arr[j][i];
}
System.out.println("Colsum " + colsum);
}
}
}

OUTPUT

10
PROGRAM 4
Develop a Java Program to create a calculator

CODE
import java.util.Scanner;

public class Calculator {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Choose an operation:");
System.out.println("1. Addition (+)");
System.out.println("2. Subtraction (-)");
System.out.println("3. Multiplication (*)");
System.out.println("4. Division (/)");

System.out.print("Enter your choice (1/2/3/4): ");


int choice = scanner.nextInt();

System.out.print("Enter the first number: ");


double num1 = scanner.nextDouble();

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


double num2 = scanner.nextDouble();

double result = 0;

switch (choice) {
case 1:
result = num1 + num2;

11
break;
case 2:
result = num1 - num2;
break;
case 3:
result = num1 * num2;
break;
case 4:
if (num2 != 0) {
result = num1 / num2;
} else {
System.out.println("Error! Division by zero is not allowed.");
return; // Exit the program
}
break;
default:
System.out.println("Error! Invalid choice.");
return; // Exit the program
}

System.out.println("Result: " + result);


}
}

OUTPUT

12
PROGRAM 5
Develop Java Program to calculate basic salary

CODE
import java.util.Scanner;

public class SalaryCalculator {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.println("Enter the basic salary:");


double basicSalary = scanner.nextDouble();

double houseRentAllowance = 0.30 * basicSalary;


double dearnessAllowance = 0.20 * basicSalary;
double totalSalary = basicSalary + houseRentAllowance + dearnessAllowance;
System.out.println("Basic Salary: $" + basicSalary);
System.out.println("House Rent Allowance: $" + houseRentAllowance);
System.out.println("Dearness Allowance: $" + dearnessAllowance);
System.out.println("Total Salary: $" + totalSalary);
}
}

OUTPUT

13
WEEK 2
PROGRAM 1
Write a program to print the area of a rectangle by creating a class named 'Area'
having two methods. First method named as 'setDim' takes length and breadth of
rectangle as parameters and the second method named as 'getArea' returns the area
of the rectangle. Length and breadth of rectangle are entered through keyboard.
CODE
package weektwo;
import java.util.*;
public class Area {
double length;
double breadth;

public void setDim(double l, double b){


this.length = l;
this.breadth = b;
}
public double getArea(){
return this.length * this.breadth;
}
public static void main(String[] args) {
Area a = new Area();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the length :");
double l = sc.nextDouble();
System.out.println("Enter the breadth :");
double b = sc.nextDouble();
a.setDim(l, b);
double ans = a.getArea();
System.out.println("The area is " + ans);
}
} OUTPUT

14
PROGRAM 2
Write a Java program to create a class called "Employee" with a name, job title,
and salary attributes, and methods to calculate and update salary.

CODE
package weektwo;

public class Employee {


String name, job_title;
double basic, da, hra, gross, tax, net;
Employee(){

}
Employee(String n, String j){
name = n;
job_title = j;
}
public void calAndUp(double base){
basic = base;
hra = basic * 0.10;
da = 0.08 * basic;
gross = basic + hra + da;
tax = 0.005 * gross;
net = gross - tax;
System.out.println("Name: " + name);
System.out.println("Job: " + job_title);
System.out.println("Basic Salary: " + basic);
System.out.println("HRA: " + hra);
System.out.println("DA: " + da);
System.out.println("Gross: " + gross);
System.out.println("Tax: " + tax);
System.out.println("Net Salary: " + net);
}
public static void main(String[] args) {
Employee Kavya = new Employee("Kavya", "IAS");
Kavya.calAndUp(100000);
}
}

15
OUTPUT

PROGRAM 3
Write a Java program to create a class called "Person" with a name and age
attribute. Create two instances of the "Person" class, set their attributes using
the constructor, and print their name and age.

CODE
package weektwo;
import java.util.*;
public class Person {
int age;
String name;
Person(){

}
Person(int age, String name){
this.age = age;
this.name = name;
}
void printDetails(){
System.out.println("Hi " + name + " you're " + age + "years old.");
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("First Person :");
System.out.println("Name :");
String name = sc.next();
System.out.println("Age");
int age = sc.nextInt();

16
Person p = new Person(age, name);
p.printDetails();
System.out.println("Second Person :");
System.out.println("Name :");
name = sc.next();
System.out.println("Age");
age = sc.nextInt();

Person p1 = new Person(age, name);


p1.printDetails();

}
}
OUTPUT

PROGRAM 4
Write a Java program to create a class called "Airplane" with a flight number,
destination, and departure time attributes, and methods to check flight
status and delay

CODE
package weektwo;

import java.time.LocalTime;
import java.util.*;

public class AirPlane{


String flightNumber;

17
String destination;
LocalTime scheduledDeparture;
int delay;

AirPlane(String f, String d, LocalTime sd){


flightNumber = f;
destination = d;
scheduledDeparture = sd;
}
AirPlane(){

}
public void delays(int minutes){
this.delay = minutes;
this.scheduledDeparture = this.scheduledDeparture.plusMinutes(minutes);

}
public void checkStatus(){
if(delay == 0){
System.out.println("Flight " + flightNumber +" is on time!!");

}else
System.out.println("Flight " + flightNumber + " is delayed by " +delay +"
minutes");
}
public static void main(String[] args) {
AirPlane f1 = new AirPlane("ABC", "XYZ", LocalTime.of(10, 20));
AirPlane f2 = new AirPlane("DEF", "HZY", LocalTime.of(10, 10));
System.out.println("Flight status :");
f1.checkStatus();;
f2.checkStatus();
f1.delays(10);
f2.delays(90);
System.out.println("Current :");
f1.checkStatus();
f2.checkStatus();
}
}

OUTPUT

18
WEEK 3
PROGRAM 1
Write a Java program to test if an array contains a specific value.

CODE

package weekthree;

import java.util.Arrays;

public class SpecificValue {


public static void main(String[] args) {
int []arr = {1, 4, 6, 4, 2, 45, 86, 2};
int key = 2;
Arrays.sort(arr);
int left = 0;
int right = arr.length - 1;
while(left <= right){
int mid = (left + right) / 2;
if(arr[mid] == key){
System.out.println("Found at " + (mid));
break;
}else if(arr[mid] < key){
left = mid + 1;
}else {
right = mid - 1;
}
}

}
}
OUTPUT

19
PROGRAM 2
Write a Java program to remove a specific element from an array and move remaining
elements up

CODE
package weekthree;

public class Remove {


public static void main(String[] args) {
int[] arr = {2, 3, 5, 6, 7, 8, 9};
int i, j = -1;
int key = 9;
int n = arr.length;
for (i = 0; i < n; i++) {
if (arr[i] == key) {
j = i;
break;
}
}
if (j != -1) {
for (i = j; i < n - 1; i++) {
arr[i] = arr[i + 1];
}
n--;
} else {
System.out.println("not found");
}
for (i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}
OUTPUT

20
PROGRAM 3

Write a Java program to insert an element (specific position) into an array

CODE

package weekthree;

public class Insert {


public static void main(String[] args) {
int []arr = {1, 2, 3, 4, 5, 6};
int pos = 3;
int data = 10;
int i, j;
int n = arr.length;
int []newarr = new int [n + 1]; j = 0;
for(i = 0; i < n + 1; i++){
if(pos == i){
newarr[i] = data;
}else{
newarr[i] = arr[j];
j++;
}
}
System.out.println("Output");
for(i = 0; i < n + 1; i++){
System.out.print(newarr[i] + " ");
}
}
}

OUTPUT

21
PROGRAM 4

Write a Java program to find common elements between two integer arrays

CODE
package weekthree;

public class Common {


public static void main(String[] args) {
int []arr1 = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int []arr2 = {4, 3, 5, 77, 55, 2, 55, 0};

int m = arr1.length;
int n = arr2.length;

int i, j;

System.out.print("Common Elements: ");


for(i = 0; i < m ; i++){
for(j = 0; j < n; j++){
if(arr1[i] == arr2[j]){
System.out.print(arr1[i] + " ");
}
}
}
}
}
OUTPUT

22
PROGRAM 5
Write a Java program to remove duplicate elements from a given array and
return the updated array length. Sample array: [20, 20, 30, 40, 50, 50, 50] After
removing the duplicate elements the program should return 4 as the new length
of the array.

CODE
package weekthree;

import java.util.Arrays;

public class Duplicates {


public static void main(String[] args) {
int []arr = {20, 20, 30, 40, 50, 50, 50};
Arrays.sort(arr);
int slow = 0;
int fast = 1;
int n = arr.length;
int count = 1;
for(fast = 1; fast < n ; fast++){
if(arr[slow] != arr[fast]){
count++;
slow++;
arr[slow] = arr[fast];
}
}
System.out.println("Length :" + count);
for(int i : arr){
System.out.print(i + " ");
}
}
}

OUTPUT

23
PROGRAM 6
Write a Java recursive method to calculate the factorial of a given positive
integer.
CODE
package weekthree;

public class Fact {


public static int fact(int n){
if(n == 1) return 1;

return n * fact(n - 1);


}
public static void main(String[] args) {
int f = fact(10);
System.out.println(f);
}

}
OUTPUT

PROGRAM 7
Write a java program to illustrate the concept

(a) static variable


(b) static method
(c) static block
(d) static inner class
CODE

package weekthree;

public class StaticExam {


static int a = 10;

public static void print(){


24
System.out.println("Inside print");
}
static{
System.out.println("Inside ststic block");
}
static class s{
void display(){
System.out.println("Inside static class");
}
}
public static void main(String[] args) {
System.out.println("Static variable :" + a);
print();

s so = new s();

so.display();
}
}

OUTPUT

WEEK 4
PROGRAM 1
Write a Java program to create an abstract class Shape with abstract methods
calculateArea() and calculatePerimeter(). Create subclasses Circle and Triangle that
extend the Shape class and implement the respective methods to calculate the area
and perimeter of each shape.

CODE

package weekfour;

25
import java.util.*;

public abstract class Shape{


abstract double calArea();
abstract double calPeri();
}
class Circle extends Shape{
double radius;
Circle (double r){
radius = r;
}
double calArea(){
return Math.PI * radius *radius;
}
double calPeri(){
return Math.PI * 2 * radius;
}
}
class Triangle extends Shape{
double a, b, c;
Triangle(double q, double w, double u){
a = q; b = w; c = u;
}
double calArea(){
double s = (a + b + c) / 2;
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
}
double calPeri(){
return a + b + c;
}
}
class Main{
public static void main(String[] args) {
Shape t = new Triangle(10, 11, 2);
System.out.println("Triangle :");
System.out.println("Area: "+ t.calArea());
System.out.println("Perimetre: " + t.calPeri());

Shape c = new Circle(10);


System.out.println("Cirle :");
System.out.println("Area: " + c.calArea());

26
System.out.println("Perimetre: " + c.calPeri());
}
}
OUTPUT

PROG
RAM 2
Write a Java program to create an abstract class BankAccount with abstract methods
deposit() and withdraw(). Create subclasses: SavingsAccount and CurrentAccount that
extend the BankAccount class and implement the respective methods to handle deposits
and withdrawals for each account type.

CODE
package weekfour;

public abstract class BankAccount {


protected double balance;

public BankAccount(double balance) {


this.balance = balance;
}

public abstract void deposit(double amount);

public abstract void withdraw(double amount);

public double getBalance() {


return balance;
}
}

class SavingsAccount extends BankAccount {


public SavingsAccount(double balance) {
super(balance);

27
}

@Override
public void deposit(double amount) {
balance += amount;
System.out.println(“Deposited: “ + amount);
}

@Override
public void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
System.out.println(“Withdrawn: “ + amount);
} else {
System.out.println(“Insufficient balance”);
}
}
}

class CurrentAccount extends BankAccount {


public CurrentAccount(double balance) {
super(balance);
}

@Override
public void deposit(double amount) {
balance += amount;
System.out.println(“Deposited: “ + amount);
}

@Override
public void withdraw(double amount) {
balance -= amount;
System.out.println(“Withdrawn: “ + amount);
}
}

class Main {
public static void main(String[] args) {
// Creating a SavingsAccount object
BankAccount savingsAccount = new SavingsAccount(1000);

28
System.out.println(“Savings Account Balance: “ + savingsAccount.getBalance());
savingsAccount.deposit(500);
System.out.println(“Savings Account Balance: “ + savingsAccount.getBalance());
savingsAccount.withdraw(200);
System.out.println(“Savings Account Balance: “ + savingsAccount.getBalance());

// Creating a CurrentAccount object


BankAccount currentAccount = new CurrentAccount(2000);
System.out.println(“Current Account Balance: “ + currentAccount.getBalance());
currentAccount.deposit(1000);
System.out.println(“Current Account Balance: “ + currentAccount.getBalance());
currentAccount.withdraw(1500);
System.out.println(“Current Account Balance: “ + currentAccount.getBalance());
}
}

OUTPUT

PROGRAM 4
Write a Java program to create an abstract class Employee with abstract methods
calculateSalary() and displayInfo(). Create subclasses Manager and Programmer that
extend the Employee class and implement the respective methods to calculate salary
and display information for each role.

CODE

package weekfour;

public abstract class Employee {

29
protected String name;
protected int employeeId;

public Employee(String name, int employeeId) {


this.name = name;
this.employeeId = employeeId;
}

public abstract double calculateSalary();

public abstract void displayInfo();


}

class Manager extends Employee {


private double baseSalary;
private double bonus;

public Manager(String name, int employeeId, double baseSalary, double bonus) {


super(name, employeeId);
this.baseSalary = baseSalary;
this.bonus = bonus;
}

@Override
public double calculateSalary() {
return baseSalary + bonus;
}

@Override
public void displayInfo() {
System.out.println("Manager Name: " + name);
System.out.println("Employee ID: " + employeeId);
System.out.println("Base Salary: " + baseSalary);
System.out.println("Bonus: " + bonus);
}
}

class Programmer extends Employee {


private double monthlySalary;

public Programmer(String name, int employeeId, double monthlySalary) {

30
super(name, employeeId);
this.monthlySalary = monthlySalary;
}

@Override
public double calculateSalary() {
return monthlySalary;
}

@Override
public void displayInfo() {
System.out.println("Programmer Name: " + name);
System.out.println("Employee ID: " + employeeId);
System.out.println("Monthly Salary: " + monthlySalary);
}
}
class Main {
public static void main(String[] args) {
// Creating a Manager object
Employee manager = new Manager("John Doe", 1001, 50000, 10000);
manager.displayInfo();
System.out.println("Manager's Salary: " + manager.calculateSalary());

System.out.println();

// Creating a Programmer object


Employee programmer = new Programmer("Jane Smith", 1002, 6000);
programmer.displayInfo();
System.out.println("Programmer's Salary: " + programmer.calculateSalary());
}
}

OUTPUT

31
PROGRAM 5

Write a Java program to create a base class Animal with methods eat() and sound().
Create three subclasses: Lion, Tiger, and Panther. Override the eat() method in each
subclass to describe what each animal eats. In addition, override the sound() method
to make a specific sound for each animal.

CODE
package weekfour;

// Base class Animal


public class Animal {
public void eat() {
System.out.println("Animal eats food.");
}

public void sound() {


System.out.println("Animal makes a sound.");
}
}

// Subclass Lion
class Lion extends Animal {
public void eat() {
System.out.println("Lion eats meat.");
}
public void sound() {
System.out.println("Lion roars.");
}
}

32
// Subclass Tiger
class Tiger extends Animal {
public void eat() {
System.out.println("Tiger eats meat and sometimes other animals.");
}
public void sound() {
System.out.println("Tiger growls.");
}
}

// Subclass Panther
class Panther extends Animal {
public void eat() {
System.out.println("Panther eats meat and small mammals.");
}
public void sound() {
System.out.println("Panther makes a low snarl.");
}
}

// Main class to test the Animal subclasses


class Main {
public static void main(String[] args) {
Animal lion = new Lion();
lion.eat();
lion.sound();

Animal tiger = new Tiger();


tiger.eat();
tiger.sound();

Animal panther = new Panther();


panther.eat();
panther.sound();
}
}

33
OUTPUT

PROG
RAM 6
Write JAVA program to illustrate all the uses of final keyword (before variable,
before method, before class)
CODE
package weekfour;

public class Final {


final int CONSTANT = 1000;

final void method(){


System.out.println("Inside final method!!");
}
static{
System.out.println("In static");
}
}
final class A{
void print(){
System.out.println("Hello World");
}
}

class C extends Final{


// void method(){

// }--> CANNOT OVERIDE FINAL METHOD


}
// class B extends A{

// } This is an error
class Main{
public static void main(String[] args) {
Final f = new Final();

34
//f.CONSTANT = 10;--> error
System.out.println(f.CONSTANT);
f.method();
A a = new A();
a.print();

}
}

OUTPUT

WEEK 5
PROGRAM 1
Write a Java program to create a method th at takes an integer as a parameter
and throws an exception if the number is odd.

CODE
package week5;

class OddException extends Exception{};


public class p1 {
public static void isOdd(int num) throws OddException{
if(num % 2 != 0) throw new OddException();
}
public static void main(String[] args) {
try{
isOdd(101);
}
catch(OddException e){
System.out.println("The number is Odd");
}
finally{
System.out.println("The end of the program");
}
}

35
}
OUTPUT

PROGRAM 2
Write a Java program that reads a list of integers from the user and throws an
exception if any numbers are duplicates. (use user defined exception Duplicate)
CODE

package week5;
import java.util.*;

class Duplicate extends Exception{}


public class p2 {
public static void method(int a, ArrayList<Integer> list) throws Duplicate{
if(list.contains(a)) throw new Duplicate();
}
public static void main(String[] args) {
try{
Scanner sc = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<>();
System.out.println("Enter the number of elements :");
int n = sc.nextInt();

for(int i = 0; i < n ; i++){


System.out.println("Enter the element :");
int a = sc.nextInt();
method(a, list);
list.add(a);
}
}
catch(Duplicate e){
System.out.println("This is a duplicate element");
}
}
}

OUTPUT

36
PRO
GRAM 3
Write a Java program to create a method that takes a string as input and throws
an exception if the string does not contain vowels (use user defined exception
NoVowels)
CODE

package week5;

import java.util.Scanner;

class NoVowels extends Exception{}


public class p3 {
public static boolean isVowel(Character c) {
return (c == 'a'|| c == 'e' || c == 'i' || c == 'o' || c == 'u');
}
public static void containsVowel(String s) throws NoVowels{
boolean containsVowel = false;
for(int i = 0 ; i < s.length(); i++){
if (isVowel(s.charAt(i))) {
return;
}
}
if(!containsVowel) throw new NoVowels();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the string :");
String s = sc.next();

37
try{
containsVowel(s);
}
catch(NoVowels e){
System.out.println("The String doesnot contains vowels");
}
}
}

OUTPUT

PROGRAM 4
Write a JAVA program to change the properties of main thread and print on
screen along with it has to print primary numbers between 1 to 50
CODE
package week5;

public class p4 extends Thread{


public void run(){
boolean isCom = false;
System.out.println("The prime numbers are :");
for(int i = 1 ; i <= 50 ; i++){
isCom = false;
for(int j = 2 ; j < i; j++){
if(i % j == 0){
isCom = true;
break;
}
}
if(!isCom){
System.out.print(i + " ");
}
}
}
public static void main(String[] args) {
p4 t1 = new p4();

38
System.out.println("Before :");
t1.setName("First Thread");
System.out.println(t1);
System.out.println("After :");
t1.setName("Second Thread");
t1.setPriority(10);
System.out.println(t1);
t1.start();
}

}
OUTPUT

PROGRAM 5
Write a JAVA program to print 1 to 10 with 1000msec duration by one thread
and another thread has to print 10 to 1 with 500msec duration
CODE
package week5;

public class p5 extends Thread{


public static void main(String[] args) {
TenToOne t1 = new TenToOne();
OneToTen t2 = new OneToTen();

t1.start();
t2.start();
}
}
class TenToOne extends Thread{
public void run(){
for(int i = 10 ; i >= 1; i--){
System.out.print(i + " ");

39
try{
Thread.sleep(500);
}catch(Exception e){System.out.println(e);};
}
}
}
class OneToTen extends Thread{
public void run(){
for(int i = 1 ; i <= 10 ; i++){
System.out.print(i + " ");
try{
Thread.sleep(1000);
}catch(Exception e){System.out.println(e);};
}

}
}
OUTPUT

PROGRAM 6
Write a JAVA program to print odd numbers by one thread and vowels by
another thread
CODE
package week5;

public class p6 {
public static void main(String[] args) {
OddNumber t1 = new OddNumber();
Vowel t2 = new Vowel();
t1.start();
t2.start();
}
}
class OddNumber extends Thread{
public void run(){
//System.out.println("Odd Numbers are :");

40
for(int i = 1 ; i <= 9 ; i += 2){
System.out.print(i + " ");
}
}
}
class Vowel extends Thread{
public void run(){
// System.out.println("The vowels are :");
char []arr = {'A', 'E', 'I', 'O', 'U'};
for(char ch : arr){
System.out.print(ch + " ");
}
}
}
OUTPUT

PROGRAM 7
Write a Java program to create and start multiple threads that increment a
shared counter variable concurrently.
CODE
package week5;

public class p7{


public static void main(String[] args) {

Counter counter = new Counter();


int numberThread = 3;

IncrementThread []threads = new IncrementThread[numberThread];


for(int i = 0; i < numberThread ; i++){
threads[i] = new IncrementThread(counter);
threads[i].start();
}
//Wait for threads to finish
for(int i = 0 ; i < numberThread; i++){
try{
threads[i].join();

41
}
catch(Exception e){
System.out.println(e);
}
}
System.out.println("Final counter value :" + counter.getCount());

}
}

class Counter{
private int count = 0;
public synchronized void increment(){
count++;
}
public int getCount(){
return count;
}
}

class IncrementThread extends Thread{


Counter counter;
IncrementThread(Counter counter){
this.counter = counter;
}
public void run(){
for(int i = 0; i < 1000; i++){
counter.increment();
}
}
}
OUTPUT

PROGRAM 8
Write a Java program to create a producer-consumer scenario using the wait()
and notify() methods for thread synchronization.

42
CODE

package week5;

public class p8 {
public static void main(String[] args) {
Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
}
}

class Q {
private int n;
private boolean valueSet = false;

synchronized int get() {


while (!valueSet) {
try {
wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
}
System.out.println("Got: " + n);
valueSet = false;
notify();
return n;
}

synchronized void put(int n) {


while (valueSet) {
try {
wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
}
this.n = n;

43
valueSet = true;
System.out.println("Put: " + n);
notify();
}
}

class Producer implements Runnable {


Q q;

Producer(Q q) {
this.q = q;
new Thread(this, "Producer").start();
}

public void run() {


int i = 0;
while (true) {
q.put(i++);
}
}
}

class Consumer implements Runnable {


Q q;

Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
}

public void run() {


while (true) {
q.get();
}
}
}

OUTPUT

44
WEEK 6
PROGRAM 1
Write a program in Java such that it demonstrates the event actions associated
with the keyboard. The program should demonstrate various keyboard events
such as key typed event, key pressed event and key released event by using
alphabets, digits and non aplha numeric keys.

CODE
package week6;

import java.awt.*;
import java.awt.event.*;
public class P1 extends Frame implements KeyListener{
Label l;
TextArea area;
P1(){
l = new Label();
l.setBounds(20, 50, 100, 20);
area = new TextArea();
area.setBounds(20, 80, 300, 300);
area.addKeyListener(this);
add(l);
add(area);
setSize(400, 400);
setLayout(null);
setVisible(true);
}
public void keyPressed(KeyEvent e){
l.setText("Key Pressed!!");
}
public void keyTyped(KeyEvent e){
l.setText("Key Typed");
}

45
public void keyReleased(KeyEvent e){
l.setText("Key Released");
}
public static void main(String[] args) {
new P1();
}
}

OUTPUT

PROGRAM 2
Write a program in Java such that it demonstrates the event actions associated
with a mouse. The program should demonstrate various mouse events such as
mouse clicked event, mouse pressed event, mouse released event, mouse
entered event and mouse exited event.
CODE
package week6;
import java.awt.*;
import java.awt.event.*;

public class P2 extends Frame implements MouseListener{


Label label;
P2(){
label = new Label();
label.setBounds(20, 50, 100, 20);
addMouseListener(this);

46
add(label);
setSize(400, 400);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e){
label.setText("Mouse is Clicked");
}
public void mouseEntered(MouseEvent e){
label.setText("Mouse has entered");
}
public void mouseExited(MouseEvent e){
label.setText("Mouse has exited");
}
public void mousePressed(MouseEvent e){
label.setText("Mouse is pressed");
}
public void mouseReleased(MouseEvent e){
label.setText("Mouse is released");
}
public static void main(String[] args) {
new P2();
}
}
OUTPUT

PROGRAM 3
Write a program in Java such that it creates a menu bar with menu items and the
the label of the menu item is displayed in the frame.

47
CODE
package week6;

import java.awt.*;
import java.awt.event.*;
public class P3 implements ActionListener{
Label label;
P3(){
Frame f = new Frame("Menu");

label = new Label(); // Initialize the label


label.setBounds(50, 200, 300, 30); // Set the bounds for the label
f.add(label); // Add the label to the frame

MenuBar mb = new MenuBar();


Menu menu = new Menu("Main Menu");
Menu submenu = new Menu("Sub Menu");

MenuItem i1=new MenuItem("Item 1");


MenuItem i2=new MenuItem("Item 2");
MenuItem i3=new MenuItem("Item 3");
MenuItem i4=new MenuItem("Item 4");
MenuItem i5=new MenuItem("Item 5");

i1.addActionListener(this);
i2.addActionListener(this);
i3.addActionListener(this);
i4.addActionListener(this);
i5.addActionListener(this);

menu.add(i1);
menu.add(i2);
menu.add(i3);
submenu.add(i4);
submenu.add(i5);
menu.add(submenu);
mb.add(menu);

f.setMenuBar(mb);
f.setSize(400, 400);
f.setLayout(null);

48
f.setVisible(true);

f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
f.dispose();
}
});
}
public void actionPerformed(ActionEvent e) {
label.setText("Selected: " + e.getActionCommand());
}

public static void main(String[] args) {


new P3();
}
}
OUTPUT

PROGRAM 4
Write a program in Java such that it creates a choice menu consisting of 5
languages (C, C++, Java, Python, R), and the selected language from the choice
menu is displayed in the frame.

49
CODE
package week6;

import java.awt.*;
import java.awt.event.*;

public class P4 implements ActionListener{


Label l;
Choice c;
P4(){
Frame f = new Frame();
l = new Label();

l.setAlignment(l.CENTER);
l.setSize(400, 100);

Button b = new Button("Show");

b.setBounds(200, 100, 50, 20);

c = new Choice();

c.setBounds(100, 100, 75, 75);

c.add("C");
c.add("C++");
c.add("Java");
c.add("Python");
c.add("R");

f.setSize(400, 400);
f.add(c);
f.add(b);
f.add(l);
f.setLayout(null);
f.setVisible(true);

b.addActionListener(this);
}
public void actionPerformed(ActionEvent e){

50
String data = "Programming language Selected: "+
c.getItem(c.getSelectedIndex());
l.setText(data);
}
public static void main(String[] args) {
new P4();
}
}
OUTPUT

PROGRAM 5
Write a program in Java such that it creates two input fields for two numbers, and
contains four buttons for the operations – Addition, Subtraction, Multiplication and
Division. When the user clicks on any button after entering the value in the two input
field, the respective operation is performed and the value is displayed in an output
text field.
CODE
package week6;

import java.awt.event.*;
import java.awt.*;

public class P5 implements ActionListener{


TextField tf1, tf2, tf3;
Button b1, b2, b3, b4;

51
P5(){
Frame f = new Frame();
tf1 = new TextField();
tf1.setBounds(50, 50, 150, 20);
tf2 = new TextField();
tf2.setBounds(50, 100, 150, 20);
tf3 = new TextField();
tf3.setBounds(50, 150, 150, 20);
tf3.setEditable(false);

b1 = new Button("+");
b1.setBounds(50, 200, 50, 50);
b2 = new Button("-");
b2.setBounds(105, 200, 50, 50);
b3 = new Button("*");
b3.setBounds(50, 255, 50, 50);
b4 = new Button("/");
b4.setBounds(105, 255, 50, 50);

Label l1 = new Label("Enter the first number :");


l1.setBounds(50, 25, 200, 20);
Label l2 = new Label("Enter the second number");
l2.setBounds(50, 78, 200, 20);
Label l3 = new Label("The result :");
l3.setBounds(50, 128, 200, 20);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
f.add(l1);
f.add(tf1);
f.add(l2);
f.add(tf2);
f.add(l3);
f.add(tf3);
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.setSize(400,400);
f.setLayout(null);

52
f.setVisible(true);
}

public void actionPerformed(ActionEvent e){


String s1 = tf1.getText();
String s2 = tf2.getText();
int a = Integer.parseInt(s1);
int b = Integer.parseInt(s2);

int c = 0;

if(e.getSource() == b1) c = a + b;
else if(e.getSource() == b2) c = a - b;
else if(e.getSource() == b3) c = a * b;
else c = a / b;
String result = String.valueOf(c);
tf3.setText(result);
}
public static void main(String[] args) {
new P5();
}
}
OUTPUT

PROGRAM 6

53
Write a program in JAVA that it creates three scroll bars represents Red, Green, Blue
color. If value of scroll bars changes applet foreground color must change
accordingly

CODE
package week6;

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class P6 extends Applet implements AdjustmentListener {


Scrollbar rs;
Scrollbar gs;
Scrollbar bs;

int red = 0;
int green = 0;
int blue = 0;

public void init() {


setLayout(new GridLayout(4, 2));

rs = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 0, 256);


gs = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 0, 256);
bs = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 0, 256);

add(new Label("Red"));
add(rs);

add(new Label("Green"));
add(gs);

add(new Label("Blue"));
add(bs);

rs.addAdjustmentListener(this);
gs.addAdjustmentListener(this);
bs.addAdjustmentListener(this);
}

54
public void adjustmentValueChanged(AdjustmentEvent e) {
if (e.getSource() == rs) {
red = rs.getValue();

} else if (e.getSource() == gs) {


green = gs.getValue();

} else if (e.getSource() == bs) {


blue = bs.getValue();

}
Color newColor = new Color(red, green, blue);
setBackground(newColor);
repaint();
}

public void paint(Graphics g) {


// Display the current color values and a filled rectangle
g.setColor(Color.BLACK);
g.drawString("Current Color: R=" + red + ", G=" + green + ", B=" + blue, 10, 150);
g.setColor(new Color(red, green, blue));
g.fillRect(10, 160, 100, 100);
}
}

/*
<applet code="week6.P6" width="300" height="300"></applet>
*/

The HTML File


file:///C:/Users/sindh/OneDrive/Desktop/java1/P6applet.html
<!DOCTYPE html>
<html>
<head>
<title>Color Selector Applet</title>
</head>
<body>
<applet code="week6.P6.class" width="300" height="300"></applet>
</body>
</html>

55
OUTPUT

PROGRAM 7
Write a program in JAVA that it creates username and password screen and give
functionality accordingly
CODE
package week6;

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class P7 extends Applet implements ActionListener{


TextField usernameField, passwordField;
Button loginButton;
Label messageLabel;
public void init() {
setLayout(new FlowLayout());
Label usernameLabel = new Label("Username:");
usernameField = new TextField(20);

56
Label passwordLabel = new Label("Password:");
passwordField = new TextField(20);
passwordField.setEchoChar('*');
loginButton = new Button("Login");
messageLabel = new Label();
add(usernameLabel);
add(usernameField);
add(passwordLabel);
add(passwordField);
add(loginButton);
add(messageLabel);
loginButton.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
String username = usernameField.getText();
String password = passwordField.getText();

if (username.equals("admin") && password.equals("password")) {


messageLabel.setText("Login successful!");
} else {
messageLabel.setText("Invalid username or password.");
}
}

}
The HTML File
file:///C:/Users/sindh/OneDrive/Desktop/java1/P7applet.html
<!DOCTYPE html>
<html>
<head>
<title>Login Applet</title>
</head>
<body>
<applet code="week6.P7" width="300" height="200">
</applet>
</body>
</html>

57
OUTPUT

PROGRAM 8
Write a program in Java such that it creates a frame containing a smiling face using
Graphics class.
CODE
package week6;

import java.awt.*;

public class P8 extends Frame{


P8(){
setTitle("Smiling Face");
setSize(300, 300);
setVisible(true);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
System.exit(0);
}

58
});
}
public void paint(Graphics g) {
g.setColor(Color.YELLOW);
g.fillOval(50, 50, 200, 200);
g.setColor(Color.BLACK);
g.fillOval(90, 100, 20, 20);
g.fillOval(190, 100, 20, 20);
g.setColor(Color.RED);
g.drawArc(100, 150, 100, 50, 0, -180);
}

public static void main(String[] args) {


new P8();
}
}
OUTPUT

PROGRAM 9
Write a program in Java such that it creates a applet containing a cylinder
using Graphics class.

CODE
package week6;

import java.applet.Applet;

import java.awt.*;

59
public class P9 extends Applet{
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.BLUE);
g.drawOval(50, 50, 150, 50);
g.drawLine(50, 75, 50, 200);
g.drawLine(200, 75, 200, 200);
g.drawOval(50, 175, 150, 50);
Graphics2D g2d = (Graphics2D) g;
float[] dashPattern = { 5, 5, 5, 5 };
g2d.setStroke(new BasicStroke(1, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER, 10, dashPattern, 0));
g2d.drawArc(50, 175, 150, 50, 0, -180);
}
}
The HTML File
file:///C:/Users/sindh/OneDrive/Desktop/java1/P7applet.html

<!DOCTYPE html>
<html>
<head>
<title>Cylinder Applet</title>
</head>
<body>
<applet code="week6.P9.class" width="300" height="300">
</applet>
</body>
</html>
OUTPUT

60
WEEK 8
PROGRAM 1
Write a Java program that creates a GUI with a text field and three checkboxes using Swing.
The text field should display a sample text. The checkboxes should be labeled
"Monospaced", "Bold", and "Italic". When a checkbox is selected or deselected, the font of
the text in the text field should update accordingly.
CODE
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JCBDemo extends JFrame implements ItemListener


{
JTextField jtf;
JCheckBox name,bold,italic;
public JCBDemo()
{
// Get content pane

61
Container c = getContentPane();
c.setLayout(new FlowLayout());

jtf=new JTextField("Swing GUI components are very popular",35);


c.add(jtf);

name = new JCheckBox("Monospaced");


c.add(name);
bold = new JCheckBox("Bold");
c.add(bold);
italic = new JCheckBox("Italic");
c.add(italic);
name.addItemListener(this);
bold.addItemListener(this);
italic.addItemListener(this);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we)
{ System.exit(0);}

});
setSize(800,400);
setVisible(true);
}

public void itemStateChanged(ItemEvent ie)


{
String fontname="";
int b=0,i=0;

if(name.isSelected())

fontname="Monospaced";

else
fontname="Serif";

if(bold.isSelected())

62
b=Font.BOLD;

else
b=Font.PLAIN;

if(italic.isSelected())

i=Font.ITALIC;

else
i=Font.PLAIN;
Font f=new Font(fontname,b+i,18);
jtf.setFont(f);
}
public static void main(String args[])
{
new JCBDemo();
}
}

OUTPUT

PROGRAM 2
Dynamic image display with JComboBox
CODE
import java.awt.*;
import java.awt.event.*;

63
import javax.swing.*;

public class JComboBoxDemo extends JFrame implements ItemListener {


JLabel jl;
ImageIcon france, germany, italy, japan;

public JComboBoxDemo() {

setTitle("JComboBox Demo");
setSize(600, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Get content pane


Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());

JComboBox<String> jc = new JComboBox<>();


jc.addItem("France");
jc.addItem("Germany");
jc.addItem("Italy");
jc.addItem("Japan");
jc.addItemListener(this);
contentPane.add(jc);

jl = new JLabel(new ImageIcon("tree.gif"));


contentPane.add(jl);

setVisible(true);
}

public void itemStateChanged(ItemEvent ie) {


if (ie.getStateChange() == ItemEvent.SELECTED) {
String s = (String) ie.getItem();
jl.setIcon(new ImageIcon(s + ".gif"));
}
}

public static void main(String[] args) {


// Create and display the form
SwingUtilities.invokeLater(new Runnable() {
public void run() {

64
new JComboBoxDemo();
}
});
}
}
OUTPUT

PROGRAM 3
Write a Java Program to demonstrate Scroll Plane
CODE
import java.awt.*;
import javax.swing.*;
/*
<applet code="JScrollPaneDemo" width=500 height=400>
</applet>
*/

public class JScrollPaneDemo extends JApplet


{
public void init()
{
// Get content pane
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());

// Add 400 buttons to a panel


JPanel jp = new JPanel();
jp.setLayout(new GridLayout(20, 20));
int b = 0;

65
for(int i = 0; i < 20; i++)
{
for(int j = 0; j < 20; j++)
{
jp.add(new JButton("Button " + b));
++b;
}
}

// Add panel to a scroll pane


int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(jp, v, h);

// Add scroll pane to the content pane


contentPane.add(jsp, BorderLayout.CENTER);
}
}

The HTML File


C:\Users\sindh\OneDrive\Desktop\java1\JScrollPaneDemo.html

<html>
<head>
<title>JScrollPaneDemo</title>
</head>
<body>
<applet code="JScrollPaneDemo.class" width="500" height="400">
</applet>
</body>
</html>

OUTPUT

66
PROGRAM 4
Write a program to demonstrate JTabbed Plane

CODE
import javax.swing.*;
/*
<applet code="JTabbedPaneDemo" width=400 height=100>
</applet>
*/
public class JTabbedPaneDemo extends JApplet
{
public void init()

67
{
JTabbedPane jtp = new JTabbedPane();
jtp.addTab("Cities", new CitiesPanel());
jtp.addTab("Colors", new ColorsPanel());
jtp.addTab("Flavors", new FlavorsPanel());
getContentPane().add(jtp);
}
}

class CitiesPanel extends JPanel


{
public CitiesPanel()
{
JButton b1 = new JButton("New York");
add(b1);
JButton b2 = new JButton("London");
add(b2);
JButton b3 = new JButton("Hong Kong");
add(b3);
JButton b4 = new JButton("Tokyo");
add(b4);
}
}

class ColorsPanel extends JPanel


{
public ColorsPanel()
{
JCheckBox cb1 = new JCheckBox("Red");
add(cb1);
JCheckBox cb2 = new JCheckBox("Green");
add(cb2);
JCheckBox cb3 = new JCheckBox("Blue");
add(cb3);
}
}

class FlavorsPanel extends JPanel


{
public FlavorsPanel()
{

68
JComboBox jcb = new JComboBox();
jcb.addItem("Vanilla");
jcb.addItem("Chocolate");
jcb.addItem("Strawberry");
add(jcb);
}
}
The HTML File
C:\Users\sindh\OneDrive\Desktop\java1\JTabbedPaneDemo.html
<html>
<head>
<title>JScrollPaneDemo</title>
</head>
<body>
<applet code="JTabbedPaneDemo.class" width="500" height="400">
</applet>
</body>
</html>

OUTPUT

69
70
PROGRAM 5
Write a program to demonstrate JTable

CODE
import java.awt.*;
import javax.swing.*;
/*
<applet code="JTableDemo" width=400 height=200>
</applet>
*/
public class JTableDemo extends JApplet
{
public void init()
{
// Get content pane
Container contentPane = getContentPane();

// Set layout manager


contentPane.setLayout(new BorderLayout());

// Initialize column headings


final String[] colHeads = { "Name", "Marks1", "Marks2" };

// Initialize data
final Object[][] data = {
{ "Sindhuja", "73", "86" },
{ "Karthika", "80", "55" },
{ "Neelima", "34", "87" },
{ "Sreeja", "73", "62" },
{ "Meghana", "92", "43" },
};

// Create the table


JTable table = new JTable(data, colHeads);

// Add table to a scroll pane


int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(table, v, h);

// Add scroll pane to the content pane

71
contentPane.add(jsp, BorderLayout.CENTER);
}
}
The HTML File
C:\Users\sindh\OneDrive\Desktop\java1\JTableDemo.html

<html>
<head>
<title></title>
</head>
<body>
<applet code="JTableDemo.class" width="500" height="400">
</applet>
</body>
</html>
OUTPUT

72
PROGRAM 6
Write a program to demonstrate JTextField

CODE
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class JTFDemo extends JFrame


{
JTextField jtf;
public JTFDemo()
{
// Get content pane
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());

// Add text field to content pane


jtf = new JTextField(15);
contentPane.add(jtf);

addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we)
{ System.exit(0);}
});
setSize(400,400);
setVisible(true);
}
public static void main(String args[])
{
new JTFDemo();
}
}
OUTPUT

73
PROGRAM 7
Write a program to demonstrate JRadio

CODE
import javax.swing.*;

public class JRadioDemo extends JFrame {


public JRadioDemo() {
JRadioButton b1 = new JRadioButton("Male");
JRadioButton b2 = new JRadioButton("Female");
JRadioButton b3 = new JRadioButton("Others");

ButtonGroup group = new ButtonGroup();


group.add(b1);
group.add(b2);
group.add(b3);

b1.setBounds(75, 50, 100, 50);


b2.setBounds(75, 100, 100, 50);
b3.setBounds(75, 150, 100, 50);

add(b1);
add(b2);

74
add(b3);

setSize(300, 300);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args) {


new JRadioDemo();
}
}
OUTPUT

PROGRAM 8
Write a program to demonstrate JTree

CODE
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
public class JTreeDemo{
JFrame f;
JTreeDemo(){
f=new JFrame();

75
DefaultMutableTreeNode style=new DefaultMutableTreeNode("Style");
DefaultMutableTreeNode color=new DefaultMutableTreeNode("color");
DefaultMutableTreeNode font=new DefaultMutableTreeNode("font");
style.add(color);
style.add(font);
DefaultMutableTreeNode red=new DefaultMutableTreeNode("red");
DefaultMutableTreeNode blue=new DefaultMutableTreeNode("blue");
DefaultMutableTreeNode black=new DefaultMutableTreeNode("black");
DefaultMutableTreeNode green=new DefaultMutableTreeNode("green");
color.add(red); color.add(blue); color.add(black); color.add(green);
JTree jt=new JTree(style);
f.add(jt);
f.setSize(400,400);
f.setVisible(true);
}
public static void main(String[] args)
{
new JTreeDemo();
}
}
OUTPUT

76
PROGRAM 9
Write a program to demonstrate JCheck

CODE
import java.awt.FlowLayout;

import javax.swing.*;
public class JCheck {
public JCheck(){
JFrame f=new JFrame();
JPanel p=new JPanel();
p.setLayout(new FlowLayout());
JCheckBox jc1=new JCheckBox("JNTUH");
JCheckBox jc2=new JCheckBox("VNR");
JCheckBox jc3=new JCheckBox("JNTUK");
JCheckBox jc4=new JCheckBox("KMIT");
p.add(jc1);
p.add(jc2);
p.add(jc3);
p.add(jc4);
f.add(p);
f.setVisible(true);
f.setContentPane(p);
f.setSize(300,300);
f.setLayout(null);
}
public static void main(String[] args) {
new JCheck();
}
}

OUTPUT

77
78

You might also like