Java Syntax (Complete Guide) – Operators & Java Program Structure

A syntax for any language is the set of rules by which the language is governed and ruled, written and interpreted. Or we can say syntax can fill the gap between machine and humans. We know what is Java, but its time to know how to code in it. Java syntax can help us to write systematic codes to get the desired output.

Here, we are not only discussing the basic Java syntax but also operators, keywords and structure of a program.

So, let’s jump-start the Java syntax tutorial.

Basic Java Syntax Introduction

1. Java Syntax

Java programming language has many features and its own set of syntax rules, structure, and programming paradigm. It is an Object-Oriented programming language. Java syntax is derived from C and C++ that’s why it is very similar to them.

2. Basic Java Concepts

A Java program starts with a package, a package further contains classes, and classes contain methods, variables, constants and more.

2.1 Identifiers in Java

Java Identifiers are the names of packages, classes methods, and variables from which we identify the type of class, variable and method used in it. They are basically the name of any element.

Identifiers in Java are case-sensitive, there are some basic conventions that we have to follow while naming any identifier, they contain,

  • Any Unicode character, which is a letter or a digit
  • Special signs such as an underscore
  • A $ sign (a currency sign)

Basic Java Concepts

2.2 Java Keywords

Keywords in Java are identifiers that are used by the programmer for variable names or method names. Java Keywords have their intended use.

Following are the major keywords used in Java-

Keyword Description
boolean It declares a boolean return type or variable.
byte It declares a byte return type or variable.
char It declares a character return type or variable.
double It declares a double return type or variable.
float It declares a floating return type or variable.
short It declares a short integer return type or variable.
void This data type declares that the method does not have a return type.
int It declares an integer return type or variable.
long It declares long integer return type or variable.
while It declares the start of a ‘while’ loop.
for It declares the start of a ‘for’ loop.
do It declares the start of a ‘do while’ loop.
switch It tests which case is true in a given number of cases.
break It prematurely exits a loop.
continue It makes the loop to immediately jump to the next iteration of the loop.
case It denotes one case in the various cases in switch statement.
default It executes the default action for a switch statement.
if It executes the statement if the condition is true.
elseIt executes the other statement if the “if” statement condition is not true.
try It is used in situations where the program may get an exception.
catchIt is used to handle the exception.
finally It is used to denote that a given block of code is executed regardless of any exception.
class It signals the start of a class.
abstract It declares that a given class or method is abstract.
extends It denotes the class of a subclass.
final It denotes that a given class or variable cannot be overridden.
implements It denotes that this class implements the interface.
import It denotes that a permit access to a class or a group of classes.
instanceof It checks whether an object is an instanceof of a class.
interface It signals the start of an interface.
native It specifies that the given method is implemented in the native code.
new It allocates a new object.
package It defines the package to which the class belongs to
private It declares that the method or the variable is private.
public It declares that the variable or the method is public.
protected It declares the variable or method to protected.
return It returns the value in a method.
static It specifies that the given method belongs to the class and not to the object.
super It specifies a reference to the parent of the current object.
synchronized It indicates that the given section is not thread safe.
this It indicates the current object.
throw It declares the exception.
throws It declares the exception thrown by a class.
transientIt declares that the given field shouldn’t serialize.
volatile It warns that the given variable changes asynchronously to the compiler.

2.3 Java Literals

Literals in java represent boolean, character, numeric or string data, that is any value which can assign to a variable.

  • For an integer type, we can specify 4 types of literals-
TypeDescription
Decimal point literalsDigits from 0-9 are allowed in this type.
Octal point literalsDigits from 0-7 allowed.
HexadecimalDigits from 0-9 and characters from a-f are allowed.
Binary literalsDigits 0 and 1 are allowed and they should have a prefix.

Example-

Class LiteralDemo
{
public static void main(String[] args )
int variable1 = 122; //decimal form
int variable2 = 5624;//octal form
int variable3 = 0xFace;// hexa- decimal form
int variable4 = 0b2222;// binary form
System.out.println(variable1);
System.out.println(variable2);
System.out.println(variable3);
System.out.println(variable4);
}
}

Example of Literal in Java

  • For floating point type we can only specify literals in a decimal point, for example:

int a = 100.888;

  • For char type, we have four types of literals-

char a = ‘p’;
char ch = 062;

