Java Fundamentals: Core Syntax Overview
1. Comments
Java supports three types of comments:
- Single-line:
// comment text - Multi-line:
/* comment text */ - Documentation:
/** comment text */— used for generating API documentation.
2. Keywords
Keywords are reserved words with predefined meanings in Java and cannot be used as identifiers (e.g., variable names). Examples include:
abstract, boolean, break, byte, case, catch, char, class, continue, default, do, double, else, enum, extends, final, finally, float, for, if, implements, import, int, interface, instanceof, long, native, new, package, private, protected, public, return, short, static, super, switch, synchronized, this, throw, throws, transient, try, void, volatile, while
3. Literals
4. Variables
A variable represents a named memory location that stores data which may change during program execution.
Syntax: dataType variableName = initialValue;
Example: int salary = 15000;
Rules for using variables:
- Variable names must be unique within the same scope.
- Multiple variables of the same type can be declared in one statement:
int x = 1, y = 2, z = 0; - A variable must be initialized before use.
public static void main(String[] args) {
int value = 1;
System.out.println(value); // Valid: initialized before use
int a = 2, b = 3, result = 0; // Multiple declarations
}
5. Identifiers
Identifiers name variables, methods, classes, etc. Rules:
- Can contain letters, digits, underscores (
_), and dollar signs ($). - Cannot start with a digit.
- Cannot be a keyword.
- Case-sensitive (e.g.,
count≠Count).
6. Data Types
Java has eight primitive data types:
Usage guidelines:
- Prefer
intfor integers; uselongonly when necessary (appendLorl:long num = 100L;). - Perfer
doublefor decimals; usefloatonly if needed (appendForf:float val = 3.14f;).
7. Keyboard Input with Scanner
To read user input, use the Scanner class:
import java.util.Scanner;
public class InputExample {
public static void main(String[] args) {
Scanner inputReader = new Scanner(System.in);
// Use inputReader.nextInt(), nextLine(), etc.
}
}
8. Operators and Expressions
Operators perform operatoins on operands (variables or literals). An expression combines operands and operators.
Example: Extract digits from a 3-digit number n:
- Units digit:
n % 10 - Tens digit:
(n / 10) % 10 - Hundreds digit:
n / 100
9. Increment and Decrement Operators
++: increments a variable by 1 (e.g.,count++)--: decrements a variable by 1 (e.g.,count--)
10. Type Conversion
Implicit (Widening) Conversion
Automatically converts a smaller type to a larger one:
int a = 10;
double b = a; // Valid: int → double
In arithmetic expressions, byte, short, and char are promoted to int:
byte x = 10, y = 20;
int sum = x + y; // x and y promoted to int before addition
Explicit (Narrowing) Conversion
Manually convert a larger type to a smaller one using casting:
double d = 10.8;
int i = (int) d; // i becomes 10 (fractional part discarded)
Syntax: (targetType) expression