Basic Java Syntax
1. Hello World Program:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
- Java programs are organized into classes.
- The
public static void main(String[] args)
method is the entry point of a Java program. - Statements end with a semicolon
;
. - Indentation is not required by the compiler but is used for readability.
2. Variables:
int age = 25;
double pi = 3.14;
char grade = 'A';
String message = "Hello";
- Variables are declared with a type (e.g.,
int
,double
,char
,String
). - Variable names are case-sensitive.
- Use meaningful names for variables.
3. Data Types:
- Primitive data types:
int
,double
,float
,char
,boolean
, etc. - Object data types:
String
, arrays, custom classes.
4. Control Flow:
Conditional Statements:
int x = 10;
if (x > 0) {
System.out.println("Positive");
} else if (x < 0) {
System.out.println("Negative");
} else {
System.out.println("Zero");
}
Loops:
for (int i = 0; i < 5; i++) {
System.out.println("Iteration: " + i);
}
while (condition) {
// code
}
do {
// code
} while (condition);
5. Arrays:
int[] numbers = {1, 2, 3, 4, 5};
String[] names = new String[3];
names[0] = "Alice";
names[1] = "Bob";
names[2] = "Charlie";
- Arrays in Java are zero-indexed.
6. Methods:
public int add(int a, int b) {
return a + b;
}
// Calling a method
int result = add(3, 5);
- Methods are defined with a return type, name, and parameters.
void
is used when a method does not return any value.
7. Classes and Objects:
public class Car {
String brand;
int year;
public Car(String brand, int year) {
this.brand = brand;
this.year = year;
}
public void start() {
System.out.println("The car is starting.");
}
}
// Creating an object
Car myCar = new Car("Toyota", 2022);
myCar.start();
- Classes encapsulate data and behavior.
- Objects are instances of classes.
8. Comments:
// This is a single-line comment
/*
This is a
multi-line comment
*/
- Comments are ignored by the compiler and are for documentation purposes.
9. Exception Handling:
try {
// code that may throw an exception
} catch (ExceptionType e) {
// code to handle the exception
} finally {
// code that will always execute
}
- Exception handling is used to manage errors during runtime.
These are some basic syntax elements in Java. As you progress, you'll encounter more advanced concepts and features of the language. It's important to practice and experiment with code to deepen your understanding.