Week1 Basic Java Practice questions – Control Structures
1. Even or Odd Number Check:
Write a program that asks the user to enter a number. Use an if statement to check if the
number is even or odd:
import java.util.Scanner;
public class OddEven {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
if(num%2==0){
System.out.println("Even");
}
else{
System.out.println("Odd");
}
scanner.close();
}
}
Output:
2. Age Verification:
Create a program that asks the user for their age. Use an if statement to determine
eligibility to
vote:
• If the user's age is 18 or above, print "You are eligible to vote."
• Otherwise, print "You are not eligible to vote."
import java.util.*;
class Age{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int age=sc.nextInt();
if(age>=18){
System.out.println("You are eligible to vote");
}
else{
System.out.println("You are not eligible to vote");
}
sc.close();
}
}
Output:
3. Vending Machine (Single Choice):
Simulate a simple vending machine with two options:
• Display a message "Press 1 for juice or 2 for soda."
• Ask the user for their choice using nextInt() method.
• Use an if statement to check the choice:
o If 1, print "Dispensing juice."
o If 2, print "Dispensing soda."
o Otherwise, print "Invalid choice."
import java.util.*;
public class Calculator {
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
System.out.print("Enter 1 for addition or 2 for subtraction: ");
int choice=sc.nextInt();
if(choice==1){
System.out.print("Enter num 1: ");
int x=sc.nextInt();
System.out.print("Enter num 2: ");
int y=sc.nextInt();
System.out.println("Sum is "+(x+y));
}
else if(choice==1){
System.out.print("Enter num 1: ");
int x=sc.nextInt();
System.out.print("Enter num 2: ");
int y=sc.nextInt();
System.out.println("Sum is "+(x-y));
}
else{
System.out.println("Invalid");
}
sc.close();
}
}
Output:
4. Temperature Check:
Write a program that asks the user for the current temperature. Use a series of if
statements to
categorize the temperature:
• If the temperature is above 30 degrees Celsius, print "It's hot!"
• If the temperature is between 20 and 30 degrees Celsius, print "It's warm."
• If the temperature is between 10 and 20 degrees Celsius, print "It's cool."
• Otherwise, print "It's cold."
import java.util.Scanner;
public class Grading {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int score = sc.nextInt();
String grade;
int gradeCategory = score / 10;
switch (gradeCategory) {
case 10:
case 9:
grade = "A+";
break;
case 8:
grade = "A";
break;
case 7:
grade = "B";
break;
case 6:
grade = "C";
break;
case 5:
grade = "D";
break;
case 4:
case 3:
case 2:
case 1:
case 0:
default:
grade = "F";
break;
}
System.out.println(grade);
sc.close();
}
}
Output:
5. Positive, Negative, or Zero:
Create a program that asks the user to enter a number. Use an if statement with else if to
check the number's sign:
• If the number is greater than 0, print "The number is positive."
• If the number is less than 0, print "The number is negative."
• Otherwise, print "The number is zero."
import java.util.*;
public class numb {
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int number=sc.nextInt();
if(number>0){
System.out.println("The numebr is positive");
}
else if(number<0){
System.out.println("The number is negetive");
}
else{
System.out.println("The numeb is zero");
}
sc.close();
}
}
Output:
6.Grading System:
Write a program that asks the user for their exam score. Use a switch statement to
assign a letter
grade based on the score:
• 90-100: "A" (Excellent)
• 80-89: "B" (Very Good)
• 70-79: "C" (Good)
• 60-69: "D" (Satisfactory)
• Below 60: "F" (Fail)
• You can add a default case for any invalid score input.
import java.util.*;
public class Temp{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int temp=sc.nextInt();
if(temp>30){
System.out.println("It's hot");
}
else if(temp>20||temp<=30){
System.out.println("It's warm");
}
else if(temp>10||temp<=20){
System.out.println("It's cool");
}
else{
System.out.println("It's cold");
}
sc.close();
}
}
Output:
7.Simple Calculator:
Create a basic calculator that performs addition or subtraction based on user input:
• Display a message "Enter 1 for addition or 2 for subtraction."
• Ask the user for their choice using nextInt().
• Use an if statement to check the choice:
o If 1, ask for two numbers and print their sum.
o If 2, ask for two numbers and print their difference.
• Add an else statement to handle invalid choices.
import java.util.*;
public class VendingMachine {
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
System.out.println("Press 1 for juice or 2 for soda");
int choice=sc.nextInt();
if(choice==1){
System.out.println("Dispensing juice");
}
else if(choice==2){
System.out.println("Dispensing soda");
}
else{
System.out.println("Invalid choice");
}
sc.close();
}
}
Output:
8.Leap Year Check:
Write a program to determine if a given year is a leap year. A leap year is a year divisible
by 4,
but not by 100 unless also divisible by 400. Use a combination of if and else if statements
to
achieve this:
• Ask the user for the year.
• Check divisibility by 4:
o If divisible by 4 but not by 100, it's a leap year.
o If divisible by 100, further check divisibility by 400.
▪ If divisible by 400, it's a leap year.
• Otherwise, it's not a leap year. (Use else statement)
import java.util.Scanner;
public class LeapYear {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a year: ");
int year = scanner.nextInt();
boolean isLeapYear = false;
if (year % 4 == 0) {
if (year % 100 == 0) {
if (year % 400 == 0) {
isLeapYear = true;
}
} else {
isLeapYear = true;
}
}
if (isLeapYear) {
System.out.println(year + " is a leap year.");
} else {
System.out.println(year + " is not a leap year.");
}
scanner.close();
}
}
Output:
Week 2 Practice Questions – Structured Programming
Paradigm (Iterative Statements)
Date:31-07-2025
For Loop:
1. Calculate and print the factorial of a given non-negative integer
using a for loop.
import java.util.*;
public class factorial {
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int fact=1;
int num=sc.nextInt();
if(num==0){
System.out.println(1);
}
else if(num<0){
System.out.println("Invalid");
}
else{
for(int x=num;x>0;x--){
fact=fact*x;
System.out.println(fact);
}
}
sc.close();
}
}
Output:
2. Print the multiplication table of a given number using for loop types
import java.util.Scanner;
public class MultiplicationTable {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
for(int i = 1; i <= 10; i++) {
System.out.println(num + " x " + i + " = " + (num * i));
}
}
}
Output:
3. Print all even numbers from 1 to a given number using a for loop.
import java.util.Scanner;
public class EvenNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = scanner.nextInt();
for(int i = 2; i <= n; i += 2) {
System.out.println(i);
}
}
}
Output:
4. Print all odd numbers from 1 to a given number using a for loop.
import java.util.Scanner;
public class OddNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = scanner.nextInt();
for(int i = 1; i <= n; i += 2) {
System.out.println(i);
}
}
}
Output:
5. Calculate and print the simple interest for a given principal, rate, and
number of years using a for loop.
import java.util.Scanner;
public class SimpleInterest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter principal amount: ");
double principal = scanner.nextDouble();
System.out.print("Enter annual interest rate (in %): ");
double rate = scanner.nextDouble();
System.out.print("Enter number of years: ");
int years = scanner.nextInt();
for (int i = 1; i <= years; i++) {
double interest = (principal * rate * i) / 100;
System.out.println("Year " + i + ": Simple Interest = " + interest);
}
}
}
Output:
While loop:
1. Print the multiplication table of a given number using While loop
import java.util.Scanner;
public class MultiplicationTableWhile {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
int i = 1;
while (i <= 10) {
System.out.println(num + " x " + i + " = " + (num * i));
i++;
}
}
}
Output:
2. Print the following pattern using nested loops:
*
**
***
****
*****
public class StarPatternWhile {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
int j = 1;
while (j <= i) {
System.out.print("*");
j++;
}
System.out.println();
i++;
}
}
}
Output:
3. Calculate the sum of natural numbers from 1 to a given number using
a while loop.
import java.util.Scanner;
public class SumOfNaturalNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = scanner.nextInt();
int sum = 0;
int i = 1;
while (i <= n) {
sum += i;
i++;
}
System.out.println("Sum of natural numbers from 1 to " + n + " is: " + sum);
}
}
Output:
4. Calculate the average of a series of numbers entered by the user using
a while loop.
import java.util.Scanner;
public class AverageCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("How many numbers do you want to enter? ");
int count = scanner.nextInt();
int i = 0;
double sum = 0;
while (i < count) {
System.out.print("Enter number " + (i + 1) + ": ");
double num = scanner.nextDouble();
sum += num;
i++;
}
if (count > 0) {
double average = sum / count;
System.out.println("Average = " + average);
} else {
System.out.println("No numbers entered.");
}
}
}
Output:
5. Print numbers from 1 to a given number using a while loop.
import java.util.Scanner;
public class PrintNumbersWhile {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = scanner.nextInt();
int i = 1;
while (i <= n) {
System.out.println(i);
i++;
}
}
}
Output:
Do while loop:
1. Find the sum of even numbers from 1 to a given number using a do-
while loop.
import java.util.Scanner;
public class SumEvenDoWhile {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = scanner.nextInt();
int i = 2;
int sum = 0;
do {
if (i % 2 == 0) {
sum += i;
}
i++;
} while (i <= n);
System.out.println("Sum of even numbers from 1 to " + n + " is: " + sum);
}
}
Output:
2. Print the powers of 2 up to a given exponent using a do-while loop.
import java.util.Scanner;
public class PowersOfTwo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the maximum exponent: ");
int exponent = scanner.nextInt();
int i = 0;
do {
int result = (int) Math.pow(2, i);
System.out.println("2^" + i + " = " + result);
i++;
} while (i <= exponent);
}
}
Output:
3. Print the multiplication table of a given number using do while loop
import java.util.Scanner;
public class MultiplicationTableDoWhile {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
int i = 1;
do {
System.out.println(num + " x " + i + " = " + (num * i));
i++;
} while (i <= 10);
}
}
Output:
4. Calculate the factorial of a non-negative number using a do-while
loop.
import java.util.Scanner;
public class FactorialDoWhile {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a non-negative number: ");
int num = scanner.nextInt();
if (num < 0) {
System.out.println("Factorial is not defined for negative numbers.");
return;
}
int i = 1;
long factorial = 1;
do {
factorial *= i;
i++;
} while (i <= num);
System.out.println("Factorial of " + num + " is: " + factorial);
}
}
Output:
5. Continuously prompt the user to enter a positive number until they
provide a valid input.
import java.util.Scanner;
public class PositiveNumberPrompt {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number;
do {
System.out.print("Enter a positive number: ");
number = scanner.nextInt();
if (number <= 0) {
System.out.println("Invalid input. Please try again.");
}
} while (number <= 0);
System.out.println("You entered a valid positive number: " + number);
}
}
Output:
Week 3 Java Practice questions – Classes and Object Creation
Date:07-08-2025
1. Create a class named Car with the following attributes:
➢ model (String)
➢ year (int)
➢ color (String)
Create a method display CarInfo() to print the car's information. Create two Car
objects and display their information.
Viva questions:
1. What is an operator used for creating an object for the class?
2. What is the purpose of the displayCarInfo() method?
3. How do you create an object of a class in Java?
4. What happens if you don’t initialize the attributes before calling the display
method?
5. Can we create multiple objects for the same class? If yes, how?
class Car {
String model;
int year;
String color;
void displayCarInfo() {
System.out.println("Model: " + model);
System.out.println("Year: " + year);
System.out.println("Color: " + color);
}
public static void main(String[] args) {
Car car1 = new Car();
car1.model = "Toyota";
car1.year = 2020;
car1.color = "Red";
Car car2 = new Car();
car2.model = "Honda";
car2.year = 2022;
car2.color = "Blue";
car1.displayCarInfo();
car2.displayCarInfo();
}
}
Output:
2. Create a class named Rectangle with attributes width and height (both double). Create
methods to calculate the area and perimeter of the rectangle. Create a Rectangle
object, set its dimensions, and calculate and print its area and perimeter.
Viva questions:
1. What are the data types used for width and height in this program? Why?
2. What is the formula for calculating the area and perimeter of a rectangle?
3. How do you call a method of a class from the main method?
4. What is the difference between instance variables and local variables?
class Rectangle {
double width;
double height;
double calculateArea() {
return width * height;
}
double calculatePerimeter() {
return 2 * (width + height);
}
public static void main(String[] args) {
Rectangle rect = new Rectangle();
rect.width = 5.5;
rect.height = 3.0;
System.out.println("Area: " + rect.calculateArea());
System.out.println("Perimeter: " + rect.calculatePerimeter());
}
}
Output:
3. Create a class named Student with attributes name, rollNumber, and marks. Create a
method calculateGrade() to calculate the grade based on marks. Create a Student
object, set its details, calculate the grade, and print the student's information along
with the grade.
Viva questions:
1. How would you modify the class if there were 5 subjects?
2. What is the return type of the calculateGrade() method?
class Student {
String name;
int rollNumber;
int marks;
String calculateGrade() {
if (marks >= 90) return "A";
else if (marks >= 75) return "B";
else if (marks >= 60) return "C";
else if (marks >= 40) return "D";
else return "F";
}
public static void main(String[] args) {
Student student = new Student();
student.name = "John";
student.rollNumber = 101;
student.marks = 82;
System.out.println("Name: " + student.name);
System.out.println("Roll Number: " + student.rollNumber);
System.out.println("Marks: " + student.marks);
System.out.println("Grade: " + student.calculateGrade());
}
}
Output:
4.Create a class named Car with the following attributes:
➢ model (String)
➢ year (int)
➢ color (String)
Create a constructor to initialize these attributes. Create a method displayCarInfo() to
print the car'sinformation. Create two Car objects and display their information.
Viva questions
1. What is a constructor?
2. How is a constructor different from a method?
3. What happens if you do not define any constructor in a class?
4. Can we have multiple constructors in the same class? What is this called?
class Car {
String model;
int year;
String color;
Car(String model, int year, String color) {
this.model = model;
this.year = year;
this.color = color;
}
void displayCarInfo() {
System.out.println("Model: " + model);
System.out.println("Year: " + year);
System.out.println("Color: " + color);
}
public static void main(String[] args) {
Car car1 = new Car("Ford", 2019, "Black");
Car car2 = new Car("BMW", 2021, "White");
car1.displayCarInfo();
car2.displayCarInfo();
}
}
Output:
5.Create a class named Person with attributes name, age, and address. Create a default
constructor and a parameterized constructor. Create a method displayPersonInfo() to
print the person's information. Create two Person objects, one using the default
constructor and the other using the parameterized constructor. Display information for
both objects.
Viva questions
1. What is a default constructor? When is it called?
2. How do you create a parameterized constructor?
3. What is constructor overloading?
4. Can a constructor be private?
5. How would you initialize object values using both constructors?
class Person {
String name;
int age;
String address;
Person() {
name = "Unknown";
age = 0;
address = "Not Provided";
}
Person(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
void displayPersonInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Address: " + address);
}
public static void main(String[] args) {
Person person1 = new Person();
Person person2 = new Person("Alice", 30, "New York");
person1.displayPersonInfo();
person2.displayPersonInfo();
}
}
Output:
Week 4 – Java Program Questions (Access Specifiers & Static) 13-08-2025
1. Private Variable with Getter & Setter
Write a program where a class Student has a private int marks.
o Use public methods setMarks(int) and getMarks() to assign and display
marks.
o Show that direct access to marks is not possible from main.
ans=
class Student {
private int marks;
public void setMarks(int m) {
marks = m;
}
public int getMarks() {
return marks;
}
}
public class Main1 {
public static void main(String[] args) {
Student s = new Student();
s.setMarks(90);
System.out.println("Marks: " + s.getMarks());
// s.marks = 100; // Error: marks has private access
}
}
Output:
2. Protected Variable Access in Subclass
Create a class Vehicle with a protected int speed.
o Create a subclass Car that modifies and displays the speed.
o Demonstrate access in both same package and a different package.
ans=
Protected Variable Access in Subclass (Same Package)
class Vehicle {
protected int speed;
}
class Car extends Vehicle {
public void setSpeed(int s) {
speed = s;
}
public void displaySpeed() {
System.out.println("Speed: " + speed);
}
}
public class Main2 {
public static void main(String[] args) {
Car c = new Car();
c.setSpeed(80);
c.displaySpeed();
}
}
Output:
Protected Variable Access in Subclass (Different Package)
File: vehicles/Vehicle.java
package vehicles;
public class Vehicle {
protected int speed;
}
File: cars/Car.java
package cars;
import vehicles.Vehicle;
public class Car extends Vehicle {
public void setSpeed(int s) {
speed = s;
}
public void displaySpeed() {
System.out.println("Speed: " + speed);
}
}
File: cars/Main3.java
package cars;
public class Main3 {
public static void main(String[] args) {
Car c = new Car();
c.setSpeed(80);
c.displaySpeed();
}
}
Output:
3. Public Method Access Across Packages Write two classes in different packages.
o Class A has a public method display().
o Class B calls display() using an object of A.
ans=
File: packagea/A.java
package packagea;
public class A {
public void display() {
System.out.println("Display from class A");
}
}
File: packageb/B.java
package packageb;
import packagea.A;
public class B {
public static void main(String[] args) {
A obj = new A();
obj.display();
}
}
Output:
4. Static Variable Counting Objects
Write a class Employee with a static int count.
o Increment count every time a new Employee object is created.
o Display total number of employees created.
ans=
Output:
Total Employees: 3
5. Static Method Usage
Create a class MathUtility with:
o A static method add(int, int)
o A non-static method multiply(int, int)
o Demonstrate calling both methods in main.
ans=
class MathUtility {
public static int add(int a, int b) {
return a + b;
}
public int multiply(int a, int b) {
return a * b;
}
}
public class Main5 {
public static void main(String[] args) {
int sum = MathUtility.add(5, 10);
MathUtility mu = new MathUtility();
int product = mu.multiply(3, 4);
System.out.println("Sum: " + sum);
System.out.println("Product: " + product);
}
}
Output: