Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
32 views

Java File

Uploaded by

getover1808
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

Java File

Uploaded by

getover1808
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 74

PROGRAM 1

Aim : WAP to print your name 20 times.


SOURCE CODE
class PrintNameTwentyTimes {
public static void main(String[] args) {
String yourName = "Sujal Goel";
for (int i = 0; i < 20; i++) {
System.out.println(yourName);
}
}
}

OUTPUT
PROGRAM 2
Aim : WAP to add two numbers.
SOURCE CODE
class AddTwoNumbers {
public static void main(String[] args) {
int number1 = 10;
int number2 = 20;
int sum = number1 + number2;
System.out.println("Sum: " + sum);
}
}

OUTPUT
PROGRAM 3
Aim : Write a program in java to find area of circle. Given that radius is 20cm.
SOURCE CODE
class SimpleAreaOfCircle {
public static void main(String[] args) {
double radius = 20.0;
double area = 3.14 * radius * radius;
System.out.println("Area of the circle with radius " + radius + " cm is: " + area + " cm square");
}
}

OUTPUT
PROGRAM 4
Aim : Write a program in Java to print all prime numbers from 1 to 50
SOURCE CODE
class PrimeNumbers {
public static void main(String[] args) {
System.out.println("Prime numbers from 1 to 50:");
for (int i = 2; i <= 50; i++) {
if (isPrime(i)) {
System.out.print(i + " ");
}
}
}
private static boolean isPrime(int number) {
If (number <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
}

OUTPUT
PROGRAM 5
Aim : Write a program to check whether a number is even or odd.
SOURCE CODE
import java.util.Scanner;
class EvenOrOdd {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
if (isEven(number)) {
System.out.println(number + " is even.");
}
else {
System.out.println(number + " is odd.");
}
scanner.close();
}
private static boolean isEven(int number) {
return number % 2 == 0;
}
}

OUTPUT
PROGRAM 6
Aim : Write a program to print a Fibonacci series upto a limit.
SOURCE CODE
import java.util.Scanner;
class FibonacciSeries {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the limit for Fibonacci series: ");
int limit = scanner.nextInt();
System.out.println("Fibonacci series up to " + limit + ":");
printFibonacciSeries(limit);
scanner.close();
}
private static void printFibonacciSeries(int limit) {
int num1 = 0, num2 = 1, nextTerm;
System.out.print(num1 + " " + num2 + " ");
for (int i = 2; i < limit; i++) {
nextTerm = num1 + num2;
System.out.print(nextTerm + " ");
num1 = num2; num2 = nextTerm;
}
}
}

OUTPUT
PROGRAM 7
Aim : Write a program to check whether a year is leap year.
SOURCE CODE
class Main {
public static void main(String[] args) {
// year to be checked
int year = 1900;
boolean leap = false;
// if the year is divided by 4
if (year % 4 == 0) {
// if the year is century
if (year % 100 == 0) {
// if year is divided by 400
// then it is a leap year
if (year % 400 == 0)
leap = true;
else
leap = false;
}
// if the year is not century
else
leap = true;
}
else
leap = false;
if (leap)
System.out.println(year + " is a leap year.");
else
System.out.println(year + " is not a leap year.");
}
}

OUTPUT
PROGRAM 8
Aim : Write a program to check if an input character is vowel or constant; if it is none, display error.
SOURCE CODE
import java.util.Scanner;
class VowelConsonantChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a character: ");
char inputChar = scanner.next().toLowerCase().charAt(0);
if (inputChar >= 'a' && inputChar <= 'z') {
if (inputChar == 'a' || inputChar == 'e' || inputChar == 'i' || inputChar == 'o' || inputChar == 'u')
{ System.out.println(inputChar + " is a vowel.");
}
else {
System.out.println(inputChar + " is a consonant.");
}
}
else {
System.out.println("Error: Invalid input. Please enter a valid alphabet character.");
}
scanner.close();
}
}

OUTPUT
PROGRAM 9
Aim : Write a program to calculate power of a number. (without Math.pow)
SOURCE CODE
import java.util.Scanner;
class PowerCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the base: ");
double base = scanner.nextDouble();
System.out.print("Enter the exponent: ");
int exponent = scanner.nextInt();
double result = calculatePower(base, exponent);
System.out.println(base + " raised to the power of " + exponent + " is: " + result);
scanner.close();
}
private static double calculatePower(double base, int exponent) {
if (exponent < 0) {
return 1 / calculatePositivePower(base, -exponent);
}
else {
return calculatePositivePower(base, exponent);
}
}
private static double calculatePositivePower(double base, int exponent) {
double result = 1;
for (int i = 0; i < exponent; i++) {
result *= base;
}
return result;
}
}

OUTPUT
PROGRAM 10
Aim :Write a program to display grade of students.
SOURCE CODE
import java.util.Scanner;
class GradeCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the student's score: ");
int score = scanner.nextInt();
displayGrade(score);
scanner.close();
}
private static void displayGrade(int score) {
char grade;
if (score >= 90) {
grade = 'A';
} else if (score >= 80) {
grade = 'B';
} else if (score >= 70) {
grade = 'C';
} else if (score >= 60) {
grade = 'D';
} else {
grade = 'F';
}
System.out.println("The student's grade is: " + grade);
}
}

OUTPUT
PROGRAM 11
Aim : Write a program to check whether two strings are equal or not.
SOURCE CODE
import java.util.Scanner;
class StringEqualityChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first string: ");
String str1 = scanner.nextLine();
System.out.print("Enter the second string: ");
String str2 = scanner.nextLine();
if (areStringsEqual(str1, str2)) {
System.out.println("The two strings are equal.");
} else {
System.out.println("The two strings are not equal.");
}
scanner.close();
}
private static boolean areStringsEqual(String str1, String str2) {
return str1.equals(str2);
}
}

OUTPUT
PROGRAM 12
Aim : Write a program to display numbers using increment and decrement operators.
SOURCE CODE
class IncrementDecrementExample {
public static void main(String[] args) {
// Using increment operator
System.out.println("Using Increment Operator:");
int i = 5;
System.out.println("Original value of i: " + i);
// Post-increment
int postIncrement = i++;
System.out.println("After post-increment, i: " + i);
System.out.println("Value returned by post-increment: " + postIncrement);
// Reset I
i = 5;
// Pre-increment
int preIncrement = ++i;
System.out.println("After pre-increment, i: " + i);
System.out.println("Value returned by pre-increment: " + preIncrement);
// Using decrement operator
System.out.println("\nUsing Decrement Operator:");
int j = 8;
System.out.println("Original value of j: " + j);
// Post-decrement
int postDecrement = j--;
System.out.println("After post-decrement, j: " + j);
System.out.println("Value returned by post-decrement: " + postDecrement);
// Reset j
j = 8;
// Pre-decrement
int preDecrement = --j;
System.out.println("After pre-decrement, j: " + j);
System.out.println("Value returned by pre-decrement: " + preDecrement);
}
}

