Java Solved Practical Slips
Java Solved Practical Slips
Output:-
B. Write a java program to validate PAN number and Mobile Number. If it is
invalid then throw user defined Exception “Invalid Data”, otherwise
display it
Code:-
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
class InvalidDataException extends Exception {
public InvalidDataException(String message) {
super(message);
}
}
public class DataValidator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter PAN number: ");
String pan = scanner.nextLine();
System.out.print("Enter Mobile number: ");
String mobileNumber = scanner.nextLine();
try {
validatePAN(pan);
validateMobileNumber(mobileNumber);
System.out.println("PAN Number: " + pan);
System.out.println("Mobile Number: " + mobileNumber);
} catch (InvalidDataException e) {
System.out.println(e.getMessage());
}
}
private static void validatePAN(String pan) throws InvalidDataException {
String panRegex = "[A-Z]{5}[0-9]{4}[A-Z]{1}";
Pattern pattern = Pattern.compile(panRegex);
Matcher matcher = pattern.matcher(pan);
if (!matcher.matches()) {
throw new InvalidDataException("Invalid PAN number. It should be in
the format: AAAAA9999A");
}
}
private static void validateMobileNumber(String mobileNumber) throws
InvalidDataException {
String mobileRegex = "\\d{10}";
Pattern pattern = Pattern.compile(mobileRegex);
Matcher matcher = pattern.matcher(mobileNumber);
if (!matcher.matches()) {
throw new InvalidDataException("Invalid Mobile number. It should be
exactly 10 digits.");
}
}
}
Output:-
SLIP-10
A. Write a java program to count the frequency of each character in a given
string.
Code:-
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class CharacterFrequencyCounter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a string:");
String input = scanner.nextLine();
scanner.close();
Map<Character, Integer> frequencyMap =
countCharacterFrequency(input);
System.out.println("Character frequencies:");
for (Map.Entry<Character, Integer> entry : frequencyMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue()); } }
public static Map<Character, Integer> countCharacterFrequency(String str)
{ Map<Character, Integer> frequencyMap = new HashMap<>();
char[] characters = str.toCharArray();
for (char c : characters) {
if (frequencyMap.containsKey(c)) {
frequencyMap.put(c, frequencyMap.get(c) + 1);
} else { frequencyMap.put(c, 1); } }
return frequencyMap; } }
Output:-
B. Write a java program for Compound Interest Calculator.
Code:-
import java.util.Scanner;
public class CompoundInterestCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the principal amount (P): ");
double principal = scanner.nextDouble();
System.out.print("Enter the annual interest rate (r) in percentage: ");
double annualInterestRate = scanner.nextDouble();
System.out.print("Enter the number of times interest is compounded per
year (n): ");
int compoundsPerYear = scanner.nextInt();
System.out.print("Enter the number of years (t): ");
int years = scanner.nextInt();
scanner.close();
double compoundInterest = calculateCompoundInterest(principal,
annualInterestRate, compoundsPerYear, years);
System.out.printf("The compound interest is: %.2f%n",
compoundInterest); }
public static double calculateCompoundInterest(double principal, double
annualInterestRate, int compoundsPerYear, int years) {
double rate = annualInterestRate / 100;
double amount = principal * Math.pow((1 + rate / compoundsPerYear),
compoundsPerYear * years);
return amount - principal;
}
}
Output:-
SLIP-11
A. Write a menu driven java program using command line arguments for
the following: 1. Addition 2. Subtraction 3. Multiplication 4. Division.
Code:-
public class Calculator {
public static void main(String[] args) {
if (args.length < 3) {
System.out.println("Usage: java Calculator <operation> <num1>
<num2>");
System.out.println("Operations: add, subtract, multiply, divide");
return;
}
String operation = args[0].toLowerCase();
double num1, num2;
try {
num1 = Double.parseDouble(args[1]);
num2 = Double.parseDouble(args[2]);
} catch (NumberFormatException e) {
System.out.println("Invalid number format. Please provide valid
numbers.");
return;
}
switch (operation) {
case "add":
System.out.println("Result: " + (num1 + num2));
break;
case "subtract":
System.out.println("Result: " + (num1 - num2));
break;
case "multiply":
System.out.println("Result: " + (num1 * num2));
break;
case "divide":
if (num2 == 0) {
System.out.println("Error: Division by zero is not allowed.");
} else {
System.out.println("Result: " + (num1 / num2));
}
break;
default:
System.out.println("Invalid operation. Please use add, subtract,
multiply, or divide.");
break;
}
}
}
Output:-
B. Write an applet application to display Table lamp. The color of lamp
should get change randomly.
Code:-
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TableLampSwing extends JPanel {
private Color lampColor = Color.YELLOW;
public TableLampSwing() {
Timer timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
lampColor = new Color((float) Math.random(), (float) Math.random(),
(float) Math.random());
repaint();
}
});
timer.start();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.BLACK);
g2d.fillRect(100, 250, 100, 20);
g2d.setColor(Color.BLACK);
g2d.fillRect(140, 160, 20, 90);
g2d.setColor(lampColor);
g2d.fillArc(85, 100, 130, 70, 0, 180);
g2d.setColor(Color.BLACK);
g2d.drawArc(85, 100, 130, 70, 0, 180);
g2d.setColor(Color.YELLOW);
g2d.fillOval(135, 145, 40, 30);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Table Lamp");
TableLampSwing lampPanel = new TableLampSwing();
frame.add(lampPanel);
frame.setSize(300, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Output:-
SLIP-12
A. Write a java program to display each String in reverse order from a
String array.
Code:-
public class ReverseStringArray {
public static void main(String[] args) {
String[] stringArray = {"hello", "world", "java", "programming"};
for (String str : stringArray) {
String reversed = reverseString(str);
System.out.println("Original: " + str + " | Reversed: " + reversed);
}
}
public static String reverseString(String str) {
StringBuilder sb = new StringBuilder(str);
sb.reverse();
return sb.toString();
}
}
Output:-
B. Write a java program to display multiplication table of a given number
into the List box by clicking on button.
Code:-
import java.util.Scanner;
public class MultiplicationTable
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print("Enter number:");
int n=s.nextInt();
for(int i=1; i <= 10; i++)
{
System.out.println(n+" * "+i+" = "+n*i);
}
}
}
Output:-
SLIP-13
A. Write a java program to accept ‘n’ integers from the user & store them in
an ArrayList collection. Display the elements of ArrayList collection in
reverse order.
Code:-
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class ReverseArrayList {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Integer> numbers = new ArrayList<>();
System.out.print("Enter the number of integers: ");
int n = scanner.nextInt();
System.out.println("Enter " + n + " integers:");
for (int i = 0; i < n; i++) {
int number = scanner.nextInt();
numbers.add(number); }
Collections.reverse(numbers);
System.out.println("The elements in reverse order are:");
for (int num : numbers) {
System.out.println(num); }
scanner.close(); }
}
Output:-
B. Write a java program that asks the user name, and then greets the user
by name. Before outputting the user's name, convert it to upper case
letters. For example, if the user's name is Raj, then the program should
respond "Hello, RAJ, nice to meet you!
Code:-
import java.util.Scanner;
public class GreetingUser {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter your name: ");
String name = scanner.nextLine();
String upperCaseName = name.toUpperCase();
System.out.println("Hello, " + upperCaseName + ", nice to meet you!");
scanner.close();
}
}
Output:-
SLIP-14
A. Write a Java program to calculate power of a number using recursion.
Code:-
import java.util.Scanner;
public class PowerUsingRecursion {
public static int power(int base, int exponent) {
if (exponent == 0) {
return 1;
}
else {
return base * power(base, exponent - 1);
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the base: ");
int base = scanner.nextInt();
System.out.print("Enter the exponent: ");
int exponent = scanner.nextInt();
int result = power(base, exponent);
System.out.println(base + " raised to the power of " + exponent + " is " +
result);
scanner.close();
}
}
Output:-
B. Write a java program to accept the details of employee (Eno, EName,
Sal) and display it on next frame using appropriate event
Code:-
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class EmployeeDetailsApp {
public static void main(String[] args) {
JFrame inputFrame = new JFrame("Employee Input");
inputFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
inputFrame.setSize(300, 200);
inputFrame.setLayout(new GridLayout(4, 2, 10, 10));
JLabel enoLabel = new JLabel("Employee Number:");
JTextField enoField = new JTextField();
JLabel nameLabel = new JLabel("Employee Name:");
JTextField nameField = new JTextField();
JLabel salLabel = new JLabel("Salary:");
JTextField salField = new JTextField();
JButton submitButton = new JButton("Submit");
inputFrame.add(enoLabel);
inputFrame.add(enoField);
inputFrame.add(nameLabel);
inputFrame.add(nameField);
inputFrame.add(salLabel);
inputFrame.add(salField);
inputFrame.add(new JLabel());
inputFrame.add(submitButton);
submitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String eno = enoField.getText();
String name = nameField.getText();
String salary = salField.getText();
double sal;
try {
sal = Double.parseDouble(salary);
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(inputFrame, "Invalid salary.
Please enter a valid number.");
return;
}
JFrame detailsFrame = new JFrame("Employee Details");
detailsFrame.setSize(300, 200);
detailsFrame.setLayout(new GridLayout(4, 2, 10, 10));
detailsFrame.add(new JLabel("Employee Number:"));
detailsFrame.add(new JLabel(eno));
detailsFrame.add(new JLabel("Employee Name:"));
detailsFrame.add(new JLabel(name));
detailsFrame.add(new JLabel("Salary:"));
detailsFrame.add(new JLabel(String.format("%.2f", sal)));
detailsFrame.setVisible(true);
}
});
inputFrame.setVisible(true);
}
}
Output:-
SLIP-15
A. Write a java program to search given name into the array, if it is found
then display its index otherwise display appropriate message.
Code:-
import java.util.Scanner;
public class NameSearch {
public static void main(String[] args) {
String[] names = {"Ashish", "Bhushan", "Ronit", "Animesh", "Satyajit"};
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the name to search: ");
String searchName = scanner.nextLine();
int index = -1;
for (int i = 0; i < names.length; i++) {
if (names[i].equalsIgnoreCase(searchName)) {
index = i;
break;
}
}
if (index != -1) {
System.out.println("Name found at index: " + index);
} else {
System.out.println("Name not found in the array.");
}
scanner.close();
}
}
Output:-
B. Write an applet application to display smiley face.
Code:-
import javax.swing.*;
import java.awt.*;
public class SmileyFaceSwing extends JPanel {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.YELLOW);
g.fillOval(50, 50, 200, 200);
g.setColor(Color.BLACK);
g.fillOval(100, 100, 30, 30);
g.fillOval(170, 100, 30, 30);
g.setColor(Color.BLACK);
g.drawArc(100, 150, 100, 50, 0, -180);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Smiley Face");
SmileyFaceSwing panel = new SmileyFaceSwing();
frame.add(panel);
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
Output:-