Some sample Java code snippets that cover the most common and essential parts of Java programming, useful for beginners and intermediate level.
1. Variables and Data Types
// Java variable declarations
int age = 25;
double price = 19.99;
boolean isStudent = true;
char grade = 'A';
String name = "Alice";
System.out.println("Name: " + name + ", Age: " + age);
2. Conditional Statements
int number = 10;
if (number > 0) {
System.out.println("Positive");
} else if (number < 0) {
System.out.println("Negative");
} else {
System.out.println("Zero");
}
3. Switch Statement
char grade = 'B';
switch (grade) {
case 'A':
System.out.println("Excellent!");
break;
case 'B':
System.out.println("Well done");
break;
case 'C':
System.out.println("Good");
break;
default:
System.out.println("Needs improvement");
}
4. Loops (for, while, do-while)
// For loop
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}
// While loop
int j = 1;
while (j <= 5) {
System.out.println("While: " + j);
j++;
}
// Do-while loop
int k = 1;
do {
System.out.println("Do-while: " + k);
k++;
} while (k <= 5);
5. Arrays
int[] numbers = {10, 20, 30, 40, 50};
for (int num : numbers) {
System.out.println("Value: " + num);
}
6. Methods (Functions)
public class Calculator {
public static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int result = add(5, 3);
System.out.println("Sum: " + result);
}
}
7. Classes and Objects
class Person {
String name;
int age;
void introduce() {
System.out.println("Hi, I'm " + name + " and I'm " + age + " years old.");
}
}
public class Main {
public static void main(String[] args) {
Person p = new Person();
p.name = "Bob";
p.age = 30;
p.introduce();
}
}
8. Exception Handling
public class ErrorDemo {
public static void main(String[] args) {
try {
int result = 10 / 0;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero");
} finally {
System.out.println("This always runs");
}
}
}
9. String Operations
String text = "Hello, World!";
System.out.println(text.toUpperCase()); // HELLO, WORLD!
System.out.println(text.length()); // 13
System.out.println(text.contains("World")); // true
10. Simple Class with Constructor
class Car {
String model;
Car(String m) {
model = m;
}
void drive() {
System.out.println("Driving " + model);
}
}
public class Main {
public static void main(String[] args) {
Car car = new Car("Toyota");
car.drive();
}
}
These examples should give a foundational understanding of core Java features. Build on these by exploring inheritance, interfaces, collections, file I/O, and more.