Basic Syntax In Java

Java is a statically-typed, object-oriented programming language known for its platform independence. This means that Java programs can be developed and compiled on one system, such as Windows, and run on another, like MacOS, without requiring any alterations to the source code.

Case Sensitivity:   

Java is case-sensitive, meaning that uppercase and lowercase letters are treated as distinct. For example, variable and Variable are considered different variables.

Class Declaration:

    • Java programs are typically organized into classes.
    • The public keyword is used to specify the visibility of the class.
    • The class keyword is followed by the class name, and the class body is enclosed in curly braces {}.
    • Rules for Naming: Class names should be nouns, in mixed case with the first letter of each internal word capitalized. Try to keep your class names simple and descriptive. Use whole words-avoid acronyms and abbreviations.
				
					public class MyClass {
    // Class members go here
}

				
			

Main Method:

  • Every Java program must have a main method, which serves as the entry point of the program.
  • The main method is defined as public static void main(String[] args).
				
					public static void main(String[] args) {
    // Program logic goes here
}

				
			

Comments:

  • Java supports both single-line and multi-line comments.
  • Single-line comments start with //, and multi-line comments are enclosed within /* */.
				
					// This is a single-line comment

/*
This is a
multi-line comment
*/

				
			

Data Types

Java has several primitive data types (e.g., int, long, double, boolean,short,float,char,byte) and reference data types (e.g., String, user-defined classes).

Variables:

    • Variables are used to store data.
    • They must be declared with a data type before they can be used.
    • To declare a variable in Java, we must specify its name (also called an identifier) and data type. The variables will receive default initial values based on their declared types.
    • We can use the assignment operator (=) to initialize variables during declaration.
    • Rules for Naming: Except for variables, all instance, class, and class constants are in mixed case with a lowercase first letter. Internal words start with capital letters. Variable names should not start with underscore _ or dollar sign $ characters, even though both are allowed
				
					int age = 29;
double pi = 3.14;
String name = "Reet";

				
			

Operators:

Java supports various operators for performing operations like arithmetic, comparison, and logical operations.

Control Flow:

Java provides conditional statements (if, else, switch) and loops (for, while, do-while) for controlling program flow.

Classes and Objects:

    • Java is an object-oriented language, so we define classes to create objects.
    • We can create objects using the new keyword and access their members using the dot (.) operator.
				
					MyClass obj = new MyClass();
obj.method();

				
			

Inheritance:

  • Java supports inheritance, allowing you to create new classes based on existing ones.
  • The extends keyword is used to establish inheritance.
				
					class ChildClass extends ParentClass {
    // Additional members and methods
}

				
			

Exception Handling:

  • Java uses try, catch, and finally blocks to handle exceptions.
  • Exceptions are used to handle runtime errors gracefully.
				
					try {
    // Code that may throw an exception
} catch (ExceptionType e) {
    // Handle the exception
} finally {
    // Code that runs regardless of whether an exception occurred
}

				
			

Packages:

  • Java classes are organized into packages for better code organization.
  • We can use the import statement to access classes from other packages.
  • Rules for Naming: The prefix of a unique package name is always written in all-lowercase ASCII letters and should be one of the top-level domain names, currently com, edu, gov, mil, net, org, or one of the English two-letter codes identifying countries as specified in ISO Standard 3166, 1981. Subsequent components of the package name vary according to an organization’s own internal naming conventions. Such conventions might specify that certain directory name components be division, department, project, machine, or login name.
				
					import java.util.ArrayList;
				
			

Access Modifiers

Java uses access modifiers like public, private, protected, and default (no modifier) to control the visibility and accessibility of class members.

Method Declaration

Methods are defined within classes and can take parameters and return values.  Rules for Naming: Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized.

				
					public int add(int num1, int num2) {
    return num1 + num2;
}

				
			

Semicolons:

Java statements are terminated with semicolons (;).

				
					int x = 50; // Semicolon terminates the statement

				
			

Java Program Structure:

Now that we have gained an understanding of data types, variables, and fundamental operators, let’s explore how we can integrate these components to create a basic, functional program. In Java, a program’s fundamental building block is a Class. A Class can encompass multiple fields (also known as properties), methods, and may even include inner classes as part of its structure. To make a Class executable, it must contain a main method. The main method serves as the starting point for the program’s execution.

Let’s construct a straightforward executable Class to demonstrate one of the code examples we discussed previously:

				
					public class Person {
    // Properties or fields
    private String name;
    private int age;

    // Constructor
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Method to get the person's name
    public String getName() {
        return name;
    }

    // Method to set the person's name
    public void setName(String name) {
        this.name = name;
    }

    // Method to get the person's age
    public int getAge() {
        return age;
    }

    // Method to set the person's age
    public void setAge(int age) {
        if (age >= 0) {
            this.age = age;
        } else {
            System.out.println("Age cannot be negative.");
        }
    }

    // Method to print information about the person
    public void displayInfo() {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }

    public static void main(String[] args) {
        // Creating an instance of the Person class
        Person person1 = new Person("Reet", 30);

        // Accessing properties and methods of the person1 object
        person1.displayInfo();

        // Changing the person's age
        person1.setAge(35);

        // Displaying updated information
        person1.displayInfo();
    }
}

				
			

In this example, we have a Person class with properties name and age, along with getter and setter methods to access and modify these properties. The displayInfo method is used to print information about the person. In the main method, we create an instance of the Person class and demonstrate how to use its properties and methods.

Conclusion

These are some of the fundamental aspects of Java’s syntax. As you delve deeper into Java programming, you’ll encounter more advanced concepts and features that build upon this basic syntax.