NameDescriptionExample
Single quoteIn this type, the literals can specify in a single quote.
Char literal an integer literalIn this type, we can represent char literal as integer literal as long as they satisfy Unicode and fall in the range 0- 65535.
Unicode representationIn this type, Unicode can specify in literals.char ch = ‘\u0061’;
Escape sequenceThis type represents the escape sequences.char ch = ‘\n’;

In string literal, a sequence of characters are within double quotes, they may not contain unescaped newline or a linefeed character.

String s = “this is an example\n’ + “for string literal”;

  • Boolean Literals-

In Boolean literal, only two values are allowed, true or false, or 0 or 1.
boolean b = true;

2.4 Code Blocks in Java

Code blocks {} are the separators in Java, they define the scope of any class or method. Class members and the body of a method are inside these code blocks.

2.5 Java Comments

There are three types of comments in Java language

  • Traditional comments – They are also known as block comments, they are multi-line comments and expand across multiple lines. They start with /* and ends with */.
  • End of line comment – This type starts with // and usually extends to the end of the line.
  • Documentation comment – These type of comments in the source files are processed by the Javadoc tool to generate documentation.

3. Structure of Java Program

Java program consists of two parts:

3.1 Main Method in Java

The main method in Java program is the entry point of any program. In a Java program, there can be multiple classes with a single main method. Java main method doesn’t return any value; that is, it has a void return type. It should always be static.

public static void main(String[] args)

3.2 Java Packages

Packages in Java are used to group similar classes and interfaces, as a folder does in a computer. It provides access protection and also namespace management.

  • lang – For fundamental classes
  • io – For input/output functions.
Java Quiz

4. Java Operators

There are basically five types of Java operators. They are-

Types of Operators in java

4.1 Arithmetic Operators in Java

OperatorDescription
+Adds value, performs the addition function.
Subtracts values.
*Performs multiplication.
/Performs division operation.
%This operator returns the remainder in a division operation.
++This operator is known is the increment operator. It increases the value of operand by 1.
This operator is known as the decrement operator. It decreases the value of the operand by 1.

4.2 Relational Operators in Java

OperatorDescription
==Checks the values are equal or not. If they are equal then the condition is true.
!=Checks whether the values are unequal or not. If they are unequal then the condition becomes true.
Checks whether the value of the operand at right is greater or not, if yes then the condition becomes true.
Checks whether the value of the operand at left is greater or not, if yes then the condition becomes true.
>=Checks whether the value of the right operand is greater or equal to the left operand, if yes then the condition becomes true.
<=Checks whether the value of the left operand is greater or equal to the right operand, if yes then the condition becomes true.

Explore 8 Types of Operators in Java with Examples

4.3 Bitwise Operators in Java

Bitwise right shift operator shifts the value of the right operand as specified by left operand. >> Shift right fills zero operators. The number of zeroes is defined by the shifted values in the left operand, and the number of zeroes depends on the number of right operands.

OperatorDescription
&Bitwise AND gives the result if both the conditions are true.
|Bitwise OR, gives results even if one condition is true.
^Bitwise XOR gives results if bit exists in both and not in both.
~Bitwise compliment usually flips the result.
<< Bitwise left shift operator, it shifts the value of left operand as specified by the right operand.
>>

4.4 Logical Operators in Java

OperatorDescription
&&Logical AND operator, if the operands are non-zero then the result is true.
||Logical OR, result true when either of the operands id 1
!Logical NOT, used to reverse or flip the logical operators.

4.5 Assignment Operators in Java

OperatorDescription
=Simple assignment operator. Assigns values to the left operand.
+=Add AND operator, it adds left operator to right and assigns the result to left operator.
-=Subtract AND operator, it subtracts the left operator to right and assigns the result to left operator.
*=Multiply AND operator, it multiplies left operator to right and further assigns the result to left operator.
/=Divide AND operator, it divides left operator to right and assigns the result to left operator.
%=Modules AND operator, it divides the left operator to right and assigns the remainder to left operator.
<<=Left shift AND operator.
>>=Right shift AND operator.
^=Bitwise Exclusive OR operator.
|=Bitwise Inclusive operator.
&=Bitwise assignment AND operator.

4.6 Conditional Operators in Java

Java Conditional operator is also known as a ternary operator, it executes the value to one of the three given variables by checking the condition.
Example-

public class Test {
public static void main(String args[]) {
int a, b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " +b );
b = (a == 10) ? 20: 30;
System.out.println( "Value of b is : " + b );
}
}

