0% found this document useful (0 votes)
4 views15 pages

Java Lab Manual with Solution 1

The document contains a series of Java programming assignments demonstrating various concepts such as type conversion, arithmetic operations, conditional statements, and loops. Each assignment includes code examples, expected outputs, and explanations of the functionality. Topics covered include automatic and explicit type casting, arithmetic operations, finding the greatest number, increment behavior, even/odd checking, voting eligibility, day of the week determination, grading based on marks, leap year checking, basic calculator operations, and calculations for natural numbers, factorials, and prime numbers.

Uploaded by

Mukesh Surela
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
4 views15 pages

Java Lab Manual with Solution 1

The document contains a series of Java programming assignments demonstrating various concepts such as type conversion, arithmetic operations, conditional statements, and loops. Each assignment includes code examples, expected outputs, and explanations of the functionality. Topics covered include automatic and explicit type casting, arithmetic operations, finding the greatest number, increment behavior, even/odd checking, voting eligibility, day of the week determination, grading based on marks, leap year checking, basic calculator operations, and calculations for natural numbers, factorials, and prime numbers.

Uploaded by

Mukesh Surela
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 15

SRI BALAJI P.

G MAHAVIDYALAYA
Java Technology
Assignments-1

Q1. Write a Java program to demonstrate automatic type conversion from int to float and double.

public class TypeConversionDemo {


public static void main(String[] args) {
// Declare an int variable
int intValue = 10;

// Automatic conversion from int to float


float floatValue = intValue; // Implicit casting
System.out.println("Integer value: " + intValue);
System.out.println("Converted to float: " + floatValue);

// Automatic conversion from int to double


double doubleValue = intValue; // Implicit casting
System.out.println("Converted to double: " + doubleValue);
}
}

Output

Integer value: 10
Converted to float: 10.0
Converted to double: 10.0

Q2. Write a program to demonstrate explicit type casting from double to int and observe the data loss.

public class TypeCastingDemo {


public static void main(String[] args) {
// Declare a double variable
double doubleValue = 9.78;

// Explicitly cast double to int


int intValue = (int) doubleValue; // This will truncate the decimal part

// Display the values


System.out.println("Double value: " + doubleValue);
System.out.println("Converted to int: " + intValue);
}
}
OUTPUT

Double value: 9.78


Converted to int: 9

Q3. Write a program to accept two numbers from the user and perform all arithmetic operations (+, -, *, /, %).

import java.util.Scanner;

public class ArithmeticOperations {


public static void main(String[] args) {
// Create a Scanner object to read input
Scanner scanner = new Scanner(System.in);

// Prompt the user to enter the first number


System.out.print("Enter the first number: ");
double num1 = scanner.nextDouble();

// Prompt the user to enter the second number


System.out.print("Enter the second number: ");
double num2 = scanner.nextDouble();

// Perform arithmetic operations


double sum = num1 + num2;
double difference = num1 - num2;
double product = num1 * num2;
double quotient = num1 / num2; // Be cautious of division by zero
double modulus = num1 % num2; // Be cautious of modulus by zero

// Display the results


System.out.println("Sum: " + sum);
System.out.println("Difference: " + difference);
System.out.println("Product: " + product);

// Check for division and modulus by zero


if (num2 != 0) {
System.out.println("Quotient: " + quotient);
System.out.println("Modulus: " + modulus);
} else {
System.out.println("Division by zero is not allowed.");
System.out.println("Modulus by zero is not allowed.");
}

// Close the scanner


scanner.close();
}
}

OUTPUT
Enter the first number: 10
Enter the second number: 2
Sum: 12.0
Difference: 8.0
Product: 20.0
Quotient: 5.0
Modulus: 0.0

Q4. Write a program that takes three numbers from the user and determines which one is the greatest using
relational and logical operators.

import java.util.Scanner;

public class GreatestNumber {


public static void main(String[] args) {
// Create a Scanner object to read input
Scanner scanner = new Scanner(System.in);

// Prompt the user to enter three numbers


System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();

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


int num2 = scanner.nextInt();

System.out.print("Enter the third number: ");


int num3 = scanner.nextInt();

// Determine the greatest number


int greatest;

if (num1 >= num2 && num1 >= num3) {


greatest = num1;
} else if (num2 >= num1 && num2 >= num3) {
greatest = num2;
} else {
greatest = num3;
}

// Display the result


System.out.println("The greatest number is: " + greatest);

// Close the scanner


scanner.close();
}
}

