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

Java Module-1 Practice based Assignment question and solution

The document contains a series of Java programming assignments for first-year students, covering fundamental concepts such as conditional statements, loops, methods, and array manipulation. Each assignment includes a description and a sample Java program that demonstrates the required functionality, such as checking for vowels, finding the largest number, calculating factorials, and generating patterns. The assignments aim to enhance students' understanding of object-oriented programming through practical coding exercises.

Uploaded by

p38981094
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Java Module-1 Practice based Assignment question and solution

The document contains a series of Java programming assignments for first-year students, covering fundamental concepts such as conditional statements, loops, methods, and array manipulation. Each assignment includes a description and a sample Java program that demonstrates the required functionality, such as checking for vowels, finding the largest number, calculating factorials, and generating patterns. The assignments aim to enhance students' understanding of object-oriented programming through practical coding exercises.

Uploaded by

p38981094
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

22AI104002 - OBJECT ORIENTED PROGRAMMINGTHROUGH JAVA

For First Year II Semester DS


Module-1 Practice based Assignment Questions

1. Write Java program that checks if an entered character is a vowel or a consonant.


Program:
import java.util.Scanner;
public class VowelOrConsonant {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

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


char ch = sc.next().charAt(0); // Read the first character
// Check if the character is a letter
if (Character.isLetter(ch)) {
// Convert the character to lowercase for easier comparison
ch = Character.toLowerCase(ch);

// Check if the character is a vowel


if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
System.out.println(ch + " is a vowel.");
} else {
System.out.println(ch + " is a consonant.");
}
} else {
System.out.println("Please enter a valid alphabetic character.");
}
sc.close();
}
}
2. Write a program that takes three numbers as input and prints the largest number using
if-else statements.
Program:
import java.util.Scanner;
public class LargestNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter three numbers: ");
int num1 = sc.nextInt();
int num2 = sc.nextInt();
int num3 = sc.nextInt();

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


System.out.println("The largest number is: " + num1);
} else if (num2 >= num1 && num2 >= num3) {
System.out.println("The largest number is: " + num2);
} else {
System.out.println("The largest number is: " + num3);
}
}
}
Output:

3. Write a Java program that asks the user to input a series of numbers and then prints
the largest number in the list.
1. Prompt the user for the number of inputs:
2. Enter the values:
3. Find the largest value:
4. Display the largest value as result:

Program:
import java.util.Scanner;
public class MinMaxArray {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements in the array: ");
int n = scanner.nextInt();

int[] numbers = new int[n]; // Create an array of the given size


System.out.println("Enter the values for the array:");
for (int i = 0; i < n; i++) {
numbers[i] = scanner.nextInt();
}

int smallest = numbers[0];


int largest = numbers[0];

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


if (numbers[i] < smallest) {
smallest = numbers[i];
}
if (numbers[i] > largest) {
largest = numbers[i];
}
}
System.out.println("The smallest value in the array is: " + smallest);
System.out.println("The largest value in the array is: " + largest);

}
}

(OR)

import java.util.Arrays;
import java.util.Scanner;
public class MinMaxArray {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Prompt the user for the number of elements in the array


System.out.print("Enter the number of elements in the array: ");
int n = scanner.nextInt();
int[] numbers = new int[n]; // Create an array of the given size

// Prompt the user to enter the values for the array


System.out.println("Enter the values for the array:");
for (int i = 0; i < n; i++) {
numbers[i] = scanner.nextInt();
}

// Find the smallest and largest values using Arrays class methods
int smallest = Arrays.stream(numbers).min().getAsInt();
int largest = Arrays.stream(numbers).max().getAsInt();

System.out.println("The smallest value in the array is: " + smallest);


System.out.println("The largest value in the array is: " + largest);

scanner.close();
}
}

