0% found this document useful (0 votes)
2 views

java codes

The document contains several Java programs demonstrating various concepts such as palindrome checking, character counting, area calculation for different shapes, exception handling, multithreading, and a registration form using AWT. Each program is designed to showcase specific functionalities, including user input handling and basic GUI operations. The examples illustrate fundamental programming techniques and object-oriented principles in Java.

Uploaded by

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

java codes

The document contains several Java programs demonstrating various concepts such as palindrome checking, character counting, area calculation for different shapes, exception handling, multithreading, and a registration form using AWT. Each program is designed to showcase specific functionalities, including user input handling and basic GUI operations. The examples illustrate fundamental programming techniques and object-oriented principles in Java.

Uploaded by

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

import java.util.

Scanner;

public class PalindromeChecker {


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

System.out.print("Enter a string: ");


String input = scanner.nextLine();
scanner.close();

if (isPalindrome(input)) {
System.out.println(input + " is a palindrome.");
} else {
System.out.println(input + " is not a palindrome.");
}
}

public static boolean isPalindrome(String input) {


input = input.replaceAll("\\s", "").toLowerCase();

int left = 0;
int right = input.length() - 1;

while (left < right) {


if (input.charAt(left) != input.charAt(right)) {
return false;
}
left++;
right--;
}

return true;
}
}

C:\Users\Kashish\OneDrive\Desktop>javac PalindromeChecker.java

C:\Users\Kashish\OneDrive\Desktop>java PalindromeChecker
Enter a string: malyalam
malyalam is not a palindrome.

C:\Users\Kashish\OneDrive\Desktop>malayalam
'malayalam' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\Kashish\OneDrive\Desktop>javac PalindromeChecker.java

C:\Users\Kashish\OneDrive\Desktop>java PalindromeChecker
Enter a string: radar
radar is a palindrome.

8b. import java.util.Scanner;

public class CharacterCounter {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();
scanner.close();

int uppercaseCount = 0;
int lowercaseCount = 0;
int specialCharacterCount = 0;
int digitCount = 0;
int spaceCount = 0;

for (char c : input.toCharArray()) {


if (Character.isUpperCase(c)) {
uppercaseCount++;
} else if (Character.isLowerCase(c)) {
lowercaseCount++;
} else if (Character.isDigit(c)) {
digitCount++;
} else if (Character.isWhitespace(c)) {
spaceCount++;
} else {
specialCharacterCount++;
}
}

System.out.println("Uppercase letters: " + uppercaseCount);


System.out.println("Lowercase letters: " + lowercaseCount);
System.out.println("Special characters: " + specialCharacterCount);
System.out.println("Digits: " + digitCount);
System.out.println("Blank spaces: " + spaceCount);
}
}

Microsoft Windows [Version 10.0.22621.2506]


(c) Microsoft Corporation. All rights reserved.

C:\Users\Kashish\OneDrive\Desktop>javac CharacterCounter.java

C:\Users\Kashish\OneDrive\Desktop>java CharacterCounter
Enter a string: My name is Kashish Jitendra jain
Uppercase letters: 3
Lowercase letters: 24
Special characters: 0
Digits: 0
Blank spaces: 5

9a
import java.util.Scanner;

class Shape {
public double calculateArea() {
return 0; // Base class method for calculating area
}
}

class Square extends Shape {


private double side;

public Square(double side) {


this.side = side;
}

@Override
public double calculateArea() {
return side * side;
}
}

class Rectangle extends Shape {


private double length;
private double width;

public Rectangle(double length, double width) {


this.length = length;
this.width = width;
}

@Override
public double calculateArea() {
return length * width;
}
}

class Circle extends Shape {


private double radius;

public Circle(double radius) {


this.radius = radius;
}

@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}