Output
Enter the first number: 15
Enter the second number: 25
Enter the third number: 20
The greatest number is: 25

Q5. Write a Java program that demonstrates both pre-increment and post-increment behavior.

public class IncrementDemo {


public static void main(String[] args) {
int a = 5;
int b = 5;

// Pre-increment
System.out.println("Initial value of a: " + a);
int preIncrement = ++a; // Increment a, then assign to preIncrement
System.out.println("After pre-increment, a: " + a);
System.out.println("Value of preIncrement: " + preIncrement);

// Resetting the value of a


a = 5;

// Post-increment
System.out.println("\nInitial value of b: " + b);
int postIncrement = b++; // Assign b to postIncrement, then increment b
System.out.println("After post-increment, b: " + b);
System.out.println("Value of postIncrement: " + postIncrement);
}
}

OUTPUT

Initial value of a: 5
After pre-increment, a: 6
Value of preIncrement: 6

Initial value of b: 5
After post-increment, b: 6
Value of postIncrement: 5

Q6. Write a Java program that checks if a number entered by the user is even or odd using the if-else
statement.

import java.util.Scanner;

public class EvenOddChecker {


public static void main(String[] args) {
// Create a Scanner object to read input
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter a number
System.out.print("Enter a number: ");
int number = scanner.nextInt();

// Check if the number is even or odd using if-else


if (number % 2 == 0) {
System.out.println(number + " is even.");
} else {
System.out.println(number + " is odd.");
}

// Close the scanner


scanner.close();
}
}

OUTPUT

Enter a number: 7
7 is odd.

Q7. Write a Java program that accepts the age of a person and checks whether the person is eligible to vote
(age >= 18). Use nested if statements to check if the person is a minor or an adult.

import java.util.Scanner;

public class VotingEligibilityChecker {


public static void main(String[] args) {
// Create a Scanner object to read input
Scanner scanner = new Scanner(System.in);

// Prompt the user to enter their age


System.out.print("Enter your age: ");
int age = scanner.nextInt();

// Check if the person is a minor or an adult


if (age < 18) {
System.out.println("You are a minor.");
System.out.println("You are not eligible to vote.");
} else {
System.out.println("You are an adult.");
// Nested if to check voting eligibility
if (age >= 18) {
System.out.println("You are eligible to vote.");
}
}

// Close the scanner


scanner.close();
}
}

OUTPUT

Enter your age: 16


You are a minor.
You are not eligible to vote.

Q8. Write a Java program that accepts a number between 1 and 7 and prints the corresponding day of the
week using the switch statement.

import java.util.Scanner;

public class DayOfWeek {


public static void main(String[] args) {
// Create a Scanner object to read input
Scanner scanner = new Scanner(System.in);

// Prompt the user to enter a number between 1 and 7


System.out.print("Enter a number (1 to 7): ");
int dayNumber = scanner.nextInt();

// Use switch statement to determine the day of the week


String day;
switch (dayNumber) {
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
break;
case 7:
day = "Sunday";
break;
default:
day = "Invalid number! Please enter a number between 1 and 7.";
break;
}

// Print the corresponding day of the week


System.out.println(day);

// Close the scanner


scanner.close();
}
}

OUTPUT

Enter a number (1 to 7): 3


Wednesday

Q9. Write a Java program that accepts marks from the user and assigns a grade based on the following
criteria:
Marks >= 90: A
Marks >= 80 and < 90: B
Marks >= 70 and < 80: C
Marks >= 60 and < 70: D
Marks < 60: F
import java.util.Scanner;

