Java Syntax and Variables
# 1. Java Syntax Basics
Java programs are made up of statements, which are executed in order. Let's break down the
syntax:
public class Example {
public static void main(String[] args) {
System.out.println("Java Syntax!");
}
}
- Every Java application must have a class.
- The main method (main()) is where the program starts.
- Statements end with a semicolon (;).
- Curly braces {} define blocks of code.
# 2. Comments in Java
Comments help explain code but are ignored by Java when running the program.
// This is a single-line comment
/*
This is a multi-line comment.
It spans multiple lines.
*/
# Variables in Java
Variables store data in memory. Java is statically typed, meaning we must declare variable types.
# 3. Types of Variables
| Type | Example | Description |
|-----------|----------------|-------------------------------|
| int | int age = 16; | Stores whole numbers |
| double | double pi = 3.14; | Stores decimal numbers |
| char | char letter = 'A'; | Stores a single character |
| boolean | boolean isJavaFun = true; | Stores true/false |
| String | String name = "Dolat"; | Stores text |
# 4. Variable Declaration & Initialization
- Declaration: int number;
- Initialization: number = 10;
- Combined: int number = 10;
Example:
public class Variables {
public static void main(String[] args) {
int age = 16;
double height = 5.9;
char grade = 'A';
boolean isJavaFun = true;
String name = "Dolat";
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Height: " + height);
System.out.println("Grade: " + grade);
System.out.println("Java is fun: " + isJavaFun);
}
}
# Task for You:
1. Run the above code and understand the output.
2. Modify it to store and print your own details.