0% found this document useful (0 votes)
20 views74 pages

Java Programs for Beginners

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)
20 views74 pages

Java Programs for Beginners

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

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++) {
[Link](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;
[Link]("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;
[Link]("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) {
[Link]("Prime numbers from 1 to 50:");
for (int i = 2; i <= 50; i++) {
if (isPrime(i)) {
[Link](i + " ");
}
}
}
private static boolean isPrime(int number) {
If (number <= 1) {
return false;
}
for (int i = 2; i <= [Link](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 [Link];
class EvenOrOdd {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a number: ");
int number = [Link]();
if (isEven(number)) {
[Link](number + " is even.");
}
else {
[Link](number + " is odd.");
}
[Link]();
}
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 [Link];
class FibonacciSeries {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the limit for Fibonacci series: ");
int limit = [Link]();
[Link]("Fibonacci series up to " + limit + ":");
printFibonacciSeries(limit);
[Link]();
}
private static void printFibonacciSeries(int limit) {
int num1 = 0, num2 = 1, nextTerm;
[Link](num1 + " " + num2 + " ");
for (int i = 2; i < limit; i++) {
nextTerm = num1 + num2;
[Link](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)
[Link](year + " is a leap year.");
else
[Link](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 [Link];
class VowelConsonantChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a character: ");
char inputChar = [Link]().toLowerCase().charAt(0);
if (inputChar >= 'a' && inputChar <= 'z') {
if (inputChar == 'a' || inputChar == 'e' || inputChar == 'i' || inputChar == 'o' || inputChar == 'u')
{ [Link](inputChar + " is a vowel.");
}
else {
[Link](inputChar + " is a consonant.");
}
}
else {
[Link]("Error: Invalid input. Please enter a valid alphabet character.");
}
[Link]();
}
}

OUTPUT
PROGRAM 9
Aim : Write a program to calculate power of a number. (without [Link])
SOURCE CODE
import [Link];
class PowerCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the base: ");
double base = [Link]();
[Link]("Enter the exponent: ");
int exponent = [Link]();
double result = calculatePower(base, exponent);
[Link](base + " raised to the power of " + exponent + " is: " + result);
[Link]();
}
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 [Link];
class GradeCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the student's score: ");
int score = [Link]();
displayGrade(score);
[Link]();
}
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';
}
[Link]("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 [Link];
class StringEqualityChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the first string: ");
String str1 = [Link]();
[Link]("Enter the second string: ");
String str2 = [Link]();
if (areStringsEqual(str1, str2)) {
[Link]("The two strings are equal.");
} else {
[Link]("The two strings are not equal.");
}
[Link]();
}
private static boolean areStringsEqual(String str1, String str2) {
return [Link](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
[Link]("Using Increment Operator:");
int i = 5;
[Link]("Original value of i: " + i);
// Post-increment
int postIncrement = i++;
[Link]("After post-increment, i: " + i);
[Link]("Value returned by post-increment: " + postIncrement);
// Reset I
i = 5;
// Pre-increment
int preIncrement = ++i;
[Link]("After pre-increment, i: " + i);
[Link]("Value returned by pre-increment: " + preIncrement);
// Using decrement operator
[Link]("\nUsing Decrement Operator:");
int j = 8;
[Link]("Original value of j: " + j);
// Post-decrement
int postDecrement = j--;
[Link]("After post-decrement, j: " + j);
[Link]("Value returned by post-decrement: " + postDecrement);
// Reset j
j = 8;
// Pre-decrement
int preDecrement = --j;
[Link]("After pre-decrement, j: " + j);
[Link]("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 [Link];
class GreaterNumberTernary {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the first number: ");
int num1 = [Link]();
[Link]("Enter the second number: ");
int num2 = [Link]();
int greaterNumber = (num1 > num2) ? num1 : num2;
[Link]("The greater number is: " + greaterNumber);
[Link]();
}
}

OUTPUT
PROGRAM 14
Aim : Write a program to reverse a given number.
SOURCE CODE
import [Link];
class ReverseNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a number: ");
int number = [Link]();
int reversedNumber = reverseNumber(number);
[Link]("Reversed number: " + reversedNumber);
[Link]();
}
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()
{
[Link]("normal function");
}
public void method1(int a)
{
[Link]("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()
{
[Link]("Some generic sound");
}
}
class Dog extends Animal {
void makeSound()
{
[Link]("Bark! Bark!");
}
}
class Cat extends Animal {
void makeSound()
{
[Link]("Meow!");
}
}
class Main {
public static void main(String[] args) {
Animal genericAnimal = new Animal();
Dog myDog = new Dog();
Cat myCat = new Cat();
[Link]();
[Link]();
[Link]();
}
}

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

SOURCE CODE

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

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

SOURCE CODE

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

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

SOURCE CODE

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

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

SOURCE CODE

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

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()
{
[Link]("Implemented method1 from Interface1");
}
public void method2()
{
[Link]("Implemented method2 from Interface2");
}
public void additionalMethod()
{
[Link]("This is an additional method in MyClass");
}
}
class MultipleInheritanceExample {
public static void main(String[] args) {
MyClass myObject = new MyClass();
myObject.method1();
myObject.method2();
[Link]();
}
}

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()
{
[Link]("Implemented method1 from Interface1");
}
public void method2()
{
[Link]("Implemented method2 from Interface2");
}
public void additionalMethod()
{
[Link]("Implemented additionalMethod from MultipleInheritanceInterface");
}
}
class MultipleInheritanceExample {
public static void main(String[] args) {
MyClass myObject = new MyClass();
myObject.method1();
myObject.method2();
[Link]();
}
}

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;
[Link]("Total Time taken: " + totalTime + "seconds");
}
public void speed()
{
avgSpeed = distance / totalTime;
[Link]("Average Speed maintained: " + avgSpeed + "m/sec");
}
public static void main(String args[]) {
TwoWheeler t1 = new TwoWheeler();
[Link]();
[Link]();
}
}

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;
[Link]("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");
[Link]("Initial name: " + name);

// You cannot change the reference, but you can modify the object's state
[Link](" Doe");
[Link]("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()
{
[Link]("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()
{
[Link]("Overridden display method in the subclass.");
}
void anotherMethod()
{
[Link]("Calling the final method from a subclass method:");
display();
}
}
class FinalMethodDemo {
public static void main(String[] args) {
SubClass subClass = new SubClass();
[Link]();
}
}

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()
{
[Link]("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();
[Link]();
}
}

OUTPUT
PROGRAM 27

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

SOURCE CODE

import [Link];
import [Link];
class ArrayInputOutput {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the size of the integer array: ");
int sizeInt = [Link]();
int[] intArray = new int[sizeInt];
[Link]("Enter the elements of the integer array:");
for (int i = 0; i < sizeInt; i++) {
intArray[i] = [Link]();
}
[Link]("Integer array: " + [Link](intArray));

[Link]("Enter the size of the double array: ");


int sizeDouble = [Link]();
double[] doubleArray = new double[sizeDouble];
[Link]("Enter the elements of the double array:");
for (int i = 0; i < sizeDouble; i++) {
doubleArray[i] = [Link]();
}
[Link]("Double array: " + [Link](doubleArray));

[Link]("Enter the number of strings: ");


int numStrings = [Link]();
String[] stringArray = new String[numStrings];
[Link](); // Consume the newline character
[Link]("Enter the strings:");
for (int i = 0; i < numStrings; i++) {
stringArray[i] = [Link]();
}
[Link]("String array: " + [Link](stringArray));
}
}

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

SOURCE CODE
import [Link];
class MatrixMultiplicationExample {
public static void main(String args[]) {
int row1, col1, row2, col2;
Scanner s = new Scanner([Link]);
[Link]("Enter number of rows in first matrix: ");
row1 = [Link]();
[Link]("Enter number of columns in first matrix: ");
col1 = [Link]();
[Link]("Enter number of rows in second matrix: ");
row2 = [Link]();
[Link]("Enter number of columns in second matrix: ");
col2 = [Link]();
// Requirement check for matrix multiplication
if (col1 != row2) {
[Link]("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
[Link]("\nEnter values for matrix A : ");
for (int i = 0; i < row1; i++) {
for (int j = 0; j < col1; j++) a[i][j] = [Link]();
}
[Link]("\nEnter values for matrix B : ");
for (int i = 0; i < row2; i++) {
for (int j = 0; j < col2; j++) b[i][j] = [Link]();
}
[Link]("\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];
}
[Link](c[i][j] + " ");
}
[Link]();
}
}
}
OUTPUT
PROGRAM 29

Aim : WAP to pass array as parameter.

SOURCE CODE

class ArrayParameterDemo {
public static void printArray(int[] arr) {
[Link]("Array elements: ");
for (int element : arr) {
[Link](element + " ");
}
[Link]();
}

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 [Link];
class ArrayReturnDemo
{
public static int[] createAndReturnArray()
{
int[] myArray = new int[5];
for (int i = 0; i < [Link]; i++)
{
myArray[i] = i * 10;
}
return myArray;
}

public static void main(String[] args)


{
int[] returnedArray = createAndReturnArray();
[Link]("Returned array: " + [Link](returnedArray));
}
}

OUTPUT
PROGRAM 31

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

SOURCE CODE

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

// Character-based methods
[Link]("Character at index 4: " + [Link](4));
[Link]("Index of 'o': " + [Link]('o'));
[Link]("Last index of 'o': " + [Link]('o'));

// Substring methods
[Link]("Substring from index 7: " + [Link](7));
[Link]("Substring from index 7 to 12: " + [Link](7, 12));

// Modification methods
[Link]("Uppercase: " + [Link]());
[Link]("Lowercase: " + [Link]());
[Link]("Trimmed: " + [Link]());
[Link]("Replaced 'World' with 'Java': " + [Link]("World", "Java"));

// Informational methods
[Link]("Length: " + [Link]());
[Link]("Starts with 'Hello': " + [Link]("Hello"));
[Link]("Ends with '!': " + [Link]("!"));
[Link]("Contains 'World': " + [Link]("World"));
[Link]("Is empty: " + [Link]());

// Aditional Methods
[Link]("Concatenated with ' Java': " + [Link](" Java"));
[Link]("Compared to 'Hello': " + [Link]("Hello"));
[Link]("Split into words: " + [Link]([Link](" ")));
}
}

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
[Link](", World!"); // Append a string
[Link](42); // Append an integer
[Link](true); // Append a boolean
[Link]("Appended string: " + sb);

// Insertion methods
[Link](7, "Java "); // Insert at a specific index
[Link]("Inserted string: " + sb);

// Deletion methods
[Link](7); // Delete a character at an index
[Link](7, 12); // Delete a substring
[Link]("Deleted string: " + sb);

// Modification methods
[Link](); // Reverse the string
[Link](0, 'J'); // Replace a character
[Link]("Modified string: " + sb);

// Informational methods
[Link]("Length: " + [Link]());
[Link]("Capacity: " + [Link]());
[Link]("Character at index 4: " + [Link](4));
[Link]("Substring from index 7: " + [Link](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
[Link](", World!"); // Append a string
[Link](42); // Append an integer
[Link](true); // Append a boolean
[Link]("Appended string: " + sb);

// Insertion methods
[Link](7, "Java "); // Insert at a specific index
[Link]("Inserted string: " + sb);

// Deletion methods
[Link](7); // Delete a character at an index
[Link](7, 12); // Delete a substring
[Link]("Deleted string: " + sb);

// Modification methods
[Link](); // Reverse the string
[Link](0, 'J'); // Replace a character
[Link]("Modified string: " + sb);

// Informational methods
[Link]("Length: " + [Link]());
[Link]("Capacity: " + [Link]());
[Link]("Character at index 4: " + [Link](4));
[Link]("Substring from index 7: " + [Link](7));
}
}

OUTPUT
PROGRAM 34

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

SOURCE CODE

import [Link];
class ArrayListExample {
public static void main(String[] args) {

// Create an ArrayList of strings


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

// Add elements to the ArrayList


[Link]("John");
[Link]("Alice");
[Link]("Bob");
[Link]("Initial list: " + names);

// Remove an element by index


[Link](1);
// Removes "Alice"
[Link]("List after removing: " + names);

// Change an element by index


[Link](0, "David");
// Changes "John" to "David"
[Link]("List after changing: " + names);

// Clear the entire ArrayList


[Link]();
[Link]("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;
[Link]("Result: " + result);
}
catch (ArithmeticException e) {
[Link]("Error: Division by zero is not allowed.");
[Link]([Link]());
}

// 2. Integer overflow
try {
int maxInt = Integer.MAX_VALUE;
int result = maxInt + 1;
[Link]("Result: " + result);
}
catch (ArithmeticException E) {
[Link]("Error: Integer overflow occurred.");
[Link]([Link]());
}
[Link]("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 = [Link](inputString);
[Link]("Converted number: " + number);
} catch (NumberFormatException e) {
[Link]("Error: Input string \"" + inputString + "\" contains non-numeric
characters."); [Link]("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 = [Link](inputString2);
[Link]("Converted number: " + number);
} catch (NumberFormatException e) {
[Link]("Error: Input string \"" + inputString2 + "\" contains leading/trailing
whitespaces."); [Link]("Remove whitespaces before parsing.");
}

// 3. Parsing a empty string


String inputString3 = null;
try {
int number = [Link](inputString3);
[Link]("Converted number: " + number);
} catch (NumberFormatException e) {
[Link]("Error: Input string cannot be null or empty.");
[Link]("Handle null/empty checks before parsing.");
}
[Link]("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];
[Link]("Element at index 3: " + invalidElement);
}
catch (ArrayIndexOutOfBoundsException e) {
[Link]("Error: Array index out of bounds!");
[Link]("Message: " + [Link]());
}

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


try {
int invalidElement2 = numbers[-1];
[Link]("Element at index -1: " + invalidElement2);
}
catch (ArrayIndexOutOfBoundsException e) {
[Link]("Error: Array index out of bounds!");
[Link]("Message: " + [Link]());
}
[Link]("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);
[Link]("Result (no exception): " + result);
} finally {
[Link]("`finally` block executed (always)");
closeConnection(); // Resource cleanup, even if no exception
}
// Case b: Exception handled
try { int result = divide(10, 0);
[Link]("Result (handled exception): " + result);
} catch (ArithmeticException e) {
[Link]("Error: Division by zero");
} finally {
[Link]("`finally` block executed (always)");
closeConnection(); // Resource cleanup after handling exception
}
// Case c: Unhandled exception
try { int result = accessInvalidArrayElement();
[Link]("Result (unhandled exception): " + result);
} finally {
[Link]("`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) {
[Link]("Error closing connection after unhandled exception: "
+ [Link]());
}
}
}
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)
[Link]("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.
[Link]("I am in try block");
}

catch(ArithmeticException ae)
{
[Link]("A number cannot be divided by zero, Illegal operation in java");
}

catch(ArrayIndexOutOfBoundsException e)
{
[Link]("Accessing array element outside of specified limit");
}

catch(Exception e)
{
[Link]([Link]());
}
[Link]("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)
{
[Link]("Caught inside fun().");
throw e;
// rethrowing the exception
}
}
public static void main(String args[])
{
try
{
fun();
}
catch (NullPointerException e)
{
[Link]("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{
[Link]("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e) {
[Link](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) {
[Link](e);
}
[Link]("other statement");
}
//catch block of outer try block
catch(Exception e) {
[Link]("handled the exception (outer catch)");
}
[Link]("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
{
[Link]("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() {
[Link]("Generic animal sound");
}
}

class Dog extends Animal {


public void makeSound() {
[Link]("Woof!");
}
}

class Cat extends Animal {


public void makeSound() {
[Link]("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


[Link]();
[Link]();
[Link]("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)
{
[Link]("Caught");
// Print the message from MyException object
[Link]([Link]());
}
}
}

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 = [Link]()-1; i >= 0 ; i--)
result += [Link](i);
return result;
};
// call the method of the interface
[Link]("Lambda reversed = " + [Link]("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()
{
[Link]("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
[Link](); // 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() {
[Link]("A bike is created with default values.");
color = "black";
gear = 1;
}
Bike(String bikeColor, int bikeGear) {
[Link]("A bike is created with specified values.");
color = bikeColor;
gear = bikeGear;
}
void displayBikeInfo() {
[Link]("Bike color: " + color);
[Link]("Bike gear: " + gear);
}
public static void main(String[] args) {
Bike bike1 = new Bike();
Bike bike2 = new Bike("red", 7);
[Link]();
[Link]();
}
}

OUTPUT
PROGRAM 48

Aim : Write a program to show constructor overloading.

SOURCE CODE

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

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() {
[Link]("(" + this.x + ", " + this.y + ")");
}
public static void main(String[] args) {
Point point1 = new Point(3, 5);
[Link]();
Point point2 = new Point(point1);
[Link]();
[Link](2, 1);
[Link]();
[Link]();
[Link]("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() {
[Link]("(" + this.x + ", " + this.y + ")");
}
public static void main(String[] args) {
Point point1 = new Point();
point1.x = 3;
point1.y = 5;
[Link]();

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


Point point2 = new Point();
point2.x = point1.x;
point2.y = point1.y;
[Link]();
[Link](2, 1);
[Link]();
[Link]();
}
}

OUTPUT
PROGRAM 51

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

SOURCE CODE

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

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);
[Link]("Creating house with address only.");
}
public House(String address, int numBedrooms) {
this(address, numBedrooms, false);
[Link]("Creating house with address and bedrooms.");
}
public House(String address, int numBedrooms, boolean hasBasement) {
[Link] = address;
[Link] = numBedrooms;
[Link] = hasBasement;
[Link]("Creating house with all details.");
}
public void displayInfo() {
[Link]("Address: " + address);
[Link]("Number of bedrooms: " + numBedrooms);
[Link]("Has basement: " + hasBasement);
[Link]();
}
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);
[Link]();
[Link]();
[Link]();
}
}

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
[Link] = name;
[Link] = 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);
[Link]("Name: " + [Link]());
[Link]("Date: " + [Link]());
}
}

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++)
{ [Link]("Thread: " + getName() + ", iteration: " + i);
try
{
[Link](1000);
}
catch (InterruptedException e)
{
[Link]();
}
}
}
public static void main(String[] args) {
MyThread thread1 = new MyThread();
[Link]("Thread 1"); // Set a custom thread name
[Link](); // Start the thread

// Main thread continues to run concurrently


[Link]("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
[Link]( "Thread " + [Link]().getId() + " is running");
}
catch (Exception e)
{
// Throwing an exception
[Link]("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());
[Link]();
}
}
}

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 [Link];
Import [Link];
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("[Link]");
byte[] array = [Link]();

// Writes byte to the file


[Link](array);
[Link]();
}

catch(Exception e)
{
[Link]();
}
}
}

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 [Link];
import [Link];
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 = [Link]("UTF-8");

// Write the byte array to the file


[Link](bytes);
[Link]("File created and data written successfully!");
}

catch (IOException e)
{
[Link]();
}
}
}

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 [Link];
import [Link];
import [Link];
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);
[Link]([Link]("UTF-8")); // Write data with UTF-8 encoding
[Link](); // Close the stream
[Link]("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 = [Link]()) != -1) {
[Link]((char) byteRead); // Convert byte to character
}
// Display the file content on screen
[Link]("\nFile content:");
[Link]([Link]());
[Link](); // 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++)
[Link]([Link]().getName() + " in control");
}
public static void main(String[]args)
{
JavaYieldExp t1 = new JavaYieldExp();
JavaYieldExp t2 = new JavaYieldExp();
[Link]();
[Link]();
for (int i=0; i<3; i++)
{
// Control passes to child thread
[Link]();
[Link]([Link]().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
{
[Link](500);
}
catch(InterruptedException e)
{
[Link](e);
}
[Link](i);
}
}
public static void main(String args[])
{
SleepExp1 t1=new SleepExp1();
SleepExp1 t2=new SleepExp1();
[Link]();
[Link]();
}
}

