Skip to content

Java Syntax and Variables – Speaking Java’s Language

📌 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):

TypeSizeExample
byte1 bytebyte a = 10;
short2 bytesshort s = 200;
int4 bytesint i = 1234;
long8 byteslong l = 123L;
float4 bytesfloat f = 1.23f;
double8 bytesdouble d = 9.87;
char2 byteschar c = 'A';
boolean1 bitboolean 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

Leave a Reply

Your email address will not be published. Required fields are marked *