public class AreaCalculator {


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

System.out.println("Choose a shape to calculate its area:");


System.out.println("1. Square");
System.out.println("2. Rectangle");
System.out.println("3. Circle");
System.out.print("Enter your choice (1/2/3): ");
int choice = scanner.nextInt();

Shape shape = null;

switch (choice) {
case 1:
System.out.print("Enter the side length of the square: ");
double squareSide = scanner.nextDouble();
shape = new Square(squareSide);
break;
case 2:
System.out.print("Enter the length of the rectangle: ");
double rectLength = scanner.nextDouble();
System.out.print("Enter the width of the rectangle: ");
double rectWidth = scanner.nextDouble();
shape = new Rectangle(rectLength, rectWidth);
C:\Users\Kashish\OneDrive\Desktop>javac AreaCalculator.java

C:\Users\Kashish\OneDrive\Desktop>java AreaCalculator
Choose a shape to calculate its area:
1. Square
2. Rectangle
3. Circle
Enter your choice (1/2/3): 1
Enter the side length of the square: 50
Area of the selected shape: 2500.0

C:\Users\Kashish\OneDrive\Desktop>

9b
import java.util.Scanner;

class Shape {
public double calculateArea() {
return 0; // Base class method for calculating area
}
}

class Square extends Shape {


private double side;

public Square(double side) {


this.side = side;
}

@Override
public double calculateArea() {
return side * side;
}
}

class Rectangle extends Shape {


private double length;
private double width;

public Rectangle(double length, double width) {


this.length = length;
this.width = width;
}

@Override
public double calculateArea() {
return length * width;
}
}

class Circle extends Shape {


private double radius;

public Circle(double radius) {


this.radius = radius;
}

@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}

public class AreaCalculators {


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

System.out.println("Choose a shape to calculate its area:");


System.out.println("1. Square");
System.out.println("2. Rectangle");
System.out.println("3. Circle");
System.out.print("Enter your choice (1/2/3): ");
int choice = scanner.nextInt();

Shape shape = null;

switch (choice) {
case 1:
System.out.print("Enter the side length of the square: ");
double squareSide = scanner.nextDouble();
shape = new Square(squareSide);
break;
case 2:
System.out.print("Enter the length of the rectangle: ");
double rectLength = scanner.nextDouble();
System.out.print("Enter the width of the rectangle: ");
double rectWidth = scanner.nextDouble();
shape = new Rectangle(rectLength, rectWidth);
break;
case 3:
System.out.print("Enter the radius of the circle: ");
double circleRadius = scanner.nextDouble();
shape = new Circle(circleRadius);
break;
default:
System.out.println("Invalid choice.");
}

if (shape != null) {
System.out.println("Area of the selected shape: " +
shape.calculateArea());
}

scanner.close();
}
}

C:\Users\Kashish\OneDrive\Desktop>javac AreaCalculators.java

C:\Users\Kashish\OneDrive\Desktop>java AreaCalculators
Choose a shape to calculate its area:
1. Square
2. Rectangle
3. Circle
Enter your choice (1/2/3): 2
Enter the length of the rectangle: 15
Enter the width of the rectangle: 20
Area of the selected shape: 300.0

C:\Users\Kashish\OneDrive\Desktop>3
'3' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\Kashish\OneDrive\Desktop>javac AreaCalculators.java

C:\Users\Kashish\OneDrive\Desktop>java AreaCalculators
Choose a shape to calculate its area:
1. Square
2. Rectangle
3. Circle
Enter your choice (1/2/3): 3
Enter the radius of the circle: 50
Area of the selected shape: 7853.981633974483

C:\Users\Kashish\OneDrive\Desktop>

10.
public class ExceptionHandlingExample {
public static void main(String[] args) {
try {
// Attempt to perform some operations that may throw exceptions
int result = divideByZero(); // Division by zero
String nullString = null; // Null pointer
int[] array = new int[5];
int value = array[10]; // ArrayIndexOutOfBoundsException
} catch (ArithmeticException e) {
// Handle the ArithmeticException
System.out.println("ArithmeticException: " + e.getMessage());
} catch (NullPointerException e) {
// Handle the NullPointerException
System.out.println("NullPointerException: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
// Handle the ArrayIndexOutOfBoundsException
System.out.println("ArrayIndexOutOfBoundsException: " +
e.getMessage());
}
}

public static int divideByZero() {


int numerator = 10;
int denominator = 0;
return numerator / denominator;
}
}

Microsoft Windows [Version 10.0.22621.2506]


(c) Microsoft Corporation. All rights reserved.

C:\Users\Kashish\OneDrive\Desktop>javac ExceptionHandlingexample.java
C:\Users\Kashish\OneDrive\Desktop>java ExceptionHandlingExample
ArithmeticException: / by zero

C:\Users\Kashish\OneDrive\Desktop>

12a
public class ThreadName {
public static void main(String[] args) {
// Create the first thread
Thread thread1 = new Thread(new MyRunnable(), "Thread-1");

// Create the second thread


Thread thread2 = new Thread(new MyRunnable(), "Thread-2");

// Start both threads


thread1.start();
thread2.start();

// Fetch and print the names of the threads


String thread1Name = thread1.getName();
String thread2Name = thread2.getName();

System.out.println("Thread 1 name: " + thread1Name);


System.out.println("Thread 2 name: " + thread2Name);
}
}

class MyRunnable implements Runnable {


@Override
public void run() {
System.out.println("Thread running: " + Thread.currentThread().getName());
}
}

C:\Users\Kashish\OneDrive\Desktop>java ThreadName
Thread 1 name: Thread-1
Thread 2 name: Thread-2
Thread running: Thread-2
Thread running: Thread-1

12b
public class MyThread {

public static void main(String[] args) {


Runnable r = new Runnable1();
Thread t = new Thread(r);
t.start();
Runnable r2 = new Runnable2();
Thread t2 = new Thread(r2);
t2.start();
}
}

class Runnable2 implements Runnable {


public void run() {
for (int i = 0; i < 11; i++) {
if (i % 2 == 1)
System.out.println(i);
}
}
}

class Runnable1 implements Runnable {


public void run() {
for (int i = 0; i < 11; i++) {
if (i % 2 == 0)
System.out.println(i);
}
}
}

C:\Users\Kashish\OneDrive\Desktop>javac MyThread
error: Class names, 'MyThread', are only accepted if annotation processing is
explicitly requested
1 error

C:\Users\Kashish\OneDrive\Desktop>java MyThread
0
2
4
6
8
10
1
3
5
7
9

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

public class RegistrationFormAWT {


public static void main(String[] args) {
Frame frame = new Frame("Registration Form");
frame.setSize(400, 250);
frame.setLayout(new GridLayout(6, 2));

Label firstNameLabel = new Label("First Name:");


TextField firstNameField = new TextField(20);

Label lastNameLabel = new Label("Last Name:");


TextField lastNameField = new TextField(20);

Label emailLabel = new Label("Email:");


TextField emailField = new TextField(20);

Label passwordLabel = new Label("Password:");


TextField passwordField = new TextField(20);
passwordField.setEchoChar('*'); // Set echo character to hide the password

Button submitButton = new Button("Submit");


Button cancelButton = new Button("Cancel");

// Action listener for the Submit button


submitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String firstName = firstNameField.getText();
String lastName = lastNameField.getText();
String email = emailField.getText();
String password = passwordField.getText();

// Perform registration logic here


// For now, we'll just display the entered data
showMessage("Registration Successful\n" +
"First Name: " + firstName + "\n" +
"Last Name: " + lastName + "\n" +
"Email: " + email);
}
});

// Action listener for the Cancel button


cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int choice = showConfirmation("Are you sure you want to cancel
registration?");
if (choice == 0) {
System.exit(0);
}
}
});

