Java Syntax:
Java syntax refers to the set of rules that define how a Java program is written and interpreted.
Basic structure:
public class ClassName {
public static void main(String[] args) {
// Code goes here
}
}- Java programs are class-based.
- Every statement ends with a semicolon (;).
- The file name must match the public class name (e.g., ClassName.java).
Java Comments:
Comments in Java are non-executable statements used to explain and document the code. The Java compiler ignores them during compilation.
They help:
- Make code easier to understand
- Explain logic
- Disable code temporarily
- Document APIs (especially with JavaDoc)
Types of Java Comments:
- Single-line Comment: Starts with
// - Multi-line Comment: Starts with
/*and ends with*/
// Single-line comment
/*
Multi-line comment
*/Java Output:
- System.out.print() prints text without moving to a new line.
- System.out.println() prints text and moves to the next line.
public class OutputExample {
public static void main(String[] args) {
System.out.print("Hello");
System.out.print(" World");
System.out.println("!");
System.out.println("This is on a new line.");
}
}Java Variables
A variable in Java is a named storage location in memory that holds a value which can be changed during program execution.
Rules for Naming Variables:
- Must begin with a letter (A–Z or a–z), _, or $.
- Cannot begin with a digit.
- Cannot use Java reserved keywords (int, class, etc.).
- Use camelCase for naming (e.g., studentName).
Syntax:
dataType variableName = value;Examples:
int age = 25;
double salary = 45000.50;
String name = "Alice";Java Constants:
A constant is a variable whose value cannot be changed after it’s assigned. Use the final keyword.
Syntax:
final dataType CONSTANT_NAME = value;Example:
final double PI = 3.14159;The main() Method:
The main() method is the starting point of every Java application.
Syntax:
public static void main(String[] args) {
// Statements
}- public: Accessible by JVM from anywhere.
- static: Runs without creating an object.
- void: Doesn’t return a value.
- String[] args: Accepts command-line arguments.
Complete Example:
public class BasicsExample {
public static void main(String[] args) {
// Display a message
System.out.println("Welcome to Java!");
// Variables
int age = 20;
String name = "Bob";
// Constant
final double PI = 3.14;
// Output
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Value of PI: " + PI);
}
}