Java is a programming language with a wide range of uses and is well-known for its versatility. If you’ve never used Java before, here are 5 easy-to-use Java programs to get you started and help you understand the basics.
1. Area of a Circle:
This program calculates the area of a circle using the formula A = πr².
public class AreaOfCircle {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the radius of the circle: ");
double radius = scanner.nextDouble();
double area = Math.PI * radius * radius;
System.out.println("Area of the circle: " + area);
scanner.close();
}
}
Output:
Area of the circle: 78.53981633974483
2. Sum of Array Elements:
This program calculates the sum of elements in an array.
public class SumOfArrayElements {
public static void main(String[] args) {
int[] numbers = { 10, 20, 30, 40, 50 };
int sum = 0;
for (int num : numbers) {
sum += num;
}
System.out.println("Sum of array elements: " + sum);
}
}
Output:
Sum of array elements: 150
3. Leap Year Checker:
This program checks whether a given year is a leap year or not.
public class LeapYearChecker {
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 || year % 400 == 0) {
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:
2024 is a leap year.
4. Prime Number Generator:
This program generates prime numbers up to a given limit.
public class PrimeNumberGenerator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the limit: ");
int limit = scanner.nextInt();
System.out.println("Prime numbers up to " + limit + ": ");
for (int i = 2; i <= limit; i++) {
if (isPrime(i)) {
System.out.print(i + " ");
}
}
scanner.close();
}
public static boolean isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}
Output:
Prime numbers up to 20:
2 3 5 7 11 13 17 19
5. Pattern Printer:
This program prints a pattern of stars in a pyramid shape.
public class PatternPrinter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int rows = scanner.nextInt();
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
scanner.close();
}
}
Output:
Enter the number of rows: 5
* *
* * *
* * * *
* * * * *
No comments:
Post a Comment