Syntax in Java


Java syntax is the set of rules that define how a Java program is written and interpreted. The syntax is mostly derived from C and C++. Unlike in C++, in Java there are no global functions or variables, but there are data members which are also regarded as global variables.

Basic Keywords and Operators

The following are some of the most basic keywords and operators in Java:

Keywords:

class
public
static
void
main
String
System
out
println

Control Flow Statements

Java provides a variety of control flow statements, which allow you to control the order in which your code executes. The following are some of the most common control flow statements:

if (condition) {
    // code to execute if condition is true
} else {
    // code to execute if condition is false
}

While Loop

while (condition) {
    // code to execute while condition is true
}

For Loop

for (int i = 0; i < 10; i++) {
    // code to execute for each value of i
}

Classes and Objects

Java is an object-oriented programming language, which means that it uses classes and objects to represent data and behavior. A class is a blueprint for an object, and an object is an instance of a class.
To create a class, you use the class keyword. For example

class MyClass {

}

To create an object, you use the new keyword. For example:

MyClass myObject = new MyClass();

Methods

Methods are functions that are defined inside a class. Methods can be used to perform actions or to return values.
To define a method, you use the public keyword, followed by the method name, followed by the parameters (if any). For example:

public void myMethod() {

}

To call a method, you use the object's name, followed by a dot, followed by the method name. For example:

myObject.myMethod();

Variables

Variables are used to store data. To declare a variable, you use the int, double, String, or char keyword, followed by the variable name. For example:

int myInt;
double myDouble;
String myString;
char myChar;

To assign a value to a variable, you use the = operator. For example:

myInt = 10;
myDouble = 3.14;
myString = "Hello, world!";
myChar = 'A';

Arrays

Arrays are used to store multiple values of the same type. To declare an array, you use the int[], double[], String[], or char[] keyword, followed by the array name. For example:

int[] myIntArray;
double[] myDoubleArray;
String[] myStringArray;
char[] myCharArray;

To assign a value to a variable, you use the = operator. For example:

myIntArray = new int[] { 10, 20, 30 };
myDoubleArray = new double[] { 3.14, 2.718, 1.618 };
myStringArray = new String[] { "Hello", "world!" };
myCharArray = new char[] { 'A', 'B', 'C' };