-
-
Notifications
You must be signed in to change notification settings - Fork 2
Java Syntax Elements
- Introduction
- Keywords
- Identifiers
- Operators
- Punctuation and Delimiters
- Understanding Java Syntax
- Complete Examples
- Practice Exercises
Understanding Java syntax elements is crucial for reading and writing code. In this guide, we'll break down every part of Java code and explain what each piece does. By the end, you'll understand exactly what makes up any Java code.
Keywords are reserved words that have special meaning in Java. You cannot use them as variable names or identifiers.
// Primitive types
int age = 25; // int - integer
double price = 19.99; // double - decimal
boolean isActive = true; // boolean - true/false
char grade = 'A'; // char - single character
// Reference types
String name = "Alice"; // String - text (capital S!)
int[] numbers = {1, 2, 3}; // Array declaration
// Constants
final int MAX_SIZE = 100; // final - constant (can't change)public class MyClass { // public - accessible everywhere
private int value; // private - only in this class
protected String name; // protected - this class + subclasses
int defaultValue; // default (package-private)
}public class Person { // class - defines blueprint
String name;
public Person(String name) { // constructor
this.name = name;
}
}
class Employee extends Person { // extends - inheritance
public Employee(String name) {
super(name); // super - call parent constructor
}
}
interface Drawable { // interface - contract
void draw(); // abstract method
}
class Circle implements Drawable { // implements - interface
@Override // Override annotation
public void draw() { }
}// If-else
if (age >= 18) { // if - conditional
System.out.println("Adult");
} else if (age >= 13) { // else if - alternative
System.out.println("Teen");
} else { // else - fallback
System.out.println("Child");
}
// Switch
switch (day) {
case 1: // case - branch
System.out.println("Monday");
break; // break - exit switch
case 2:
System.out.println("Tuesday");
break;
default: // default - fallback
System.out.println("Unknown");
}
// Loops
for (int i = 0; i < 10; i++) { // for - counted loop
System.out.println(i);
}
while (condition) { // while - loop while true
// code
}
do { // do - runs at least once
// code
} while (condition);try {
// Code that might throw exception
int result = 10 / 0;
} catch (ArithmeticException e) { // catch - handle error
System.out.println("Error: " + e.getMessage());
} finally { // finally - always runs
System.out.println("Done");
}
throw new Exception("Error message"); // throw - create exceptionpublic static void main(String[] args) { // main - program entry
// program starts here
}
public int calculate(int a, int b) { // return type
return a + b; // return - send back value
}
void process() {
return; // return - exit method (void)
}// Type checking
Object obj = "Hello";
if (obj instanceof String) { // instanceof - check type
String str = (String) obj;
}
// this keyword
class Person {
String name;
public Person(String name) {
this.name = name; // this - current object
}
}
// static keyword
class Utils {
static int count = 0; // static - class-level
static void greet() { } // static method
}
// new keyword
Object obj = new Object(); // new - create object
// import keyword
import java.util.Scanner; // import - bring in class
import java.util.*; // wildcard import
// package keyword
package com.example.app; // package - namespace
// true, false, null
boolean flag = true; // true/false - boolean values
Object obj = null; // null - no value// These are reserved and cannot be used as identifiers:
// abstract, assert, boolean, break, byte, case, catch,
// char, class, const, continue, default, do, double,
// else, enum, extends, final, finally, float, for,
// goto, if, implements, import, instanceof, int, interface,
// long, native, new, package, private, protected, public,
// return, short, static, strictfp, super, switch, synchronized,
// this, throw, throws, transient, try, void, volatile, whileIdentifiers are names you create to identify variables, methods, classes, and other user-defined elements.
// ✓ Valid identifiers
int x; // Single letter
int counter; // CamelCase (recommended)
int playerScore; // Descriptive
int _private; // Starting with underscore
int $element; // Starting with dollar sign
int firstName2; // Can include numbers (not start)
int MAX_SIZE; // UPPER_CASE (constants)
int myFunction; // Functions
int MyClass; // Classes (PascalCase)
// ✗ Invalid identifiers
// int 2fast; // Can't start with number
// int my-variable; // Can't use hyphens
// int my variable; // Can't have spaces
// int for; // Can't use keywords
// int class; // Can't use reserved words// Variables - camelCase
String firstName = "John";
int lastName = "Doe";
int userAge = 25;
boolean isActive = true;
// Constants - UPPER_SNAKE_CASE
final int MAX_SIZE = 100;
final String API_BASE_URL = "https://api.example.com";
final int DAYS_IN_WEEK = 7;
// Methods - camelCase with verb
int calculateTotal() { }
String findUserById(int id) { }
boolean validateEmail(String email) { }
// Classes - PascalCase
class User { }
class BankAccount { }
class ShoppingCart { }
class Animal { }
// Interfaces - PascalCase (often with -able or -er)
interface Drawable { }
interface Comparable { }
interface Runnable { }
// Packages - lowercase with dots
package com.example.myapp;
package org.springframework.core;
// Enums - PascalCase
enum Day { MONDAY, TUESDAY, WEDNESDAY }
// Annotations - PascalCase with @ prefix
@Override
@Deprecated
@FunctionalInterfaceOperators are symbols that perform operations on values (operands).
// Basic assignment
int x = 5;
// Compound assignment
int a = 10;
a += 5; // a = a + 5 → 15
a -= 3; // a = a - 3 → 12
a *= 2; // a = a * 2 → 24
a /= 4; // a = a / 4 → 6
a %= 4; // a = a % 4 → 2
// Bitwise assignment
int b = 5;
b <<= 1; // b = b << 1 → 10
b >>= 1; // b = b >> 1 → 2
b &= 3; // b = b & 3
b |= 3; // b = b | 3
b ^= 3; // b = b ^ 3// Basic math
int sum = 10 + 5; // 15 - addition
int diff = 10 - 5; // 5 - subtraction
int product = 10 * 5; // 50 - multiplication
int quotient = 10 / 5; // 2 - division
int remainder = 10 % 3; // 1 - modulo (remainder)
// Increment/decrement
int counter = 5;
counter++; // Post-increment
++counter; // Pre-increment
counter--; // Post-decrement
--counter; // Pre-decrement// Equality (primitives)
5 == 5; // true - equal
5 != 3; // true - not equal
// Relational
5 > 3; // true - greater than
5 < 3; // false - less than
5 >= 5; // true - greater or equal
5 <= 4; // false - less or equal
// For objects, use .equals()
String s1 = "Hello";
String s2 = "Hello";
s1.equals(s2); // true - content comparison
s1 == s2; // might be false! (reference comparison)// AND - both must be true
true && true; // true
true && false; // false
// OR - at least one must be true
true || false; // true
false || false; // false
// NOT - inverts value
!true; // false
!false; // true
// Short-circuit
boolean result = (a != null) && (a.equals("value"));// condition ? valueIfTrue : valueIfFalse
int age = 20;
String status = age >= 18 ? "Adult" : "Minor";
int score = 85;
String grade = score >= 90 ? "A" :
score >= 80 ? "B" :
score >= 70 ? "C" : "F";// AND
5 & 3; // 1 (0101 & 0011 = 0001)
// OR
5 | 3; // 7 (0101 | 0011 = 0111)
// XOR
5 ^ 3; // 6 (0101 ^ 0011 = 0110)
// NOT
~5; // -6 (complement)
// Shift
5 << 1; // 10 (shift left)
5 >> 1; // 2 (signed right shift)
5 >>> 1; // 2 (unsigned right shift)Object obj = "Hello";
if (obj instanceof String) {
String str = (String) obj; // Safe cast
}
// Java 16+ pattern matching
if (obj instanceof String str) {
System.out.println(str.toUpperCase()); // str is cast automatically
}Punctuation (also called delimiters) are symbols that structure and organize code but don't perform operations.
// Method calls
System.out.println("Hello");
myFunction(arg1, arg2);
// Method declarations
public void greet(String name) {
return "Hello, " + name;
}
// Grouping expressions
int result = (a + b) * c;
// Conditionals
if (age > 18) { }
// Cast
(int) 3.14
// Lambda expressions
list.forEach(s -> System.out.println(s));// Class definitions
public class MyClass {
// class body
}
// Method bodies
public void doSomething() {
// code
}
// Code blocks
if (condition) {
int x = 1;
int y = 2;
}
// Array initialization
int[] numbers = {1, 2, 3, 4, 5};
// Static initializer
static {
System.out.println("Class loaded");
}// Array declarations
int[] numbers;
String[] names;
// Array access
int[] arr = {10, 20, 30};
System.out.println(arr[0]); // 10 (0-indexed)
// Multi-dimensional arrays
int[][] matrix = {{1, 2}, {3, 4}};
System.out.println(matrix[1][0]); // 3
// Variable arguments
public void printAll(String... args) { }// Statement terminators (REQUIRED in Java)
int x = 5;
String name = "Alice";
System.out.println("Hello");
// In for loops
for (int i = 0; i < 10; i++) {
System.out.println(i);
}// Variable declarations
int a = 1, b = 2, c = 3;
// Array elements
int[] arr = {1, 2, 3, 4, 5};
// Method parameters
public void process(int a, String b, double c) { }
// For loop parts
for (int i = 0, j = 10; i < j; i++, j--) { }// Ternary operator
String status = (age >= 18) ? "Adult" : "Minor";
// Enhanced for loop
for (String name : names) {
System.out.println(name);
}
// Switch expression (Java 14+)
String result = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
default -> "Unknown";
};
// Labeled statements (rarely used)
outer: for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (j == 1) break outer;
}
}// Package separator
import java.util.Scanner;
package com.example.myapp;
// Method/field access
String str = "Hello";
int len = str.length(); // method call
str.toUpperCase(); // instance methods
// Static access
Math.PI; // static field
Math.max(a, b); // static method
this.name; // this reference
super.method(); // super reference// Method references (Java 8+)
// Static method reference
Function<String, Integer> parser = Integer::parseInt;
// Instance method of particular object
String str = "Hello";
Supplier<Integer> len = str::length;
// Instance method of type
Function<String, String> upper = String::toUpperCase;
// Constructor reference
Supplier<ArrayList<String>> supplier = ArrayList::new;// Annotations
@Override
@Deprecated
@SuppressWarnings("unchecked")
@FunctionalInterface
// Custom annotation
@interface Author {
String name();
String date();
}
@Author(name = "John", date = "2024-01-01")
public class MyClass { }// char literals
char c = 'A';
char digit = '5';
char symbol = '#';
// Escape sequences
char newline = '\n';
char tab = '\t';
char backslash = '\\';
char quote = '\'';// String literals
String name = "Alice";
String message = "Hello, World!";
// Empty string
String empty = "";
// Multi-line (Java 15+)
String text = """
This is a
multi-line
string
""";// 1. Package declaration
package com.example.myapp;
// 2. Imports
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import static java.lang.System.out;
// 3. Class declaration
public class MyClass extends BaseClass implements Interface1, Interface2 {
// 4. Static variables (class-level)
private static int classCount = 0;
public static final String VERSION = "1.0";
// 5. Instance variables (fields)
private String name;
protected int age;
public boolean isActive;
// 6. Constructors
public MyClass() {
// Default constructor
}
public MyClass(String name) {
this.name = name;
classCount++;
}
public MyClass(String name, int age) {
this(name); // Constructor chaining
this.age = age;
}
// 7. Methods
public void instanceMethod() {
// Instance method
}
public static void staticMethod() {
// Static method
}
private helperMethod() {
// Private helper
}
// 8. Inner classes
static class InnerClass { }
class NestedClass { }
}[access] [static] [final] [abstract] <return_type> <name>([parameters]) [throws exceptions]
public static final int calculateSum(int a, int b) throws IOException {
return a + b;
}package com.example;
import java.util.Scanner;
public class Calculator {
// Static constant
private static final String VERSION = "1.0";
// Instance variable
private double lastResult;
// Constructor
public Calculator() {
this.lastResult = 0;
}
// Static method
public static void main(String[] args) {
Calculator calc = new Calculator();
calc.run();
}
// Instance method
public void run() {
Scanner scanner = new Scanner(System.in);
System.out.println("Calculator v" + VERSION);
while (true) {
System.out.print("Enter operation (+,-,*,/,q): ");
String op = scanner.nextLine();
if (op.equals("q")) {
System.out.println("Goodbye!");
break;
}
System.out.print("Enter first number: ");
double a = scanner.nextDouble();
System.out.print("Enter second number: ");
double b = scanner.nextDouble();
scanner.nextLine(); // consume newline
try {
double result = calculate(a, op, b);
System.out.println("Result: " + result);
this.lastResult = result;
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
scanner.close();
}
// Method with parameters and return
private double calculate(double a, String op, double b) {
return switch (op) {
case "+" -> a + b;
case "-" -> a - b;
case "*" -> a * b;
case "/" -> {
if (b == 0) {
throw new ArithmeticException("Cannot divide by zero!");
}
yield a / b;
}
default -> throw new IllegalArgumentException("Invalid operation");
};
}
}Identify the keywords, identifiers, operators, and punctuation in this code:
public class HelloWorld {
public static void main(String[] args) {
String message = "Hello, World!";
System.out.println(message);
}
}Create a class with:
- A package declaration
- Import statements
- Multiple constructors
- Static and instance variables
- Methods with various access levels
package com.example;
import java.util.Date;
public class Person {
// Static variable
private static int personCount = 0;
// Instance variables
private String name;
private int age;
private Date createdAt;
// Constructor 1
public Person() {
this("Unknown", 0);
}
// Constructor 2
public Person(String name) {
this(name, 0);
}
// Constructor 3
public Person(String name, int age) {
this.name = name;
this.age = age;
this.createdAt = new Date();
personCount++;
}
// Getters and setters
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
public static int getPersonCount() { return personCount; }
// toString method
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}
}In this guide, you learned:
- ✅ Java keywords and their usage
- ✅ Rules for creating identifiers
- ✅ All Java operators
- ✅ Punctuation and delimiters in Java
- ✅ Complete class structure
- ✅ Method signatures
- ✅ Complete code examples
- Java Beginner Guide - Part 1 - Fundamentals
- Java Beginner Guide - Part 2 - Control Flow
- Java Beginner Guide - Part 3 - Methods & Arrays
- Java Intermediate Guide - OOP Deep Dive
- Java Advanced Guide - Modern Java
Keep practicing your Java syntax! 🚀