OUTPUT
PROGRAM 13
Aim : Write a program to find greater number out of two using ternary operator.
SOURCE CODE
import java.util.Scanner;
class GreaterNumberTernary {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter the second number: ");
int num2 = scanner.nextInt();
int greaterNumber = (num1 > num2) ? num1 : num2;
System.out.println("The greater number is: " + greaterNumber);
scanner.close();
}
}

OUTPUT
PROGRAM 14
Aim : Write a program to reverse a given number.
SOURCE CODE
import java.util.Scanner;
class ReverseNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
int reversedNumber = reverseNumber(number);
System.out.println("Reversed number: " + reversedNumber);
scanner.close();
}
private static int reverseNumber(int num) {
int reversedNum = 0;
while (num != 0) {
int digit = num % 10;
reversedNum = reversedNum * 10 + digit;
num /= 10;
}
return reversedNum;
}
}

OUTPUT
PROGRAM 15
Aim : Write a program to show method overloading.

SOURCE CODE

class A{
public void method1()
{
System.out.println("normal function");
}
public void method1(int a)
{
System.out.println("overloaded function");
}
}

class Main {
public static void main(String[] args){
A obj2 = new A();
obj2.method1();
obj2.method1(1);
}
}

OUTPUT
PROGRAM 16
Aim : Write a program to show method overriding.

SOURCE CODE

class Animal {
void makeSound()
{
System.out.println("Some generic sound");
}
}
class Dog extends Animal {
void makeSound()
{
System.out.println("Bark! Bark!");
}
}
class Cat extends Animal {
void makeSound()
{
System.out.println("Meow!");
}
}
class Main {
public static void main(String[] args) {
Animal genericAnimal = new Animal();
Dog myDog = new Dog();
Cat myCat = new Cat();
genericAnimal.makeSound();
myDog.makeSound();
myCat.makeSound();
}
}

OUTPUT
PROGRAM 17
Aim : Write a program to show single level inheritance.

SOURCE CODE

class Vehicle {
void start()
{
System.out.println("Vehicle started");
}
void stop()
{
System.out.println("Vehicle stopped");
}
}
class Car extends Vehicle {
void drive()
{
System.out.println("Car is moving");
}
}
class Main {
public static void main(String[] args) {
Car myCar = new Car();
myCar.start();
myCar.drive();
myCar.stop();
}
}

OUTPUT
PROGRAM 18
Aim : Write a program to show multi-level inheritance.

SOURCE CODE

class Animal {
void eat()
{
System.out.println("Animal is eating");
}
}
class Mammal extends Animal {
void breathe()
{
System.out.println("Mammal is breathing");
}
}
class Dog extends Mammal {
void bark()
{
System.out.println("Dog is barking");
}
}
class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.eat();
myDog.breathe();
myDog.bark();
}
}

OUTPUT
PROGRAM 19
Aim : Write a program to show hierarchical inheritance.

SOURCE CODE

class Animal {
void eat()
{
System.out.println("Animal is eating");
}
}
class Cat extends Animal {
void meow()
{
System.out.println("Cat is meowing");
}
}
class Dog extends Animal {
void bark()
{
System.out.println("Dog is barking");
}
}
class Main {
public static void main(String[] args) {
Cat myCat = new Cat();
Dog myDog = new Dog();
myCat.eat();
myCat.meow();
myDog.eat();
myDog.bark();
}
}

OUTPUT
PROGRAM 20
Aim : Write a program to show hybrid inheritance.

SOURCE CODE

class Animal {
void eat()
{
System.out.println("Animal is eating");
}
}
class Mammal extends Animal {
void breathe()
{
System.out.println("Mammal is breathing");
}
}
class Bird extends Animal {
void fly()
{
System.out.println("Bird is flying");
}
}
class Bat extends Mammal {
void fly()
{
System.out.println("Bat is flying");
}
}
class Main {
public static void main(String[] args) {
Bat myBat = new Bat();
myBat.eat();
myBat.breathe();
myBat.fly();
}
}

OUTPUT
PROGRAM 21
Aim : WAP to show concept of multiple inheritance through implementation of interfaces in a class.

SOURCE CODE

interface Interface1
{
void method1();
}
interface Interface2
{
void method2();
}
class MyClass implements Interface1, Interface2 {
public void method1()
{
System.out.println("Implemented method1 from Interface1");
}
public void method2()
{
System.out.println("Implemented method2 from Interface2");
}
public void additionalMethod()
{
System.out.println("This is an additional method in MyClass");
}
}
class MultipleInheritanceExample {
public static void main(String[] args) {
MyClass myObject = new MyClass();
myObject.method1();
myObject.method2();
myObject.additionalMethod();
}
}

OUTPUT
PROGRAM 22

Aim : Write a program to show concept of multiple inheritance through implementation of interfaces in
another interface that then gets extended in a class.

SOURCE CODE

interface Interface1
{
void method1();
}
interface Interface2
{
void method2();
}
interface MultipleInheritanceInterface extends Interface1, Interface2
{
void additionalMethod();
}
class MyClass implements MultipleInheritanceInterface {
public void method1()
{
System.out.println("Implemented method1 from Interface1");
}
public void method2()
{
System.out.println("Implemented method2 from Interface2");
}
public void additionalMethod()
{
System.out.println("Implemented additionalMethod from MultipleInheritanceInterface");
}
}
class MultipleInheritanceExample {
public static void main(String[] args) {
MyClass myObject = new MyClass();
myObject.method1();
myObject.method2();
myObject.additionalMethod();
}
}

OUTPUT
PROGRAM 23
Aim : Write a program with given interfaces MotorBike and Cycle, then implement in child class
TwoWheeler and display distance & speed.

SOURCE CODE

interface MotorBike
{
int speed = 50;
void totalTime();
}
interface Cycle
{
int distance = 150;
public void speed();
}
class TwoWheeler implements MotorBike, Cycle {
int totalTime;
int avgSpeed;
public void totalTime()
{
totalTime = distance/speed;
System.out.println("Total Time taken: " + totalTime + "seconds");
}
public void speed()
{
avgSpeed = distance / totalTime;
System.out.println("Average Speed maintained: " + avgSpeed + "m/sec");
}
public static void main(String args[]) {
TwoWheeler t1 = new TwoWheeler();
t1.totalTime();
t1.speed();
}
}

OUTPUT
PROGRAM 24

Aim : Write a program in Java to use final variables.

SOURCE CODE

