Java Basic Syntax
Java - Basic Syntax
Section titled “Java - Basic Syntax”Welcome to the fundamentals of Java programming! A Java program is essentially a collection of objects that interact by calling each other’s methods. Before diving deep, let’s understand the basic building blocks and syntax rules.
Core Concepts Recap:
Section titled “Core Concepts Recap:”- Object: An instance of a class, having state (data/fields) and behavior (methods). Example: A specific
Dogobject might have states likecolor="Brown",name="Buddy"and behaviors likebark(),fetch(). - Class: A blueprint or template for creating objects. It defines the common properties (fields) and actions (methods) that all objects of that type will have. Example: The
Dogclass defines that all dogs have a name and can bark. - Method: A block of code within a class that performs a specific action or behavior. Methods manipulate data and execute logic.
- Instance Variables (Fields): Variables declared within a class but outside any method. Each object (instance) of the class gets its own copy of these variables, defining its unique state.
Your First Java Program
Section titled “Your First Java Program”Let’s start with the classic “Hello, World!” example. This simple program demonstrates the basic structure.
/** * This is a simple Java program. * It demonstrates the basic structure and prints "Hello, World!". */public class HelloWorld {
// The main method is the entry point of the application. public static void main(String[] args) { // Print the text "Hello, World!" to the console. System.out.println("Hello, World!"); }
} // End of HelloWorld classUnderstanding the Code:
Section titled “Understanding the Code:”public class HelloWorld: Declares a class namedHelloWorld. Thepublickeyword means this class is accessible from anywhere.public static void main(String[] args): This is the main method. Every Java application needs one.-
public: Accessible from anywhere.
-
static: Means the method belongs to theHelloWorldclass itself, not to any specific object instance. It can be run without creating an object of the class.
-
void: Indicates that this method does not return any value.
-
main: This specific name tells the Java Virtual Machine (JVM) where to start execution.
-
String[] args: Declares a parameter namedargs, which is an array ofStringobjects. This array holds any command-line arguments passed to the program when it runs.
System.out.println("Hello, World!");: This line does the work.-
System: A built-in Java class from thejava.langpackage.
-
out: A static field within theSystemclass, representing the standard output stream (usually the console).
-
println(): A method of theoutobject that prints the provided text (the argument) to the console, followed by a newline.
//and/** ... */: These are comments. The compiler ignores them. They are used to explain the code.
Saving, Compiling, and Running:
Section titled “Saving, Compiling, and Running:”- Save: Save the code in a text file named exactly
HelloWorld.java. The filename must match the public class name, including capitalization. - Compile: Open a terminal or command prompt, navigate to the directory where you saved the file, and type:
javac HelloWorld.java- This command invokes the Java compiler (
javac). If there are no errors, it will create a bytecode file namedHelloWorld.classin the same directory. - Run: In the same terminal, type:
java HelloWorld- This command starts the Java Virtual Machine (JVM) and tells it to run the
HelloWorldclass (specifically, itsmainmethod). Do not include the.classextension here.
Expected Output:
Hello, World!Basic Syntax Rules
Section titled “Basic Syntax Rules”Keep these fundamental rules in mind:
- Case Sensitivity: Java is case-sensitive.
myVariableandmyvariableare different identifiers. - Class Names: By convention, class names start with an uppercase letter and use CamelCase (e.g.,
MyFirstClass,String,ArrayList). - Method Names: By convention, method names start with a lowercase letter and use camelCase (e.g.,
calculateTotal(),getUserName()). - File Names: The name of the
.javafile must exactly match the name of thepublicclass declared within it. mainMethod: Every Java application must contain apublic static void main(String[] args)method as its starting point.- Statements: Each statement typically ends with a semicolon (
;). - Code Blocks: Code blocks are defined by curly braces
{}. They group statements together (e.g., within classes, methods, loops, conditional statements). - Whitespace: Java ignores extra whitespace (spaces, tabs, newlines) between tokens, but proper indentation makes code readable.
Java Identifiers
Section titled “Java Identifiers”Identifiers are names given to Java elements like classes, methods, variables, packages, etc.
Rules for Identifiers:
- Must start with a letter (a-z, A-Z), an underscore (
_), or a dollar sign ($). - Subsequent characters can be letters, digits (0-9), underscores, or dollar signs.
- Cannot be a Java keyword (reserved word like
class,int,public,if, etc.). - Cannot be
true,false, ornull. - Are case-sensitive.
- Can be of any length theoretically, but keep them meaningful and reasonably concise.
Examples:
- Valid:
age,userName,_balance,$amount,MAX_VALUE,calculateInterest - Invalid:
1stName(starts with digit),user name(contains space),class(keyword),max-value(contains hyphen)
Java Modifiers
Section titled “Java Modifiers”Modifiers are keywords that you add to definitions (like classes, methods, variables) to change their meaning or accessibility.
- Access Modifiers: Control visibility.
-
public: Accessible from anywhere.
-
private: Accessible only within the same class.
-
protected: Accessible within the same class, same package, and subclasses.
-
- (Default/Package-Private): (No keyword) Accessible only within the same package.
- Non-Access Modifiers: Provide other characteristics.
-
static: Belongs to the class, not an instance.
-
final: Value cannot be changed (variables), method cannot be overridden, class cannot be subclassed.
-
abstract: Class cannot be instantiated, method has no implementation (must be overridden).
-
synchronized,volatile: Related to multithreading (covered later).
We’ll explore these in more detail in later chapters.
Java Variables
Section titled “Java Variables”Variables are containers for storing data values. In Java, there are three main types based on where they are declared:
- Local Variables: Declared inside a method, constructor, or block. They exist only within that scope.
- Instance Variables (Non-Static Fields): Declared inside a class but outside any method. Each object instance has its own copy.
- Class Variables (Static Fields): Declared inside a class, outside any method, using the
statickeyword. There is only one copy shared by all instances of the class.
These are covered in detail in the ‘Java Variable Types’ chapter.
Java Arrays
Section titled “Java Arrays”Arrays are objects that store a fixed-size sequence of elements of the same type. We’ll cover how to declare, create, and initialize arrays in a dedicated chapter.
Java Enums (Enumerations)
Section titled “Java Enums (Enumerations)”Introduced in Java 5, an enum is a special type that defines a set of named constants. Enums restrict a variable to hold only one of these predefined constant values, improving type safety and code clarity.
Example:
Section titled “Example:”// Define an enum for T-shirt sizesenum Size { SMALL, MEDIUM, LARGE, EXTRA_LARGE}
public class TshirtOrder { Size shirtSize; // Variable can only hold one of the Size constants
public static void main(String[] args) { TshirtOrder order = new TshirtOrder(); order.shirtSize = Size.MEDIUM; // Assigning an enum constant
System.out.println("Selected size: " + order.shirtSize);
// Enums are great in switch statements switch (order.shirtSize) { case SMALL: System.out.println("Ordering a small shirt."); break; case MEDIUM: System.out.println("Ordering a medium shirt."); break; // ... other cases default: System.out.println("Unknown size selected."); } }}Output:
Selected size: MEDIUMOrdering a medium shirt.Java Keywords
Section titled “Java Keywords”Keywords are reserved words with predefined meanings in Java. You cannot use them as identifiers (names for variables, classes, methods, etc.).
abstract | assert | boolean | break |
byte | case | catch | char |
class | const* | continue | default |
do | double | else | enum |
extends | final | finally | float |
for | goto* | if | implements |
import | instanceof | int | interface |
long | native | new | package |
private | protected | public | return |
short | static | strictfp | super |
switch | synchronized | this | throw |
throws | transient | try | void |
volatile | while | _ (underscore, restricted since Java 9) |
Note: const and goto are reserved but not currently used. true, false, and null are literals, not keywords, but cannot be used as identifiers. var (since Java 10) is a reserved type name, not strictly a keyword.
Comments in Java
Section titled “Comments in Java”Comments are used to explain code and are ignored by the compiler. Java supports three types:
- Single-line comment: Starts with
//and continues to the end of the line. - Multi-line comment: Starts with
/*and ends with*/. Can span multiple lines. - Javadoc comment: Starts with
/**and ends with*/. Similar to multi-line but used specifically for generating API documentation using thejavadoctool.
// This is a single-line comment.int count = 0; // Initialize count
/*This is a multi-line comment.It can span several lines.*/
/** * This is a Javadoc comment for the calculate method. * It explains what the method does. * @param x The first operand. * @param y The second operand. * @return The sum of x and y. */public int calculate(int x, int y) { return x + y;}What is Next?
Section titled “What is Next?”Now that you have a grasp of the basic syntax and structure, the next chapter, ‘Java Object & Classes’, will delve deeper into the core concepts of object-oriented programming in Java, explaining how to define your own classes and create objects from them.