Java All Code Question :
// 1. Write a Java program that calculates the factorial of a number
entered by the user using a for
// loop
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter N : ");
int n = sc.nextInt();
int fact = 1;
for(int i = 1; i <= n; i++){
fact = fact * i;
}
System.out.println("Factorial = " + fact);
}
}
// 2. Write a Java program that initializes an ArrayList of 5 strings.
Ask the user for an index and
// print the item at that index.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<String> s1 = new ArrayList<>();
s1.add("Devraj");
s1.add("Mayur");
s1.add("Dinesh");
s1.add("Het");
s1.add("Vashu");
System.out.print("What Index Would You Print : ");
int que = sc.nextInt();
System.out.println(que + " Index String = " + s1.get(que));
}
}
// 8. Write a program that creates an array of int with 5 elements
initialized with values. Use a for
// loop to find the maximum value in the array and print it.
public class Main {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5};
int n = 5;
// Check the Maximum value :
int max = Integer.MIN_VALUE;
for(int i = 0; i < n; i++){
if(max < arr[i]){
max = arr[i];
}
}
System.out.println("Maximum Value = " + max);
}
}
// 9. Write a Java program that takes an integer input from the user and
determines whether the
// entered year is a leap year or not.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Any Year : ");
int n = sc.nextInt();
if(n%100 == 0 && n%400 == 0 || n%100 != 0 && n%4 == 0){
System.out.println("Leap Year...");
} else {
System.out.println("Not Leap Year...");
}
}
}
// 10. Write a Java program that prints the numbers from 1 to 10 using a
while loop.
public class Main {
public static void main(String[] args) {
int i = 1;
while(i <= 10){
System.out.println(i);
i++;
}
}
}
// 11. Write a Java program that takes an integer input from the user and
prints whether the number is
// positive, negative, or zero using an if-else statement.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Number : ");
int n = sc.nextInt();
if(n == 0){
System.out.println("Number Is Zero.");
} else if(n > 0){
System.out.println("Number Is Positive.");
} else {
System.out.println("Number Is Negitive.");
}
}
}
// 12. Implement an if-else statement to determine if a user-entered age
is greater than or equal to 18.
// If true then print message “You are eligible for voting.”
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Your Age : ");
int age = sc.nextInt();
if(age >= 18){
System.out.println("You Are Eligible For Voting.");
} else {
System.out.println("You are Not Eligible For Voting.");
}
}
}
// 13. Create a program that uses a while loop to count down from 20 to
1.
import java.util.*;
public class Main {
public static void main(String[] args) {
int i = 20;
while(i >= 1){
System.out.println(i + " Left");
i--;
}
}
}
// 14. Write a method in a Calculator class to find the maximum of two
numbers and call this method
// from main.
import java.util.*;
public class Calculator {
static int max(int i, int j){
if(i > j) return i;
else return j;
}
public static void main(String[] args) {
int i = 20;
int j = 10;
System.out.println("Max = " + max(i, j));
}
}
// 16. Write a method convertTemperature that converts a temperature from
Celsius to Fahrenheit.
// Create a program that uses this method to convert a given temperature
and displays the result.
// Provide the complete code.
import java.util.*;
public class Main {
static double convertTemperature(double c){
double f = (1.8 * c) + 32;
return f;
}
public static void main(String[] args) {
double c = 26.5;
System.out.println("Fahrenheit = " + convertTemperature(c));
}
}
// 18. Create an ArrayList of Integer and populate it with/ 5 different
integers. Write a program that
// calculates and prints the average of these integers.
import java.util.*;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> num = new ArrayList<>();
num.add(1);
num.add(5);
num.add(7);
num.add(9);
num.add(10);
double sum = 0;
for(int i = 0; i < num.size(); i++){
sum = sum + num.get(i);
}
double avg = sum / num.size();
System.out.println("Average Of ArrayList = " + avg);
}
}
// 21. Write a Java program that takes a day of the week as input (1 for
Monday, 2 for Tuesday, etc.)
// and prints the name of the day using a switch statement.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Number : ");
int n = sc.nextInt();
switch(n){
case 1:
System.out.println("MonDay");
break;
case 2:
System.out.println("TuesDay");
break;
case 3:
System.out.println("WednesDay");
break;
case 4:
System.out.println("ThrusDay");
break;
case 5:
System.out.println("FriDay");
break;
case 6:
System.out.println("SaturDay");
break;
case 7:
System.out.println("SunDay");
break;
default:
System.out.println("Please Enter Only 1 To 7 Number
Only.");
}
}
}
// 22. Write a Java program that creates an ArrayList of strings and
populates it with a few items.
// Then, prompt the user to enter an item to remove. After removing the
item, display the updated
// ArrayList.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<String> s1 = new ArrayList<>();
s1.add("devraj");
s1.add("dhaval");
s1.add("dhanraj");
s1.add("jasmeet");
s1.add("mohan");
s1.add("mehul");
System.out.println(s1.toString());
System.out.println("Enter Name You Wan't to Remove :");
String removeItem = sc.nextLine();
sc.close();
}
}
// 24. Write a program that grades a student's score into letter grades
(A, B, C, D, F) using if-else else-if
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Marks : ");
int mark = sc.nextInt();
if(mark >= 85 && mark <= 100){
System.out.println("Grades A");
} else if(mark >= 70 && mark <=84){
System.out.println("Grades B");
} else if(mark >= 55 && mark <=69){
System.out.println("Grades C");
} else if(mark >= 33 && mark <=54){
System.out.println("Grades D");
} else if(mark > 0 && mark < 33){
System.out.println("Grades F");
}
sc.close();
}
}
// 25. Create an ArrayList of String called animals and initialize it
with a few animal names (e.g.,
// "Lion", "Tiger", "Elephant"). Write a program that prompts the user to
enter an animal name.
// Check if the entered animal name is present in the ArrayList. Print a
message indicating whether
// the animal is in the list or not.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<String> s1 = new ArrayList<>();
s1.add("lion");
s1.add("tiger");
s1.add("elephant");
System.out.println("Enter Value You Wan't To Check.");
String check = sc.nextLine();
if(s1.contains(check) == true){
System.out.println(check + " Is Present In the ArrayList.");
}
if(s1.contains(check) == false){
System.out.println(check + " Is Not Present In the
ArrayList. ");
}
sc.close();
}
}
// 29. Write a program that prompts the user to input a number and prints
whether it is even or odd.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Number : ");
int n = sc.nextInt();
if(n %2 == 0) System.out.println(n + " Is Even.");
else System.out.println(n + " Is Odd");
sc.close();
}
}
// 30. Create a program that uses a for loop to calculate the sum of
numbers from 1 to 100.
public class Main {
public static void main(String[] args) {
int sum = 0;
for(int i = 1; i <= 100; i++){
sum += i;
}
System.out.println("Sum = " + sum);
}
}
Output : 5050.
// 32. Write a Java program that uses recursion to calculate the
factorial of a number entered by the
// user
import java.util.*;
public class Main {
static int factorial(int n){
if(n == 0){
return 1;
}
int prev = factorial(n-1);
return n * prev;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Number : ");
int n = sc.nextInt();
System.out.println("Factorial Of " + n + " = " + factorial(n));
}
}
// 31. Create a class Calculator that defines a method addNumbers() which
takes two integers as input
// from the user and prints their sum. Define and call this method from
the main method.
import java.util.*;
public class Main {
static int addNumber(int a, int b){
return a + b;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Num 1 :");
int num1 = sc.nextInt();
System.out.print("Enter Num 2 :");
int num2 = sc.nextInt();
System.out.println("Sum Of " + num1 + " And " + num2 + " = " +
addNumber(num1, num2));
}
}
// 33. Create a program that uses a for-each loop to print all elements
in an ArrayList of Strings
import java.util.*;
public class Main {
public static void main(String[] args) {
ArrayList<String> s1 = new ArrayList<>();
s1.add("Devraj");
s1.add("Dinesh");
s1.add("Devang");
for(String element : s1){
System.out.print(element + " ");
}
}
}
// 35. Write a Java program that accepts a list of numbers from the user, stores them in an array,
and // // then prints the numbers in reverse order
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();
Integer[] numbers = new Integer[n];
System.out.println("Enter the numbers: ");
for (int i = 0; i < n; i++) {
numbers[i] = scanner.nextInt();
}
Collections.reverse(Arrays.asList(numbers));
System.out.println("Numbers in reverse order: ");
for (int num : numbers) {
System.out.print(num + " ");
}
}
}
// 38. Write a program that prompts the user to enter a number and checks
whether it is prime.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if(n > 1){
if(n == 2)
System.out.println("Prime NUmber.");
else if(n %2 == 0)
System.out.println("Not Prime Number.");
else if(n % n == 0 && n % 1 == 0)
System.out.println("Prime Number.");
} else
System.out.println("Please Enter Greater Then 1.");
}
}
// 39. Implement a simple calculator in Java that can perform addition,
subtraction, multiplication, and
// division based on user input.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Num 1 : ");
double num1 = sc.nextDouble();
System.out.print("Enter Num 2 : ");
double num2 = sc.nextDouble();
System.out.println("Enter Operator : '+', '-', '*', '/' ");
char ch = sc.next().charAt(0);
double result;
switch(ch){
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
default:
System.out.println("Enter valid Operator...");
return;
}
System.out.println(num1 + " " + ch + " " + num2 + " = " +
result);
}
}
//40. Write a Java program that reads a string input from the user and
counts the number of vowels in
// it.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter A Word : ");
String str = sc.nextLine();
str = str.toUpperCase();
int count = 0;
for(int i = 0; i < str.length(); i++){
char ch = str.charAt(i);
if(ch != ' '){
if(ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch
== 'U'){
count++;
}
}
}
System.out.println("No Of Vowels : " + count);
}
}
// 42. What is a two-dimensional array in Java? Write a program that uses
a 2D array to store a matrix
// of integers and prints the matrix.
import java.util.*;
public class Main {
static void printMatrix(int[][] arr){
for(int i=0; i<arr.length; i++){
for(int j=0; j<arr[i].length; j++){
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
int[][] arr = {{1,2},{3,4}};
printMatrix(arr);
}
}
// 46. Write a program that takes a number from the user and prints the
multiplication table for that
// number.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter No : ");
int n = sc.nextInt();
for(int i = 1; i <= 10; i++){
System.out.println(n + " x " + i + " = " + n*i);
}
}
}
// 51. Create a program that calculates the sum of all elements in an
array using a for-each loop.
import java.util.*;
public class Main {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5};
int sum = 0;
for(int elements : arr){
sum += elements;
}
System.out.println("Sum = " + sum);
}
}
// 52. Write a Java program that takes a sentence as input from the user
and reverses the order of
// words in the sentence.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Sentance : ");
String str = sc.nextLine();
String[] words = str.split(" ");
String rev = "";
for(int i=words.length -1; i >= 0; i--){
rev = rev + words[i] + " ";
}
System.out.println(rev.trim());
}
}
// 54 . Write a program that demonstrates exception handling by dividing
two numbers and catching
// any ArithmeticException if the divisor is zero.
import java.util.*;
public class Main {
static int quotient(int n, int d){
return n / d;
}
public static void main(String[] args) {
int n = 8;
int d = 2;
try{
int result = quotient(n, d);
System.out.println("Result : " + n + " / " + d + " = " +
result);
}
catch(ArithmeticException e){
System.out.println("Division By Zero");
}
System.out.println("BYE");
}
}
// 57. Write a program that takes an array of integers as input and
checks if the array is sorted in
// ascending order.
import java.util.*;
public class main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter No Of Element : ");
int n = sc.nextInt();
int[] arr = new int[n];
System.out.println("Enter " + n + " Elements");
for(int i = 0; i < n; i++){
arr[i] = sc.nextInt();
}
boolean check = true;
for(int i = 1, j = 0; i < n; i++, j++){
if(arr[j] > arr[i]){
check = false;
break;
}
}
if(check == false) System.out.println("Array Is Not Asending
Order.");
else System.out.println("Array Is Asending Order.");
}
}
// 61. Write a program that reads a list of integers from the user and
prints the smallest and largest
// values in the list using a for loop.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter No of Elements : ");
int n = sc.nextInt();
int[] arr = new int[n];
System.out.println("Enter " + n + " Elements");
for(int i = 0; i < n; i++){
arr[i] = sc.nextInt();
}
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for(int i = 0; i < n; i++){
if(arr[i] > max){
max = arr[i];
}
}
for(int i = 0; i < n; i++){
if(min > arr[i]){
min = arr[i];
}
}
System.out.println("Max = " + max);
System.out.println("Min = " + min);
}
}
// 3. Define a Student class with fields for name, studentID, and
semester. Write a method that prints
// out a summary of the student’s information.
package JavaQue;
public class A_StudentClass {
private String name;
private int studentID;
private int sem;
public A_StudentClass(String name, int studentID, int sem){
this.name = name;
this.studentID = studentID;
this.sem = sem;
}
public void print(){
System.out.println("Name : " + name);
System.out.println("Student ID : " + studentID);
System.out.println("Sem : " + sem);
}
public static void main(String[] args) {
A_StudentClass s1 = new A_StudentClass("Devraj", 1234, 3);
s1.print();
}
}
// QUESTION 17. What is a method and what role does it play in a class?
Define a method in a class that returns a greeting message.
/*
A **method** in Java is a block of code within a class that performs a
specific task. It defines the behavior of objects created from that
class. Methods allow objects to perform actions, interact with other
objects, and encapsulate functionality.
### Role in a Class:
- **Encapsulates behavior**: Defines what an object can do.
- **Enables reuse**: Allows code to be reused by calling the method
multiple times.
- **Supports abstraction**: Hides internal implementation, exposing only
what the method does.
- **Facilitates object interaction**: Methods allow objects to
communicate and perform tasks.
*/
package JavaQue;
public class B_greetingMethod {
static void greeting(){
System.out.println("Hello !!!");
System.out.println("Good Morning !!!");
}
public static void main(String[] args) {
// What is a method and what role does it play in a class? :::
// -->
greeting();
}
}
// 20. Write a Java class Rectangle with a constructor that initializes
width and height. Include a
// method to calculate and print the area of the rectangle.
package JavaQue;
public class C_Rectangle {
double width;
double height;
// Making Constructor :
public C_Rectangle(double width, double height){
this.width = width;
this.height = height;
}
// Making Method to Calculate Area Of Rectangle :
public void areaOfRectangle(){
double area = width * height;
System.out.println("The Area Of RecTangle = " + area);
}
public static void main(String[] args) {
C_Rectangle rect = new C_Rectangle(5, 3);
rect.areaOfRectangle();
}
// 26. Define a class Student with a String field name and an int field
age. Write a method
// displayInfo() that prints the student's name and age. Create an object
of the Student class, assign
// values to the fields, and call the displayInfo() method.
package JavaQue;
public class D_Student {
String name;
int age;
public D_Student(String name, int age){
this.name = name;
this.age = age;
}
public void displayInfo(){
System.out.println("Student Name Is : " + name);
System.out.println("And Student Age is : " + age);
}
public static void main(String[] args) {
D_Student stu1 = new D_Student("Devraj", 19);
D_Student stu2 = new D_Student("HET", 20);
stu1.displayInfo();
stu2.displayInfo();
}
}
// 34. Define a Book class with fields for title, author, and price.
Create a method that applies a
// discount to the price and prints the new price.
package JavaQue;
public class E_Book {
String title;
String author;
int price;
public E_Book(String title, String author, int price){
this.title = title;
this.author = author;
this.price = price;
}
public void discountPrice(int discountPercentage){
int discount = (price * discountPercentage)/ 100;
int afterDiscount = price - discount;
System.out.println("After Discount This Book's Price = " +
afterDiscount + "$");
}
public static void main(String[] args) {
E_Book book1 = new E_Book("Veni na Phool", "Jhaverchand Meghani",
1000);
book1.discountPrice(20);
}
}
// 36. Create a Car class with attributes for model, year, and mileage.
Write a method to calculate the
// car’s depreciation and print the result.
package JavaQue;
public class F_Car {
String model;
int year;
double mileage;
public F_Car(String model, int year, double mileage){
this.model = model;
this.year = year;
this.mileage = mileage;
}
public void depreciation(){
int currentYear = 2024; // You can adjust this based on the
actual year
int age = currentYear - year;
// Simple depreciation formula: assume a car loses 15% of its
value per year
double depreciationRate = 0.15;
double originalValue = 20000; // Assume the car's original value
is $20,000
double depreciation = originalValue * Math.pow(1 -
depreciationRate, age);
System.out.println("The depreciation value of the car is: $" +
depreciation);
}
public static void main(String[] args) {
F_Car car1 = new F_Car("i20", 2019, 50000);
car1.depreciation();
}
}
// QUESTION 41. Create a class Employee with fields for name, employeeID,
and salary. Write a method to give
// the employee a raise and print their new salary.
package JavaQue;
public class G_Employees {
String name;
int employeeID;
double salary;
public G_Employees(String name, int employeeID, double salary){
this.name = name;
this.employeeID = employeeID;
this.salary = salary;
}
public void incriment(double raise){
double hike = (salary * raise) / 100;
double totalSalary = salary + hike;
System.out.println("Employees Total Salary = " + totalSalary);
}
public static void main(String[] args) {
G_Employees emp1 = new G_Employees("Mukesh", 0123, 100000);
emp1.incriment(25);
}
}
// 50. Define a BankAccount class with fields for account number and
balance. Write a method to
// deposit money into the account and another method to withdraw money,
ensuring that the
// balance never goes negative.
package JavaQue;
// import java.util.Scanner;
public class H_BankAccount {
int accountNo;
double balance;
public H_BankAccount(int accountNo, double balance){
this.accountNo = accountNo;
this.balance = balance;
}
public void depositMoney(double deposit){
balance = balance + deposit;
System.out.println("Your Money Is Succesfully Credited.");
System.out.println("Your latest Bank Balance = " + balance);
}
public void withdwaw(double debit){
if(balance >= debit){
balance -= debit;
System.out.println("Your Money Is Suceesfully Debited...");
System.out.println("Your Letest Bank Balance = " + balance);
} else {
System.out.println("Insuffciant Balance..." + balance);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
H_BankAccount acc1 = new H_BankAccount(12345, 2000);
acc1.depositMoney(20000);
acc1.withdwaw(1500);
}
}
// 58. Define an Invoice class with fields for item description,
quantity, and price. Write a method to
// calculate and print the total cost of the invoice.
package JavaQue;
public class I_Invoice {
String itemDescription;
int quantity;
double price;
public I_Invoice(String itemDescription, int quantity, double price){
this.itemDescription = itemDescription;
this.quantity = quantity;
this.price = price;
}
public void invoice(){
System.out.println(" " + quantity + " Quantity");
System.out.println(" " + price + " Per Peice Price");
System.out.println();
double beforeTax = quantity * price;
System.out.println(" " + beforeTax + " Before Tax");
double cgst = (9 * beforeTax) / 100;
System.out.println("+ " + cgst + " CGST");
double sgst = (9 * beforeTax) / 100;
System.out.println("+ " + sgst + " SGST");
System.out.println(" -------------");
double totalBill = beforeTax + cgst + sgst;
System.out.println(" " + totalBill + " Total Payable Amount.");
}
public static void main(String[] args) {
I_Invoice inv1 = new I_Invoice("Cotton Seed Cake", 10, 1000);
inv1.invoice();
}
}