class FinalVariableDemo {
public static void main(String[] args) {

// Primitive final variable


final int MAX_VALUE = 100;
System.out.println("Initial value of MAX_VALUE: " + MAX_VALUE);

// Attempting to change MAX_VALUE will result in a compiler error


MAX_VALUE = 200;

// Final reference variable


final StringBuilder name = new StringBuilder("John");
System.out.println("Initial name: " + name);

// You cannot change the reference, but you can modify the object's state
name.append(" Doe");
System.out.println("Modified name: " + name);

// Attempting to assign a new object to name will result in an error


name = new StringBuilder("Jane");
}
}

OUTPUT
PROGRAM 25

Aim : Write a program in Java to use final methods.

SOURCE CODE

class BaseClass {
final void display()
{
System.out.println("This is a final method in the base class.");
}
}
class SubClass extends BaseClass {

// Attempting to override display() will result in a compiler error


void display()
{
System.out.println("Overridden display method in the subclass.");
}
void anotherMethod()
{
System.out.println("Calling the final method from a subclass method:");
display();
}
}
class FinalMethodDemo {
public static void main(String[] args) {
SubClass subClass = new SubClass();
subClass.anotherMethod();
}
}

OUTPUT
PROGRAM 26

Aim : Write a program in Java to use final classes.

SOURCE CODE

// Final class
final class FinalClassExample
{
// Final variable in a final class
final int constantValue = 10;

// Final method in a final class


final void displayInfo()
{
System.out.println("The constant value is: " + constantValue);
}
}

// Attempting to extend a final class will result in a compilation error


class SubClass extends FinalClassExample {}
class Main
{
public static void main(String[] args)
{
FinalClassExample example = new FinalClassExample();
example.displayInfo();
}
}

OUTPUT
PROGRAM 27

Aim : WAP to input and print various 1-D arrays.

SOURCE CODE

import java.util.Arrays;
import java.util.Scanner;
class ArrayInputOutput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of the integer array: ");
int sizeInt = scanner.nextInt();
int[] intArray = new int[sizeInt];
System.out.println("Enter the elements of the integer array:");
for (int i = 0; i < sizeInt; i++) {
intArray[i] = scanner.nextInt();
}
System.out.println("Integer array: " + Arrays.toString(intArray));

System.out.print("Enter the size of the double array: ");


int sizeDouble = scanner.nextInt();
double[] doubleArray = new double[sizeDouble];
System.out.println("Enter the elements of the double array:");
for (int i = 0; i < sizeDouble; i++) {
doubleArray[i] = scanner.nextDouble();
}
System.out.println("Double array: " + Arrays.toString(doubleArray));

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


int numStrings = scanner.nextInt();
String[] stringArray = new String[numStrings];
scanner.nextLine(); // Consume the newline character
System.out.println("Enter the strings:");
for (int i = 0; i < numStrings; i++) {
stringArray[i] = scanner.nextLine();
}
System.out.println("String array: " + Arrays.toString(stringArray));
}
}

OUTPUT
PROGRAM 28
Aim : WAP to multiply two 2-D arrays.

