- Learn Java naming conventions and coding standards
- Understand variables and data types
- Master basic operators and expressions
Understanding Basic Syntax
You've written your first Java program. Now let's understand the rules and conventions that make Java code readable and maintainable. Think of this as learning the grammar of the language—not the most exciting part, but essential.
Java Naming Conventions: Speaking the Language Properly
Java has well-established naming conventions that the entire community follows. Using these conventions makes your code instantly recognizable to other Java developers.
Class Names: PascalCase
Class names should be nouns and use PascalCase (also called UpperCamelCase):
// Good class names:
public class StudentRecord { }
public class BankAccount { }
public class StringUtils { }
// Avoid:
public class student_record { } // snake_case - wrong
public class STUDENTRECORD { } // SCREAMING_CASE - wrong
Method Names: camelCase
Method names should be verbs or verb phrases and use camelCase:
// Good method names:
public void calculateTotal() { }
public String getFirstName() { }
public boolean isValid() { }
// Avoid:
public void Calculate_Total() { } // PascalCase and underscore - wrong
Variable Names: camelCase
Variables should be descriptive and use camelCase:
// Good variable names:
int studentAge;
String firstName;
double accountBalance;
// Avoid:
int a; // Too vague
String first_name; // snake_case - wrong
double ACCOUNTBALANCE; // SCREAMING_CASE - wrong
Constants: SCREAMING_SNAKE_CASE
Constants (variables that don't change) should be in SCREAMING_SNAKE_CASE:
// Good constant names:
public static final int MAX_STUDENTS = 100;
public static final String DEFAULT_COUNTRY = "USA";
public static final double PI = 3.14159;
Variables and Data Types: Storing Information
Variables are like containers that store data in your program. Java is a statically-typed language, which means you must declare the type of data each variable will hold.
Primitive Data Types
Java has eight primitive data types for storing basic values:
| Type | Size | Description | Example |
|---|---|---|---|
byte |
8 bits | Very small integers | byte age = 25; |
short |
16 bits | Small integers | short year = 2024; |
int |
32 bits | Standard integers | int population = 85000; |
long |
64 bits | Large integers | long worldPopulation = 7800000000L; |
float |
32 bits | Decimal numbers | float price = 19.99f; |
double |
64 bits | Precise decimals | double preciseValue = 3.1415926535; |
char |
16 bits | Single character | char grade = 'A'; |
boolean |
1 bit | True/false values | boolean isActive = true; |
Declaring and Initializing Variables
// Declaration only
int count;
String name;
// Declaration with initialization
int age = 25;
double salary = 45000.00;
boolean isEmployed = true;
char middleInitial = 'M';
// Multiple variables of same type
int x = 5, y = 10, z = 15;
The Rules for Variable Names
- Must start with a letter, underscore (_), or dollar sign ($)
- Can contain letters, numbers, underscores, or dollar signs
- Cannot be Java keywords (like
class,public,void) - Are case-sensitive (
age≠Age≠AGE)
// Legal variable names:
int age;
String _temp;
double $price;
int student2Score;
// Illegal variable names:
int 2ndPlace; // Cannot start with number
String first name; // Cannot contain spaces
double class; // 'class' is a keyword
Operators: Working with Data
Operators let you perform operations on variables and values.
Arithmetic Operators
int a = 10, b = 3;
System.out.println(a + b); // 13 - Addition
System.out.println(a - b); // 7 - Subtraction
System.out.println(a * b); // 30 - Multiplication
System.out.println(a / b); // 3 - Division (integer result)
System.out.println(a % b); // 1 - Modulus (remainder)
Assignment Operators
int x = 10; // Basic assignment
x += 5; // x = x + 5 (now 15)
x -= 3; // x = x - 3 (now 12)
x *= 2; // x = x * 2 (now 24)
x /= 4; // x = x / 4 (now 6)
Comparison Operators
int a = 10, b = 5;
System.out.println(a == b); // false - Equal to
System.out.println(a != b); // true - Not equal to
System.out.println(a > b); // true - Greater than
System.out.println(a < b); // false - Less than
System.out.println(a >= b); // true - Greater than or equal to
System.out.println(a <= b); // false - Less than or equal to
Logical Operators
boolean isSunny = true;
boolean isWeekend = false;
System.out.println(isSunny && isWeekend); // false - AND
System.out.println(isSunny || isWeekend); // true - OR
System.out.println(!isSunny); // false - NOT
Understanding Operator Precedence
When multiple operators appear in an expression, Java follows specific rules about which operations to perform first:
int result = 10 + 5 * 2; // Result is 20, not 30
// Multiplication (*) happens before addition (+)
int result2 = (10 + 5) * 2; // Result is 30
// Parentheses override the normal precedence
Order of precedence (highest to lowest):
- Parentheses
() - Multiplication/Division/Modulus
* / % - Addition/Subtraction
+ - - Comparison
== != < > <= >= - Logical AND
&& - Logical OR
|| - Assignment
=
Comments: Documenting Your Code
Comments are essential for explaining your code to other developers (and to your future self!).
Single-line Comments
// This is a single-line comment
int age = 25; // This comment explains the variable
Multi-line Comments
/*
This is a multi-line comment.
It can span multiple lines.
Useful for longer explanations.
*/
int totalStudents = 150;
Javadoc Comments
Javadoc comments are special comments used to generate documentation automatically:
/**
* Calculates the area of a rectangle.
*
* @param length the length of the rectangle
* @param width the width of the rectangle
* @return the area of the rectangle
*/
public double calculateArea(double length, double width) {
return length * width;
}
Code Structure and Organization
Proper Indentation and Formatting
Good formatting:
public class Calculator {
public int add(int a, int b) {
int result = a + b;
return result;
}
public void displayResult(int value) {
System.out.println("The result is: " + value);
}
}
Poor formatting (avoid this):
public class Calculator {
public int add(int a, int b) {
int result = a + b;
return result;
}
public void displayResult(int value) {
System.out.println("The result is: " + value);
}
}
One Statement Per Line
// Good:
int age = 25;
String name = "John";
// Avoid:
int age = 25; String name = "John";
Using Whitespace Effectively
// Good use of whitespace:
public static void main(String[] args) {
int result = calculateSum(10, 20);
displayResult(result);
}
// Too cramped (avoid):
public static void main(String[] args){
int result=calculateSum(10,20);
displayResult(result);
}
Putting It All Together: A Complete Example
/**
* This program demonstrates basic Java syntax including
* variables, operators, and code structure.
*/
public class SyntaxDemo {
// Class constant
public static final double TAX_RATE = 0.08;
public static void main(String[] args) {
// Variable declarations
String productName = "Laptop";
double price = 999.99;
int quantity = 2;
// Calculations
double subtotal = price * quantity;
double tax = subtotal * TAX_RATE;
double total = subtotal + tax;
// Display results
displayReceipt(productName, quantity, price, subtotal, tax, total);
}
/**
* Displays a formatted receipt with purchase details.
*/
public static void displayReceipt(String product, int qty,
double unitPrice, double subTotal,
double taxAmount, double totalAmount) {
System.out.println("=== RECEIPT ===");
System.out.println("Product: " + product);
System.out.println("Quantity: " + qty);
System.out.println("Unit Price: $" + unitPrice);
System.out.println("Subtotal: $" + subTotal);
System.out.println("Tax: $" + taxAmount);
System.out.println("Total: $" + totalAmount);
System.out.println("===============");
}
}
Common Syntax Errors to Avoid
Error 1: Missing Semicolons
int age = 25 // ERROR: missing semicolon
System.out.println("Hello") // ERROR: missing semicolon
Error 2: Mismatched Braces
public class Demo {
public static void main(String[] args) {
System.out.println("Hello");
// ERROR: missing closing brace for class
Error 3: Wrong Variable Declaration
int 123abc = 10; // ERROR: cannot start with number
String first name; // ERROR: space in variable name
double class = 5.5; // ERROR: 'class' is a keyword
Error 4: Type Mismatches
int number = "hello"; // ERROR: can't assign String to int
String text = 123; // ERROR: can't assign int to String
Error 5: Case Sensitivity Issues
String name = "John";
System.out.println(NAME); // ERROR: 'NAME' ≠ 'name'
Best Practices for Readable Code
1. Use Descriptive Names
// Good:
int studentAge;
double accountBalance;
// Avoid:
int a;
double b;
2. Initialize Variables When Possible
// Good:
int count = 0;
String name = "";
// Avoid:
int count; // Might contain garbage value
3. Keep Lines Reasonable Length
Try to keep lines under 80-100 characters for readability.
4. Use Constants for Magic Numbers
// Good:
public static final int MAX_LOGIN_ATTEMPTS = 3;
if (loginAttempts > MAX_LOGIN_ATTEMPTS) { ... }
// Avoid:
if (loginAttempts > 3) { ... } // What does 3 mean?
5. Group Related Code Together
Keep related variable declarations and operations close to each other.
Debugging Syntax Errors
When you encounter errors:
- Read the error message - Java compiler messages are quite descriptive
- Check the line number - The error message usually tells you where to look
- Look for common mistakes - Missing semicolons, mismatched braces, wrong types
- Check your spelling - Java is case-sensitive!
Practice Exercises
Try these to reinforce your understanding:
- Fix the errors in this code:
public class broken code {
public static void main(String[] args) {
int number = 10
string message = "Hello"
System.out.println(message + number)
}
}
Write a program that:
- Declares variables for a person's name, age, and salary
- Uses appropriate data types for each
- Prints a formatted biography using those variables
Create constants for:
- The number of days in a week
- The value of PI
- Your country's name
Key Takeaways
- Naming conventions make your code professional and readable
- Variables store data and must be declared with specific types
- Operators let you manipulate data and make decisions
- Comments explain your code to other developers
- Proper formatting makes code easier to read and maintain
- Java is case-sensitive - pay attention to capitalization
- Every opening brace
{needs a closing brace} - Every statement ends with a semicolon
;
What You've Accomplished
You've now learned the fundamental rules of Java syntax—the grammar that makes Java code work. These rules might seem restrictive at first, but they're what make Java programs reliable and maintainable.
You've completed the Getting Started module! You now understand what Java is, how to set up your development environment, how to write and run programs, and the basic syntax rules that govern Java code.
In the next module, we'll dive deeper into Java's building blocks and start creating more interactive and useful programs. You've built a solid foundation—now you're ready to start building!
