SIMPLE JAVA PROGRAMS
✅ Program: Print “Hello, World!”
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
✅ 1. Addition of Two Numbers
public class AddNumbers {
public static void main(String[] args) {
int a = 10;
int b = 20;
int sum = a + b;
System.out.println("Sum = " + sum);
}
}
✅ 2. Check Even or Odd Number
public class EvenOdd {
public static void main(String[] args) {
int num = 7;
if (num % 2 == 0) {
System.out.println(num + " is Even");
} else {
System.out.println(num + " is Odd");
}
}
}
✅ 3. Print Numbers from 1 to 5 (Using Loop)
public class PrintNumbers {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
}
}
✅ 4. Find the Largest of Two Numbers
public class Largest {
public static void main(String[] args) {
int a = 25, b = 40;
if (a > b) {
System.out.println(a + " is larger");
} else {
System.out.println(b + " is larger");
}
}
}
✅ 5. Check Positive or Negative Number
public class PosNeg {
public static void main(String[] args) {
int num = -10;
if (num >= 0) {
System.out.println(num + " is Positive");
} else {
System.out.println(num + " is Negative");
}
}
}
✅ 6. Print Multiplication Table of a Number
public class MultiplicationTable {
public static void main(String[] args) {
int num = 5;
for (int i = 1; i <= 10; i++) {
System.out.println(num + " x " + i + " = " + (num * i));
}
}
}
✅ 7. Calculate 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 of " + num + " is " + fact);
}
}
✅ 8. Reverse a Number
public class ReverseNumber {
public static void main(String[] args) {
int num = 1234;
int rev = 0;
while (num != 0) {
int digit = num % 10;
rev = rev * 10 + digit;
num /= 10;
}
System.out.println("Reversed number = " + rev);
}
}
✅ 9. Check Leap Year
public class LeapYear {
public static void main(String[] args) {
int year = 2024;
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");
}
}
}
✅ 10. Count the Number of Digits in a Number
public class CountDigits {
public static void main(String[] args) {
int num = 12345;
int count = 0;
while (num != 0) {
num /= 10; // remove last digit
count++;
}
System.out.println("Number of digits: " + count);
}
}