Java Syntax – A Complete Guide to Master Java

Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java

In this Java Tutorial, we will learn about Java Syntax. So let’s start!!!

What does Syntax mean?

Well, simply put, syntax is a particular format for writing commands in a programming language. Every language has its individual syntax.

Without proper knowledge of syntax, it would be difficult to generate desired output from a programming language. Syntax are also referred to as the language of the computer.

Java Syntax

Java Syntax

Java syntax is similar to C and C++ because it comes from them. So, let’s dive into the depths of syntax in Java!

As soon as a Java program starts, it has a package. A package consists of many classes, each consisting of functions, variables and methods. We start with knowing the syntax for identifiers in Java.

Identifiers in Java

Identifiers are the names given to entities such as classes, variables, and functions to uniquely identify them throughout the program.

They contain:

  • Underscore( _ ) and dollar($) (only special characters allowed in naming identifiers.)
  • Unicode characters such as numbers and letters.

Java Keywords

Keywords are the identifiers that have special meaning to the compiler. These cannot be used to name variables, classes, functions, etc. These are reserved words.

Some of the keywords are:

  • abstract – This keyword specifies that the class is abstract.
  • boolean– This is a data type specifier which mentions that a particular variable is a Boolean.
  • byte– this is a data type specifier that specifies a particular variable to be of byte type.
  • Case– a switch case keyword which specifies a program to be performed if a particular case is satisfied
  • catch – during a throw case of error handling, catch encloses actions to be performed if an exception occurs
  • break– The break keyword breaks the control out of a loop
  • Void – this keyword renders a method non-returnable
  • char– This is a data type specifier that specifies that the variable is of character type
  • Class– This keyword specifies the creation of a new class followed by a class name.
  • Extends– This is used to indicate that the class mentioned after it is the derivation of a superclass.

Java Literals

These are the identifiers that have a particular value in themselves. These can be assigned to variables. Literals can also be thought of as constants.
These are of different types, such as numeric, characters, strings, etc.

a. Numeric Literals

For numeric literals, there are 4 kinds of variations:

i. Decimal(Any number of base 10), Example- 87,53
ii. Binary(Any number with a base 2), Example- 1011,110
iii. Octal Point(Any number with base 8), Example= 1177
iv. Hexadecimal Point(Any number with base 16), Example- A54C

b. Floating point Literals

We can specify the numeric values only with the use of a decimal point(.). These numbers represent fractional numbers that cannot be expressed as whole integers.

For Example: 10.876

c. Character Literals

These are the literals which deal with characters, i.e., inputs which are not numeric in type.

i. Single quoted character– This encloses all the uni-length characters enclosed within single quotes. Example- ‘a ’,’j’.

ii. Escape Sequences– These are the characters preceded by a backslash that perform a specific function when printed on screen such as a tab, creating a new line, etc. Example-’\n’

iii. Unicode Representation– It can be represented by specifying the concerned Unicode value of the character after ‘\u’. Example- “\u0054’

Comments in Java

Comments are needed whenever the developer needs to add documentation about a function that is defined within the program. This is to enhance the code-readability and understandability. Comments are not executed by the compiler and are simply ignored during execution.

The comments are of the following types:

a. Single Line Comments in Java

