Java Basic Concepts and Syntax Study Guide

Java Syntax Structure

  • Every line of executable code in Java must reside inside a class.

  • Class names must always begin with an uppercase first letter (e.g., Main).

  • Java is strictly case-sensitive; for example, MyClass and myclass represent two entirely distinct identifiers.

  • The filename of a Java source file must match the name of the public class it contains, appended with the .java file extension (for instance, the class Main must be saved inside a file named Main.java).


Java class and main method structure

The main Method

  • Any code contained inside the main() method will be executed upon running the application.

  • Every runnable Java program must contain a main() method.

  • The standard signature for the main entry point is:

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}

Output and Printing in Java

  • System is a built-in Java class that contains useful members, such as out, which stands for standard output.

  • The println() method (short for "print line") prints a specified value to the console or standard output stream.

  • System, out, and println() must be combined together as System.out.println() to output text or data to the terminal stream.

  • Every individual statement in Java must end with a semicolon (;).

  • Calling println() multiple times outputs each supplied argument on a new line.

System.out.println("Hello World!");
System.out.println("I am learning Java.");
System.out.println("It is awesome!");


Multiple println method executions

String Quotation Rules and Compiler Syntax Errors

  • Text literals and strings in Java must always be enclosed inside double quotation marks ("").

  • If double quotes are omitted around a string, a compilation error occurs because the compiler cannot recognize or parse raw text as a string literal.

  • Valid statement example:

System.out.println("This sentence will work!");
  • Invalid statement example (produces a compilation error):

System.out.println(This sentence will produce an error);


String syntax error demonstration

Printing Numbers

  • The println() method can print numerical values directly.

  • Double quotation marks must be omitted when printing numeric literals.

System.out.println(3);
System.out.println(358);
System.out.println(50000);


Printing numbers with println

