Java Programs
Java Programs
1. Hello World
2. Sum of Two Numbers
3. Even or Odd
4. Factorial of a Number
6. Reverse a String
Signature:
Name
(Supervisor)
Name:
(Internal examiner)
Signature:
Name:
(External Examiner)
Signature:
Name:
(Head of Department)
1. Hello World
System.out.println("Hello, World!");
Output:
Hello, World!
Output:
Sum: 12
3. Even or Odd
Output:
4 is Even
4. Factorial of a Number
public class Factorial {
public static void main(String[] args) {
int num = 5;
int fact = 1;
for(int i = 1; i <= num; i++) {
fact *= i;
}
System.out.println("Factorial: " + fact);
}
}
Output:
Factorial: 120
Output:
3 x 1 = 3
3 x 2 = 6
...
3 x 10 = 30
6. Reverse a String
public class ReverseString {
public static void main(String[] args) {
String str = "Java";
String reversed = "";
for(int i = str.length() - 1; i >= 0; i--) {
reversed += str.charAt(i);
}
System.out.println("Reversed: " + reversed);
}
}
Output:
Reversed: avaJ
Output:
7 is a Prime number.
Output:
Largest: 25
Output:
Sum of array: 15
Output (Example):
import java.util.Scanner;
// Input numbers
System.out.print("Enter first number: ");
double num1 = scanner.nextDouble();
// Choose operation
System.out.print("Enter an operator (+, -, *, /): ");
char operator = scanner.next().charAt(0);
double result;
switch (operator) {
case '+':
result = num1 + num2;
System.out.println("Result: " + result);
break;
case '-':
result = num1 - num2;
System.out.println("Result: " + result);
break;
case '*':
result = num1 * num2;
System.out.println("Result: " + result);
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
System.out.println("Result: " + result);
} else {
System.out.println("Error: Cannot divide by zero.");
}
break;
default:
System.out.println("Invalid operator.");
}
scanner.close();
}
}
Sample Output:
Enter first number: 10
Enter second number: 5
Enter an operator (+, -, *, /): *
Result: 50.0
Output:
1
2
3
4
5
Output:
APPLE
BANANA
CHERRY
public static void main(String[] args) throws public static void main(String[]
IOException { args) throws IOException {
Output
Client: Hello from client!