📌 What is Java Syntax?
Java syntax is the set of rules that define how Java programs are written and interpreted. Like grammar in English, you need to follow it to make your code compile.
🧱 Basic Structure of a Java Program
public class MyClass {
public static void main(String[] args) {
// This is a comment
System.out.println("Hello, Java!");
}
}
Key Parts:
public class MyClass
: The class name must match the filename.public static void main(String[] args)
: The starting point of execution.System.out.println(...)
: Used to print to the console.//
: Single-line comment
📦 Java Variables
A variable is a container that holds a value during program execution.
✅ Syntax:
dataType variableName = value;
int age = 25;
String name = "Raaz";
🔢 Java Data Types
Java is a strongly typed language, meaning every variable must be declared with a type.
🔸 Primitive Data Types (8 total):
Type | Size | Example |
---|---|---|
byte | 1 byte | byte a = 10; |
short | 2 bytes | short s = 200; |
int | 4 bytes | int i = 1234; |
long | 8 bytes | long l = 123L; |
float | 4 bytes | float f = 1.23f; |
double | 8 bytes | double d = 9.87; |
char | 2 bytes | char c = 'A'; |
boolean | 1 bit | boolean b = true; |
🔹 Non-Primitive Types
String
,Array
,Class
,Interface
, etc.
String greeting = "Welcome to Java!";
🛠️ Type Casting
Widening Casting (automatic):
int myInt = 9;
double myDouble = myInt; // 9.0
Narrowing Casting (manual):
double myDouble = 9.78;
int myInt = (int) myDouble; // 9
🔍 Java Naming Rules
- Variable names are case-sensitive
- Must start with a letter or
_
or$
(not a digit) - Follow camelCase convention:
studentName
,maxScore
public class VariablesDemo {
public static void main(String[] args) {
int age = 30;
double salary = 55000.50;
boolean isJavaFun = true;
String message = "Java is awesome!";
System.out.println("Age: " + age);
System.out.println("Salary: $" + salary);
System.out.println("Is Java fun? " + isJavaFun);
System.out.println(message);
}
}
🎯 What You Learned
- Basic Java syntax and structure
- Declaring and using variables
- Primitive data types
- Type casting in Java