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

Java Solve

Uploaded by

labdhigandhi2003
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Java Solve

Uploaded by

labdhigandhi2003
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

Q1->Write a Java class to swap two numbers without using third variable.

import java.util.*;
public class swap {
public static void main(String[] args) {
Scanner Sc=new Scanner(System.in);
System.out.println("Before Swapping enter two Number:");
int num1=Sc.nextInt();
int num2=Sc.nextInt();
num1=num1+num2;
num2=num1-num2;
num1=num1-num2;
System.out.println("After Swapping enter two Number:");
System.out.println(num1);
System.out.println(num2);
Sc.close();
}
}
Q2=>Write a program to perform arithmetic operations What are the commands used to
compile and run this JAVA Programs.
public class ArithmeticOperations {
public static void main(String[] args) {
int a = 10;
int b = 5;
// Addition
int sum = a + b;
System.out.println("Sum: " + sum);
// Subtraction
int difference = a - b;
System.out.println("Difference: " + difference);
// Multiplication
int product = a * b;
System.out.println("Product: " + product);
// Division
int quotient = a / b;
System.out.println("Quotient: " + quotient)
// Modulus
int remainder = a % b;
System.out.println("Remainder: " + remainder);
}
}
Q3=>
i)Write a Java Program to convert “32” to Primitive as well as Wrapper.
public class main {
public static void main(String[] args) {
// Convert string "32" to primitive int
int primitiveInt = Integer.parseInt("32");
System.out.println("Primitive int: " + primitiveInt);

// Convert string "32" to Integer wrapper class


Integer wrapperInt = Integer.valueOf("32");
System.out.println("Integer wrapper: " + wrapperInt);
}
}
ii. Write a Java program to convert 110011 to decimal value.
public class BinaryToDecimal {
public static void main(String[] args) {
String binary = "110011";

// Convert binary string to decimal


int decimal = Integer.parseInt(binary, 2);

System.out.println("Binary " + binary + " is equivalent to decimal " +


decimal);
}
}
Q4=> Write a Java Program to convert the “60” to Primitive float (without using
Constructor of Float)
public class FloatConversion {
public static void main(String[] args) {
String numberString = "60";
// Parse string to int
int intValue = Integer.parseInt(numberString);
// Cast int to float
float floatValue = (float) intValue;
System.out.println("Primitive float: " + floatValue);
}
}
Q5=> gram to Sort the given list of objects in order of their email Contact: student_id,
student_name, email, phone
Write a pro import java.util.*;

class Student implements Comparable<Student> {


private int studentId;
private String studentName;
private String email;
private String phone;

public Student(int studentId, String studentName, String email, String


phone) {
this.studentId = studentId;
this.studentName = studentName;
this.email = email;
this.phone = phone;
}

public String getEmail() {


return email;
}

@Override
public int compareTo(Student other) {
return this.getEmail().compareTo(other.getEmail());
}

@Override
public String toString() {
return "Student{" +
"studentId=" + studentId +
", studentName='" + studentName + '\'' +
", email='" + email + '\'' +
", phone='" + phone + '\'' +
'}';
}
}

public class main {


public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student(101, "mohan", "[email protected]",
"1234567890"));
students.add(new Student(102, "arjun", "[email protected]",
"9876543210"));
students.add(new Student(103, "mihir", "[email protected]",
"1112223333"));

System.out.println("Before sorting:");
for (Student student : students) {
System.out.println(student);
}

Collections.sort(students);

System.out.println("\nAfter sorting by email:");


for (Student student : students) {
System.out.println(student);
}
}
}

Q6=>Write a Java Program to store the following data, in the collection you feel will suite
best.
Name- Ram
Email- [email protected]
Phone:99887545445
import java.util.*;

