Code Snippets
Java Snippets
Base Structure
Class Declaration
public class MyClass {
// code
}
Main Method
public static void main(String[] args) {
// code
}
Constructor
public MyClass() {
// initialization code
}
Instance Variable
public class MyClass {
int myVar = 10;
}
Loops
For Loop
for(int i = 0; i < 10; i++) {
System.out.println(i);
}
While Loop
int i = 0;
while(i < 10) {
System.out.println(i);
i++;
}
Do-While Loop
int i = 0;
do {
System.out.println(i);
i++;
} while(i < 10);
Enhanced For Loop
int[] numbers = {1, 2, 3};
for(int num : numbers) {
System.out.println(num);
}
Decision Making
If-Else Statement
if (condition) {
// code
} else {
// code
}
Switch Statement
switch (value) {
case 1:
System.out.println("One");
break;
default:
System.out.println("Other");
}
Ternary Operator
int result = (a > b) ? a : b;
Nested If
if (a > 0) {
if (b > 0) {
System.out.println("Both positive");
}
}
Methods
Method Declaration
public void myMethod() {
// code
}
Return Method
public int add(int a, int b) {
return a + b;
}
Static Method
public static void print() {
System.out.println("Hello");
}
Method with Parameters
public void greet(String name) {
System.out.println("Hello, " + name);
}
Back to categories