These comments, as the name suggests, consist of a single line of comment generally written after a code line to explain its meaning.
They are marked with two backslashes(//) and are automatically terminated when there
A new line is inserted in the editor.

For Example:

int i = 6;
String s = “DataFlair”; // The value of i is set to 6 initially.The string has value “DataFlair”

b. Multi-Line Comments in Java

These comments span multiple lines throughout the codebase. They are generally written at the beginning of the program to elaborate about the algorithm. These are also used by developers to comment out blocks of code during debugging. They comprise of a starting tag(/*) and an ending tag(*/)

For Example:

class Comment {
  public static void main(String[] args) throws IOException {
    /* all this is under a multiline comment
    These wont be executed by compiler
    Thank you*/
  }
}

c. Documentation Comment

The javadoc tool processes these comments while generating documentation

Basic structure of a Java program

There are two basic parts of a Java program, namely, Packages and the main method.

1. Java Package

This is the same thing as a folder in your computer. It contains classes, interfaces, and many more. It organizes the classes into namespaces. The classes that are in the same package can access each other’s protected and private members.

They are generally imported by using the import keyword, i.e., import java.util.*, where we are importing Java’s util package

2. Main Method in Java

If the main method is not present in a program or it is not correct, then the program will compile but won’t run. The main method marks the entry point of the compiler in the program. The main method must always be static.

For Example:

public class DataFlair {
  void teachJava() {
    System.out.println(“Teaching Java by DataFlair”);
  }
  public static void main(String[] args) throws IOException {
    System.out.println(“In main”);
    DataFlair ob = new DatFlair();
    ob.teachJava();
  }
}

Output:

In main
Teaching Java by DataFlair

The compiler first executes the main method and then the object method.

5. Java Control Statements

These are the statements in a Java program that control the flow of a program. Several control statements manage the flow of the program by making decisions, performing repetitive tasks, or jumping to other statements.

The syntax of control statements in Java is pretty straightforward. Let’s take a deeper look at the control statements in Java.

a. Conditional Statements in Java

These statements are purely based on condition flow of the program. It’s divided into the following 3 parts

i. if statement

The statement suggests that if a particular statement yields true, then the block enclosed within the if statement gets executed.

if (condition) {
  action to be performed
}

ii. if else statement

This statement is of the format that if a condition enclosed is true, then the if block gets executed. If not, the else block gets executed

Example:

if (condition) {
  action1;
}
else {
  action2
}

iii. Else if statement

This statement encloses an if statement in an else block.

Example:

if (condition) {
  action 1
}
else if (condition2) {
  action 2
}

iv. Switch case

The switch case is used for multiple condition checking. It’s based on the value of the variable. The value of the variable mentioned marks the flow of the control to either of the case blocks mentioned.

Example:

switch (var_name)
case value1:
  action1;
  break;
case value2:
  action2;
  break;
default:
  action3;
  break;

b. Iteration Statements in Java

These are the statements which are primarily known as loops in programming, which run a particular set of programs a fixed number of times,

Some of the types of iterative statements are:

i. For loop in Java

The for loop is responsible for running the snippet of code inside it for a predetermined number of times.

Example:

for (i = 0; i < 5; i++) {
  System.out.println(“Hi”);
}

This prints “Hi” 5 times on the output screen

ii. While loop in Java

This type of loop runs indefinitely until the condition is false

Example:

while (i < 6) {
  System.out.println(“Hi”);
  i++;
}

This prints Hi on the screen five times until the value of i becomes 6

iii. Do-while loop in Java

This is the same as the while loop. The only difference lies in the fact that the execution occurs once, even if the condition is false.

Example:

do {
  System.out.println(“Hi”);
}
while ( i > 6 );

c. Control Flow Statements/Jump Statements in Java

Sometimes we need to discontinue a loop during execution.

i. Break statement in Java

This breaks the nearest loop inside which is mentioned. The execution continues from the next line just when the current scope ends.

ii. Continue Statement in Java

This continues the execution from the next iteration of the loop and skips the current execution.

Example:

while (i < 10) {
  if (i == 3) continue;
  i++;
}

This prints all the values from 0 to 9 except 3

iii. Return statement in Java

The return statements are generally useful in methods when returning a value when the function is done executing. After the return statement executes, the remaining function does not execute.

Exception Handling in Java

Exception handling is important to custom output the errors in the unfortunate case of an error occurrence. The syntax of the exception handling is fairly simple and structured.

It goes as follows:

try {
  // Code block within which error can occur
}
catch(Exception e) {
  //Code block to perform when error thrown
}
Finally {
  //Code to be executed after the end of try block. This block is executed even if there is no error
}

There is a special keyword called throws, it is useful to throw custom exceptions.

For Example, throw new ArithmeticException();

Try: This block houses the code that is responsible for an error thrown. Generally, programmers enclose the code that they think may throw an error in the try block.

Catch: This block houses the code to be performed when a particular exception is found. There can be custom messages defining what kind of error has occurred for better documentation and flow of the program.

Finally: The finally block executes whether or not there is any error faced by the compiler. This part is generally used to enclose the code that has to be executed irrespective of the errors occurred during compilation/execution of the program.

Example program to evaluate exception handling in Java

import java.io. * ;
class ExcptionHandle {
  public static void main(String[] args) throws IOException {
    int a = 10,
    b = 0;
    int c;
    try {
      c = a / b;
    } catch(Exception e) {
      System.out.println(e);
      //TODO: handle exception
    }
  }

Output:

java.lang.ArithmeticException: / by zero

Operators in Java

As the name suggests, operators are the ones for performing operations on two or more entities. They are of multiple types as follows:

a. Arithmetic Operators in Java

These are the operators that are solely for performing arithmetic operations. These include addition (+), subtraction(-), multiplication (*), division (/), modulo(%) and many more.

b. Relational Operators in Java

These are the operators that obtain the relation between two different entities in a program. These include less than(<), greater than(>), less than or equals to(<=), greater than or equals to(>=) ,equals to(==), not equals to(!=)

Example:

if (a < b) {
  System.out.println(“A greater”);
}

c. Bitwise Operators in Java

These operators are useful for performing bitwise operations on an entity. These include AND(&), bitwise OR(|), bitwise XOR(^), bitwise complement (~), bitwise left shift(<<) and so on.

Example: (A&B) will give 12 if a = 0000 and b= 1100

d. Logical Operators in Java

These operators are useful to check the logic of a particular operation of two operands. These include Logical AND(&&), Logical OR(||), logical NOT(!) and so on.

For Example:

if (a == 6 && b == 5)

e. Assignment Operators in Java

These operators are responsible for assigning variables to variables. These include equal(=),add AND(+=), subtract AND operator(-=) and so on.
Example:

int x = 65;
int y += 6

int y+=6(equivalent to int y=y+6;)

Object in Java

Objects are created from classes in Java. Once we define a class, we can create an object of the class using the following simple syntax. These are the instances of the class:

< class - name > <object - name > =new < class - name of instance creation > ()

Example of a Java object:

DataFlair java = new DataFlair();

Class in Java

Classes generally start with the class name, which has its first letter capital. Generally, the case is CamelCase for class names. It has a very simple syntax as follows:

class < Class - name > {
  instance variables;
  class method1() {}
  class method2() {}
} //end class

Example of a Java class:

class DataFlair {
  int a;
  void teach() {
    System.out.println(“Learning java from DataFlair”);
  }
}

Methods in Java

Methods or functions are specific entities that return a value only when they are called. They have a syntax similar to classes.

<
return type > <
function - name > {
  action1;
  action2;
}

Example Methods in Java:

void print() {
  System.out.println(“hey I am learning Java at DataFlair”);
}

Java Interfaces

Interfaces are a collection of abstract methods in Java. We will learn more about Java in the following articles. We define interfaces as follows;

interface < interface - name > {
  static functions;
  abstract methods;
}

Example of Java Interfaces:

interface DataFlair {
  void teach();
  static void evaluate();
}

Access modifiers in Java

Access modifiers, as the name suggests, limit the access of the entities they are defined with. The access modifiers used by Java are:

a. Public – Accessible to every other class or interface. There is no restriction on access.

b. Private– This keyword renders all entities to be accessible only inside the class in which they are declared.

c. Protected– The protected members of the class are accessible to classes within the same package or subclasses of different packages.

d. Default– If no access modifier is mentioned, then the default access modifier is invoked. This limits the access of the particular entity within the same package.

For Example:
public int a=8;

Arrays in Java

Arrays are consecutive data items of the same datatype. They have a fairly simple syntax of declaration.

If the array has to be declared explicitly, it has the syntax of:

< data type > <array - name > [ < array - size > ] = {
  data1,
  data2,
  data3...
};

Example of Java Arrays:

int arr[3] = {
  1,
  2,
  3
};

else if the array has to be declared during runtime.

< data type > <array - name > [] = new < array - name > [ < sizeofArray > ]

Example:

int arr[] = new int[10];

Variables in Java

The variables concept has been explained in the following articles, the syntax of variables is simple and easy to learn.

Java Syntax for variables:

< data type > <variable - name >

Example of Java variables:

String s = ”DataFlair”;

Datatype

The datatypes come before variables to define the type of data they would be storing. These include int,short,byte,float,double;

Syntax

< datatype > <
var - name >

Example:

int b = 12;

Compiling and Executing a Java Program

Once we have written a Java program and saved it, we need to compile and execute it using the following methods.

  • Open up a CMD window on the saved location by <Shift+right-click> and then select your configured CLI, i,e CMD or PowerShell. If you are using any other OS like Ubuntu or Linux, open up a terminal and navigate to the directory in which you have saved the Java program.
  • Next, type in javac <filename.java>
  • follow that by typing java <filename>

Example:

javac DataFlair.java (This compiles the file and lets us know if there are errors. )
java DataFlair (if no errors are found, run this command in CLI)

Java Apps: Driving a Range of Solutions

Java’s flexibility goes beyond syntax, allowing it to be used in a multitude of contexts. These are a few well-known examples:

1. Word processors, spreadsheets, and games are just a few examples of the easily navigable desktop apps that Java can produce.

2. Web Applications: A large percentage of web applications use Java on the client (with Java applets for interactive elements) and server (with Java servlets and JSP).

3. Android mobile applications: Java is a key component of the Android development platform, so knowing it is a must for Android app developers.

4. Cloud Computing: Java works well for cloud-based applications because of its portability and scalability. Strong support for Java deployments is offered by numerous cloud platforms.

Summary

Syntax is important as they are the language that the compiler understands. If the syntax is incorrect, even the fastest algorithms can come to a standstill. So we must strengthen our concepts of Java syntax before proceeding further into the concepts of Java.

Did you like this article? If Yes, please give DataFlair 5 Stars on Google

courses

DataFlair Team

DataFlair Team specializes in creating clear, actionable content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Backed by industry expertise, we make learning easy and career-oriented for beginners and pros alike.

12 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.

  5. Clem says:

    Nice and comprehensive tutorial
    I noticed this while compiling example 2.3 “int variable4 = 0b2222;// binary form”
    However the code in the output is different.
    Can you please explain

  6. Clare Jarvis says:

    The are some errors in the examples.
    int variable2 = 5463; // has nothing to do with octal
    should be:
    int variable3 = 05463l

    likewise b222 is not a binary value. Please replace with 0b101

  7. Venkat says:

    Want learn how picture are created, like Control Statements(picture is good). Could you please provide info .

    Tutorial is having awesome content.

  8. Marcus says:

    Hi.
    First i like the short summery you did.
    I found a never ending loop in the article.

    This is a loop that is never ending
    while (i < 10) {
    if (i == 3) continue;
    i++;
    }
    when i ==3 it never reach i++ so you need to move i++ to above the if statment. And put a print under the if statment so it prints the value of i.

  9. Jacob says:

    This work is amazing I would love to have it

Leave a Reply

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