public class main {


public static void main(String[] args) {
// Create a HashMap to store contact information
Map<String, String> contactInfo = new HashMap<>();

// Add data to the map


contactInfo.put("Name", "Ram");
contactInfo.put("Email", "[email protected]");
contactInfo.put("Phone", "99887545445");

// Print the contact information


System.out.println("Contact Information:");
for (Map.Entry<String, String> entry : contactInfo.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
Q7=> Write a Java program to make a package com.shapes, make classes Circle and Square
in the same package.

Q8=> Write a Java program to write the following, class A with method m1( ) and m2( ) and
write a class B with methods m3( ) and m4( ), Override the methods of A in class B.
class A {
public void m1() {
System.out.println("Method m1() in class A");
}

public void m2() {


System.out.println("Method m2() in class A");
}
}

class B extends A {
@Override
public void m1() {
System.out.println("Overridden method m1() in class B");
}

@Override
public void m2() {
System.out.println("Overridden method m2() in class B");
}

public void m3() {


System.out.println("Method m3() in class B");
}

public void m4() {


System.out.println("Method m4() in class B");
}
}

public class TestAB {


public static void main(String[] args) {
A objA = new A();
objA.m1();
objA.m2();

B objB = new B();


objB.m1();
objB.m2();
objB.m3();
objB.m4();
}
}

Q9=> Write a Java class for following methods display() -- Display number from 1 to 100
using while loop in Java fibonacci() -- Prints Fibonacci series till 100
public class NumberUtils {
public void display() {
int i = 1;
while (i <= 100) {
System.out.print(i + " ");
i++;
}
System.out.println();
}

public void fibonacci() {


int num1 = 0, num2 = 1;
System.out.print(num1 + " " + num2 + " ");

int nextTerm = num1 + num2;


while (nextTerm <= 100) {
System.out.print(nextTerm + " ");
num1 = num2;
num2 = nextTerm;
nextTerm = num1 + num2;
}
System.out.println();
}

public static void main(String[] args) {


NumberUtils utils = new NumberUtils();

System.out.println("Displaying numbers from 1 to 100:");


utils.display();

System.out.println("Fibonacci series till 100:");


utils.fibonacci();
}
}

Q10a=> Write a Java program to print the following Floyd Triangle


public class FloydTriangle {
public static void main(String[] args) {
int rows = 5;
int number = 1;
System.out.println("Floyd's Triangle:");
for(int i = 1; i <= rows; i++) {
for(int j = 1; j <= i; j++) {
System.out.print(number + " ");
number++;
}
System.out.println();
}
}
}

Q10b=> Write a Java Program to find the number of String starting with „S‟ from following
TreeSet [ Smith, Alex , Tom, Steve, Mark, Sammy]
import java.util.TreeSet;

public class StringsWithS {


public static void main(String[] args) {
TreeSet<String> treeSet = new TreeSet<>();
treeSet.add("Smith");
treeSet.add("Alex");
treeSet.add("Tom");
treeSet.add("Steve");
treeSet.add("Mark");
treeSet.add("Sammy");

int count = 0;
for (String str : treeSet) {
if (str.startsWith("S")) {
count++;
}
}

System.out.println("Number of strings starting with 'S': " + count);


}
}

Q11=> Write a java program to find biggest of three numbers.


public class BiggestOfThree {
public static void main(String[] args) {
int num1 = 10;
int num2 = 20;
int num3 = 15;

int biggest = num1;


if (num2 > biggest) {
biggest = num2;
}

if (num3 > biggest) {


biggest = num3;
}

System.out.println("The biggest of the three numbers is: " + biggest);


}
}

Q12=> Write an abstract class Car with methods start() and stop(). Write a class Santro and
Audi and override the methods.
abstract class Car {
public abstract void start();
public abstract void stop();
}

class Santro extends Car {


@Override
public void start() {
System.out.println("Santro is starting...");
}

@Override
public void stop() {
System.out.println("Santro is stopping...");
}
}

class Audi extends Car {


@Override
public void start() {
System.out.println("Audi is starting...");
}

@Override
public void stop() {
System.out.println("Audi is stopping...");
}
}

public class main {


public static void main(String[] args) {
Car santro = new Santro();
santro.start();
santro.stop();

Car audi = new Audi();


audi.start();
audi.stop();
}
}

Q13=> Write a program for using the switch statement to execute a particular task depending
on color value.
public class ColorTask {
public static void main(String[] args) {
String color = "red"; // Change this to test different colors

switch(color) {
case "red":
System.out.println("Stop!");
break;
case "yellow":
System.out.println("Slow down!");
break;
case "green":
System.out.println("Go!");
break;
default:
System.out.println("Invalid color");
}
}
}
Q14=> Write a class Automobile with default constructor, write a class Plane which extends
Automobile and has a default as well as parameterized constructor, write a class Airbus with
a default constructor which extends Plane
class Automobile {
public Automobile() {
System.out.println("Automobile constructor");
}
}

// Plane class extending Automobile


class Plane extends Automobile {
public Plane() {
System.out.println("Plane default constructor");
}

public Plane(int seats) {


System.out.println("Plane parameterized constructor with " + seats + "
seats");
}
}

// Airbus class extending Plane


class Airbus extends Plane {
public Airbus() {
System.out.println("Airbus default constructor");
}
}

// Main class to test the inheritance hierarchy


public class main {
public static void main(String[] args) {
System.out.println("Creating an Automobile:");
Automobile auto = new Automobile();
System.out.println();

System.out.println("Creating a Plane with default constructor:");


Plane planeDefault = new Plane();
System.out.println();

System.out.println("Creating a Plane with parameterized


constructor:");
Plane planeParameterized = new Plane(200);
System.out.println();

System.out.println("Creating an Airbus:");
Airbus airbus = new Airbus();
}
}

Q15=> Write a program to take a 2D array and display its elements in the form of a matrix.
public class MatrixDisplay {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

System.out.println("Matrix:");
displayMatrix(matrix);
}

public static void displayMatrix(int[][] matrix) {


int rows = matrix.length;
int cols = matrix[0].length;

for (int i = 0; i < rows; i++) {


for (int j = 0; j < cols; j++) {
System.out.print(matrix[i][j] + "\t");
}
System.out.println();
}
}
}

Q16=> Write a class User with abstract methods pay() and receive(), later make two concrete
class GoldUser and SilverUser, override the abstract method.
abstract class User {
// Abstract methods
public abstract void pay();
public abstract void receive();
}
class GoldUser extends User {
@Override
public void pay() {
System.out.println("Gold user is making a payment.");
}
@Override
public void receive() {
System.out.println("Gold user is receiving a payment.");
}
}
class SilverUser extends User {
@Override
public void pay() {
System.out.println("Silver user is making a payment.");
}
@Override
public void receive() {
System.out.println("Silver user is receiving a payment.");
}
}
public class Main {
public static void main(String[] args) {
User goldUser = new GoldUser();
User silverUser = new SilverUser();

goldUser.pay();
goldUser.receive();

silverUser.pay();
silverUser.receive();
}
}

Q17=> Create an Exception StringNotPalindromeException. Write a class with method which


throws this Exception when String passed is not palindrome.
// Main class to test the PalindromeChecker
public class PalindromeTest {
public static void main(String[] args) {
PalindromeChecker checker = new PalindromeChecker();
String palindrome = "radar";
String notPalindrome = "hello";

try {
checker.checkPalindrome(palindrome);
System.out.println(palindrome + " is a palindrome.");
} catch (StringNotPalindromeException e) {
System.out.println(e.getMessage());
}

try {
checker.checkPalindrome(notPalindrome);
System.out.println(notPalindrome + " is a palindrome.");
} catch (StringNotPalindromeException e) {
System.out.println(e.getMessage());
}
}
}

Q18=> Write a Java program for separate hours, minutes and seconds from following string
01:23:45 PM.

public class TimeSeparator {


public static void main(String[] args) {
String timeString = "01:23:45 PM";

// Split the time string using ":" and " " as delimiters
String[] parts = timeString.split("[:\\s]");

// Extract hours, minutes, seconds, and time period (AM/PM)


from the parts array
int hours = Integer.parseInt(parts[0]);
int minutes = Integer.parseInt(parts[1]);
int seconds = Integer.parseInt(parts[2]);
String period = parts[3];

// Print the separated components


System.out.println("Hours: " + hours);
System.out.println("Minutes: " + minutes);
System.out.println("Seconds: " + seconds);
System.out.println("Time period: " + period);
}
}
Q19=> Make an Interface CE which have methods call(), sms (), Make another interface ISO
which have methods radiation() and sound(). Make two classes IPhone and Galaxy and make
them implement both the interfaces.
// Interface CE
interface CE {
void call();
void sms();
}

// Interface ISO
interface ISO {
void radiation();
void sound();
}

// IPhone class implementing CE and ISO interfaces


class IPhone implements CE, ISO {
@Override
public void call() {
System.out.println("Calling from iPhone");
}

@Override
public void sms() {
System.out.println("Sending SMS from iPhone");
}

@Override
public void radiation() {
System.out.println("Measuring radiation with iPhone");
}

@Override
public void sound() {
System.out.println("Adjusting sound settings with iPhone");
}
}

// Galaxy class implementing CE and ISO interfaces


class Galaxy implements CE, ISO {
@Override
public void call() {
System.out.println("Calling from Galaxy");
}

@Override
public void sms() {
System.out.println("Sending SMS from Galaxy");
}

@Override
public void radiation() {
System.out.println("Measuring radiation with Galaxy");
}

@Override
public void sound() {
System.out.println("Adjusting sound settings with Galaxy");
}
}

// Main class to test the IPhone and Galaxy classes


public class PhoneTest {
public static void main(String[] args) {
// Create objects of IPhone and Galaxy
IPhone iphone = new IPhone();
Galaxy galaxy = new Galaxy();

// Test IPhone methods


System.out.println("Using iPhone:");
iphone.call();
iphone.sms();
iphone.radiation();
iphone.sound();

// Test Galaxy methods


System.out.println("\nUsing Galaxy:");
galaxy.call();
galaxy.sms();
galaxy.radiation();
galaxy.sound();
}
}

Q20=> Write a Java Program to find the minimum value in Vector [18,9,21,3,4].
import java.util.Vector;

public class MinValueInVector {

public static void main(String[] args) {

// Create a Vector with the given elements


Vector<Integer> vector = new Vector<>();

vector.add(18);

vector.add(9);

vector.add(21);

vector.add(3);

vector.add(4);

// Find the minimum value in the Vector

int min = vector.get(0); // Assume the first element is the minimum initially

for (int i = 1; i < vector.size(); i++) {

int current = vector.get(i);

if (current < min) {

min = current;

// Print the minimum value

System.out.println("Minimum value in the Vector: " + min);

21. Write an abstract class Car with methods start() and stop(). Write a class Santro and Audi and
override the methods.

CODE:

abstract class Car {

public abstract void start();

public abstract void stop();

class Santro extends Car {

@Override

public void start() {

System.out.println("Santro started.");

}
@Override

public void stop() {

System.out.println("Santro stopped.");

class Audi extends Car {

@Override

public void start() {

System.out.println("Audi started.");

@Override

public void stop() {

System.out.println("Audi stopped.");

public class Main {

public static void main(String[] args) {

Car santro = new Santro();

santro.start();

santro.stop();

Car audi = new Audi();

audi.start();

audi.stop();

22. Write a Java Program to determine whether the number is prime or not

CODE:
import java.util.Scanner;

public class PrimeChecker {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number to check if it's prime: ");

int num = scanner.nextInt();

boolean isPrime = true;

if (num <= 1) {

isPrime = false;

} else {

for (int i = 2; i <= num / 2; i++) {

if (num % i == 0) {

isPrime = false;

break;

if (isPrime) {

System.out.println(num + " is a prime number.");

} else {

System.out.println(num + " is not a prime number.");

scanner.close();

}
24. Write a Java Program to print following

CODE:

public class PatternPrinting {

public static void main(String[] args) {

int rows = 5;

for (int i = rows; i >= 1; i--) {

for (int j = 1; j <= i; j++) {

System.out.print(j + " ");

System.out.println();

25. Write a class MathDemo with methods square() with one parameter and add() with two
parameters. Call these methods to get the output.

CODE:

import java.util.Scanner;

public class MathDemo {

public static void main(String[] args) {

MathDemo demo = new MathDemo();

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the value to square: ");

double numToSquare = scanner.nextDouble();


double squaredValue = demo.square(numToSquare);

System.out.println("Square of " + numToSquare + " is: " + squaredValue);

System.out.print("Enter the first number to add: ");

double num1 = scanner.nextDouble();

System.out.print("Enter the second number to add: ");

double num2 = scanner.nextDouble();

double sum = demo.add(num1, num2);

System.out.println("Sum of " + num1 + " and " + num2 + " is: " + sum);

scanner.close();

public double square(double num) {

return num * num;

public double add(double num1, double num2) {

return num1 + num2;

26. Create an Exception StringNotPalindromeException. Write a class with method which throws
this Exception when String passed is not palindrome.

CODE:

class StringNotPalindromeException extends Exception {

public StringNotPalindromeException(String message) {

super(message);

public class PalindromeChecker {


public static void main(String[] args) {

try {

String palindrome = "radar"; // Example palindrome, you can modify it

checkPalindrome(palindrome);

System.out.println("'" + palindrome + "' is a palindrome.");

String notPalindrome = "hello"; // Example non-palindrome, you can modify it

checkPalindrome(notPalindrome);

System.out.println("'" + notPalindrome + "' is a palindrome."); // This line won't be reached

} catch (StringNotPalindromeException e) {

System.out.println("StringNotPalindromeException: " + e.getMessage());

public static void checkPalindrome(String str) throws StringNotPalindromeException {

StringBuilder reversed = new StringBuilder(str).reverse();

if (!str.equals(reversed.toString())) {

throw new StringNotPalindromeException("The string '" + str + "' is not a palindrome.");

27. Write a Java class to print the Fibonacci sequence till 100.

CODE:

public class Fibonacci {

public static void main(String[] args) {

printFibonacci();
}

public static void printFibonacci() {

int a = 0, b = 1, c;

System.out.println("Fibonacci series up to 100:");

System.out.print(a + " " + b + " ");

while ((c = a + b) <= 100) {

System.out.print(c + " ");

a = b;

b = c;

29. Write a class mobile with methods call() and sms(). Write a class Demo and access it.

CODE:

import.java.util.scanner;

class Mobile

public void call()

System.out.println(“Incoming call from…”);

public void sms()

System.out.println(“ Received a message..”)

}
}

class Demo extends Mobile

public static void main (String [] args)

Demo demobj= new Demo();

demobj.call()

demobj.sms()

30. Write a class Automobile with default constructor, write a class Plane which extends Automobile
and has a default as well as parameterized constructor, write a class Airbus with a default
constructor which extends Plane.

CODE:

// Automobile class

class Automobile {

// Default constructor

public Automobile() {

System.out.println("Automobile created.");

// Plane class extending Automobile

class Plane extends Automobile {

// Default constructor

public Plane() {

super(); // Call to the superclass constructor

System.out.println("Plane created.");

}
// Parameterized constructor

public Plane(String model) {

super(); // Call to the superclass constructor

System.out.println("Plane created with model: " + model);

// Airbus class extending Plane

class Airbus extends Plane {

// Default constructor

public Airbus() {

super(); // Call to the superclass constructor

System.out.println("Airbus created.");

public class Main {

public static void main(String[] args) {

// Creating objects

Automobile automobile = new Automobile();

Plane plane1 = new Plane();

Plane plane2 = new Plane("Boeing 747");

Airbus airbus = new Airbus();

31. Write a Java Program to determine whether the number is Armstrong or not

import java.util.Scanner;
public class ArmstrongChecker {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number to check if it's an Armstrong number: ");

int num = scanner.nextInt();

int originalNum, remainder, result = 0, n = 0;

originalNum = num;

// Count number of digits

while (originalNum != 0) {

originalNum /= 10;

++n;

originalNum = num;

// Calculate Armstrong number

while (originalNum != 0) {

remainder = originalNum % 10;

result += Math.pow(remainder, n);

originalNum /= 10;

if (result == num) {

System.out.println(num + " is an Armstrong number.");

} else {

System.out.println(num + " is not an Armstrong number.");

scanner.close();

}
32. Write a Java Program to make an Exception AgeException. When user passes some age and if
age is less than 18 throw this Exception

CODE:

class AgeException extends Exception {

public AgeException(String message) {

super(message);

public class Main {

public static void main(String[] args) {

try {

int age = 15; // Example age, you can modify it

validateAge(age);

System.out.println("Age is valid.");

} catch (AgeException e) {

System.out.println("AgeException: " + e.getMessage());

public static void validateAge(int age) throws AgeException {

if (age < 18) {

throw new AgeException("Age should be 18 or above.");

33. Write a java program to check palindrome number

CODE:
import java.util.Scanner;

public class PalindromeCheck {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

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

int number = scanner.nextInt();

scanner.close();

if (isPalindrome(number)) {

System.out.println(number + " is a palindrome number.");

} else {

System.out.println(number + " is not a palindrome number.");

public static boolean isPalindrome(int number) {

int originalNumber = number;

int reversedNumber = 0;

while (number != 0) {

int digit = number % 10;

reversedNumber = reversedNumber * 10 + digit;

number /= 10;

return originalNumber == reversedNumber;

}
}

34. Write a Java program for the following scenario:


Run a loop from 1 to 100, while looping when the number is even print its square and
when the number is odd print its cube

CODE:

public class NumberLoop {


public static void main(String[] args) {
for (int i = 1; i <= 100; i++) {
if (i % 2 == 0) {
System.out.println("Square of " + i + ": " + (i * i));
} else {
System.out.println("Cube of " + i + ": " + (i * i * i));
}
}
}
}

You might also like