Conditional Operator in java

Have a Look at Decision Making in Java with Syntax and Examples

5. Control Statements in Java

5.1 Conditional statements in Java

Java Control Statements in Java Syntax

i. If statement in Java

Checks the condition and if the condition holds true then executes the operation.

Example-

If(i==3)
action();

ii. If else in Java

Checks the condition, if it is not true then the else action is executed.

Example-

if (i == 2) {
action1();
} else {
action2();
}

iii. Else if in Java

This is a series of If else statements.

Example-

if (i == 3) {
action1();
} else if (i == 2) {
action2();
} else {
action3();
}

iv. Switch statement in Java

This statement checks the different cases and then runs according to the condition.

Example-

switch (ch) {
case 'A':
action1(); // Runs if ch == 'A'
break;
case 'B':
case 'C':
action2(); // Runs if ch == 'B' or ch == 'C'
break;
default:
action3(); // Runs in any other case
break;
}

5.2 Iteration statements in Java

Iteration statements are the statements that create a loop until the condition turns false.

i. While loop in Java

The condition is checked after every iteration.

Example-

If(i==3)
action();

ii. Do…while loop in Java

In this loop the code is always executed once, it is also tested after every iteration.

Example-

do {
action();
} while (i < 10);

iii. For loop in Java

In a Java code, the for loop contains an initializer and an ending condition.

Example-

for (int i = 0; i &lt; 10; i++) {
action();
}

5.3 Jump Statements in Java

i. Break statements in Java

It breaks the closest loop or the switch statement, though the execution continues after this termination.

Example-

for (int i = 0; i < 10; i++)
{
while (true) {
break;
}

ii. Continue statement in Java

It discontinuous the current iteration and starts a new one.

Example-

int ch;
while (ch == getChar()) {
if (ch == ' ') {
continue;
}
action();
}

iii. Return statement in Java

It is used to end the execution and return a value. It returns void if the keyword void is mentioned in the class.

Example-

int calculateSum(int a, int b) {
int result = a + b;
return result;
}

5.4 Exception Handling Statements in Java

These statements manage exceptions in the code.

i. Try-Catch-Finally in Java

In this type, the try method is iterated and if this throws an exception then the catch method is iterated.

Example-

try {
// Statements that may throw exceptions
methodThrowingExceptions();
} catch (Exception ex) {
// Exception caught and handled here
reportException(ex);
} finally {
// Statements always executed after the try/catch blocks
freeResources();
}

ii. Throw Statements in Java

This statement is used to throw an exception and the present iteration.

Example-

void methodThrowingExceptions(Object obj) {
if (obj == null) {
// Throws exception
throw new NullPointerException();
}
// Will not be called, if the object is null
doSomethingWithObject(obj);
}

6. Summary

A tree with strong roots laughs at storm  by Malay Proverb

Here, we can consider syntax as roots, roots have to be strong to fight with a heavy storm. That’s why you should know the Java syntax to master the language. Every concept we studied in this “Java Syntax” tutorial holds equal importance. Now, it’s your turn to beat the storm by practicing Java syntax.

Is this information helps you? Share your feedback with us!

It’s time to check out the latest Java Tutorial Series and master all the concepts for free.

7 Responses

  1. nisha says:

    I am about to complete my engineering soon and I found this blog to be very informative and enlightning. Post reading it, I got valuable insights into my field; which would be useful going ahead. Thank you so much for basic java study material.

  2. Gowsalya says:

    The Java compiler. When you program for the Java platform, you write source code in .java files and then compile them. i am glad to leave a comment except more articles in future. chicle the selenium tutorial for update knowledge on selenium. https://bit.ly/2NjdPr0

    • Data Flair says:

      Hi Gowsalya,
      Thank you, for commenting on “Java Syntax Tutorial”, we are glad readers like you share their knowledge with other readers. Keep Learning and Keep Sharing knowledge.
      Regard,
      Data-Flair

  3. hurtchriss says:

    Thanks anyway

    • DataFlair Team says:

      Thanks hurtchriss, for taking time and giving us your valuable feedback.

      Keep Visiting Data Flair for more Java Tutorials.

  4. ryan says:

    why does it show II instead of || ?

    • DataFlair Team says:

      Hello Ryan,
      Nice Catch, thanks for correcting us. It was a typo mistake and we made the necessary changes.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.