public class GradeCalculator {


public static void main(String[] args) {
// Create a scanner object to read input from user
Scanner scanner = new Scanner(System.in);

// Prompt the user to enter marks


System.out.print("Enter your marks: ");
int marks = scanner.nextInt();

// Determine and display the grade based on the marks


if (marks >= 90) {
System.out.println("Your grade is: A");
} else if (marks >= 80) {
System.out.println("Your grade is: B");
} else if (marks >= 70) {
System.out.println("Your grade is: C");
} else if (marks >= 60) {
System.out.println("Your grade is: D");
} else {
System.out.println("Your grade is: F");
}
// Close the scanner
scanner.close();
}
}

OUTPUT

Q10. Write a program that accepts a year from the user and checks whether it is a leap year using the
conditional (?:) operator.
import java.util.Scanner;

public class LeapYearChecker {


public static void main(String[] args) {
// Create a scanner object to read input from user
Scanner scanner = new Scanner(System.in);

// Prompt the user to enter a year


System.out.print("Enter a year: ");
int year = scanner.nextInt();

// Determine if the year is a leap year using the conditional (ternary)


operator
System.out.println((year % 4 == 0 && (year % 100 != 0 || year % 400 ==
0))
? year + " is a leap year."
: year + " is not a leap year.");

// Close the scanner


scanner.close();
}
}

OUTPUT
Enter a year: 2024
2024 is a leap year.

Q11. Write a Java program that accepts two numbers and an operator (+, -, *, /) from the user and performs
the corresponding operation using the switch statement.

import java.util.Scanner;

public class Calculator {


public static void main(String[] args) {
// Create a scanner object to read input from the user
Scanner scanner = new Scanner(System.in);

// Prompt the user to enter the first number


System.out.print("Enter the first number: ");
double num1 = scanner.nextDouble();

// Prompt the user to enter the second number


System.out.print("Enter the second number: ");
double num2 = scanner.nextDouble();

// Prompt the user to enter an operator


System.out.print("Enter an operator (+, -, *, /): ");
char operator = scanner.next().charAt(0);

// Variable to store the result


double result;

// Perform the operation based on the operator using switch statement


switch (operator) {
case '+':
result = num1 + num2;
System.out.println("Result: " + num1 + " + " + num2 + " = " +
result);
break;
case '-':
result = num1 - num2;
System.out.println("Result: " + num1 + " - " + num2 + " = " +
result);
break;
case '*':
result = num1 * num2;
System.out.println("Result: " + num1 + " * " + num2 + " = " +
result);
break;
case '/':
// Check if the denominator is zero
if (num2 != 0) {
result = num1 / num2;
System.out.println("Result: " + num1 + " / " + num2 + " = "
+ result);
} else {
System.out.println("Error: Division by zero is undefined.");
}
break;
default:
System.out.println("Error: Invalid operator entered.");
break;
}

// Close the scanner


scanner.close();
}
}
OUTPUT

Enter the first number: 10


Enter the second number: 5
Enter an operator (+, -, *, /): /
Result: 10.0 / 5.0 = 2.0

Q12. Write a Java program to find the sum of the first n natural numbers using a for loop.

import java.util.Scanner;

public class SumOfNaturalNumbers {


public static void main(String[] args) {
// Create a scanner object to read input from user
Scanner scanner = new Scanner(System.in);

// Prompt the user to enter a value for n


System.out.print("Enter a positive integer: ");
int n = scanner.nextInt();

// Variable to store the sum


int sum = 0;

// Calculate the sum of first n natural numbers using a for loop


for (int i = 1; i <= n; i++) {
sum += i; // Add i to sum in each iteration
}

// Display the result


System.out.println("The sum of the first " + n + " natural numbers is: "
+ sum);

// Close the scanner


scanner.close();
}
}

OUTPUT

Enter a positive integer: 5


The sum of the first 5 natural numbers is: 15

Q13. Write a Java program to calculate the factorial of a number using a while loop.

import java.util.Scanner;

public class FactorialCalculator {


public static void main(String[] args) {
// Create a scanner object to read input from user
Scanner scanner = new Scanner(System.in);

// Prompt the user to enter a number


System.out.print("Enter a positive integer: ");
int number = scanner.nextInt();

// Initialize variables for the factorial calculation


long factorial = 1; // Use long to handle large numbers
int i = number; // Start the counter from the input number

// Calculate factorial using a while loop


while (i > 0) {
factorial *= i; // Multiply the current value of i with factorial
i--; // Decrement i by 1 in each iteration
}

// Display the result


System.out.println("The factorial of " + number + " is: " + factorial);

// Close the scanner


scanner.close();
}
}

