Java is a widely-used programming language known for its "write once, run anywhere" principle. This guide provides a brief overview of the syntax commonly used in Java programming.
Basic Structure
In Java, every program starts with a class. The main class contains the main
method, which is the entry point of the program.
public class Main {
public static void main(String[] args) {
// Your code here
}
}
Variables and Data Types
Java uses data types to define the kind of data a variable can hold. Common data types include:
int
for integersdouble
for floating-point numbersboolean
for true/false valuesString
for text
int number = 5;
double pi = 3.14159;
boolean isTrue = true;
String name = "John Doe";
Control Structures
Java provides various control structures for controlling the flow of the program.
If-Else
if (number > 0) {
System.out.println("Number is positive.");
} else {
System.out.println("Number is not positive.");
}
For Loop
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
While Loop
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
Functions
Functions are reusable blocks of code that perform a specific task.
public static void greet(String name) {
System.out.println("Hello, " + name + "!");
}
public static void main(String[] args) {
greet("John Doe");
}
Object-Oriented Programming (OOP)
Java is an object-oriented programming language. Classes and objects are at the core of OOP.
public class Car {
private String brand;
private int year;
public Car(String brand, int year) {
this.brand = brand;
this.year = year;
}
public void displayInfo() {
System.out.println("Brand: " + brand);
System.out.println("Year: " + year);
}
}
public static void main(String[] args) {
Car myCar = new Car("Toyota", 2020);
myCar.displayInfo();
}
Resources
For more detailed information about Java syntax, you can visit our comprehensive Java Tutorial.