📘 [3] Java Syntax & Basics — Structure, Statements, and Starting Right!
🧱 Java: A Structured Language
Java is known for being verbose — but also clear and strict. Its syntax borrows from C/C++, but adds safety, structure, and readability. To code effectively in Java, you must understand how files, classes, methods, statements, and variables come together to form a complete program.
📄 The Minimal Java Program
This is the smallest valid Java program you can write:
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, Java!");
}
}
- public class Hello → The class must match the filename (
Hello.java) - main → The entry point for any Java program
- System.out.println → Built-in print function (prints to console)
⚙️ Anatomy of a Java Program
- Every Java file contains at least one class
main()is where the program starts execution- Curly braces
{ }group code into blocks - Every statement ends in a semicolon
; //is a single-line comment,/* */for multi-line
🗂️ File Structure & Naming Rules
- The filename must match the public class name
- Class names start with an uppercase letter (e.g.,
MyClass) - Method names start with lowercase (e.g.,
main) - Java is case-sensitive →
Main≠main
🔤 Variables & Data Types
Java is statically typed, so every variable must have a type. Examples:
int age = 25;
double pi = 3.14;
char grade = 'A';
boolean isJavaFun = true;
String name = "Aelify";
📋 Common Data Types
int→ Whole numbers (e.g., 42)double→ Decimal numbers (e.g., 3.14)char→ Single characters (e.g., 'A')boolean→ true / falseString→ Text (actually a class, not a primitive)
✏️ Comments & Readability
// This is a single-line comment
/*
This is a
multi-line comment
*/
- Use comments to explain why, not what
- Good indentation makes code readable
- Use meaningful variable names — avoid
int x, preferint itemCount
🚧 Java Compilation Flow
- You write code in
Hello.java - Compile with:
javac Hello.java→ createsHello.class - Run with:
java Hello(no .class or .java)
Example output:
Hello, Java!
🧠 Pro Tips for Beginners
- 👁️ Always match class name with filename
- 💡 Use an IDE — helps catch syntax errors early
- 🧪 Practice writing, compiling, and running without an IDE too
- 🧼 Format your code! Use auto-format (Ctrl+Alt+L in IntelliJ)
- 🔎 Understand errors — read the compiler messages carefully
🧪 Try This Exercise
public class PersonalInfo {
public static void main(String[] args) {
String name = "Aelify";
int age = 21;
boolean learningJava = true;
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Learning Java? " + learningJava);
}
}
💡 Try modifying the values and adding a new variable for height!
✅ Recap
Java is strict, but predictable. Once you understand its structure — classes, main method, semicolons, and variable types — everything starts to click. You’ve now written your first real Java code and understood how it flows from source file to output.
✍️ Java Syntax Basics
✅ Semicolons
Every statement ends with a semicolon ;.
✅ Case Sensitivity
Java is case-sensitive: System ≠ system
✅ Braces { } define blocks
if (true) {
System.out.println("Inside block");
}
🧮 Variables & Data Types
| Type | Description | Example |
|---|---|---|
int |
Whole numbers | int age = 25; |
double |
Decimal numbers | double pi = 3.14; |
char |
Single character | char grade = 'A'; |
boolean |
True/False | boolean alive = true; |
String |
Text (non-primitive) | String name = "Aelify"; |
🧪 Example:
int age = 30;
double height = 5.9;
boolean isStudent = true;
String language = "Java";
➕ Operators
| Operator | Purpose | Example |
|---|---|---|
+ - * / % |
Arithmetic | a + b, x % y |
== != > < >= <= |
Comparison | a == b |
&& || ! |
Logical | a > 0 && b < 5 |
= |
Assignment | x = 5 |
🧪 Example:
int a = 10, b = 5;
System.out.println("Sum: " + (a + b));
System.out.println("Is A greater? " + (a > b));
🔁 Conditional Statements
✅ If-Else
int score = 85;
if (score >= 90) {
System.out.println("Grade A");
} else if (score >= 75) {
System.out.println("Grade B");
} else {
System.out.println("Grade C");
}
✅ Switch Case
char grade = 'B';
switch (grade) {
case 'A':
System.out.println("Excellent");
break;
case 'B':
System.out.println("Good Job");
break;
default:
System.out.println("Keep Trying");
}
🔁 Loops in Java
✅ For Loop
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}
✅ While Loop
int i = 1;
while (i <= 5) {
System.out.println("i = " + i);
i++;
}
✅ Do-While Loop
int j = 1;
do {
System.out.println("j = " + j);
j++;
} while (j <= 5);
📚 User Input (Scanner)
import java.util.Scanner;
public class InputExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = sc.nextLine();
System.out.println("Hello, " + name + "!");
}
}
🧠 Exercises — Practice Zone with Answers
💡 Beginner
- ✅ Write a Java program that adds two integers.
import java.util.Scanner;
public class AddTwoNumbers {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter first number: ");
int a = sc.nextInt();
System.out.print("Enter second number: ");
int b = sc.nextInt();
int sum = a + b;
System.out.println("Sum = " + sum);
}
}
- ✅ Print multiplication table of 7 using a loop.
public class TableOf7 {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
System.out.println("7 x " + i + " = " + (7 * i));
}
}
}
- ✅ Check if a number is even or odd.
import java.util.Scanner;
public class EvenOdd {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
if (num % 2 == 0)
System.out.println(num + " is Even");
else
System.out.println(num + " is Odd");
}
}
🧪 Intermediate
- ✅ Accept user age and classify: “Child”, “Teen”, “Adult”, “Senior”.
import java.util.Scanner;
public class AgeClassifier {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = sc.nextInt();
if (age < 13)
System.out.println("Child");
else if (age < 20)
System.out.println("Teen");
else if (age < 60)
System.out.println("Adult");
else
System.out.println("Senior");
}
}
- ✅ Calculate factorial of a number using
forloop.
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
int fact = 1;
for (int i = 1; i <= num; i++) {
fact *= i;
}
System.out.println("Factorial = " + fact);
}
}
- ✅ Take a sentence input and print each word on a new line.
import java.util.Scanner;
public class SplitSentence {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String sentence = sc.nextLine();
String[] words = sentence.split(" ");
for (String word : words) {
System.out.println(word);
}
}
}
🔥 Challenge
- ✅ FizzBuzz (1 to 100): Print “Fizz” if divisible by 3, “Buzz” if divisible by 5, “FizzBuzz” if both, else the number.
public class FizzBuzz {
public static void main(String[] args) {
for (int i = 1; i <= 100; i++) {
if (i % 3 == 0 && i % 5 == 0)
System.out.println("FizzBuzz");
else if (i % 3 == 0)
System.out.println("Fizz");
else if (i % 5 == 0)
System.out.println("Buzz");
else
System.out.println(i);
}
}
}
✅ Recap
You’ve covered the most essential building blocks of Java:
- Syntax and formatting rules
- Variables and data types
- Conditions and logic
- Looping structures
- User input with Scanner
- Tons of hands-on code and exercises — with answers!
⚠️ Common Mistakes
- ❌ Missing semicolons (
;) — Every Java statement must end with a semicolon. - ❌ Incorrect capitalization — Java is case-sensitive.
System≠system,Main≠main. - ❌ Using assignment (
=) instead of comparison (==) in conditions. - ❌ Unmatched or missing braces
{ }— leads to "illegal start of type" or logical errors. - ❌ Missing
classormainmethod — program won’t run without:public static void main(String[] args) - ❌ Writing code outside class — all code must be inside a class block.
- ❌ Incorrect file name — must match the public class name exactly (e.g.,
HelloWorld.javaforpublic class HelloWorld). - ❌ Using undeclared variables — must declare before use.
- ❌ Type mismatch — assigning a
Stringtointordoubletointwithout casting. - ❌ Uninitialized variables — Java won’t let you use a local variable before assigning a value.
- ❌ Incorrect
chardeclaration — use single quotes:char c = 'a';(not"a"). - ❌ Not importing
java.util.Scannerbefore using it. - ❌ Using
nextLine()afternextInt()ornextDouble()without consuming the newline. - ❌ Infinite loops — forgetting to update loop counters (like
i++inwhile/for). - ❌ Wrong loop condition — such as
i >= 0withi++, causing endless loop. - ❌ Confusing
=with==inifconditions. - ❌ Using
else ifwithout a precedingif. - ❌ Switch-case without
break;— leads to fall-through bugs. - ❌ Concatenating numbers without parentheses —
"Sum: " + a + bgives string like "Sum: 105" instead of 15. - ❌ Trying to run Java file without compiling it first — must run
javac FileName.javabeforejava FileName.
🛠️ Example Fix for Scanner Bug
If you use nextInt() followed by nextLine(), always clear the newline buffer:
import java.util.Scanner;
public class ScannerExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = sc.nextInt();
sc.nextLine(); // ⚠️ This clears the \n left behind by nextInt()
System.out.print("Enter your name: ");
String name = sc.nextLine();
System.out.println("Hi " + name + ", you are " + age + " years old.");
}
}
You're now ready to build interactive, logical Java programs. Up next, we’ll explore variables in detail — primitive vs reference, memory, type casting, and more!
In our next post, we’ll dive into 🧮 [4] Data Types & Variables — The Core Foundation of Java!
— Blog by Aelify (ML2AI.com)