Basic Java Syntax To Master Java Programming

Every programming language has some specific syntax. In this Java article, we will learn about the syntax of Java. In this article, we will learn the syntax for each and everything in Java that you should know before learning the language and getting familiar with it.

Keeping you updated with latest technology trends, Join TechVidvan on Telegram

What is the syntax?

The syntax is a particular format for writing a program in Java and the commands to compile and execute it. Without proper knowledge of syntax, it will be difficult for a programmer or a learner to get the desired outputs from a program. We can also refer to the syntax as the language of the compiler.

What is Java syntax?

Java Syntax

A syntax in Java refers to the set of rules that define how to write a Java program and interpret it. The syntax of Java is derived from C and C++. But there are many differences, like, in Java, there are no global variables as in C++. The code belongs to objects and classes in Java. Java omits some of the features like operator overloading and the use of explicit pointers to avoid programming mistakes.

So let’s start looking at basic syntax of java.

Identifiers in Java

Identifiers are the basic building blocks of a Java program. We use identifiers to give names to the different parts of the program such as variables, objects, classes, methods, arrays, etc.

The rules for naming identifiers in Java are:

1. Identifiers can contain alphabets, digits, and underscore(_) and dollar($) sign characters.
2. They must not be a reserved word or keyword in Java, like true, false, while, etc.
3. Identifiers must not begin with digits
4. Identifiers can be of any length
5. Java is case sensitive, so uppercase and lowercase identifiers are treated differently.

Keywords in Java

Keywords are the reserved words in Java that convey a different meaning to the compiler. We cannot use the keywords as normal identifier names but only for a special purpose. In Java, there are 51 keywords.

Some of the keywords in Java are:

abstract, boolean, byte, char, long, short, int, finally, extends, implements, interface, package, new, while, for, do, break, continue, return, public, private, this, case, final, default, etc.

Literals in Java

A literal in Java refers to the constants or the data items that have fixed values. There are different types of Literals in Java. They are Numeric, Floating, character, strings, boolean, null. They are also divided further into subcategories. Let’s discuss them separately:

a. Numeric Literals

Numeric literals represent numbers. There are 4 types of numeric literals in Java:

i. Integer Literals: Integer literals are the whole numbers without fractional part and they are the number of base 10. For example, 34, 76, 9896, etc.

ii. Binary Literals: Binary literals are the number with base 2. For example, 0101, 0011, 011, etc.

iii. Octal Literals: Octal literals are the numbers with base 8. They must not contain 8 and 9. For example, 77, 565, 450, etc.

iv. Hexadecimal Literals: Hexadecimal literals are the numbers with base 16. They can contain the digits from 0 to 9 and alphabets from A to F. For Example, AC87, 1F7B, 24D6, etc.

b. Floating-point Literals

We can call floating-point literals as real literals. The floating-point literal specifies the numeric values only with the use of a fractional point(.). They can be a fractional form or exponential form. For Example, 10.876, 152.4E07, -15.6, etc.

c. Character Literals in Java

The character-literals deal with characters enclosed in single-quote. They can contain only a single character within single quotes ‘ ’. They are of following types:
i. Single quoted character: The single-quoted character encloses all the uni-length characters within single quotes. Example- ‘z’,’j’, ‘A’, etc.

ii. Escape Sequences: These are the characters that come after backslash and perform a specific function when printed on the screen such as a tab, creating a new line, etc. Example: ’\n’, ‘\b’, ‘\t’, etc.

iii. Unicode Representation: We can represent it by specifying the concerned Unicode value of the character after ‘\u’. For Example- ‘\u0067’, etc.

d. Boolean literals

A boolean literal has only two values: true and false. These values are formed from ASCII letters. Example: true, false.

e. String Literals

The String-literals are the multiple character constants enclosed within double quotes “ ”. For example, “java tutorial”, “HelloWorld”, “\abc”, etc.

Comments in Java

The programmers can put the comments whenever they need to add documentation about a function or any line defined within the program. The compiler does not read the comments while compiling and ignores them. The comments enhance code readability and understandability of the program.

The comments are of the following types:

a. Single-Line Comments in Java

These single-line comments consist of a single line of a comment written after a code line to explain its meaning. To define a single-lie comment, we can mark it with two backslashes(//) and it is automatically terminated when there is a new line inserted in the editor.

For example:

int num = 6;
//Defining the value of num
System.out.println(“The value of num is: “ + num);
//Printing the value of num

b. Multi-Line Comments in Java

The multi-line line comments span for multiple lines throughout the program. We can write them at the beginning of the program to elaborate the algorithm. The developers also use them to comment out blocks of code during debugging. We can use them by starting tag(/*) and an ending tag(*/).

For example:

int num = 6;
System.out.println(“The value of num is: “ + num);
/* Defining the value of num and printing the value of num. This is a multi-line comment. The compiler will not execute it. */

Control Statements in Java

Control statements are the statements that affect the flow of control of a program. The syntax of control statements in Java is very simple. Let’s take a deeper look at the types of control statements in Java.

a. Conditional Statements in Java

The conditional statements are purely based on the condition flow of the program. They are of the following 3 types:

i. if statement

The if statement tells that if a particular statement results in true then the block enclosed within the if statement gets executed. The syntax of ‘if’ statement is:

if (condition) {
  //action to be performed
}

ii. if-else statement in Java

The else if statement states that if a particular condition in the if statement yields to false then it goes to the else block. Its syntax is:

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

iii. else if statement in java

This statement encloses an if statement in an ‘else’ block. Its syntax is:

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

iv. Switch case in Java

The switch case in Java is checking multiple conditions at the same time. It works on the basis of the value of the variable that we pass into it. There are many cases according to the values and if the value matches that case, then the statements inside that case are executed. The syntax of the switch case is:

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

b. Iteration Statements in Java

Iteration Statements are also called loops that execute for a fixed number of times until a particular condition is fulfilled.

Types of iterative statements are:

i. For loop in Java

The for loop is responsible for executing a part of the code inside it for a predetermined number of times. It contains the initialization, update statement, and condition statements in the same line. Its syntax is:

for (int num = 0; num < 5; num++) {
  System.out.println(“Hello World”);
}

This prints “Hello World” for 5 times on the output screen

ii. While loop in Java

The while loop runs indefinitely until the condition is false. The syntax of while loop is:

while (num <= 6) {
  System.out.println(“Helloworld”);
  num++;
}

This prints Helloworld on the screen six times until the value of num becomes 7.

iii. Do-while loop in java

The do-while loop is alomost same as the while loop. The only difference is that the execution occurs once even if the condition is false.

do {
  System.out.println(“Hello”);
}
while ( num >= 5 );

This prints Hello for five times.

c. Jump Statements in java

Sometimes we need to discontinue or break from a loop during execution for a particular condition. We can use them with loops. They are three types:

i. Break statement in Java

The break statement breaks the flow of the execution from the nearest loop inside which it is present. The execution of the program continues from the next line just when the scope of that loop ends. The syntax of this statement is:

while (num <= 10) {
  if (num == 6) break;
  num++;
}

This prints all the numbers from 0 to 5.

ii. Continue Statement in Java

The continue statement continues the execution from the next iteration of the loop and skips the current execution. It is opposite to the break statement.

while (num <= 10) {
  if (num == 6) continue;
  num++;
}

This prints all the values from 0 to 10 except 6.

iii. Return statement in Java

The return statements are useful in the methods when we need to return a value when the function completes an execution. When the return statement encounters, the remaining function does not execute.

Exception Handling in Java

Exception handling is a very crucial concept in Java that handles the unexpected errors that occur during the execution of the program. The syntax of the exception handling is simple and structured. The syntax is like:

try {
  //Code block in which error can occur
}
catch(Exception e) {
  //Code block when the error occurs
}
finally {
  //Code that executes after the end of the try block. 
  //This block executes even if there is no error.
}

There is also a special keyword called throws which is useful to throw custom exceptions. For Example:

throw new ArithmeticException();

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

Catch: The catch block contains the code that executes when a particular exception occurs. We can write custom messages defining the kind of occurred error for better documentation and the flow of the program.

Finally: The ‘finally’ block executes whether there is an error or not. The ‘finally’ block encloses the code that needs execution irrespective of the errors that occurred during the compilation or execution of the program.

The basic structure of the Java program

There are two basic parts of a Java program which are: Packages and the main() Method.

a. Package in Java

A package is the same thing as a folder or directory on our computer systems. A package contains classes, interfaces, and many more. The classes which are in the same package can access protected and private members of each other. We can define a package using the package keyword in Java.

We can import them in our program by using the import keyword

Example:

import java.util. * ;
//we are importing all the classes of the util package of Java.

b. Main() Method

The main() method specifies the entry point of the compiler in the program. The main() method must always be static.

For Example:

package com.techvidvan.javasyntax;
public class MyClass {
  void learnJava() {
    System.out.println(“Learning Java from TechVidvan”);
  }
  public static void main(String[] args) {
    System.out.println(“Inside the main() method”);
    MyClass obj = new MyClass();
    obj.learnJava();
  }
}

Output:

Inside the main() method
Learning Java from TechVidvan

Compiling and Executing a Java Program

Once we write and save our Java program, we need to compile and execute using the following steps:

  • Open a command-line window on the saved location by <Shift+right-click>.If you have any other Operating System such as Ubuntu or Linux, then open the terminal and navigate to the directory in which the saved java program is present.
  • To compile: Type javac <filename.java>
  • To run/execute: Type java <filename> (file name should be the one in which there is a main() method)

Example:

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

Operators in Java

The operators are the ones that perform operations on two or more entities. They are of multiple types as:

a. Arithmetic Operator

Arithmetic Operators are solely for performing arithmetic operations. They include addition (+), subtraction(-), multiplication (*), division (/), modulus(%) and many more.

b. Relational Operator

Relational operators 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 (num1 > num2) {
  System.out.println(“Number 1 is greater”);
}

c. Bitwise Operator

Bitwise operators are useful to perform bitwise operations on an entity. They are AND(&), bitwise OR(|), bitwise XOR(^), bitwise complement (~), bitwise left shift(<<), bitwise right shift(>>), and so on.

Example:

(num1 & num2) will give 12 if num1 = 0000 and num2 = 1100

d. Logical Operator

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

e. Assignment Operator

Assignment operators are useful to assign values to variables. They include equal(=), add AND(+=), subtract AND operator(-=), multiply AND (*=), and so on.

Example:

int y += 6; //equivalent to int y = y+6;

Objects in Java

An object in Java is the most basic unit of Object-Oriented programming. An object is a real-world entity that has property, state, and behavior. We can create objects from classes in Java. We can create the object of the class using the new operator. The syntax to create an object of a class is:

ClassName objectName  = new ClassName();

Example:

MyClass obj = new MyClass();
Vehicle car = new Vehicle();

Class in Java

A class in Java is a collection of similar objects having the same behavior. It has properties and methods. We declare a class in Java using the class keyword. Classes generally start with the first letter capital. Generally, we use CamelCase for writing class names. We can also use access modifiers for the class before the class keyword. The syntax to define a class is:

acessModifier class ClassName {
  instance variables;
  method1() {}
  method2() {}
} //end of class

Example:

public class TechVidvan {
  int number;
  void learn() {
    System.out.println(“Learning Java from TechVidvan”);
  }
}

Methods in Java

Methods or functions are the specific entities in Java that perform some functionality and that returns a value only when we call them. The syntax of defining methods is:

returnType methodName() {
  action1;
  action2;
  return statement
  if any
}

For Example:

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

or,

int sum() {
  int sum = num1 + num2;
  return sum;
}

Interfaces in Java

Interfaces in Java are the collection of abstract methods. We will learn more about Interfaces in our upcoming articles. We can define an interface using the interface keyword as follows:

interface interfaceName {
  //abstract methods;
  //abstract methods are the method without implementation
}

Example:

interface TechVidvan {
  abstract void teach();
  abstract void learn();
}

Access modifiers in Java

Access modifiers are useful for limiting the access of the entities they are defined with. We can use access modifiers with classes, variables, interfaces, constructors. Java uses the following access specifiers:

a. Public: The public specifier is accessible to every other class or interface. There is no restriction of access when using a public access specifier.
b. Private: The private specifier restricts all entities to be accessible only inside the class they are declared.
c. Protected: The protected specifier allows the members of the class to be accessible to classes within the same package or the derived classes of different packages.
d. Default: If there is no access modifier then the default access modifier is used.

Arrays in Java

Arrays in Java are the consecutive data items of the same datatype. The syntax of declaring arrays is:

dataType arrayName = new dataType[size of the array];

For example:

int myArray[] = new int[10];

or,

dataType arrayName[size] = { array elements separated by commas};

For example:

int myArray[3] = {1,2,3,4,5};

Variables in Java

A variable is a named storage location, that holds a data value of a particular data type. We will understand the concept of variables in the following articles, however the syntax of variables is simple and easy to learn.

Java Syntax for declaring variables:

dataType variableName;

Example:

int number;

Java syntax for initializing variables:

variableName=value;

Example:

number = 8;
int number = 8;

(Declaring and initializing at the same time)

Datatype in Java

The datatypes are the means to identify the type of data and associated operations of handling it. Data types come before variables to define the type of data they are storing. There are two types of data types in Java- Primitive data types and Reference data types. Primitive data types include int, short, byte, float, double, long, char, boolean. Reference data types include classes, arrays, String, etc.

Syntax of data type:

datatype  variableName;

Example:

int length = 15;

Conclusion

Syntax is most important for a programming language as it is the language which the compiler understands. If the syntax is incorrect then even the fastest algorithms can not compile the program. So we must strengthen the concepts of Java syntax before proceeding further into the concepts of Java. We must learn them to use correctly to avoid compilation errors. We have covered the syntax of each and every small concept in Java.

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.