4. In an Inventory Management System for a store, the system allows the user to input
the prices of 5 different products using array. The program calculates the total price,
the highest price, and the lowest price of the products.
Program:
import java.util.Scanner;
public class InventoryManagement {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double[] prices = new double[5];
System.out.println("Enter the prices of 5 different products:");
for (int i = 0; i < prices.length; i++) {
System.out.print("Enter price of product " + (i + 1) + ": ");
prices[i] = scanner.nextDouble();
}
double totalPrice = 0;
double highestPrice = prices[0];
double lowestPrice = prices[0];

for (int i = 0; i < prices.length; i++) {


totalPrice += prices[i];
if (prices[i] > highestPrice) {
highestPrice = prices[i];
}
if (prices[i] < lowestPrice) {
lowestPrice = prices[i];
}
}
System.out.println("\nTotal Price of all products: " + totalPrice);
System.out.println("Highest Price: " + highestPrice);
System.out.println("Lowest Price: " + lowestPrice);

}
}

5. Write a Java program that checks if a given number is prime or not by using a for
loop.
Program:
import java.util.Scanner;

public class PrimeNumber {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();

boolean isPrime = true;


for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}

if (isPrime && num > 1) {


System.out.println(num + " is a prime number.");
} else {
System.out.println(num + " is not a prime number.");
}
}
}
6. Write a program that takes an integer and calculates its factorial using a method.
Program:
import java.util.Scanner;

public class Factorial {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();

System.out.println("Factorial of " + num + " is: " + factorial(num));


}

public static int factorial(int num) {


int fact = 1;
for (int i = 1; i <= num; i++) {
fact *= i;
}
return fact;
}
}
7. Write a Java program to sum the elements of an integer array using a method.
Program:
public class SumArray {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
System.out.println("Sum of array elements is: " + sumArray(arr));
}

public static int sumArray(int[] arr) {


int sum = 0;
for (int num : arr) {
sum += num;
}
return sum;
}
}
8. Write a program that checks if a number is even or odd using a conditional statement.
Program:
import java.util.Scanner;
public class EvenOdd {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();

if (num % 2 == 0) {
System.out.println(num + " is even.");
} else {
System.out.println(num + " is odd.");
}
}
}
9. Write a program that generates the Fibonacci series using a recursive method.
Program:
public class Fibonacci {
public static void main(String[] args) {
int n = 10; // Print first 10 Fibonacci numbers
System.out.println("Fibonacci series:");
for (int i = 0; i < n; i++) {
System.out.print(fibonacci(i) + " ");
}
}

public static int fibonacci(int n) {


if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
10. Write a program that checks if a given number is a palindrome using conditional
statements and a for loop.
Program:
import java.util.Scanner;

public class Palindrome {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();

int original = num, reversed = 0;

while (num != 0) {
int digit = num % 10;
reversed = reversed * 10 + digit;
num /= 10;
}

if (original == reversed) {
System.out.println(original + " is a palindrome.");
} else {
System.out.println(original + " is not a palindrome.");
}
}
}
11. Write a method that calculates the sum of digits of a given number.
Program:
import java.util.Scanner;

public class SumOfDigits {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();

System.out.println("Sum of digits is: " + sumOfDigits(num));


}

public static int sumOfDigits(int num) {


int sum = 0;
while (num != 0) {
sum += num % 10;
num /= 10;
}
return sum;
}
}
12. Write a program that uses a method to calculate and return the area of a circle given
its radius.
Program:
import java.util.Scanner;
public class CircleArea {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the radius of the circle: ");
double radius = sc.nextDouble();

System.out.println("Area of the circle is: " + areaOfCircle(radius));


}

public static double areaOfCircle(double radius) {


return Math.PI * radius * radius;
}
}
13. Create a program that uses the this keyword to refer to the current class instance, and
explain its usage in constructors and methods.
Program:
class Student {
private String name;
private int age;

Student(String name, int age) {


this.name = name; // `this` refers to the current object
this.age = age;
}

void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}

public class ThisKeyword {


public static void main(String[] args) {
Student student = new Student("Alice", 20);
student.display();
}
}
14. Write a program that reverses an array using a method and prints the reversed array.
Program:
import java.util.Arrays;
public class ReverseArray {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
System.out.println("Original array: " + Arrays.toString(arr));
reverseArray(arr);
System.out.println("Reversed array: " + Arrays.toString(arr));
}