Java Comments

  • Comments are used to explain Java code, enhance readability, and temporarily prevent code execution during testing or debugging.

  • Java supports two distinct formats for comments:

    • Single-line comments: Start with two forward slashes (//). Any text between // and the end of that specific line is ignored by the Java compiler.

// This is a comment
System.out.println("Hello World");

System.out.println("Hello World"); // This is a comment


Single-line comment examples
  • Multi-line comments: Start with /* and end with */. All text contained between /* and */ is completely ignored by the Java compiler.

/* The code below will print the words Hello World
to the screen, and it is amazing */
System.out.println("Hello World");


Multi-line comment example

Variables and Primitive Data Types

  • Variables serve as named memory containers for storing data values.

  • Primary variable data types in Java include:

    • String: Stores text sequences (e.g., "Hello"). String values must be enclosed in double quotation marks.

    • int: Stores whole integers without decimal points (e.g., 123 or -123).

    • float: Stores floating-point numbers containing decimals (e.g., 19.99 or -19.99). Float literals require an f or F suffix.

    • char: Stores a single character (e.g., 'a' or 'B'). Character values must be enclosed in single quotation marks ('').

    • boolean: Stores binary states containing one of two values: true or false.

  • Steps to declare a variable:

    • Specify the data type (e.g., int or String).

    • Assign an identifier name (e.g., x, age, or name).

    • Assign a value using the assignment operator (=).

Variable Declaration and Assignment Patterns

  • Declaring and initializing a String variable:

String name = "John";
System.out.println("Hello " + name);
  • Declaring and initializing an integer variable:

int myNum = 15;
System.out.println(myNum);


Declaring an integer variable
  • Declaring a variable without immediate initialization, and assigning its value later:

int myNum;
myNum = 15;
System.out.println(myNum);


Separate variable declaration and assignment
  • Overwriting existing variable values: Assigning a new value to a pre-existing variable replaces and overwrites the previous value stored in memory.

int myNum = 15;
myNum = 20; // myNum is now 20
System.out.println(myNum);


Overwriting variable values

Constants and Final Variables

  • To prevent variable modification or overwriting, declare the variable using the final keyword.

  • Marking a variable as final defines it as a read-only constant, making its assigned value unchangeable.

  • Attempting to reassign a final variable raises a compilation error (cannot assign a value to a final variable).

final int myNum = 15;
myNum = 20; // will generate an error: cannot assign a value to a final variable


Final variable error example
  • Syntax summary of diverse data types:

int myNum = 5;
float myFloatNum = 5.99f;
char myLetter = 'D';
boolean myBool = true;
String myText = "Hello";

Displaying Variables and Concatenation

  • The + operator combines text strings with variables inside System.out.println().

String name = "John";
System.out.println("Hello " + name);


Combining text and variable
  • The + operator can also append a string variable to another string variable:

String firstName = "John ";
String lastName = "Doe";
String fullName = firstName + lastName;
System.out.println(fullName);


Combining two string variables

Multiple Variable Declarations

  • Multiple variables of the exact same type can be declared in a comma-separated list:

int x = 5, y = 6, z = 50;
System.out.println(x + y + z);


Declaring multiple variables
  • A single identical value can be assigned to multiple variables on a single line using chained assignment statements:

int x, y, z;
x = y = z = 50;
System.out.println(x + y + z);


Assigning one value to multiple variables

Identifiers and Best Practices

  • Every variable in Java must be uniquely identified by a distinctive name known as an identifier.

  • Identifiers can consist of short names (such as x and y) or descriptive labels (such as age, sum, or totalVolume).

  • Using descriptive identifiers is recommended to construct readable, self-documenting, and maintainable codebases.

  • Practical Application (Student Profile Example):

// Student data
String studentName = "John Doe";
int studentID = 15;
int studentAge = 23;
float studentFee = 75.25f;
char studentGrade = 'B';

// Print variables
System.out.println("Student name: " + studentName);
System.out.println("Student id: " + studentID);
System.out.println("Student age: " + studentAge);
System.out.println("Student fee: " + studentFee);
System.out.println("Student grade: " + studentGrade);


Student data variable code example

Java Strings and Built-In Methods

  • A String object represents an instance containing sequence characters surrounded by double quotes.

  • Because strings are instantiated objects, they carry built-in methods designed for string processing:

    • length(): Returns the total count of characters in a string.

String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println("The length of the txt string is: " + txt.length());
  • toUpperCase() and toLowerCase(): Convert string character casings entirely to upper or lower case.

String txt = "Hello World";
System.out.println(txt.toUpperCase()); // Outputs "HELLO WORLD"
System.out.println(txt.toLowerCase()); // Outputs "hello world"


String casing transformation methods
  • indexOf(): Returns the zero-based index position of the first occurrence of specified text within a string, accounting for all characters including whitespace.

String Concatenation and Arithmetic Behaviors

  • Strings can be joined via the + concatenation operator:

String firstName = "John";
String lastName = "Doe";
System.out.println(firstName + " " + lastName);


String concatenation with standard plus operator
  • Strings can also be concatenated using the built-in concat() method:

String firstName = "John ";
String lastName = "Doe";
System.out.println(firstName.concat(lastName));


String concatenation using concat method
  • Java utilizes the + symbol for both arithmetic addition and string concatenation:

    • Adding two numbers performs mathematical addition (e.g., 10+20=3010 + 20 = 30).

    • Adding two string representations performs string concatenation (e.g., "10" + "20" evaluates to "1020").

    • Adding a number to a string forces type coercion, resulting in string concatenation.

Escape Characters and Special Characters

  • Writing reserved characters (such as quotes) inside string literals causes compiler syntax errors.

  • The backslash (\) escape character transforms special control characters into valid text literals inside strings.


Escape characters reference table
  • Reference for core escape sequences:

    • \' : Produces a single quote character (').

    • \" : Produces a double quote character (").

    • \\ : Produces a literal backslash character (\).