1. Write a Java program to check if a number is even or odd.
solution:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = input.nextInt();
if (num % 2 == 0) {
System.out.println(num + " is even.");
} else {
System.out.println(num + " is odd.");
}
}
}
2. Write a Java program to find the largest among three numbers.
solution:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter three numbers: ");
int num1 = input.nextInt();
int num2 = input.nextInt();
int num3 = input.nextInt();
int largest = num1;
if (num2 > largest) {
largest = num2;
}
if (num3 > largest) {
largest = num3;
}
System.out.println("The largest number is " + largest);
}
}
3. Write a Java program to reverse a string.
solution:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = input.nextLine();
String reversed = "";
for (int i = str.length() - 1; i >= 0; i--) {
reversed += str.charAt(i);
}
System.out.println("The reversed string is " + reversed);
}
}
4. Write a Java program to find the factorial of a number.
solution:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = input.nextInt();
int factorial = 1;
for (int i = 1; i <= num; i++) {
factorial *= i;
}
System.out.println("The factorial of " + num + " is " + factorial);
}
}
5. Write a Java program to check if a string is a palindrome.
solution:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = input.nextLine();
boolean isPalindrome = true;
for (int i = 0; i < str.length() / 2; i++) {
if (str.charAt(i) != str.charAt(str.length() - 1 - i)) {
isPalindrome = false;
break;
}
}
if (isPalindrome) {
System.out.println(str + " is a palindrome.");
} else {
System.out.println(str + " is not a palindrome.");
}
}
}
I hope this helps! 😊
Comments
Post a Comment