Java Syntax

18-Sep-2024

Understand Java's basic syntax and structure for writing your first program.

Java syntax is a set of rules and conventions that determine how Java programs are written. Demonstrates some important aspects of Java syntax.
1.Case Sensitivity::

Java treats uppercase and lowercase letters as different, so it is case sensitive. For example, my Variable and my variable are considered different variables.



2.Class Declaration:

  Class Declaration: Every Java program consists of at least one class, and  program execution begins with the main method within this class.


The basic syntax for declaring a class is as follows:



public class MyClass {
    public static void main(String[] args) {
        // Program code goes here
    }
}


3. Comments:

Comments are used to add explanations within the code. Java has single-line comments ("//") and multi-line comments ("/* ...*/").



// This is a single-line comment

/*
 * This is a multi-line comment
 * spanning multiple lines
 */

4. Variables:

 Variables must be declared before they can be used. The syntax for declaring variables is:




 data_type variableName;


5. Data types:

Java supports a variety of data types, including primitive types (int, double, char, boolean) and reference types (objects).


 
 int myInt = 42;
double myDouble = 3.14;
char myChar = 'A';
boolean myBoolean = true;

6. Operators:

Java supports a variety of operators for arithmetic, relational, logical, and bitwise operations. Examples are +, -, *, / (arithmetic), ==, !=, (relational), &&, ||, ! (Logical).


7. Control Flow Statements:

Java uses control flow statements such as if, else, for, while, and switch to control the flow of execution of a program.

8.Method:

A method is a Java function.
The basic syntax for defining a method is:


return_type methodName(parameter1_type parameter1_name, parameter2_type parameter2_name) {
    // Method body
    // Return statement if applicable
}

9.Classes and Objects:

Java is an object-oriented programming language. Classes are used to define blueprints for objects. An object is an instance of a class. The basic class declaration is:



public class MyClass {
    // Class members (fields, methods, etc.)
}

10.Packages:

Packages are used to organize classes into namespaces.

The package statement is used at the beginning of a source code file.



package com.example.mypackage;

These are some of the basic aspects of Java syntax. Proper understanding and adherence to these rules is essential to writing correct and maintainable Java code.


Comments