Getting Started with Java Fundamentals
0. Comments
// Single-line comment
/* Multi-line comment */
/** Documentation comment for classes and methods */
1. Basic Output
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
2. Reading Input from Console
import java.util.Scanner;
public class ReadInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double value = scanner.nextDouble();
System.out.println("You entered: " + value);
}
}
3. Identifiers
Identifiers in Java are sequences composed of letters, digits, underscores (_), and dollar signs ($). Rules include:
- Must start with a letter, underscore, or dollar sign—not a digit.
- Cannot be Java keywords (e.g.,
class,public). - Cannot be the literals
true,false, ornull. - Can be of any length.
Java is case-sensitive. Prefer descriptive names over abbreviations. Avoid using single characters except in auto-generated code.
4. Variable Declaration
// Declaration only
int count;
double price;
long total, balance;
// Declaration with initialization
int score = 100;
double width = 5.5, height = 3.2;
5. Assignment Statements
int y = 1;
double radius = 1.0;
int result = 5 * (3 / 2); // Integer division: 3/2 = 1
result = y + 1;
result = result + 1; // Increment by 1
6. Constants
final double PI = 3.14159;
7. Naming Conventions
Use clear, descriptive names for variables, constants, classes, and methods:
- Variables and methods: Use camelCase—start with lowercase, capitalize subsequent words (e.g.,
studentCount,calculateArea). - Classes: Use PascalCase—capitalize the first lettter of every word (e.g.,
CircleCalculator,FileHandler). - Constants: Use uppercase with underscores between words (e.g.,
MAX_SIZE,DEFAULT_TIMEOUT).