public static void reverseArray(int[] arr) {


int start = 0;
int end = arr.length - 1;
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
}
15. Write a program that demonstrates the use of the break and continue statements
inside a loop.
Program:
public class BreakContinue {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
continue; // Skip the iteration when i is 5
}
if (i == 8) {
break; // Exit the loop when i is 8
}
System.out.println(i);
}
}
}
16. Write a program using a for loop to print the multiplication table for a given number.
Program:
import java.util.Scanner;
public class MultiplicationTable {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number for which multiplication table you want: ");
int number = scanner.nextInt();
System.out.println("Multiplication table of " + number + ":");
for (int i = 1; i <= 10; i++) {
System.out.println(number + " * " + i + " = " + (number * i));
}
}
}

17. Write a program that prints a pattern of numbers (e.g., a triangle of numbers) using
nested for loops.
1
12
123
1234
12345
Program:
public class NumberPattern {
public static void main(String[] args) {
// Number of rows for the pattern
int rows = 5;
// Outer loop for each row
for (int i = 1; i <= rows; i++) {
// Inner loop to print numbers for each row
for (int j = 1; j <= i; j++) {
System.out.print(j); // Print number without new line
}
System.out.println(); // Move to the next line after each row
}
}
}

18. Write a program to print a right-angled triangle pattern of stars using nested for
loops.
*
**
***
****
*****
******
Program:
public class RightAngledTriangle {
public static void main(String[] args) {
int rows = 6;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
19. Write a program that prints a pyramid of stars (*) with a given number of rows using
a for loop.
*
**
***
****
*****
******
Program:
public class Pyramid {
public static void main(String[] args) {
int rows = 6;
for (int i = 1; i <= rows; i++) {
for (int j = i; j < rows; j++) {
System.out.print(" ");
}
for (int j = 1; j <= i * 2 - 1; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
20. Write a Java program using a do-while loop that simulates a simple ATM system.
The program should:
1. Prompt the user to enter their PIN code.
2. Allow the user to enter the PIN multiple times if the correct one is not
entered (maximum of 3 attempts).
If the correct PIN is entered, the program should display a welcome message. If
the wrong PIN is entered 3 times, the program should display a "Card Blocked"
message and exit.
Program:
import java.util.Scanner;
public class ATMSystem {
public static void main(String[] args) {
final int CORRECT_PIN = 1234;
int attempts = 0;
Scanner scanner = new Scanner(System.in);
int enteredPin; // Variable to store entered PIN
do {
System.out.print("Enter your PIN: ");
enteredPin = scanner.nextInt(); // Read the entered PIN
if (enteredPin == CORRECT_PIN) {
System.out.println("Welcome to your ATM account!");
break; // Exit the loop if the PIN is correct
} else {
attempts++; // Increment the number of attempts
if (attempts < 3) {
System.out.println("Incorrect PIN. You have " + (3 - attempts) + " attempts
left.");
}
}
} while (attempts < 3); // Continue the loop until 3 attempts are reached
if (attempts == 3) {
System.out.println("Card Blocked. Too many incorrect attempts.");
}
}
}

21. Write a Java program using a switch statement to simulate a restaurant menu. The
program should:
1. Display the following options:
1: View Menu
2: Order Food
3: View Bill
4: Exit
2. For each choice:
Option 1: Display available food items.
Option 2: Prompt for a food order and confirm it.
Option 3: Display a placeholder bill.
Option 4: Exit the program.
Invalid input: Show an error message and prompt again.
Program:
import java.util.Scanner;
public class RestaurantMenu {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int choice;
do {
// Display the menu
System.out.println("\nRestaurant Menu:");
System.out.println("1: View Menu");
System.out.println("2: Order Food");
System.out.println("3: View Bill");
System.out.println("4: Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
switch (choice) {
case 1:
// View the menu
System.out.println("\nAvailable Food Items:");
System.out.println("1. Burger");
System.out.println("2. Pizza");
System.out.println("3. Pasta");
System.out.println("4. Salad");
break;

case 2:
// Order food
System.out.print("Enter your food choice (1-4): ");
int foodChoice = scanner.nextInt();
System.out.println("You have ordered item " + foodChoice + ".");
break;

case 3:
// View bill (Placeholder)
System.out.println("\nBill: ");
System.out.println("Burger - 500.00");
System.out.println("Pizza - 600.00");
System.out.println("Pasta - 450.00");
System.out.println("Salad - 200.00");
System.out.println("Total: 1750.00");
break;

case 4:
// Exit the program
System.out.println("Thank you for visiting!");
break;

default:
// Invalid input
System.out.println("Invalid choice. Please try again.");
}
} while (choice != 4); // Loop until the user selects option 4 to exit
}
}

22. Write a program that checks if a given year is a leap year or not using conditional
statements.
Program:
import java.util.Scanner;
public class LeapYear {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a year: ");
int year = sc.nextInt();

if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {


System.out.println(year + " is a leap year.");
} else {
System.out.println(year + " is not a leap year.");
}
}
}
23. Write a program that swaps two numbers using a method (without using a third
variable).
Program:
public class SwapNumbers {
public static void main(String[] args) {
int a = 5, b = 10;
System.out.println("Before swapping: a = " + a + ", b = " + b);
swap(a, b);
}

public static void swap(int a, int b) {


a = a + b;
b = a - b;
a = a - b;
System.out.println("After swapping: a = " + a + ", b = " + b);
}
}
24. To demonstrate method overloading by defining two methods for calculating the area
of different shapes: a rectangle and a circle.
Program:
public class AreaCalculator {
public static void main(String[] args) {
System.out.println("Area of rectangle: " + area(5, 10));
System.out.println("Area of circle: " + area(7));
}

public static int area(int length, int width) {


return length * width;
}

public static double area(int radius) {


return Math.PI * radius * radius;
}
}
25. Write a Java class Book that demonstrates constructor overloading. The class should
represent a book in a library and allow the creation of Book objects with different
sets of details such as title, author, and price. Provide multiple constructors in the
class with different parameter lists to allow for flexibility in object creation.
Program:
class Book {
private String title;
private String author;
private double price;

// Constructor 1: No parameters
public Book() {
title = "Unknown";
author = "Unknown";
price = 0.0;
}

// Constructor 2: Title and author only


public Book(String title, String author) {
this.title = title;
this.author = author;
this.price = 0.0; // Default price
}

// Constructor 3: Title, author, and price


public Book(String title, String author, double price) {
this.title = title;
this.author = author;
this.price = price;
}

// Method to display book details


public void displayDetails() {
System.out.println("Book Title: " + title);
System.out.println("Author: " + author);
System.out.println("Price: $" + price);
}

public static void main(String[] args) {


// Creating Book objects using different constructors
Book book1 = new Book(); // Using the constructor with no parameters
Book book2 = new Book("The Great Gatsby", "F. Scott Fitzgerald"); // Using
constructor with title and author
Book book3 = new Book("1984", "George Orwell", 9.99); // Using constructor
with title, author, and price

System.out.println("Book 1 Details:");
book1.displayDetails();
System.out.println("\nBook 2 Details:");
book2.displayDetails();
System.out.println("\nBook 3 Details:");
book3.displayDetails();
}
}
Design a class called Student to represent the details of a student. The class should include the following
attributes:
 Student ID
 Name of the Student
 Branch
 Year
 Location
 College Name
Use a constructor to assign initial values to these attributes. Additionally, include methods to:
1. Calculate the average marks of the student across 6 subjects.
2. Calculate the student's attendance percentage.
Program:
class Student {
// Attributes
String studentId;
String name;
String branch;
String year;
String location;
String collegeName;
public Student(String studentId, String name, String branch, String year, String location,
String collegeName) {
this.studentId = studentId;
this.name = name;
this.branch = branch;
this.year = year;
this.location = location;
this.collegeName = collegeName;
}
public double calculateAverageMarks(int[] marks) {
int sum = 0;
for (int mark : marks) {
sum += mark;
}
return (double) sum / marks.length;
}
public double calculateAttendancePercentage(int attendedClasses, int totalClasses) {
return ((double) attendedClasses / totalClasses) * 100;
}
}
public class StudentDetails {
public static void main(String[] args) {
// Creating a Student object
Student student = new Student("S123", "John Doe", "Computer Science", "2nd", "New
York", "XYZ University");
int[] marks = {85, 90, 78, 88, 92, 79};
int attendedClasses = 45;
int totalClasses = 50;
double averageMarks = student.calculateAverageMarks(marks);
System.out.println("Average Marks: " + averageMarks);
double attendancePercentage = student.calculateAttendancePercentage(attendedClasses,
totalClasses);
System.out.println("Attendance Percentage: " + attendancePercentage + "%");
}
}

You might also like