Here are some Java programming examples to illustrate various concepts and features of the language:
- Hello World Program
This is a simple program that outputs the message "Hello, World!" to the console.
javapublic class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
- Calculation Program
This program prompts the user to enter two numbers and performs a calculation based on the operator entered.
javaimport java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter the second number: ");
double num2 = scanner.nextDouble();
System.out.print("Enter the operator (+, -, *, /): ");
char operator = scanner.next().charAt(0);
double result;
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
default:
System.out.println("Invalid operator");
return;
}
System.out.println(num1 + " " + operator + " " + num2 + " = " + result);
}
}
- Fibonacci Series Program
This program prints the Fibonacci series up to a specified number of terms.
javaimport java.util.Scanner;
public class Fibonacci {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of terms: ");
int n = scanner.nextInt();
int a = 0, b = 1, c;
System.out.print("Fibonacci series: ");
for (int i = 1; i <= n; i++) {
System.out.print(a + " ");
c = a + b;
a = b;
b = c;
}
}
}
- Factorial Program
This program calculates the factorial of a given number.
javaimport java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = scanner.nextInt();
int fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
System.out.println("Factorial of " + n + " is " + fact);
}
}
- File Handling Program
This program reads a file and prints its contents to the console.
javaimport java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FileHandler {
public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
String line = reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
These are just a few examples of what can be accomplished with Java. By understanding the syntax and features of the language, you can build a wide variety of programs for different purposes.