What is Java Syntax?
Java syntax refers to the set of rules and structure that define how Java code is written. Every Java application starts with a class, contains methods, statements, blocks, and expressions.
Basic Java Syntax
// This is a single line comment
/* This is a
multi-line comment */
/*
Every Java application starts with a class
with the main method.
*/
public class HelloWorld {
// main method — entry point for the application
public static void main(String[] args) {
System.out.println("Hello, Java!");
}
}
Explanation
public class HelloWorld
:
public
= Access modifierclass
= Declares a classHelloWorld
= Name of the class (should match file name)
public static void main(String[] args)
:
public
= Accessible from anywherestatic
= We can callmain
without instantiating the classvoid
= This method doesn’t return a valueString[] args
= Command-like array of strings passed when we run the application
System.out.println("Hello, Java!");
:
- Prints text to the console.
Java Statements
Variable Declaration:
int number = 10;
String message = "Hello, Java.";
double price = 99.99;
boolean isValid = true;
Control Structures
If-Else:
if (number > 5) {
System.out.println("number is greater than 5.");
} else {
System.out.println("number is not greater than 5.");
}
For Loop:
for (int i = 0; i < 5; i++) {
System.out.println("Iteration: " + i);
}
While Loop:
int count = 0;
while (count < 5) {
System.out.println("Count is: " + count);
count++;
}
Method Definition
public static int addNumbers(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int sum = addNumbers(5, 10);
System.out.println("Sum = " + sum);
}
Summary
- Java is case-sensitive.
- All code belongs to a class.
- The main method is the entry point for a Java application.
- Comments aid understanding code.
- Statements typically end with a semicolon (
;
).
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.