SlideShare a Scribd company logo
1 of 20
Download to read offline
1
1
Slip 1:
Q 1
public class Slip1q1 {
public static void main(String[] args) {
for(char c='A';c<='Z';c++){
System.out.print(c+" ");
}
System.out.println();
for(char c='a';c<='z';c++){
System.out.print(c+" ");
}
}
}
Q2
import java.io.*;
public class Slip1q2 {
public static void main(String[] args) throws IOException {
System.out.println("reading file...");
FileReader fileReader = new FileReader("Slip1/src/sourcefile1q2.txt");
// enter your source file location
FileWriter fileWriter = new FileWriter("Slip1/src/destinationfile1Q2.txt");
// enter your destination file location
int data = fileReader.read();
System.out.println("writing file...");
while (data != -1){
String content = String.valueOf((char)data);
if(Character.isAlphabetic(data)) {
fileWriter.append(content);
}else if(content.equals(" ")){
fileWriter.append(" ");
}
data = fileReader.read();
}
System.out.println("nCOPY FINISHED SUCCESSFULLY...");
fileWriter.close();
fileReader.close();
}
}
2
2
SLIP 2
Q1
import java.util.Scanner;
public class Slip2q1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a string to find vowels on it.");
String user_string = scanner.nextLine();
scanner.close();
int vowel_count = 0;
for(int i=0;i<user_string.length();i++){
if(user_string.charAt(i)=='a' ||user_string.charAt(i)=='e'
||user_string.charAt(i)=='i' ||user_string.charAt(i)=='o'
||user_string.charAt(i)=='u' ||user_string.charAt(i)=='A'
||user_string.charAt(i)=='E' ||user_string.charAt(i)=='I'
||user_string.charAt(i)=='O' ||user_string.charAt(i)=='U'){
vowel_count++;
System.out.println("Vowel found ("+user_string.charAt(i)+") at index "+i);
}
}
if (vowel_count == 0){
System.out.println("Vowel not found in given string.");
}
}
}
Q2
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Slip2q2 {
public static void main(String[] args) {
new MyFrame("Mouse Events");
}
}
class MyFrame extends JFrame {
TextField click_text_field, mouse_move_field;
Label click_text_label, mouse_move_label;
int x,y;
Panel panel;
MyFrame(String title) {
super(title);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
3
3
setLayout(new FlowLayout());
panel =new Panel();
panel.setLayout(new GridLayout(2,2,5,5));
click_text_label = new Label("Co-ordinates of clicking");
mouse_move_label = new Label("Co-ordinates of movement");
click_text_field=new TextField(20);
mouse_move_field =new TextField(20);
panel.add(click_text_label);
panel.add(click_text_field);
panel.add(mouse_move_label);
panel.add(mouse_move_field);
add(panel);
addMouseListener(new MyClick());
addMouseMotionListener(new MyMove());
setSize(500,500);
setVisible(true);
}
class MyClick extends MouseAdapter {
public void mouseClicked(MouseEvent me) {
x=me.getX();
y=me.getY();
click_text_field.setText("X="+x+" Y="+y);
}
}
class MyMove extends MouseMotionAdapter
{
public void mouseMoved(MouseEvent me)
{
x=me.getX();
y=me.getY();
mouse_move_field.setText("X="+ x +" Y="+y);
}
}
}
4
4
SLIP 3
Q1
import java.util.Scanner;
public class Slip3Q1 {
static boolean is_armstrong(int n){
int temp,last,digits=0,sum=0;
temp = n;
while (temp>0){
temp=temp/10;
digits++;
}
temp = n;
while (temp>0){
last = temp%10;
sum+=Math.pow(last,digits);
temp=temp/10;
}
return n == sum;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number to check armstrong : ");
int number = scanner.nextInt();
scanner.close();
if (is_armstrong(number)){
System.out.println(number+" is a armstrong number.");
}
else {
System.out.println(number+" is not a armstrong number.");
}
}
}
Q2
import java.util.Scanner;
public class Slip3q2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Shape shape;
System.out.println("""
ENTER YOUR CHOICE
1. Cone
2. Cylinder""");
int choice = scanner.nextInt();
5
5
if (choice==1){
System.out.println("Enter radius");
int radius = scanner.nextInt();
System.out.println("Enter height");
int height = scanner.nextInt();
shape=new Cone(radius,height);
shape.area();
shape.volume();
}else if (choice==2){
System.out.println("Enter radius");
int radius = scanner.nextInt();
System.out.println("Enter height");
int height = scanner.nextInt();
shape=new Cylinder(radius,height);
shape.area();
shape.volume();
}else {
System.out.println("invalid input");
}
}
abstract static class Shape{
abstract void area();
abstract void volume();
}
static class Cone extends Shape {
int radius,height;
Cone(int radius,int height){
this.radius=radius;
this.height=height;
}
void area(){
float slant_height=(height*height)+(radius*radius);
float area = (float)(Math.PI*radius*(radius+Math.sqrt(slant_height)));
System.out.println("Area of Cone : "+area);
}
void volume(){
float volume = (float)(Math.PI*radius*radius*(height/3));
System.out.println("Volume of cone : "+volume);
}
}
static class Cylinder extends Shape {
int radius, height;
Cylinder(int r,int h){
radius =r;
height =h;
}
public void area(){
float area=(float)((2*Math.PI* radius * height)+(2*Math.PI* radius * radius));
System.out.println("Area of Cylinder : "+area);
}
6
6
public void volume(){
float volume=(float)(Math.PI* radius * radius * height);
System.out.println("Volume of Cylinder : "+volume);
}
}
}
7
7
SLIP 5
Q1
public class pattern {
public static void main(String[] args) {
int n=5;
for (int i=n;i>0;i--){
for (int j=i;j<=n;j++){
System.out.print(j+" ");
}
System.out.println();
}
}
}
Q2
import java.io.*;
class Slip12
{
public static void main(String args[]) throws Exception
{
for(int i=0;i<args.length;i++)
{
File file=new File(args[i]);
if(file.isFile())
{
String name = file.getName();
if(name.endsWith(".txt"))
{
file.delete();
System.out.println("file is deleted " + file);
}
else
{
System.out.println(name + " "+file.length()+" bytes");
}
}
else
{
System.out.println(args[i]+ "is not a file");
}
}
}
}
8
8
SLIP 6
Q1
import java.util.*;
class ZeroException extends Exception
{
ZeroException()
{
super("Number is 0");
}
}
class Slip19
{
static int n;
public static void main(String args[])
{
int i,rem,sum=0;
try
{
Scanner sr=new Scanner(System.in);
n=sr.nextInt();
if(n==0)
{
throw new ZeroException();
}
else
{
rem=n%10;
sum=sum+rem;
if(n>9)
{
while(n>0)
{
rem=n%10;
n=n/10;
}
sum=sum+rem;
}
System.out.println("Sum is: "+sum);
}
}
catch(ZeroException e)
{
System.out.println(e);
}
}
}
Q2
import java.util.Scanner;
9
9
public class Transposematrix {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
System.out.print("Enter rows of matrix : ");
int row=sc.nextInt();
System.out.print("Enter column of matrix : ");
int col=sc.nextInt();
int[][] matrix = new int[row][col];
//create and insert value
for (int i=0;i<row;i++){
for(int j=0;j<col;j++){
System.out.print("element at index ["+i+"]["+j+"] :");
matrix[i][j]=sc.nextInt();
}
}
sc.close();
//print value of matrix
System.out.println("nReal matrix :-n");
for (int i=0;i<row;i++){
for(int j=0;j<col;j++){
System.out.print(matrix[i][j]+" ");
}
System.out.println();
}
System.out.println("nTranspose of matrix :-n");
for (int i=0;i<row;i++){
for(int j=0;j<col;j++){
System.out.print(matrix[j][i]+" ");
}
System.out.println();
}
}
}
10
10
SLIP 7
Q1
import java.awt.*;
class Slip7 extends Frame
{
Slip7()
{
Label l=new Label("Dr. D Y Patil College");
Font f=new Font("Georgia",Font.BOLD,40);
l.setFont(f);
setForeground(Color.blue);
setBackground(Color.red);
add(l);
setLayout(new FlowLayout());
setSize(200,200);
setVisible(true);
}
public static void main(String arg[])
{
new Slip7();
}
}
Q2
import java.io.*;
import java.util.Scanner;
11
11
class CricketPlayer1 {
int pid;
String pname;
int totalRuns;
int inningsPlayed;
int notOutTimes;
double average;
CricketPlayer1(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;
this.average = (double) totalRuns / (inningsPlayed - notOutTimes);
}
}
public class CricketPlayer {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of cricket players: ");
int n = scanner.nextInt();
12
12
CricketPlayer1[] players = new CricketPlayer1[n];
for (int i = 0; i < n; i++) {
System.out.println("nEnter details for player " + (i + 1) + ":");
System.out.print("Player ID: ");
int pid = scanner.nextInt();
scanner.nextLine(); // Consume the newline
System.out.print("Player 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 CricketPlayer1(pid, pname, totalRuns, inningsPlayed,
notOutTimes);
}
double maxAverage = 0;
int maxAverageIndex = 0;
for (int i = 0; i < n; i++) {
if (players[i].average > maxAverage) {
13
13
maxAverage = players[i].average;
maxAverageIndex = i;
}
}
System.out.println("nPlayer with the maximum average:");
System.out.println("Player ID: " + players[maxAverageIndex].pid);
System.out.println("Player Name: " + players[maxAverageIndex].pname);
System.out.println("Average: " + players[maxAverageIndex].average);
scanner.close();
}
}
14
14
SLIP 8
Q1
import java.util.Scanner;
interface Shape{
void area();
}
class Circle implements Shape{
final float PI=3.14f;
float areacircle,radius;
Scanner s=new Scanner(System.in);
void accept(){
System.out.print("Enter the Radius of circle : ");
radius=s.nextFloat();
}
public void area(){
areacircle=PI*radius*radius;
}
public void show()
{
System.out.println("Area of circle is : "+areacircle);
}
}
class Sphere implements Shape{
final float PI=3.14f;
float areasphere,radius;
Scanner s=new Scanner(System.in);
void accept(){
System.out.print("Enter the Radius of sphere : ");
radius=s.nextFloat();
}
public void area(){
areasphere=4*PI*radius*radius;
}
public void show(){
System.out.println("Area of Sphere is : "+areasphere);
}
}
class InterfaceCircleSphere
{
public static void main(String args[]){
Circle s1=new Circle();
s1.accept();
s1.area();
s1.show();
Sphere s2=new Sphere();
s2.accept();
s2.area();
15
15
s2.show();
}
}
Q2
import java.io.File;
public class ListTxtFiles {
public static void main(String[] args) {
// Specify the directory path where you want to search for .txt files
String directoryPath = "C:/Program Files/Java/jdk1.7.0_80/bin"; // Replace with
your directory path
File directory = new File(directoryPath);
if (directory.exists() && directory.isDirectory()) {
File[] files = directory.listFiles();
if (files != null) {
System.out.println("List of .txt files in the directory:");
for (File file : files) {
if (file.isFile() && file.getName().toLowerCase().endsWith(".txt")) {
System.out.println(file.getName());
}
}
} else {
16
16
System.out.println("No files found in the directory.");
}
} else {
System.out.println("The specified directory does not exist or is not a
directory.");
}
}
}
17
17
SLIP 9
Q1
public class Pattern1 {
public static void main(String[] args) {
int num = 4;
for (int i=0;i<num;i++){
for(int j=0;j<=i;j++){
if (i<2){
if ((i+j)%2==0){
System.out.print("1 ");
}else{
System.out.print("0 ");
}
}else{
if ((i+j)%2==0){
System.out.print("0 ");
}else{
System.out.print("1 ");
}
}
}System.out.println();
}
}
}
Q2
class InvalidDataException extends Exception {
public InvalidDataException(String message) {
super(message);
}
}
public class DataValidator {
public static void main(String[] args) {
try {
String panNumber = "ABC12"; // Replace with the PAN number to validate
String mobileNumber = "1234567890"; // Replace with the mobile number to
validate
18
18
validatePAN(panNumber);
validateMobileNumber(mobileNumber);
System.out.println("Valid PAN Number: " + panNumber);
System.out.println("Valid Mobile Number: " + mobileNumber);
} catch (InvalidDataException e) {
System.out.println("Error: " + e.getMessage());
}
}
public static void validatePAN(String pan) throws InvalidDataException {
if (pan.matches("[A-Z]{5}[0-9]{4}[A-Z]{1}")) {
// PAN is valid
} else {
throw new InvalidDataException("Invalid PAN Number");
}
}
public static void validateMobileNumber(String mobileNumber) throws
InvalidDataException {
if (mobileNumber.matches("[0-9]{10}")) {
// Mobile number is valid
} else {
throw new InvalidDataException("Invalid Mobile Number");
}
}
}
19
19
SLIP 13
Q1
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class arrayList {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
System.out.print("enter limit of array : ");
int num=sc.nextInt();
ArrayList<String> alist=new ArrayList<>(num);
for(int i=0;i<num;i++){
System.out.println("Enter "+i+" Element of ArrayList :");
String elmt=sc.next();
alist.add(elmt);
}
sc.close();
System.out.println("Orignal list :"+alist);
Collections.reverse(alist);
System.out.println("Reverse of a ArrayList is :"+alist);
}
}
Q2
import java.util.Scanner;
import java.io.*;
public class GreetUser {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String userName = scanner.nextLine();
// Convert the user's name to uppercase
String upperCaseName = userName.toUpperCase();
20
20
System.out.println("Hello, " + upperCaseName + ", nice to meet you!");
scanner.close();
}
}
21
21
SLIP 16
Q1
import java.io.*;
public class SumOfDigits {
public static void main(String[] args) {
int number = 123; // Change this to the number you want to calculate the sum for
int sum = calculateSumOfDigits(number);
System.out.println("The sum of digits in " + number + " is: " + sum);
}
public static int calculateSumOfDigits(int num) {
if (num == 0) {
return 0; // Base case: If the number is 0, the sum is 0
} else {
// Calculate the sum of digits for the remaining part of the number
int lastDigit = num % 10; // Get the last digit
int remainingNumber = num / 10; // Remove the last digit
return lastDigit + calculateSumOfDigits(remainingNumber); // Recursive call
}
}
}
Q2
import java.io.*;
import java.util.Scanner;
public class EmployeeSort
22
22
{
static class Employee
{
String name;
Employee(String name)
{
this.name = name;
}
static void sortEmployeesByName(Employee[] employees)
{
for (int i = 0; i < employees.length; i++)
{
for (int j = i + 1; j < employees.length; j++)
{
if (employees[i].name.compareTo(employees[j].name) > 0)
{
Employee temp = employees[i];
employees[i] = employees[j];
employees[j] = temp;
}
}
}
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of employees (n): ");
int n = scanner.nextInt();
scanner.nextLine(); // Consume the newline character
Employee[] employees = new Employee[n];
// Accept employee names from the user
for (int i = 0; i < n; i++) {
System.out.print("Enter the name of employee " + (i + 1) + ": ");
String name = scanner.nextLine();
employees[i] = new Employee(name);
}
// Sort the employee names in ascending order using a static method
Employee.sortEmployeesByName(employees);
// Display the sorted employee names
23
23
System.out.println("Sorted Employee Names:");
for (int i = 0; i < n; i++) {
System.out.println(employees[i].name);
}
scanner.close();
}
}
24
24
SLIP 17
Q1
import java.util.ArrayList;
import java.io.*;
public class ArmstrongNumbers {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Please provide some numbers as command-line
arguments.");
return;
}
int n = args.length;
int[] numbers = new int[n];
for (int i = 0; i < n; i++) {
try {
numbers[i] = Integer.parseInt(args[i]);
} catch (NumberFormatException e) {
System.out.println("Invalid input: " + args[i] + " is not a valid number.");
return;
}
}
ArrayList<Integer> armstrongNumbers = new ArrayList<>();
for (int number : numbers) {
25
25
if (isArmstrongNumber(number)) {
armstrongNumbers.add(number);
}
}
if (armstrongNumbers.isEmpty()) {
System.out.println("No Armstrong numbers found in the provided input.");
} else {
System.out.println("Armstrong numbers in the input:");
for (int armstrongNumber : armstrongNumbers) {
System.out.println(armstrongNumber);
}
}
}
public static boolean isArmstrongNumber(int number) {
int originalNumber, remainder, result = 0;
originalNumber = number;
while (originalNumber != 0) {
remainder = originalNumber % 10;
result += Math.pow(remainder, 3);
originalNumber /= 10;
}
26
26
return result == number;
}
}
Q2
import java.util.Scanner;
import java.io.*;
class Product {
int pid;
String pname;
double price;
int qty;
public Product(int pid, String pname, double price, int qty) {
this.pid = pid;
this.pname = pname;
this.price = price;
this.qty = qty;
}
public double calculateTotal() {
return price * qty;
}
public void displayProduct() {
System.out.println("Product ID: " + pid);
27
27
System.out.println("Product Name: " + pname);
System.out.println("Price: $" + price);
System.out.println("Quantity: " + qty);
}
}
public class ProductDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of products: ");
int numProducts = scanner.nextInt();
Product[] products = new Product[numProducts];
for (int i = 0; i < numProducts; i++) {
System.out.println("Enter details for product #" + (i + 1));
System.out.print("Product ID: ");
int pid = scanner.nextInt();
scanner.nextLine(); // Consume newline
System.out.print("Product Name: ");
String pname = scanner.nextLine();
System.out.print("Price: $");
double price = scanner.nextDouble();
System.out.print("Quantity: ");
28
28
int qty = scanner.nextInt();
products[i] = new Product(pid, pname, price, qty);
}
System.out.println("Product Details:");
double totalAmount = 0;
for (Product product : products) {
product.displayProduct();
double productTotal = product.calculateTotal();
System.out.println("Total Amount for this product: $" + productTotal);
totalAmount += productTotal;
System.out.println();
}
System.out.println("Total Amount for all products: $" + totalAmount);
}
}
29
29
SLIP 20
Q1
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class RedFrame {
public static void main(String[] args) {
Frame frame = new Frame("TYBBACA");
frame.setBackground(Color.RED);
// Add a window listener to close the frame when the close button is clicked
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.setSize(400, 400);
frame.setVisible(true);
}
}
Q2
import java.util.LinkedList;
import java.util.List;
30
30
import java.util.ListIterator;
import java.util.Iterator;
public class LinkedListDemo {
public static void main(String[] args) {
// Create a linked list of names
List<String> names = new LinkedList<>();
names.add("CPP");
names.add("Java");
names.add("Python");
names.add("PHP");
// Display the contents of the list using an Iterator
System.out.println("Contents of the List using an Iterator:");
Iterator<String> iterator = names.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
// Display the contents of the list in reverse order using a ListIterator
System.out.println("nContents of the List in Reverse Order using a
ListIterator:");
ListIterator<String> listIterator = names.listIterator(names.size());
while (listIterator.hasPrevious()) {
System.out.println(listIterator.previous());
}
}
}
31
31
SLIP 21
Q1
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Main
{
public static void main(String args[])throws Exception,IOException
{
Scanner scanner=new Scanner(new File("a.txt")).useDelimiter("z");
String contents=scanner.next();
contents=new StringBuffer(contents).reverse().toString();
System.out.println("Reversed String:"+contents);
FileWriter fstream=new FileWriter("a.txt");
BufferedWriter out=new BufferedWriter(fstream);
out.write(contents);
out.close();
}
}
Q2
import java.util.Hashtable;
import java.util.Scanner;
import java.io.*;
public class CitySTDHashtable {
public static void main(String[] args) {
Hashtable<String, String> citySTDTable = new Hashtable<>();
// Populate the Hashtable with city names and STD codes
citySTDTable.put("New York", "212");
citySTDTable.put("Los Angeles", "213");
citySTDTable.put("Chicago", "312");
citySTDTable.put("San Francisco", "415");
citySTDTable.put("Boston", "617");
32
32
// Display the details of the Hashtable
System.out.println("City STD Codes:");
for (String city : citySTDTable.keySet()) {
System.out.println(city + " - STD Code: " + citySTDTable.get(city));
}
// Search for a specific city and display its STD code
Scanner scanner = new Scanner(System.in);
System.out.print("nEnter a city name to search for STD code: ");
String searchCity = scanner.nextLine();
String stdCode = citySTDTable.get(searchCity);
if (stdCode != null) {
System.out.println("STD Code for " + searchCity + ": " + stdCode);
} else {
System.out.println("City not found in the Hashtable.");
}
}
}
33
33
SLIP 22
Q1
import java.util.Scanner;
public class FactorialCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a non-negative integer to calculate its factorial: ");
int n = scanner.nextInt();
if (n < 0) {
System.out.println("Factorial is not defined for negative numbers.");
} else {
long factorial = calculateFactorial(n);
System.out.println("Factorial of " + n + " is: " + factorial);
}
}
public static long calculateFactorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * calculateFactorial(n - 1);
}
}
34
34
}
Q2
import java.io.File;
import java.io.IOException;
public class FileOperations {
public static void main(String[] args) {
// Create a file
createFile("sample.txt");
// Rename a file
renameFile("sample.txt", "newSample.txt");
// Display the path of a file
displayFilePath("newSample.txt");
// Delete a file
deleteFile("newSample.txt");
}
public static void createFile(String fileName) {
File file = new File(fileName);
try {
if (file.createNewFile()) {
35
35
System.out.println("File created: " + file.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred while creating the file.");
e.printStackTrace();
}
}
public static void renameFile(String oldFileName, String newFileName) {
File oldFile = new File(oldFileName);
File newFile = new File(newFileName);
if (oldFile.renameTo(newFile)) {
System.out.println("File renamed to: " + newFileName);
} else {
System.out.println("Unable to rename the file.");
}
}
public static void displayFilePath(String fileName) {
File file = new File(fileName);
System.out.println("File path: " + file.getAbsolutePath());
}
36
36
public static void deleteFile(String fileName) {
File file = new File(fileName);
if (file.delete()) {
System.out.println("File deleted: " + fileName);
} else {
System.out.println("Unable to delete the file.");
}
}
}
37
37
SLIP 25
Q1
public class PalindromeChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string to check for palindrome: ");
String input = scanner.nextLine();
if (isPalindrome(input)) {
System.out.println("The entered string is a palindrome.");
} else {
System.out.println("The entered string is not a palindrome.");
}
}
public static boolean isPalindrome(String str) {
str = str.replaceAll("[^a-zA-Z0-9]", "").toLowerCase(); // Remove non-
alphanumeric characters and convert to lowercase
int left = 0;
int right = str.length() - 1;
while (left < right) {
if (str.charAt(left) != str.charAt(right)) {
return false;
}
38
38
left++;
right--;
}
return true;
}
}
Q2
Fibonacci.java
package Series;
public class Fibonacci {
public static void generateFibonacciSeries(int n) {
int a = 0, b = 1;
System.out.print("Fibonacci Series (" + n + " terms): ");
for (int i = 1; i <= n; i++) {
System.out.print(a + " ");
int sum = a + b;
a = b;
b = sum;
}
}
}
CubeOfNumbers.java
package Series;
39
39
public class CubeOfNumbers {
public static void generateCubeSeries(int n) {
System.out.print("Cube of Numbers (" + n + " terms): ");
for (int i = 1; i <= n; i++) {
int cube = i * i * i;
System.out.print(cube + " ");
}
}
}
SquareOfNumbers.java
package Series;
public class SquareOfNumbers {
public static void generateSquareSeries(int n) {
System.out.print("Square of Numbers (" + n + " terms): ");
for (int i = 1; i <= n; i++) {
int square = i * i;
System.out.print(square + " ");
}
}
}
SeriesMain.java
import Series.*;
public class SeriesMain {
40
40
public static void main(String[] args) {
int n = 10; // Number of terms
Fibonacci.generateFibonacciSeries(n);
System.out.println();
CubeOfNumbers.generateCubeSeries(n);
System.out.println();
SquareOfNumbers.generateSquareSeries(n);
System.out.println();
}
}