OUTPUT
PROGRAM 61

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

SOURCE CODE

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

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()
{
[Link]("task one");
}
}

class Simple2 extends Thread


{
public void run()
{
[Link]("task two");
}
}

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

OUTPUT
PROGRAM 63

Aim : Write a program in Java to prioritize threads.

SOURCE CODE

import [Link].*;
public class ThreadPriorityExample extends Thread {
public void run() {
[Link]("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
[Link]("Priority of the thread th1 is : " + [Link]());
// 2nd Thread
[Link]("Priority of the thread th2 is : " + [Link]());
// 3rd Thread
[Link]("Priority of the thread th2 is : " + [Link]());
// Setting priorities of above threads by
// passing integer arguments
[Link](6);
[Link](3);
[Link](9);
[Link]("Priority of the thread th1 is : " + [Link]());
[Link]("Priority of the thread th2 is : " + [Link]());
[Link]("Priority of the thread th3 is : " + [Link]());
// Main thread
// Displaying name of the currently executing thread
[Link]("Currently Executing The Thread : " + [Link]().getName());
[Link]("Priority of the main thread is : " + [Link]().getPriority());
// Priority of the main thread is 10 now
[Link]().setPriority(10);
[Link]("Priority of the main thread is : " + [Link]().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++){
[Link](n*i);
try{
[Link](400);
}
catch(Exception e){
[Link](e);
}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
[Link](5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
[Link](100);
}
}
class Main{
public static void main(String args[]){
Table obj = new Table();
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
[Link]();
[Link]();
}
}

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++){
[Link](n*i);
try{
[Link](400);
}
catch(Exception e){
[Link](e);
}
}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
[Link](5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
[Link](100);
}
}
class Main{
public static void main(String args[]){
Table obj = new Table();
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
[Link]();
[Link]();
}
}

OUTPUT
PROGRAM 66

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

SOURCE CODE

class JavaInterruptExp1 extends Thread {


public void run() {
try
{
[Link](1000);
[Link]("javatpoint");
}
catch(InterruptedException e)
{
throw new RuntimeException("Thread interrupted..."+e);
}
}
public static void main(String args[]) {
JavaInterruptExp1 t1=new JavaInterruptExp1();
[Link]();
try {
[Link]();
}
catch(Exception e){
[Link]("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 [Link].*;
import [Link].*;
public class test2 extends Frame {
Button submit, cancel;
test2() {
submit = new Button("Submit");
cancel = new Button("Cancel");
[Link](250 - 50, 250 - 50, 100, 30);
[Link](false);
[Link](250 - 50, 281 - 50, 100, 30);
[Link](false);
[Link](submit);
[Link](cancel);
[Link](
new WindowAdapter(){
public void windowClosing(WindowEvent e) {
[Link](0);
}
}
);
[Link](500, 500);
[Link](null);
[Link](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 [Link].*;
import [Link].*;
public class test2 extends Frame implements ActionListener{
Button submit, cancel;
TextField emailID, password;
Label emailText, passwordText;
public void actionPerformed(ActionEvent e) {
if([Link]() == submit)
{
[Link]("EMAIL: " + [Link]() + " " + "PASS: " + [Link]());
}
if([Link]() == cancel)
{
[Link]("");
[Link]("");
}
}
test2() {
emailID = new TextField();
password = new TextField();
emailText = new Label("Email: "); passwordText = new Label("Password: ");
submit = new Button("Submit");
cancel = new Button("Cancel");
[Link](150 - 30, 150 - 50, 60, 30);
[Link](150 - 30, 200 - 50, 60, 30);
[Link](300 - 100, 150 - 50, 200, 30);
[Link](300 - 100, 200 - 50, 200, 30);
[Link]('*');
[Link](250 - 50, 250 - 50, 100, 30);
[Link](false);
[Link](this);
[Link](250 - 50, 281 - 50, 100, 30);
[Link](false);
[Link](this);
[Link](emailText);
[Link](passwordText);
[Link](submit);
[Link](cancel);
[Link](emailID);
[Link](password);
[Link](
new WindowAdapter(){
public void windowClosing(WindowEvent e) {
[Link](0);
}
}
);
[Link](500, 500);
[Link](null);
[Link](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 [Link].*;
import [Link].*;
public class test2 extends Frame implements ActionListener{
List listOptions;
Button select;
public void actionPerformed(ActionEvent e) {
[Link]([Link]());
}
test2() {
listOptions = new List(6, false);
select = new Button("Select");
[Link](250 - 50, 250 - 50, 100, 100);
[Link](250 - 50, 320 - 10, 100, 20);
[Link](this);
[Link]("Apple");
[Link]("Banana");
[Link]("Avocado");
[Link]("Orange");
[Link]("Eggplant");
[Link]("Pomegranate");
[Link](false);
[Link](listOptions);
[Link](select);
[Link](
new WindowAdapter(){
public void windowClosing(WindowEvent e) {
[Link](0);
}
}
);
[Link](500, 500);
[Link](null);
[Link](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 [Link].*;
import [Link].*;
public class test2 extends Frame implements ActionListener{
Button select;
Choice choiceOptions;
public void actionPerformed(ActionEvent e) {
[Link]([Link]());
}
test2() {
choiceOptions = new Choice();
select = new Button("Select");
[Link](250 - 50, 250 - 50, 100, 100);
[Link](250 - 50, 320 - 10, 100, 20);
[Link](this);
[Link]("Apple");
[Link]("Banana");
[Link]("Avocado");
[Link]("Orange");
[Link]("Eggplant");
[Link]("Pomegranate");
[Link](false);
[Link](choiceOptions);
[Link](select);
[Link](
new WindowAdapter(){
public void windowClosing(WindowEvent e) {
[Link](0);
}
}
);
[Link](500, 500);
[Link](null);
[Link](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 [Link].*;
import [Link].*;
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");
[Link](250 - 100, 100 - 25, 200, 50);
[Link](250 - 100, 150 - 25, 200, 50);
[Link](
new WindowAdapter(){
public void windowClosing(WindowEvent e) {
[Link](0);
}
}
);
[Link](textField);
[Link](textArea);
[Link](500, 500);
[Link](null);
[Link](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 [Link].*;
import [Link].*;
public class test2 extends Frame implements ActionListener{
Button select;
Checkbox checkbox;
public void actionPerformed(ActionEvent e) {
[Link]([Link]());
}
test2() {
select = new Button("Get Current Option");
checkbox = new Checkbox("Try Ticking this Checkbox");
[Link](250 - 75, 200 - 15, 150, 30);
[Link](false);
[Link](false);
[Link](250 - 50, 250 - 10, 100, 20);
[Link](false);
[Link](this);
[Link](
new WindowAdapter(){
public void windowClosing(WindowEvent e) {
[Link](0);
}
}
);
[Link](checkbox);
[Link](select);
[Link](500, 500);
[Link](null);
[Link](true);
}
public static void main(String[] args) {
new test2();
}
}

OUTPUT
PROGRAM 73

Aim : WAP to create panels using awt.

SOURCE CODE
import [Link].*;
import [Link].*;
public class test2 extends Frame implements ActionListener{
Button button1, button2;
Panel panelCol1, panelCol2;
public void actionPerformed(ActionEvent e) {
if([Link]() == button1)
{
[Link]("Button pressed in panel 1");
}
if([Link]() == button2)
{
[Link]("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");
[Link](this);
[Link](this);
[Link](150 - 50, 200 - 10, 100, 20);
[Link](150 - 50, 200 - 10, 100, 20);
[Link](
new WindowAdapter(){
public void windowClosing(WindowEvent e) {
[Link](0);
}
}
);
[Link](button1);
[Link](button2);
[Link](panelCol1);
[Link](panelCol2);
[Link](500, 500);
[Link](new GridLayout(1, 2));
[Link](true);
}
public static void main(String[] args) {
new test2();
}
}

OUTPUT

You might also like