SOURCE CODE
import java.util.Scanner;
class MatrixMultiplicationExample {
public static void main(String args[]) {
int row1, col1, row2, col2;
Scanner s = new Scanner(System.in);
System.out.print("Enter number of rows in first matrix: ");
row1 = s.nextInt();
System.out.print("Enter number of columns in first matrix: ");
col1 = s.nextInt();
System.out.print("Enter number of rows in second matrix: ");
row2 = s.nextInt();
System.out.print("Enter number of columns in second matrix: ");
col2 = s.nextInt();
// Requirement check for matrix multiplication
if (col1 != row2) {
System.out.println("Matrix multiplication is not possible");
return;
}
int a[][] = new int[row1][col1];
int b[][] = new int[row2][col2];
int c[][] = new int[row1][col2];
// Input the values of matrices
System.out.println("\nEnter values for matrix A : ");
for (int i = 0; i < row1; i++) {
for (int j = 0; j < col1; j++) a[i][j] = s.nextInt();
}
System.out.println("\nEnter values for matrix B : ");
for (int i = 0; i < row2; i++) {
for (int j = 0; j < col2; j++) b[i][j] = s.nextInt();
}
System.out.println("\nMatrix multiplication is : ");
for (int i = 0; i < row1; i++) {
for (int j = 0; j < col2; j++) {
// Initialize the element C(i,j) with zero
c[i][j] = 0;
// Dot product calculation
for (int k = 0; k < col1; k++) {
c[i][j] += a[i][k] * b[k][j];
}
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
}
OUTPUT
PROGRAM 29

Aim : WAP to pass array as parameter.

SOURCE CODE

class ArrayParameterDemo {
public static void printArray(int[] arr) {
System.out.print("Array elements: ");
for (int element : arr) {
System.out.print(element + " ");
}
System.out.println();
}

public static void main(String[] args) {


int[] myArray = {10, 20, 30, 40};

// Pass the array to the printArray method


printArray(myArray);

// Modify an element within the method (this will affect the original array)
myArray[1] = 50;

// Print the array again to see the changes


printArray(myArray);
}
}

OUTPUT
PROGRAM 30

Aim : WAP to create method that returns array.

SOURCE CODE

import java.util.Arrays;
class ArrayReturnDemo
{
public static int[] createAndReturnArray()
{
int[] myArray = new int[5];
for (int i = 0; i < myArray.length; i++)
{
myArray[i] = i * 10;
}
return myArray;
}

public static void main(String[] args)


{
int[] returnedArray = createAndReturnArray();
System.out.println("Returned array: " + Arrays.toString(returnedArray));
}
}

OUTPUT
PROGRAM 31

Aim : WAP based on Class String and call various inbuilt methods present in String class.

SOURCE CODE

import java.util.Arrays;
class StringMethodsDemo {
public static void main(String[] args) {
String myString = "Hello, World!";

// Character-based methods
System.out.println("Character at index 4: " + myString.charAt(4));
System.out.println("Index of 'o': " + myString.indexOf('o'));
System.out.println("Last index of 'o': " + myString.lastIndexOf('o'));

// Substring methods
System.out.println("Substring from index 7: " + myString.substring(7));
System.out.println("Substring from index 7 to 12: " + myString.substring(7, 12));

// Modification methods
System.out.println("Uppercase: " + myString.toUpperCase());
System.out.println("Lowercase: " + myString.toLowerCase());
System.out.println("Trimmed: " + myString.trim());
System.out.println("Replaced 'World' with 'Java': " + myString.replace("World", "Java"));

// Informational methods
System.out.println("Length: " + myString.length());
System.out.println("Starts with 'Hello': " + myString.startsWith("Hello"));
System.out.println("Ends with '!': " + myString.endsWith("!"));
System.out.println("Contains 'World': " + myString.contains("World"));
System.out.println("Is empty: " + myString.isEmpty());

// Aditional Methods
System.out.println("Concatenated with ' Java': " + myString.concat(" Java"));
System.out.println("Compared to 'Hello': " + myString.compareTo("Hello"));
System.out.println("Split into words: " + Arrays.toString(myString.split(" ")));
}
}

OUTPUT
PROGRAM 32

Aim : WAP based on Class StringBuilder and call various inbuilt methods present in StringBuilder class.

SOURCE CODE

class StringBuilderDemo {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello");

// Appending methods
sb.append(", World!"); // Append a string
sb.append(42); // Append an integer
sb.append(true); // Append a boolean
System.out.println("Appended string: " + sb);

// Insertion methods
sb.insert(7, "Java "); // Insert at a specific index
System.out.println("Inserted string: " + sb);

// Deletion methods
sb.deleteCharAt(7); // Delete a character at an index
sb.delete(7, 12); // Delete a substring
System.out.println("Deleted string: " + sb);

// Modification methods
sb.reverse(); // Reverse the string
sb.setCharAt(0, 'J'); // Replace a character
System.out.println("Modified string: " + sb);

// Informational methods
System.out.println("Length: " + sb.length());
System.out.println("Capacity: " + sb.capacity());
System.out.println("Character at index 4: " + sb.charAt(4));
System.out.println("Substring from index 7: " + sb.substring(7));
}
}

OUTPUT
PROGRAM 33

Aim : WAP based on Class StringBuffer and call various inbuilt methods present in StringBuffer class.

SOURCE CODE

class StringBufferDemo {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");

// Appending methods
sb.append(", World!"); // Append a string
sb.append(42); // Append an integer
sb.append(true); // Append a boolean
System.out.println("Appended string: " + sb);

// Insertion methods
sb.insert(7, "Java "); // Insert at a specific index
System.out.println("Inserted string: " + sb);

// Deletion methods
sb.deleteCharAt(7); // Delete a character at an index
sb.delete(7, 12); // Delete a substring
System.out.println("Deleted string: " + sb);

// Modification methods
sb.reverse(); // Reverse the string
sb.setCharAt(0, 'J'); // Replace a character
System.out.println("Modified string: " + sb);

// Informational methods
System.out.println("Length: " + sb.length());
System.out.println("Capacity: " + sb.capacity());
System.out.println("Character at index 4: " + sb.charAt(4));
System.out.println("Substring from index 7: " + sb.substring(7));
}
}

OUTPUT
PROGRAM 34

Aim : WAP to create ArrayList, also add, remove, change and clear the elements of ArrayList.

SOURCE CODE

import java.util.ArrayList;
class ArrayListExample {
public static void main(String[] args) {

// Create an ArrayList of strings


ArrayList<String> names = new ArrayList<>();

// Add elements to the ArrayList


names.add("John");
names.add("Alice");
names.add("Bob");
System.out.println("Initial list: " + names);

// Remove an element by index


names.remove(1);
// Removes "Alice"
System.out.println("List after removing: " + names);

// Change an element by index


names.set(0, "David");
// Changes "John" to "David"
System.out.println("List after changing: " + names);

// Clear the entire ArrayList


names.clear();
System.out.println("List after clearing: " + names);
}
}

OUTPUT
PROGRAM 35

Aim : Write a program to show ArithmeticException.

SOURCE CODE

class ArithmeticExceptionShowcase {
public static void main(String[] args) {

// 1. Division by zero
int num1 = 10;
int num2 = 0;
try {
int result = num1 / num2;
System.out.println("Result: " + result);
}
catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
System.out.println(e.getMessage());
}

// 2. Integer overflow
try {
int maxInt = Integer.MAX_VALUE;
int result = maxInt + 1;
System.out.println("Result: " + result);
}
catch (ArithmeticException E) {
System.out.println("Error: Integer overflow occurred.");
System.out.println(E.getMessage());
}
System.out.println("Program execution continued...");
}
}

OUTPUT
PROGRAM 36

Aim : Write a program to show NumberFormatException.

SOURCE CODE