More Related Content

Similar to java slip for bachelors of business administration.pdf

Lab01.pptx
Lab01.pptxLab01.pptx
Lab01.pptxKimVeeL
 
Java practice programs for beginners
Java practice programs for beginnersJava practice programs for beginners
Java practice programs for beginnersishan0019
 
DS LAB RECORD.docx
DS LAB RECORD.docxDS LAB RECORD.docx
DS LAB RECORD.docxdavinci54
 
Basic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIBasic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIjagriti srivastava
 
Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Nishan Barot
 
import java.util.Scanner;public class Main {    public static in.pdf
import java.util.Scanner;public class Main {    public static in.pdfimport java.util.Scanner;public class Main {    public static in.pdf
import java.util.Scanner;public class Main {    public static in.pdfanwarsadath111
 
import java.io.BufferedReader;import java.io.File;import java.io.pdf
import java.io.BufferedReader;import java.io.File;import java.io.pdfimport java.io.BufferedReader;import java.io.File;import java.io.pdf
import java.io.BufferedReader;import java.io.File;import java.io.pdfmanojmozy
 
Java Programs
Java ProgramsJava Programs
Java Programsvvpadhu
 
Core java pract_sem iii
Core java pract_sem iiiCore java pract_sem iii
Core java pract_sem iiiNiraj Bharambe
 
FileName EX06_1java Programmer import ja.pdf
FileName EX06_1java Programmer  import ja.pdfFileName EX06_1java Programmer  import ja.pdf
FileName EX06_1java Programmer import ja.pdfactocomputer
 

Similar to java slip for bachelors of business administration.pdf (20)

Lab4
Lab4Lab4
Lab4
 
Lab01.pptx
Lab01.pptxLab01.pptx
Lab01.pptx
 
54240326 (1)
54240326 (1)54240326 (1)
54240326 (1)
 
54240326 copy
54240326   copy54240326   copy
54240326 copy
 
Java oops features
Java oops featuresJava oops features
Java oops features
 
Dotnet 18
Dotnet 18Dotnet 18
Dotnet 18
 
Java practice programs for beginners
Java practice programs for beginnersJava practice programs for beginners
Java practice programs for beginners
 
PRACTICAL COMPUTING
PRACTICAL COMPUTINGPRACTICAL COMPUTING
PRACTICAL COMPUTING
 
DS LAB RECORD.docx
DS LAB RECORD.docxDS LAB RECORD.docx
DS LAB RECORD.docx
 
Basic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIBasic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time API
 
Java Program
Java ProgramJava Program
Java Program
 
Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.
 
.net progrmming part1
.net progrmming part1.net progrmming part1
.net progrmming part1
 
import java.util.Scanner;public class Main {    public static in.pdf
import java.util.Scanner;public class Main {    public static in.pdfimport java.util.Scanner;public class Main {    public static in.pdf
import java.util.Scanner;public class Main {    public static in.pdf
 
Awt
AwtAwt
Awt
 
import java.io.BufferedReader;import java.io.File;import java.io.pdf
import java.io.BufferedReader;import java.io.File;import java.io.pdfimport java.io.BufferedReader;import java.io.File;import java.io.pdf
import java.io.BufferedReader;import java.io.File;import java.io.pdf
 
Java Programs
Java ProgramsJava Programs
Java Programs
 
Anti patterns
Anti patternsAnti patterns
Anti patterns
 
Core java pract_sem iii
Core java pract_sem iiiCore java pract_sem iii
Core java pract_sem iii
 
FileName EX06_1java Programmer import ja.pdf
FileName EX06_1java Programmer  import ja.pdfFileName EX06_1java Programmer  import ja.pdf
FileName EX06_1java Programmer import ja.pdf
 

Recently uploaded

The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxUnboundStockton
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Science lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonScience lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonJericReyAuditor
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 

Recently uploaded (20)

The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Science lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonScience lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lesson
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 

java slip for bachelors of business administration.pdf

  • 1. 1 1 Slip 1: Q 1 public class Slip1q1 { public static void main(String[] args) { for(char c='A';c<='Z';c++){ System.out.print(c+" "); } System.out.println(); for(char c='a';c<='z';c++){ System.out.print(c+" "); } } } Q2 import java.io.*; public class Slip1q2 { public static void main(String[] args) throws IOException { System.out.println("reading file..."); FileReader fileReader = new FileReader("Slip1/src/sourcefile1q2.txt"); // enter your source file location FileWriter fileWriter = new FileWriter("Slip1/src/destinationfile1Q2.txt"); // enter your destination file location int data = fileReader.read(); System.out.println("writing file..."); while (data != -1){ String content = String.valueOf((char)data); if(Character.isAlphabetic(data)) { fileWriter.append(content); }else if(content.equals(" ")){ fileWriter.append(" "); } data = fileReader.read(); } System.out.println("nCOPY FINISHED SUCCESSFULLY..."); fileWriter.close(); fileReader.close(); } } 2 2 SLIP 2 Q1 import java.util.Scanner; public class Slip2q1 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter a string to find vowels on it."); String user_string = scanner.nextLine(); scanner.close(); int vowel_count = 0; for(int i=0;i<user_string.length();i++){ if(user_string.charAt(i)=='a' ||user_string.charAt(i)=='e' ||user_string.charAt(i)=='i' ||user_string.charAt(i)=='o' ||user_string.charAt(i)=='u' ||user_string.charAt(i)=='A' ||user_string.charAt(i)=='E' ||user_string.charAt(i)=='I' ||user_string.charAt(i)=='O' ||user_string.charAt(i)=='U'){ vowel_count++; System.out.println("Vowel found ("+user_string.charAt(i)+") at index "+i); } } if (vowel_count == 0){ System.out.println("Vowel not found in given string."); } } } Q2 import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Slip2q2 { public static void main(String[] args) { new MyFrame("Mouse Events"); } } class MyFrame extends JFrame { TextField click_text_field, mouse_move_field; Label click_text_label, mouse_move_label; int x,y; Panel panel; MyFrame(String title) { super(title); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  • 2. 3 3 setLayout(new FlowLayout()); panel =new Panel(); panel.setLayout(new GridLayout(2,2,5,5)); click_text_label = new Label("Co-ordinates of clicking"); mouse_move_label = new Label("Co-ordinates of movement"); click_text_field=new TextField(20); mouse_move_field =new TextField(20); panel.add(click_text_label); panel.add(click_text_field); panel.add(mouse_move_label); panel.add(mouse_move_field); add(panel); addMouseListener(new MyClick()); addMouseMotionListener(new MyMove()); setSize(500,500); setVisible(true); } class MyClick extends MouseAdapter { public void mouseClicked(MouseEvent me) { x=me.getX(); y=me.getY(); click_text_field.setText("X="+x+" Y="+y); } } class MyMove extends MouseMotionAdapter { public void mouseMoved(MouseEvent me) { x=me.getX(); y=me.getY(); mouse_move_field.setText("X="+ x +" Y="+y); } } } 4 4 SLIP 3 Q1 import java.util.Scanner; public class Slip3Q1 { static boolean is_armstrong(int n){ int temp,last,digits=0,sum=0; temp = n; while (temp>0){ temp=temp/10; digits++; } temp = n; while (temp>0){ last = temp%10; sum+=Math.pow(last,digits); temp=temp/10; } return n == sum; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a number to check armstrong : "); int number = scanner.nextInt(); scanner.close(); if (is_armstrong(number)){ System.out.println(number+" is a armstrong number."); } else { System.out.println(number+" is not a armstrong number."); } } } Q2 import java.util.Scanner; public class Slip3q2 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Shape shape; System.out.println(""" ENTER YOUR CHOICE 1. Cone 2. Cylinder"""); int choice = scanner.nextInt();
  • 3. 5 5 if (choice==1){ System.out.println("Enter radius"); int radius = scanner.nextInt(); System.out.println("Enter height"); int height = scanner.nextInt(); shape=new Cone(radius,height); shape.area(); shape.volume(); }else if (choice==2){ System.out.println("Enter radius"); int radius = scanner.nextInt(); System.out.println("Enter height"); int height = scanner.nextInt(); shape=new Cylinder(radius,height); shape.area(); shape.volume(); }else { System.out.println("invalid input"); } } abstract static class Shape{ abstract void area(); abstract void volume(); } static class Cone extends Shape { int radius,height; Cone(int radius,int height){ this.radius=radius; this.height=height; } void area(){ float slant_height=(height*height)+(radius*radius); float area = (float)(Math.PI*radius*(radius+Math.sqrt(slant_height))); System.out.println("Area of Cone : "+area); } void volume(){ float volume = (float)(Math.PI*radius*radius*(height/3)); System.out.println("Volume of cone : "+volume); } } static class Cylinder extends Shape { int radius, height; Cylinder(int r,int h){ radius =r; height =h; } public void area(){ float area=(float)((2*Math.PI* radius * height)+(2*Math.PI* radius * radius)); System.out.println("Area of Cylinder : "+area); } 6 6 public void volume(){ float volume=(float)(Math.PI* radius * radius * height); System.out.println("Volume of Cylinder : "+volume); } } }
  • 4. 7 7 SLIP 5 Q1 public class pattern { public static void main(String[] args) { int n=5; for (int i=n;i>0;i--){ for (int j=i;j<=n;j++){ System.out.print(j+" "); } System.out.println(); } } } Q2 import java.io.*; class Slip12 { public static void main(String args[]) throws Exception { for(int i=0;i<args.length;i++) { File file=new File(args[i]); if(file.isFile()) { String name = file.getName(); if(name.endsWith(".txt")) { file.delete(); System.out.println("file is deleted " + file); } else { System.out.println(name + " "+file.length()+" bytes"); } } else { System.out.println(args[i]+ "is not a file"); } } } } 8 8 SLIP 6 Q1 import java.util.*; class ZeroException extends Exception { ZeroException() { super("Number is 0"); } } class Slip19 { static int n; public static void main(String args[]) { int i,rem,sum=0; try { Scanner sr=new Scanner(System.in); n=sr.nextInt(); if(n==0) { throw new ZeroException(); } else { rem=n%10; sum=sum+rem; if(n>9) { while(n>0) { rem=n%10; n=n/10; } sum=sum+rem; } System.out.println("Sum is: "+sum); } } catch(ZeroException e) { System.out.println(e); } } } Q2 import java.util.Scanner;
  • 5. 9 9 public class Transposematrix { public static void main(String[] args) { Scanner sc= new Scanner(System.in); System.out.print("Enter rows of matrix : "); int row=sc.nextInt(); System.out.print("Enter column of matrix : "); int col=sc.nextInt(); int[][] matrix = new int[row][col]; //create and insert value for (int i=0;i<row;i++){ for(int j=0;j<col;j++){ System.out.print("element at index ["+i+"]["+j+"] :"); matrix[i][j]=sc.nextInt(); } } sc.close(); //print value of matrix System.out.println("nReal matrix :-n"); for (int i=0;i<row;i++){ for(int j=0;j<col;j++){ System.out.print(matrix[i][j]+" "); } System.out.println(); } System.out.println("nTranspose of matrix :-n"); for (int i=0;i<row;i++){ for(int j=0;j<col;j++){ System.out.print(matrix[j][i]+" "); } System.out.println(); } } } 10 10 SLIP 7 Q1 import java.awt.*; class Slip7 extends Frame { Slip7() { Label l=new Label("Dr. D Y Patil College"); Font f=new Font("Georgia",Font.BOLD,40); l.setFont(f); setForeground(Color.blue); setBackground(Color.red); add(l); setLayout(new FlowLayout()); setSize(200,200); setVisible(true); } public static void main(String arg[]) { new Slip7(); } } Q2 import java.io.*; import java.util.Scanner;
  • 6. 11 11 class CricketPlayer1 { int pid; String pname; int totalRuns; int inningsPlayed; int notOutTimes; double average; CricketPlayer1(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; this.average = (double) totalRuns / (inningsPlayed - notOutTimes); } } public class CricketPlayer { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the number of cricket players: "); int n = scanner.nextInt(); 12 12 CricketPlayer1[] players = new CricketPlayer1[n]; for (int i = 0; i < n; i++) { System.out.println("nEnter details for player " + (i + 1) + ":"); System.out.print("Player ID: "); int pid = scanner.nextInt(); scanner.nextLine(); // Consume the newline System.out.print("Player 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 CricketPlayer1(pid, pname, totalRuns, inningsPlayed, notOutTimes); } double maxAverage = 0; int maxAverageIndex = 0; for (int i = 0; i < n; i++) { if (players[i].average > maxAverage) {
  • 7. 13 13 maxAverage = players[i].average; maxAverageIndex = i; } } System.out.println("nPlayer with the maximum average:"); System.out.println("Player ID: " + players[maxAverageIndex].pid); System.out.println("Player Name: " + players[maxAverageIndex].pname); System.out.println("Average: " + players[maxAverageIndex].average); scanner.close(); } } 14 14 SLIP 8 Q1 import java.util.Scanner; interface Shape{ void area(); } class Circle implements Shape{ final float PI=3.14f; float areacircle,radius; Scanner s=new Scanner(System.in); void accept(){ System.out.print("Enter the Radius of circle : "); radius=s.nextFloat(); } public void area(){ areacircle=PI*radius*radius; } public void show() { System.out.println("Area of circle is : "+areacircle); } } class Sphere implements Shape{ final float PI=3.14f; float areasphere,radius; Scanner s=new Scanner(System.in); void accept(){ System.out.print("Enter the Radius of sphere : "); radius=s.nextFloat(); } public void area(){ areasphere=4*PI*radius*radius; } public void show(){ System.out.println("Area of Sphere is : "+areasphere); } } class InterfaceCircleSphere { public static void main(String args[]){ Circle s1=new Circle(); s1.accept(); s1.area(); s1.show(); Sphere s2=new Sphere(); s2.accept(); s2.area();
  • 8. 15 15 s2.show(); } } Q2 import java.io.File; public class ListTxtFiles { public static void main(String[] args) { // Specify the directory path where you want to search for .txt files String directoryPath = "C:/Program Files/Java/jdk1.7.0_80/bin"; // Replace with your directory path File directory = new File(directoryPath); if (directory.exists() && directory.isDirectory()) { File[] files = directory.listFiles(); if (files != null) { System.out.println("List of .txt files in the directory:"); for (File file : files) { if (file.isFile() && file.getName().toLowerCase().endsWith(".txt")) { System.out.println(file.getName()); } } } else { 16 16 System.out.println("No files found in the directory."); } } else { System.out.println("The specified directory does not exist or is not a directory."); } } }
  • 9. 17 17 SLIP 9 Q1 public class Pattern1 { public static void main(String[] args) { int num = 4; for (int i=0;i<num;i++){ for(int j=0;j<=i;j++){ if (i<2){ if ((i+j)%2==0){ System.out.print("1 "); }else{ System.out.print("0 "); } }else{ if ((i+j)%2==0){ System.out.print("0 "); }else{ System.out.print("1 "); } } }System.out.println(); } } } Q2 class InvalidDataException extends Exception { public InvalidDataException(String message) { super(message); } } public class DataValidator { public static void main(String[] args) { try { String panNumber = "ABC12"; // Replace with the PAN number to validate String mobileNumber = "1234567890"; // Replace with the mobile number to validate 18 18 validatePAN(panNumber); validateMobileNumber(mobileNumber); System.out.println("Valid PAN Number: " + panNumber); System.out.println("Valid Mobile Number: " + mobileNumber); } catch (InvalidDataException e) { System.out.println("Error: " + e.getMessage()); } } public static void validatePAN(String pan) throws InvalidDataException { if (pan.matches("[A-Z]{5}[0-9]{4}[A-Z]{1}")) { // PAN is valid } else { throw new InvalidDataException("Invalid PAN Number"); } } public static void validateMobileNumber(String mobileNumber) throws InvalidDataException { if (mobileNumber.matches("[0-9]{10}")) { // Mobile number is valid } else { throw new InvalidDataException("Invalid Mobile Number"); } } }
  • 10. 19 19 SLIP 13 Q1 import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class arrayList { public static void main(String[] args) { Scanner sc= new Scanner(System.in); System.out.print("enter limit of array : "); int num=sc.nextInt(); ArrayList<String> alist=new ArrayList<>(num); for(int i=0;i<num;i++){ System.out.println("Enter "+i+" Element of ArrayList :"); String elmt=sc.next(); alist.add(elmt); } sc.close(); System.out.println("Orignal list :"+alist); Collections.reverse(alist); System.out.println("Reverse of a ArrayList is :"+alist); } } Q2 import java.util.Scanner; import java.io.*; public class GreetUser { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter your name: "); String userName = scanner.nextLine(); // Convert the user's name to uppercase String upperCaseName = userName.toUpperCase(); 20 20 System.out.println("Hello, " + upperCaseName + ", nice to meet you!"); scanner.close(); } }
  • 11. 21 21 SLIP 16 Q1 import java.io.*; public class SumOfDigits { public static void main(String[] args) { int number = 123; // Change this to the number you want to calculate the sum for int sum = calculateSumOfDigits(number); System.out.println("The sum of digits in " + number + " is: " + sum); } public static int calculateSumOfDigits(int num) { if (num == 0) { return 0; // Base case: If the number is 0, the sum is 0 } else { // Calculate the sum of digits for the remaining part of the number int lastDigit = num % 10; // Get the last digit int remainingNumber = num / 10; // Remove the last digit return lastDigit + calculateSumOfDigits(remainingNumber); // Recursive call } } } Q2 import java.io.*; import java.util.Scanner; public class EmployeeSort 22 22 { static class Employee { String name; Employee(String name) { this.name = name; } static void sortEmployeesByName(Employee[] employees) { for (int i = 0; i < employees.length; i++) { for (int j = i + 1; j < employees.length; j++) { if (employees[i].name.compareTo(employees[j].name) > 0) { Employee temp = employees[i]; employees[i] = employees[j]; employees[j] = temp; } } } } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the number of employees (n): "); int n = scanner.nextInt(); scanner.nextLine(); // Consume the newline character Employee[] employees = new Employee[n]; // Accept employee names from the user for (int i = 0; i < n; i++) { System.out.print("Enter the name of employee " + (i + 1) + ": "); String name = scanner.nextLine(); employees[i] = new Employee(name); } // Sort the employee names in ascending order using a static method Employee.sortEmployeesByName(employees); // Display the sorted employee names
  • 12. 23 23 System.out.println("Sorted Employee Names:"); for (int i = 0; i < n; i++) { System.out.println(employees[i].name); } scanner.close(); } } 24 24 SLIP 17 Q1 import java.util.ArrayList; import java.io.*; public class ArmstrongNumbers { public static void main(String[] args) { if (args.length == 0) { System.out.println("Please provide some numbers as command-line arguments."); return; } int n = args.length; int[] numbers = new int[n]; for (int i = 0; i < n; i++) { try { numbers[i] = Integer.parseInt(args[i]); } catch (NumberFormatException e) { System.out.println("Invalid input: " + args[i] + " is not a valid number."); return; } } ArrayList<Integer> armstrongNumbers = new ArrayList<>(); for (int number : numbers) {
  • 13. 25 25 if (isArmstrongNumber(number)) { armstrongNumbers.add(number); } } if (armstrongNumbers.isEmpty()) { System.out.println("No Armstrong numbers found in the provided input."); } else { System.out.println("Armstrong numbers in the input:"); for (int armstrongNumber : armstrongNumbers) { System.out.println(armstrongNumber); } } } public static boolean isArmstrongNumber(int number) { int originalNumber, remainder, result = 0; originalNumber = number; while (originalNumber != 0) { remainder = originalNumber % 10; result += Math.pow(remainder, 3); originalNumber /= 10; } 26 26 return result == number; } } Q2 import java.util.Scanner; import java.io.*; class Product { int pid; String pname; double price; int qty; public Product(int pid, String pname, double price, int qty) { this.pid = pid; this.pname = pname; this.price = price; this.qty = qty; } public double calculateTotal() { return price * qty; } public void displayProduct() { System.out.println("Product ID: " + pid);
  • 14. 27 27 System.out.println("Product Name: " + pname); System.out.println("Price: $" + price); System.out.println("Quantity: " + qty); } } public class ProductDemo { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the number of products: "); int numProducts = scanner.nextInt(); Product[] products = new Product[numProducts]; for (int i = 0; i < numProducts; i++) { System.out.println("Enter details for product #" + (i + 1)); System.out.print("Product ID: "); int pid = scanner.nextInt(); scanner.nextLine(); // Consume newline System.out.print("Product Name: "); String pname = scanner.nextLine(); System.out.print("Price: $"); double price = scanner.nextDouble(); System.out.print("Quantity: "); 28 28 int qty = scanner.nextInt(); products[i] = new Product(pid, pname, price, qty); } System.out.println("Product Details:"); double totalAmount = 0; for (Product product : products) { product.displayProduct(); double productTotal = product.calculateTotal(); System.out.println("Total Amount for this product: $" + productTotal); totalAmount += productTotal; System.out.println(); } System.out.println("Total Amount for all products: $" + totalAmount); } }
  • 15. 29 29 SLIP 20 Q1 import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class RedFrame { public static void main(String[] args) { Frame frame = new Frame("TYBBACA"); frame.setBackground(Color.RED); // Add a window listener to close the frame when the close button is clicked frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.setSize(400, 400); frame.setVisible(true); } } Q2 import java.util.LinkedList; import java.util.List; 30 30 import java.util.ListIterator; import java.util.Iterator; public class LinkedListDemo { public static void main(String[] args) { // Create a linked list of names List<String> names = new LinkedList<>(); names.add("CPP"); names.add("Java"); names.add("Python"); names.add("PHP"); // Display the contents of the list using an Iterator System.out.println("Contents of the List using an Iterator:"); Iterator<String> iterator = names.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } // Display the contents of the list in reverse order using a ListIterator System.out.println("nContents of the List in Reverse Order using a ListIterator:"); ListIterator<String> listIterator = names.listIterator(names.size()); while (listIterator.hasPrevious()) { System.out.println(listIterator.previous()); } } }
  • 16. 31 31 SLIP 21 Q1 import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class Main { public static void main(String args[])throws Exception,IOException { Scanner scanner=new Scanner(new File("a.txt")).useDelimiter("z"); String contents=scanner.next(); contents=new StringBuffer(contents).reverse().toString(); System.out.println("Reversed String:"+contents); FileWriter fstream=new FileWriter("a.txt"); BufferedWriter out=new BufferedWriter(fstream); out.write(contents); out.close(); } } Q2 import java.util.Hashtable; import java.util.Scanner; import java.io.*; public class CitySTDHashtable { public static void main(String[] args) { Hashtable<String, String> citySTDTable = new Hashtable<>(); // Populate the Hashtable with city names and STD codes citySTDTable.put("New York", "212"); citySTDTable.put("Los Angeles", "213"); citySTDTable.put("Chicago", "312"); citySTDTable.put("San Francisco", "415"); citySTDTable.put("Boston", "617"); 32 32 // Display the details of the Hashtable System.out.println("City STD Codes:"); for (String city : citySTDTable.keySet()) { System.out.println(city + " - STD Code: " + citySTDTable.get(city)); } // Search for a specific city and display its STD code Scanner scanner = new Scanner(System.in); System.out.print("nEnter a city name to search for STD code: "); String searchCity = scanner.nextLine(); String stdCode = citySTDTable.get(searchCity); if (stdCode != null) { System.out.println("STD Code for " + searchCity + ": " + stdCode); } else { System.out.println("City not found in the Hashtable."); } } }
  • 17. 33 33 SLIP 22 Q1 import java.util.Scanner; public class FactorialCalculator { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a non-negative integer to calculate its factorial: "); int n = scanner.nextInt(); if (n < 0) { System.out.println("Factorial is not defined for negative numbers."); } else { long factorial = calculateFactorial(n); System.out.println("Factorial of " + n + " is: " + factorial); } } public static long calculateFactorial(int n) { if (n == 0 || n == 1) { return 1; } else { return n * calculateFactorial(n - 1); } } 34 34 } Q2 import java.io.File; import java.io.IOException; public class FileOperations { public static void main(String[] args) { // Create a file createFile("sample.txt"); // Rename a file renameFile("sample.txt", "newSample.txt"); // Display the path of a file displayFilePath("newSample.txt"); // Delete a file deleteFile("newSample.txt"); } public static void createFile(String fileName) { File file = new File(fileName); try { if (file.createNewFile()) {
  • 18. 35 35 System.out.println("File created: " + file.getName()); } else { System.out.println("File already exists."); } } catch (IOException e) { System.out.println("An error occurred while creating the file."); e.printStackTrace(); } } public static void renameFile(String oldFileName, String newFileName) { File oldFile = new File(oldFileName); File newFile = new File(newFileName); if (oldFile.renameTo(newFile)) { System.out.println("File renamed to: " + newFileName); } else { System.out.println("Unable to rename the file."); } } public static void displayFilePath(String fileName) { File file = new File(fileName); System.out.println("File path: " + file.getAbsolutePath()); } 36 36 public static void deleteFile(String fileName) { File file = new File(fileName); if (file.delete()) { System.out.println("File deleted: " + fileName); } else { System.out.println("Unable to delete the file."); } } }
  • 19. 37 37 SLIP 25 Q1 public class PalindromeChecker { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a string to check for palindrome: "); String input = scanner.nextLine(); if (isPalindrome(input)) { System.out.println("The entered string is a palindrome."); } else { System.out.println("The entered string is not a palindrome."); } } public static boolean isPalindrome(String str) { str = str.replaceAll("[^a-zA-Z0-9]", "").toLowerCase(); // Remove non- alphanumeric characters and convert to lowercase int left = 0; int right = str.length() - 1; while (left < right) { if (str.charAt(left) != str.charAt(right)) { return false; } 38 38 left++; right--; } return true; } } Q2 Fibonacci.java package Series; public class Fibonacci { public static void generateFibonacciSeries(int n) { int a = 0, b = 1; System.out.print("Fibonacci Series (" + n + " terms): "); for (int i = 1; i <= n; i++) { System.out.print(a + " "); int sum = a + b; a = b; b = sum; } } } CubeOfNumbers.java package Series;
  • 20. 39 39 public class CubeOfNumbers { public static void generateCubeSeries(int n) { System.out.print("Cube of Numbers (" + n + " terms): "); for (int i = 1; i <= n; i++) { int cube = i * i * i; System.out.print(cube + " "); } } } SquareOfNumbers.java package Series; public class SquareOfNumbers { public static void generateSquareSeries(int n) { System.out.print("Square of Numbers (" + n + " terms): "); for (int i = 1; i <= n; i++) { int square = i * i; System.out.print(square + " "); } } } SeriesMain.java import Series.*; public class SeriesMain { 40 40 public static void main(String[] args) { int n = 10; // Number of terms Fibonacci.generateFibonacciSeries(n); System.out.println(); CubeOfNumbers.generateCubeSeries(n); System.out.println(); SquareOfNumbers.generateSquareSeries(n); System.out.println(); } }