100% found this document useful (1 vote)
26 views

Java Solved Practical Slips

The document contains multiple Java programming tasks, each with code examples and expected outputs. Tasks include displaying characters, copying non-numeric data from files, handling mouse events, checking Armstrong numbers, and calculating averages for cricket players. Each task is presented with its respective Java code and output format.

Uploaded by

Sakshi Takwale
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
26 views

Java Solved Practical Slips

The document contains multiple Java programming tasks, each with code examples and expected outputs. Tasks include displaying characters, copying non-numeric data from files, handling mouse events, checking Armstrong numbers, and calculating averages for cricket players. Each task is presented with its respective Java code and output format.

Uploaded by

Sakshi Takwale
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

SLIP-1

A) Write a ‘java’ program to display characters from ‘A’ to ‘Z’.


Code:-
public class DisplayCharacters {
public static void main(String[] args) {
for (char c = 'A'; c <= 'Z'; c++) {
System.out.print(c + " ");
}
}
}
Output:-
B) Write a ‘java’ program to copy only non-numeric data from one file to
another file.
Code:-
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class NonNumericFileCopy {
public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Usage: java NonNumericFileCopy <sourceFile>
<destinationFile>");
return;
}
String sourceFile = args[0];
String destinationFile = args[1];
try (BufferedReader reader = new BufferedReader(new
FileReader(sourceFile));
BufferedWriter writer = new BufferedWriter(new
FileWriter(destinationFile))) {
String line;
while ((line = reader.readLine()) != null) {
if (!isNumeric(line)) {
writer.write(line);
writer.newLine();
}
}
System.out.println("Non-numeric data has been copied successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
return str != null && str.matches("\\d+");
}
}
Output:-
SLIP-2
A) Write a java program to display all the vowels from a given string.
Code:-
import java.io.*;
public class vowel {
public static void main(String[] args)
throws IOException
{
String str = "AshishSolanki";
str = str.toLowerCase();
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == 'a' || str.charAt(i) == 'e'
|| str.charAt(i) == 'i'
|| str.charAt(i) == 'o'
|| str.charAt(i) == 'u') {
count++;
}
}
System.out.println(
"Total no of vowels in string are: " + count);
}
}
Output:-
B. Design a screen in Java to handle the Mouse Events such as
MOUSE_MOVED and MOUSE_CLICK and display the position of the
Mouse_Click in a TextField.
Code:-
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseListener;
public class MouseEvents {
public static void main(String[] args) {
JFrame frame = new JFrame("Mouse Event Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setLayout(new BorderLayout());
JPanel panel = new JPanel();
panel.setBackground(Color.WHITE);
JTextField positionField = new JTextField("Click position will appear here");
positionField.setEditable(false);
frame.add(panel, BorderLayout.CENTER);
frame.add(positionField, BorderLayout.SOUTH);
panel.addMouseMotionListener(new MouseMotionListener() {
public void mouseDragged(MouseEvent e) {}
public void mouseMoved(MouseEvent e) {}
});
panel.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
positionField.setText("Mouse clicked at: X=" + e.getX() + ", Y=" +
e.getY());
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
});
frame.setVisible(true);
}
}
Output:-
SLIP-3
A. Write a ‘java’ program to check whether given number is Armstrong or
not. (Use static keyword).
Code:-
import java.util.Scanner;
public class ArmstrongNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number:");
int number = scanner.nextInt();
scanner.close();
if (isArmstrong(number)) {
System.out.println(number + " is an Armstrong number.");
} else {
System.out.println(number + " is not an Armstrong number.");
}
}
public static boolean isArmstrong(int number) {
int originalNumber = number;
int numberOfDigits = String.valueOf(number).length();
int sum = 0;
while (number > 0) {
int digit = number % 10;
sum += Math.pow(digit, numberOfDigits);
number /= 10;
}
return sum == originalNumber;
}
}
Output:-
B. Define an abstract class Shape with abstract methods area () and
volume (). Derive abstract class Shape into two classes Cone and
Cylinder. Write a java Program to calculate area and volume of Cone and
Cylinder. (Use Super Keyword.)
Code:-
abstract class Shape {
abstract double area();
abstract double volume();
}
class Cone extends Shape {
private double radius;
private double height;
public Cone(double radius, double height) {
this.radius = radius;
this.height = height;
}
double area() {
return Math.PI * radius * (radius + Math.sqrt(height * height + radius *
radius));
}
double volume() {
return (Math.PI * radius * radius * height) / 3;
}
}
class Cylinder extends Shape {
private double radius;
private double height;
public Cylinder(double radius, double height) {
this.radius = radius;
this.height = height;
}
double area() {
return 2 * Math.PI * radius * (radius + height);
}
double volume() {
return Math.PI * radius * radius * height;
}
}
public class ShapeTest {
public static void main(String[] args) {
Shape cone = new Cone(5, 10);
Shape cylinder = new Cylinder(5, 10);
System.out.println("Cone:");
System.out.println("Area: " + cone.area());
System.out.println("Volume: " + cone.volume());
System.out.println("\nCylinder:");
System.out.println("Area: " + cylinder.area());
System.out.println("Volume: " + cylinder.volume());
}
}
Output:-
SLIP-4
A. Write a java program to display alternate character from a given string.
Code:-
import java.util.Scanner;
public class AlternateCharacters {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a string:");
String input = scanner.nextLine();
scanner.close();
displayAlternateCharacters(input);
}
private static void displayAlternateCharacters(String input) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < input.length(); i += 2) {
result.append(input.charAt(i));
}
System.out.println("Alternate characters: " + result.toString());
}
}
Output:-
B. Write a java program using Applet to implement a simple arithmetic
calculator.
Code:-
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SimpleCalculator {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new CalculatorFrame().setVisible(true));
}
}
class CalculatorFrame extends JFrame {
private final JTextField num1Field;
private final JTextField num2Field;
private final JTextField resultField;
public CalculatorFrame() {
setTitle("Simple Calculator");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(5, 2, 10, 10));
setLocationRelativeTo(null);
num1Field = new JTextField();
num2Field = new JTextField();
resultField = new JTextField();
resultField.setEditable(false);
JButton addButton = new JButton("Add");
JButton subButton = new JButton("Subtract");
JButton mulButton = new JButton("Multiply");
JButton divButton = new JButton("Divide");
addButton.addActionListener(new CalculatorActionListener());
subButton.addActionListener(new CalculatorActionListener());
mulButton.addActionListener(new CalculatorActionListener());
divButton.addActionListener(new CalculatorActionListener());
add(new JLabel("Number 1:"));
add(num1Field);
add(new JLabel("Number 2:"));
add(num2Field);
add(addButton);
add(subButton);
add(mulButton);
add(divButton);
add(new JLabel("Result:"));
add(resultField);
}
private class CalculatorActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
double number1 = Double.parseDouble(num1Field.getText());
double number2 = Double.parseDouble(num2Field.getText());
double result = 0;
switch (e.getActionCommand()) {
case "Add":
result = number1 + number2;
break;
case "Subtract":
result = number1 - number2;
break;
case "Multiply":
result = number1 * number2;
break;
case "Divide":
if (number2 != 0) {
result = number1 / number2;
} else {
resultField.setText("Error");
return;
}
break;
}
resultField.setText(String.valueOf(result));
} catch (NumberFormatException ex) {
resultField.setText("Invalid Input");
}
}
}
}
Output:-
SLIP-5
A. Write a java program to display following pattern.
5
345
2345
12345
Code:-
public class NumberPattern {
public static void main(String[] args) {
int n = 5;
for (int i = n; i >= 1; i--) {
for (int j = i; j <= n; j++) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
Output:-
B. Write a java program to accept list of file names through command line.
Delete the files having extension .txt. Display name, location and size of
remaining files.
Code:-
import java.io.File;
import java.io.IOException;
public class FileHandler {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("No file names provided. Please provide a list of file
names.");
return; }
for (String fileName : args) {
File file = new File(fileName);
if (!file.exists()) {
System.out.println("File not found: " + fileName);
continue; }
if (fileName.toLowerCase().endsWith(".txt")) {
if (file.delete()) {
System.out.println("Deleted file: " + fileName);
} else {
System.out.println("Failed to delete file: " + fileName); }
continue; }
System.out.println("File Name: " + file.getName());
System.out.println("Location: " + file.getAbsolutePath());
System.out.println("Size: " + file.length() + " bytes");
System.out.println(); } }}
Output:-
SLIP-6
A. Write a java program to accept a number from user, if it zero then throw
user defined Exception “Number Is Zero”, otherwise calculate the sum of
first and last digit of that number. (Use static keyword).
Code:-
import java.util.Scanner;
class NumberIsZeroException extends Exception {
public NumberIsZeroException(String message) {
super(message); } }
public class NumberProcessing {
public static int calculateSumOfFirstAndLastDigit(int number) throws
NumberIsZeroException {
if (number == 0) {
throw new NumberIsZeroException("Number Is Zero");}
String numberStr = Integer.toString(Math.abs(number));
char firstDigitChar = numberStr.charAt(0);
char lastDigitChar = numberStr.charAt(numberStr.length() - 1);
int firstDigit = Character.getNumericValue(firstDigitChar);
int lastDigit = Character.getNumericValue(lastDigitChar);
return firstDigit + lastDigit; }
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
try {
int sum = calculateSumOfFirstAndLastDigit(number);
System.out.println("Sum of the first and last digit is: " + sum); } catch
(NumberIsZeroException e) { System.out.println(e.getMessage()); }
scanner.close(); } }
Output:-
B. Write a java program to display transpose of a given matrix.
Code:-
import java.util.Scanner;
public class MatrixTranspose {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of rows and columns of the
matrix:");
int rows = scanner.nextInt();
int columns = scanner.nextInt();
int[][] matrix = new int[rows][columns];
int[][] transpose = new int[columns][rows];
System.out.println("Enter the elements of the matrix:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
matrix[i][j] = scanner.nextInt();
}
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
transpose[j][i] = matrix[i][j];
}
}
System.out.println("Original Matrix:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
System.out.println("Transpose Matrix:");
for (int i = 0; i < columns; i++) {
for (int j = 0; j < rows; j++) {
System.out.print(transpose[i][j] + " ");
}
System.out.println();
}
scanner.close();
}
}
Output:-
SLIP-7
A. Write a java program to display Label with text “Dr. D Y Patil College”,
background color Red and font size 20 on the frame.
Code:-
import javax.swing.*;
import java.awt.*;
public class LabelDisplay {
public static void main(String[] args) {
JFrame frame = new JFrame("Label Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 200);
JLabel label = new JLabel("Dr. D Y Patil College", JLabel.CENTER);
label.setOpaque(true);
label.setBackground(Color.RED);
label.setFont(new Font("Arial", Font.PLAIN, 20));
label.setForeground(Color.WHITE);
frame.add(label);
frame.setVisible(true);
}
}
Output:-
B. Write a java program to accept details of ‘n’ cricket player (pid, pname,
totalRuns, InningsPlayed, NotOuttimes). Calculate the average of all the
players. Display the details of player having maximum average. (Use Array
of Object).
Code:-
import java.util.Scanner;
class CricketPlayer {
int pid;
String pname;
int totalRuns;
int inningsPlayed;
int notOutTimes;
public CricketPlayer(int pid, String pname, int totalRuns, int inningsPlayed,
int notOutTimes) {
this.pid = pid;
this.pname = pname;
this.totalRuns = totalRuns;
this.inningsPlayed = inningsPlayed;
this.notOutTimes = notOutTimes;}
public double calculateAverage() {
if (inningsPlayed == 0) {
return 0; }
return (double) totalRuns / inningsPlayed; }
public String getDetails() {
return "PID: " + pid + ", Name: " + pname + ", Total Runs: " + totalRuns +
", Innings Played: " + inningsPlayed + ", Not Out Times: " + notOutTimes
+ ", Average: " + String.format("%.2f", calculateAverage()); } }
public class CricketPlayerDetails {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of players:");
int n = scanner.nextInt();
CricketPlayer[] players = new CricketPlayer[n];
for (int i = 0; i < n; i++) {
System.out.println("Enter details for player " + (i + 1) + ":");
System.out.print("PID: ");
int pid = scanner.nextInt();
scanner.nextLine();
System.out.print("Name: ");
String pname = scanner.nextLine();
System.out.print("Total Runs: ");
int totalRuns = scanner.nextInt();
System.out.print("Innings Played: ");
int inningsPlayed = scanner.nextInt();
System.out.print("Not Out Times: ");
int notOutTimes = scanner.nextInt();
players[i] = new CricketPlayer(pid, pname, totalRuns, inningsPlayed,
notOutTimes); }
CricketPlayer maxAveragePlayer = players[0];
for (CricketPlayer player : players) {
if (player.calculateAverage() > maxAveragePlayer.calculateAverage()) {
maxAveragePlayer = player; } }
System.out.println("\nPlayer with maximum average:");
System.out.println(maxAveragePlayer.getDetails());
scanner.close();
}
}
Output:-
SLIP-8
A. Define an Interface Shape with abstract method area(). Write a java
program to calculate an area of Circle and Sphere.(use final keyword)
Code:-
public class AreaCalculator {
public static double calculateArea(double radius) {
return Math.PI * radius * radius;
}
public static double calculateArea(double length, double width) {
return length * width;
}
public static double calculateAreas(double base, double height) {
return 0.5 * base * height;
}
public static void main(String[] args) {
double circleRadius = 7.5;
double rectangleLength = 10.0;
double rectangleWidth = 5.0;
double triangleBase = 6.0;
double triangleHeight = 8.0;
System.out.println("Area of Circle with radius " + circleRadius + ": " +
calculateArea(circleRadius));
System.out.println("Area of Rectangle with length " + rectangleLength + "
and width " + rectangleWidth + ": " + calculateArea(rectangleLength,
rectangleWidth));
System.out.println("Area of Triangle with base " + triangleBase + " and
height " + triangleHeight + ": " + calculateArea(triangleBase, triangleHeight));
}
}
Output:-
B. Write a java program to display the files having extension .txt from a
given directory.
Code:-
import java.io.File;
import java.io.FilenameFilter;
public class ListTextFiles {
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: java ListTextFiles <directory-path>");
return; }
String directoryPath = args[0];
File directory = new File(directoryPath);
if (!directory.isDirectory()) {
System.out.println("The provided path is not a directory.");
return; }
FilenameFilter txtFileFilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".txt"); } };
File[] txtFiles = directory.listFiles(txtFileFilter);
if (txtFiles == null || txtFiles.length == 0) {
System.out.println("No .txt files found in the directory.");
} else {
System.out.println("List of .txt files in the directory:");
for (File file : txtFiles) {
System.out.println(file.getName());} } } }
Output:-
SLIP-9
A. Write a java Program to display following pattern:
1
01
010
1010
Code:-
public class PatternDisplay {
public static void main(String[] args) {
int rows = 4;
for (int i = 0; i < rows; i++) {
for (int j = 0; j <= i; j++) {
System.out.print((i + j) % 2 + " ");
}
System.out.println();
}
}
}

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:-

You might also like