OUTPUT

Enter a positive integer: 5


The factorial of 5 is: 120

Q14. Write a Java program that takes an integer input from the user and checks whether the number is prime
using a for loop.

import java.util.Scanner;

public class PrimeChecker {


public static void main(String[] args) {
// Create a scanner object to read input from user
Scanner scanner = new Scanner(System.in);

// Prompt the user to enter an integer


System.out.print("Enter an integer: ");
int number = scanner.nextInt();

// Variable to track whether the number is prime


boolean isPrime = true;

// Check if the number is less than 2


if (number < 2) {
isPrime = false; // Numbers less than 2 are not prime
} else {
// Check for factors of the number using a for loop
for (int i = 2; i <= number / 2; i++) {
// If the number is divisible by any i, it's not prime
if (number % i == 0) {
isPrime = false;
break; // No need to check further
}
}
}

// Display whether the number is prime or not


if (isPrime) {
System.out.println(number + " is a prime number.");
} else {
System.out.println(number + " is not a prime number.");
}

// Close the scanner


scanner.close();
}
}

OUTPUT

Enter an integer: 7
7 is a prime number.

Q15. Write a Java program that prints the Fibonacci series up to n terms using a while loop.

import java.util.Scanner;

public class FibonacciSeries {


public static void main(String[] args) {
// Create a scanner object to read input from the user
Scanner scanner = new Scanner(System.in);

// Prompt the user to enter the number of terms


System.out.print("Enter the number of terms for Fibonacci series: ");
int n = scanner.nextInt();

// Variables to hold the first two numbers of the Fibonacci series


int firstTerm = 0, secondTerm = 1;

// Initialize a counter to track the number of terms printed


int count = 0;

// Print Fibonacci series using a while loop


System.out.println("Fibonacci Series up to " + n + " terms:");
while (count < n) {
// Print the current term
System.out.print(firstTerm + " ");

// Calculate the next term


int nextTerm = firstTerm + secondTerm;
firstTerm = secondTerm;
secondTerm = nextTerm;

// Increment the counter


count++;
}

// Close the scanner


scanner.close();
}
}

OUTPUT

Enter the number of terms for Fibonacci series: 7


Fibonacci Series up to 7 terms:
0 1 1 2 3 5 8

Q16. Write a program to reverse the digits of a number using a while loop.

Q17. Write a Java program to print the multiplication table of a given number using a for loop.

Q18. Write a Java program using nested loops to print the following pattern:
1
12
123
1234
Q19. Write a Java program that takes an integer input and calculates the sum of its digits using a do-while
loop.

Q20. Write a Java program to check if a number is a palindrome or not using a while loop.

Q21. Write a Java program to count the number of vowels in a given string using a for loop.

Q22. Write a Java program that prints the numbers from 1 to 10. Use a break statement to stop the loop when
the number is equal to 7.

Q23. Write a Java program that prints numbers from 1 to 10, but uses the continue statement to skip printing
the number 4.

Q24. Write a Java program that uses a switch statement to display the name of a month based on its number
(1 for January, 2 for February, etc.). Use break to terminate each case.

Q25. Write a Java program that defines a method to find the maximum of two numbers using the return
Q26. Write a Java program that uses both break and continue in the same loop to print numbers from 1 to 10
but stops the loop if the number is 8 and skips the number 5.

Q27. Create a Java class Student with attributes name, rollNumber, and marks. Add methods to input and
display the student’s details. Create objects of the Student class and display the details of multiple students.

Q28. Write a Java program that defines a class Rectangle with attributes length and breadth. Implement two
constructors: one default constructor and one parameterized constructor. Use the constructors to initialize
the rectangle’s dimensions and calculate its area.

Q29. Write a Java class Employee that has the attributes name, salary, and department. Include a method to
display the employee’s details and another method to calculate an annual bonus based on the employee’s
salary.

Q30. Write a Java program that defines a class Car with attributes brand, model, and price. Use private access
for price, public for brand, and protected for model.

You might also like