class NumberFormatExceptionShowcase {
public static void main(String[] args) {
// 1. Attempting to parse non-numeric characters
String inputString = "abc 123";
try {
int number = Integer.parseInt(inputString);
System.out.println("Converted number: " + number);
} catch (NumberFormatException e) {
System.out.println("Error: Input string \"" + inputString + "\" contains non-numeric
characters."); System.out.println("Only the numeric part (\"123\") can be parsed as an integer.");
}

// 2. Parsing a string with leading/trailing whitespaces


String inputString2 = " 1234 ";
try {
int number = Integer.parseInt(inputString2);
System.out.println("Converted number: " + number);
} catch (NumberFormatException e) {
System.out.println("Error: Input string \"" + inputString2 + "\" contains leading/trailing
whitespaces."); System.out.println("Remove whitespaces before parsing.");
}

// 3. Parsing a empty string


String inputString3 = null;
try {
int number = Integer.parseInt(inputString3);
System.out.println("Converted number: " + number);
} catch (NumberFormatException e) {
System.out.println("Error: Input string cannot be null or empty.");
System.out.println("Handle null/empty checks before parsing.");
}
System.out.println("Program execution continued...");
}
}

OUTPUT
PROGRAM 37

Aim : Write a program to show ArrayIndexOutOfBoundsException.

SOURCE CODE

class ArrayIndexOutOfBoundsExceptionExample {
public static void main(String[] args) {

// Create an array with 3 elements


int[] numbers = {1, 2, 3};

// Try to access element at index 3 (out of bounds)


try {
int invalidElement = numbers[3];
System.out.println("Element at index 3: " + invalidElement);
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Array index out of bounds!");
System.out.println("Message: " + e.getMessage());
}

// Another way to trigger the exception (negative index)


try {
int invalidElement2 = numbers[-1];
System.out.println("Element at index -1: " + invalidElement2);
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Array index out of bounds!");
System.out.println("Message: " + e.getMessage());
}
System.out.println("Program execution continued...");
}
}

OUTPUT
PROGRAM 38

Aim : Write a program to show finally block.

SOURCE CODE

class FinallyBlockAllCases {
public static void main(String[] args) {
// Case a: No exception
try { int result = divide(10, 2);
System.out.println("Result (no exception): " + result);
} finally {
System.out.println("`finally` block executed (always)");
closeConnection(); // Resource cleanup, even if no exception
}
// Case b: Exception handled
try { int result = divide(10, 0);
System.out.println("Result (handled exception): " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero");
} finally {
System.out.println("`finally` block executed (always)");
closeConnection(); // Resource cleanup after handling exception
}
// Case c: Unhandled exception
try { int result = accessInvalidArrayElement();
System.out.println("Result (unhandled exception): " + result);
} finally {
System.out.println("`finally` block executed (always)");
// Attempt to close connection even if exception isn't handled
try {
closeConnection();
// Might throw another exception if resources are in an inconsistent state
} catch (Exception e) {
System.out.println("Error closing connection after unhandled exception: "
+ e.getMessage());
}
}
}
private static int divide(int a, int b)
{ return a / b; }
private static int accessInvalidArrayElement() {
int[] numbers = {1, 2, 3};
return numbers[5];
}
private static void closeConnection() {
// Simulate resource closing (replace with actual code)
System.out.println("Closing connection...");
}
}

OUTPUT
PROGRAM 39

Aim : Write a program to show multiple catch blocks.

SOURCE CODE

class MultiCatchBlockExample {
public static void main(String[] args) {
try
{
// Creating an array of six integer elements.
int arr[] = new int[6];
arr[3] = 20/0; // Exception occurred.
System.out.println("I am in try block");
}

catch(ArithmeticException ae)
{
System.out.println("A number cannot be divided by zero, Illegal operation in java");
}

catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Accessing array element outside of specified limit");
}

catch(Exception e)
{
System.out.println(e.getMessage());
}
System.out.println("I am out of try-catch block");
}
}

OUTPUT
PROGRAM 40

Aim : Write a program to show usage of throw keyword.

SOURCE CODE

class ThrowExample
{
static void fun()
{
try
{
throw new NullPointerException("demo");
}
catch (NullPointerException e)
{
System.out.println("Caught inside fun().");
throw e;
// rethrowing the exception
}
}
public static void main(String args[])
{
try
{
fun();
}
catch (NullPointerException e)
{
System.out.println("Caught in main.");
}
}
}

OUTPUT
PROGRAM 41

Aim : Write a program to show nested try blocks.

SOURCE CODE

class NestedTryBlock{
public static void main(String args[]){
//outer try block
try{
//inner try block 1
try{
System.out.println("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e) {
System.out.println(e);
}
//inner try block 2
try{
int a[]=new int[5];
//assigning the value out of array bounds
a[5]=4;
}
//catch block of inner try block 2
catch(ArrayIndexOutOfBoundsException e) {
System.out.println(e);
}
System.out.println("other statement");
}
//catch block of outer try block
catch(Exception e) {
System.out.println("handled the exception (outer catch)");
}
System.out.println("normal flow..");
}
}

OUTPUT
PROGRAM 42

Aim : Write a program to show usage of throws keyword.

SOURCE CODE

class ThrowsExample
{
static void checkAge(int age) throws ArithmeticException
{
if (age < 18)
{
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}

else
{
System.out.println("Access granted - You are old enough!");
}
}

public static void main(String[] args)


{
checkAge(15);
// Set age to 15 (which is below 18...)
}
}

OUTPUT
PROGRAM 43

Aim : Write a program to show runtime polymorphism/upcasting.

SOURCE CODE

class Animal {
public void makeSound() {
System.out.println("Generic animal sound");
}
}

class Dog extends Animal {


public void makeSound() {
System.out.println("Woof!");
}
}

class Cat extends Animal {


public void makeSound() {
System.out.println("Meow!");
}
}

class RuntimePolymorphism {
public static void main(String[] args) {
// Animal reference can hold objects of its subclasses
Animal animal1 = new Dog();
Animal animal2 = new Cat();

// Runtime polymorphism - actual object's behavior determines the output


animal1.makeSound();
animal2.makeSound();
System.out.println("Program execution completed.");
}
}

OUTPUT
PROGRAM 44

Aim : Write a program to create custom exception.

SOURCE CODE

class MyException extends Exception


{
public MyException(String s)
{
// Call constructor of parent Exception
super(s);
}
}
class Main
{
public static void main(String args[])
{
try
{
// Throw an object of user defined exception
throw new MyException("Exception Handled");
}
catch (MyException ex)
{
System.out.println("Caught");
// Print the message from MyException object
System.out.println(ex.getMessage());
}
}
}

OUTPUT
PROGRAM 45

Aim : Write a program to show usage of lambda expression.

SOURCE CODE

interface MyInterface
{
// abstract method
String reverse(String n);
}

class Main
{
public static void main( String[] args )
{
// declare a reference to MyInterface
// assign a lambda expression to the reference
MyInterface ref = (str) -> {
String result = "";
for (int i = str.length()-1; i >= 0 ; i--)
result += str.charAt(i);
return result;
};
// call the method of the interface
System.out.println("Lambda reversed = " + ref.reverse("Lambda"));
}
}

OUTPUT
PROGRAM 46

Aim : Write a program to create your own package. Also import it in other package to show its usage.

SOURCE CODE

package one;

public class A
{
public void sayHello()
{
System.out.println("Hello from one.A!");
}
}

import one.A;

// Import the A class from one

public class Main


{
public static void main(String[] args)
{
A obj = new A(); // Create an instance of MyClass
obj.sayHello(); // Call the sayHello()
}
}

OUTPUT
PROGRAM 47

Aim : Write a program to use constructors in a class.

SOURCE CODE

class Bike {
String color;
int gear;
Bike() {
System.out.println("A bike is created with default values.");
color = "black";
gear = 1;
}
Bike(String bikeColor, int bikeGear) {
System.out.println("A bike is created with specified values.");
color = bikeColor;
gear = bikeGear;
}
void displayBikeInfo() {
System.out.println("Bike color: " + color);
System.out.println("Bike gear: " + gear);
}
public static void main(String[] args) {
Bike bike1 = new Bike();
Bike bike2 = new Bike("red", 7);
bike1.displayBikeInfo();
bike2.displayBikeInfo();
}
}

OUTPUT
PROGRAM 48

Aim : Write a program to show constructor overloading.

SOURCE CODE

class Employee {
String name;
int age;
String department;
// Default constructor
Employee() {
System.out.println("Creating employee with default values...");
name = "John Doe";
age = 30;
department = "Unassigned";
}
// Constructor with name and age
Employee(String empName, int empAge) {
System.out.println("Creating employee with name and age...");
name = empName;
age = empAge;
department = "Unassigned";
}
// Constructor with name, age, and department
Employee(String empName, int empAge, String empDepartment) {
System.out.println("Creating employee with detailed information...");
name = empName;
age = empAge;
department = empDepartment;
}
// Method to display employee information
void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Department: " + department);
System.out.println();
}
public static void main(String[] args) {
Employee emp1 = new Employee();
Employee emp2 = new Employee("Alice", 25);
Employee emp3 = new Employee("Bob", 32, "Marketing");
emp1.displayInfo();
emp2.displayInfo();
emp3.displayInfo();
}
}

OUTPUT
PROGRAM 49

Aim : Write a program to show the copy constructor effect through constructors.

SOURCE CODE

class Point {
private int x;
private int y;
public Point() {
this.x = 0;
this.y = 0;
}
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public Point(Point other) {
this.x = other.x;
this.y = other.y;
}
public void move(int dx, int dy) {
this.x += dx;
this.y += dy;
}
public void display() {
System.out.println("(" + this.x + ", " + this.y + ")");
}
public static void main(String[] args) {
Point point1 = new Point(3, 5);
point1.display();
Point point2 = new Point(point1);
point2.display();
point1.move(2, 1);
point1.display();
point2.display();
System.out.println("point1 and point2 are independent objects.");
}
}

OUTPUT
PROGRAM 50

Aim : Write a program to show the copy constructor effect without constructors.

SOURCE CODE

class Point {
private int x;
private int y;
public void move(int dx, int dy) {
this.x += dx;
this.y += dy;
}
public void display() {
System.out.println("(" + this.x + ", " + this.y + ")");
}
public static void main(String[] args) {
Point point1 = new Point();
point1.x = 3;
point1.y = 5;
point1.display();

// Create point2 as a copy of point1 by directly accessing variables


Point point2 = new Point();
point2.x = point1.x;
point2.y = point1.y;
point2.display();
point1.move(2, 1);
point1.display();
point2.display();
}
}

OUTPUT
PROGRAM 51

Aim : Write a program to show use of super keyword.

SOURCE CODE

class Vehicle {
String name;
int speed;
Vehicle(String vehicleName) {
this.name = vehicleName;
this.speed = 0;
System.out.println("Creating a new vehicle: " + this.name);
}
void startEngine() {
System.out.println(this.name + " engine started.");
}
}
class Car extends Vehicle {
int numDoors;
Car(String carName, int doors) {
super(carName); // Call parent class constructor
this.numDoors = doors;
System.out.println("Creating a new car: " + this.name + " with " + this.numDoors + " doors.");
}
void accelerate(int speedIncrease) {
this.speed += speedIncrease;
System.out.println(this.name + " accelerated to " + this.speed + " mph.");
}
void displayInfo() {
System.out.println("Car name: " + this.name);
System.out.println("Number of doors: " + this.numDoors);
System.out.println("Current speed: " + this.speed + " mph.");
}
void honkHorn() {
System.out.println(this.name + " honking horn!");
super.startEngine(); // Call parent class method
}
}
class SuperKeywordDemo {
public static void main(String[] args) {
Car myCar = new Car("Mustang", 2);
myCar.honkHorn(); // Demonstrates using super for both parent method and
constructor myCar.accelerate(20);
myCar.displayInfo();
}
}

OUTPUT
PROGRAM 52

Aim : Write a program to show use of ‘this’ in constructor chaining.

SOURCE CODE

class House {
private String address;
private int numBedrooms;
private boolean hasBasement;
public House(String address) {
this(address, 2, false);
System.out.println("Creating house with address only.");
}
public House(String address, int numBedrooms) {
this(address, numBedrooms, false);
System.out.println("Creating house with address and bedrooms.");
}
public House(String address, int numBedrooms, boolean hasBasement) {
this.address = address;
this.numBedrooms = numBedrooms;
this.hasBasement = hasBasement;
System.out.println("Creating house with all details.");
}
public void displayInfo() {
System.out.println("Address: " + address);
System.out.println("Number of bedrooms: " + numBedrooms);
System.out.println("Has basement: " + hasBasement);
System.out.println();
}
public static void main(String[] args) {
House house1 = new House("123 Main St");
House house2 = new House("456 Maple Ave", 3);
House house3 = new House("789 Elm St", 4, true);
house1.displayInfo();
house2.displayInfo();
house3.displayInfo();
}
}

OUTPUT
PROGRAM 53

Aim : Write a program in Java to create an immutable class.

SOURCE CODE

final class Immutable


{
// private class members
private String name;
private int date;
Immutable(String name, int date) {
// class members are initialized using constructor
this.name = name;
this.date = date;
}
// getter method returns the copy of class members
public String getName()
{
return name;
}
public int getDate()
{
return date;
}
}
class Main {
public static void main(String[] args) {
// create object of Immutable
Immutable obj = new Immutable("Immutable Class", 2024);
System.out.println("Name: " + obj.getName());
System.out.println("Date: " + obj.getDate());
}
}

OUTPUT
PROGRAM 54

Aim : Write a program in Java to create thread by extending Thread class.

SOURCE CODE

public class MyThread extends Thread


{
public void run()
{
for (int i = 0; i < 10; i++)
{ System.out.println("Thread: " + getName() + ", iteration: " + i);
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
public static void main(String[] args) {
MyThread thread1 = new MyThread();
thread1.setName("Thread 1"); // Set a custom thread name
thread1.start(); // Start the thread

// Main thread continues to run concurrently


System.out.println("Main thread running...");
}
}

OUTPUT
PROGRAM 55

Aim : Write a program in Java to create thread by implementing Runnable interface.

SOURCE CODE

class MultithreadingDemo implements Runnable


{
public void run()
{
try
{
// Displaying the thread that is running
System.out.println( "Thread " + Thread.currentThread().getId() + " is running");
}
catch (Exception e)
{
// Throwing an exception
System.out.println("Exception is caught");
}
}
}

class Multithread
{
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
Thread object = new Thread(new MultithreadingDemo());
object.start();
}
}
}

OUTPUT
PROGRAM 56

Aim : Write a program to create a file in Java using FileOutputStream class and enter byte data into it.

SOURCE CODE

import java.io.FileOutputStream;
Import java.io.IOException;
public class Main
{
public static void main(String[] args)
{
String data = "This is a line of text inside the file.";

try
{
FileOutputStream output = new FileOutputStream("output.txt");
byte[] array = data.getBytes();

// Writes byte to the file


output.write(array);
output.close();
}

catch(Exception e)
{
e.getStackTrace();
}
}
}

OUTPUT
PROGRAM 57

Aim : Write a program to create a file in Java using FileOutputStream class and enter String data into it.

SOURCE CODE

import java.io.FileOutputStream;
import java.io.IOException;
public class WriteStringToFile
{
public static void main(String[] args)
{
String fileName = "my_file.txt";
String data = "This is some string data to write to the file.";

try
(FileOutputStream outputStream = new FileOutputStream(fileName))
{
// Convert string to bytes using UTF-8 encoding
byte[] bytes = data.getBytes("UTF-8");

// Write the byte array to the file


outputStream.write(bytes);
System.out.println("File created and data written successfully!");
}

catch (IOException e)
{
e.printStackTrace();
}
}
}

OUTPUT
PROGRAM 58

Aim : Open a file using FileInputStream, read its content and diplay on screen. (Remember to create a file
in Java using FileOutputStream class and enter data into it before opening it.)

SOURCE CODE

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CreateAndReadFile {
public static void main(String[] args) throws IOException {
String fileName = "my_file.txt";
String data = "This is some data to write to the file.";

// Create a FileOutputStream to write data to the file


FileOutputStream outputStream = new FileOutputStream(fileName);
outputStream.write(data.getBytes("UTF-8")); // Write data with UTF-8 encoding
outputStream.close(); // Close the stream
System.out.println("File created and data written successfully!");

// Open the file using FileInputStream


FileInputStream inputStream = new FileInputStream(fileName);
// Read the file content byte by byte
StringBuilder content = new StringBuilder();
int byteRead;
while ((byteRead = inputStream.read()) != -1) {
content.append((char) byteRead); // Convert byte to character
}
// Display the file content on screen
System.out.println("\nFile content:");
System.out.println(content.toString());
inputStream.close(); // Close the stream
}
}

OUTPUT
PROGRAM 59

Aim : Write a program in Java to use yield() function with threads.

SOURCE CODE

public class JavaYieldExp extends Thread


{
public void run()
{
for (int i=0; i<3 ; i++)
System.out.println(Thread.currentThread().getName() + " in control");
}
public static void main(String[]args)
{
JavaYieldExp t1 = new JavaYieldExp();
JavaYieldExp t2 = new JavaYieldExp();
t1.start();
t2.start();
for (int i=0; i<3; i++)
{
// Control passes to child thread
t1.yield();
System.out.println(Thread.currentThread().getName() + " in control");
}
}
}

OUTPUT
PROGRAM 60

Aim : Write a program in Java to use sleep() function with threads.

SOURCE CODE

public class SleepExp1 extends Thread


{
public void run()
{
for(int i=1;i<5;i++)
{
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[])
{
SleepExp1 t1=new SleepExp1();
SleepExp1 t2=new SleepExp1();
t1.start();
t2.start();
}
}

OUTPUT
PROGRAM 61

Aim : Write a program in Java to use join() function with threads.

SOURCE CODE

import java.io.*;
class ThreadJoining extends Thread {
public void run() {
for (int i = 0; i < 2; i++) {
try {
Thread.sleep(500);
System.out.println("Current Thread: " + Thread.currentThread().getName());
}
catch(Exception ex) {
System.out.println("Exception has" + " been caught" + ex);
}
System.out.println(i);
}
}
}
class Main {
public static void main (String[] args) {
ThreadJoining t1 = new ThreadJoining();
ThreadJoining t2 = new ThreadJoining();
ThreadJoining t3 = new ThreadJoining();
t1.start();
// starts second thread after when
// first thread t1 has died.
try {
System.out.println("Current Thread: " + Thread.currentThread().getName());
t1.join();
}
catch(Exception ex) {
System.out.println("Exception has " + "been caught" + ex);
}
t2.start();
try {
System.out.println("Current Thread: " + Thread.currentThread().getName());
t2.join();
}
catch(Exception ex) {
System.out.println("Exception has been" + " caught" + ex);
}
t3.start();
}
}

OUTPUT
PROGRAM 62

Aim : Write a program in Java to create multiple threads that perform different tasks.

SOURCE CODE

class Simple1 extends Thread


{
public void run()
{
System.out.println("task one");
}
}

class Simple2 extends Thread


{
public void run()
{
System.out.println("task two");
}
}

class TestMultitasking3
{
public static void main(String args[])
{
Simple1 t1=new Simple1();
Simple2 t2=new Simple2();
t1.start();
t2.start();
}
}

OUTPUT
PROGRAM 63

Aim : Write a program in Java to prioritize threads.

SOURCE CODE

import java.lang.*;
public class ThreadPriorityExample extends Thread {
public void run() {
System.out.println("Inside the run() method");
}
public static void main(String argvs[]) {
ThreadPriorityExample th1 = new ThreadPriorityExample();
ThreadPriorityExample th2 = new ThreadPriorityExample();
ThreadPriorityExample th3 = new ThreadPriorityExample();
// We did not mention the priority of the thread.
// Therefore, the priorities of the thread is 5, the default value
// 1st Thread
// Displaying the priority of the thread
// using the getPriority() method
System.out.println("Priority of the thread th1 is : " + th1.getPriority());
// 2nd Thread
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
// 3rd Thread
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
// Setting priorities of above threads by
// passing integer arguments
th1.setPriority(6);
th2.setPriority(3);
th3.setPriority(9);
System.out.println("Priority of the thread th1 is : " + th1.getPriority());
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
System.out.println("Priority of the thread th3 is : " + th3.getPriority());
// Main thread
// Displaying name of the currently executing thread
System.out.println("Currently Executing The Thread : " + Thread.currentThread().getName());
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());
// Priority of the main thread is 10 now
Thread.currentThread().setPriority(10);
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());
}
}

OUTPUT
PROGRAM 64

Aim : Write a program in Java to use synchronized methods.

SOURCE CODE

class Table{
synchronized void printTable(int n){
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}
catch(Exception e){
System.out.println(e);
}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
class Main{
public static void main(String args[]){
Table obj = new Table();
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}

OUTPUT
PROGRAM 65

Aim : Write a program in Java to use synchronized block.

SOURCE CODE

class Table{
void printTable(int n){
synchronized(this){
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}
catch(Exception e){
System.out.println(e);
}
}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
class Main{
public static void main(String args[]){
Table obj = new Table();
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}

OUTPUT
PROGRAM 66

Aim : Write a program in Java to use interrupt() method.

SOURCE CODE

class JavaInterruptExp1 extends Thread {


public void run() {
try
{
Thread.sleep(1000);
System.out.println("javatpoint");
}
catch(InterruptedException e)
{
throw new RuntimeException("Thread interrupted..."+e);
}
}
public static void main(String args[]) {
JavaInterruptExp1 t1=new JavaInterruptExp1();
t1.start();
try {
t1.interrupt();
}
catch(Exception e){
System.out.println("Exception handled "+e);
}
}
}

OUTPUT
PROGRAM 67

Aim : WAP in java using AWT. Extend frame class and add two buttons ‘Submit’ and ‘Cancel’ to it.

SOURCE CODE

import java.awt.*;
import java.awt.event.*;
public class test2 extends Frame {
Button submit, cancel;
test2() {
submit = new Button("Submit");
cancel = new Button("Cancel");
submit.setBounds(250 - 50, 250 - 50, 100, 30);
submit.setFocusable(false);
cancel.setBounds(250 - 50, 281 - 50, 100, 30);
cancel.setFocusable(false);
this.add(submit);
this.add(cancel);
this.addWindowListener(
new WindowAdapter(){
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
this.setSize(500, 500);
this.setLayout(null);
this.setVisible(true);
}
public static void main(String[] args) {
new test2();
}
}

OUTPUT
PROGRAM 68

Aim : Design a registration form in java using AWT. Use various components like label, button, textfield etc

SOURCE CODE

import java.awt.*;
import java.awt.event.*;
public class test2 extends Frame implements ActionListener{
Button submit, cancel;
TextField emailID, password;
Label emailText, passwordText;
public void actionPerformed(ActionEvent e) {
if(e.getSource() == submit)
{
System.out.println("EMAIL: " + emailID.getText() + " " + "PASS: " + password.getText());
}
if(e.getSource() == cancel)
{
emailID.setText("");
password.setText("");
}
}
test2() {
emailID = new TextField();
password = new TextField();
emailText = new Label("Email: "); passwordText = new Label("Password: ");
submit = new Button("Submit");
cancel = new Button("Cancel");
emailText.setBounds(150 - 30, 150 - 50, 60, 30);
passwordText.setBounds(150 - 30, 200 - 50, 60, 30);
emailID.setBounds(300 - 100, 150 - 50, 200, 30);
password.setBounds(300 - 100, 200 - 50, 200, 30);
password.setEchoChar('*');
submit.setBounds(250 - 50, 250 - 50, 100, 30);
submit.setFocusable(false);
submit.addActionListener(this);
cancel.setBounds(250 - 50, 281 - 50, 100, 30);
cancel.setFocusable(false);
cancel.addActionListener(this);
this.add(emailText);
this.add(passwordText);
this.add(submit);
this.add(cancel);
this.add(emailID);
this.add(password);
this.addWindowListener(
new WindowAdapter(){
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
this.setSize(500, 500);
this.setLayout(null);
this.setVisible(true);
}
public static void main(String[] args) {
new test2();
}
}
OUTPUT
PROGRAM 69

Aim : Create a program in java using AWT and show usage of List component.

SOURCE CODE

import java.awt.*;
import java.awt.event.*;
public class test2 extends Frame implements ActionListener{
List listOptions;
Button select;
public void actionPerformed(ActionEvent e) {
System.out.println(listOptions.getSelectedItem());
}
test2() {
listOptions = new List(6, false);
select = new Button("Select");
listOptions.setBounds(250 - 50, 250 - 50, 100, 100);
select.setBounds(250 - 50, 320 - 10, 100, 20);
select.addActionListener(this);
listOptions.add("Apple");
listOptions.add("Banana");
listOptions.add("Avocado");
listOptions.add("Orange");
listOptions.add("Eggplant");
listOptions.add("Pomegranate");
listOptions.setFocusable(false);
this.add(listOptions);
this.add(select);
this.addWindowListener(
new WindowAdapter(){
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
this.setSize(500, 500);
this.setLayout(null);
this.setVisible(true);
}
public static void main(String[] args) {
new test2();
}
}

OUTPUT
PROGRAM 70

Aim : Create a program in java using AWT and show usage of Choice component.

SOURCE CODE

import java.awt.*;
import java.awt.event.*;
public class test2 extends Frame implements ActionListener{
Button select;
Choice choiceOptions;
public void actionPerformed(ActionEvent e) {
System.out.println(choiceOptions.getSelectedItem());
}
test2() {
choiceOptions = new Choice();
select = new Button("Select");
choiceOptions.setBounds(250 - 50, 250 - 50, 100, 100);
select.setBounds(250 - 50, 320 - 10, 100, 20);
select.addActionListener(this);
choiceOptions.add("Apple");
choiceOptions.add("Banana");
choiceOptions.add("Avocado");
choiceOptions.add("Orange");
choiceOptions.add("Eggplant");
choiceOptions.add("Pomegranate");
choiceOptions.setFocusable(false);
this.add(choiceOptions);
this.add(select);
this.addWindowListener(
new WindowAdapter(){
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
this.setSize(500, 500);
this.setLayout(null);
this.setVisible(true);
}
public static void main(String[] args) {
new test2();
}
}

OUTPUT
PROGRAM 71

Aim : Create a program in java using AWT and show difference of text field and textarea components.

SOURCE CODE

import java.awt.*;
import java.awt.event.*;
public class test2 extends Frame {
// Button select;
TextField textField;
TextArea textArea;
// public void actionPerformed(ActionEvent e) // {

// }
test2() {
textField = new TextField("Default-TextField");
textArea = new TextArea("Default-TextArea");
textField.setBounds(250 - 100, 100 - 25, 200, 50);
textArea.setBounds(250 - 100, 150 - 25, 200, 50);
this.addWindowListener(
new WindowAdapter(){
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
this.add(textField);
this.add(textArea);
this.setSize(500, 500);
this.setLayout(null);
this.setVisible(true);
}
public static void main(String[] args) {
new test2();
}
}

OUTPUT
PROGRAM 72

Aim : Create a program in java using AWT and show usage of checkbox component.

SOURCE CODE

import java.awt.*;
import java.awt.event.*;
public class test2 extends Frame implements ActionListener{
Button select;
Checkbox checkbox;
public void actionPerformed(ActionEvent e) {
System.out.println(checkbox.getState());
}
test2() {
select = new Button("Get Current Option");
checkbox = new Checkbox("Try Ticking this Checkbox");
checkbox.setBounds(250 - 75, 200 - 15, 150, 30);
checkbox.setFocusable(false);
checkbox.setState(false);
select.setBounds(250 - 50, 250 - 10, 100, 20);
select.setFocusable(false);
select.addActionListener(this);
this.addWindowListener(
new WindowAdapter(){
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
this.add(checkbox);
this.add(select);
this.setSize(500, 500);
this.setLayout(null);
this.setVisible(true);
}
public static void main(String[] args) {
new test2();
}
}

OUTPUT
PROGRAM 73

Aim : WAP to create panels using awt.

SOURCE CODE
import java.awt.*;
import java.awt.event.*;
public class test2 extends Frame implements ActionListener{
Button button1, button2;
Panel panelCol1, panelCol2;
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button1)
{
System.out.println("Button pressed in panel 1");
}
if(e.getSource() == button2)
{
System.out.println("Button pressed in panel 2");
}
}
test2() {
panelCol1 = new Panel(null);
panelCol2 = new Panel(null);
button1 = new Button("Button - Panel 1st");
button2 = new Button("Button - Panel 2nd");
button1.addActionListener(this);
button2.addActionListener(this);
button1.setBounds(150 - 50, 200 - 10, 100, 20);
button2.setBounds(150 - 50, 200 - 10, 100, 20);
this.addWindowListener(
new WindowAdapter(){
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
panelCol1.add(button1);
panelCol2.add(button2);
this.add(panelCol1);
this.add(panelCol2);
this.setSize(500, 500);
this.setLayout(new GridLayout(1, 2));
this.setVisible(true);
}
public static void main(String[] args) {
new test2();
}
}

OUTPUT

You might also like