frame.add(firstNameLabel);
frame.add(firstNameField);
frame.add(lastNameLabel);
frame.add(lastNameField);
frame.add(emailLabel);
frame.add(emailField);
frame.add(passwordLabel);
frame.add(passwordField);
frame.add(submitButton);
frame.add(cancelButton);

frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});

frame.setVisible(true);
}

// Helper method to display a message dialog


private static void showMessage(String message) {
Dialog messageDialog = new Dialog(new Frame(), "Message", true);
Label label = new Label(message);
messageDialog.add(label);
messageDialog.setSize(300, 100);
messageDialog.setVisible(true);
}

// Helper method to display a confirmation dialog


private static int showConfirmation(String message) {
Dialog confirmDialog = new Dialog(new Frame(), "Confirmation", true);
Label label = new Label(message);
confirmDialog.add(label);

Button yesButton = new Button("Yes");


Button noButton = new Button("No");
confirmDialog.add(yesButton);
confirmDialog.add(noButton);

yesButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
confirmDialog.dispose();
}
});

noButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
confirmDialog.dispose();
}
});

confirmDialog.setLayout(new GridLayout(2, 2));


confirmDialog.setSize(300, 100);
confirmDialog.setVisible(true);

return 0; // Return 0 for 'Yes' (in this example)


}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy