Java Syntax to Learn Java Programming 2


1. Objective

In this Java tutorial, we are going to learn about the basic syntax used in Java language. A syntax for any language is the set of rules by which the language is governed and ruled, written and interpreted. By the end of java syntax tutorial, we will be able to learn Java and write basic Java programs.

Java Syntax - Introduction

Introduction of Java Syntax

2. Introduction of Java Syntax

Java has many features and own set of syntax rules, structure, and programming paradigm. The Java programming paradigm is based on Object-Oriented Programming. The syntax for Java language is derived from C and C++, and that is the reason for Java syntax looks very similar to C codes. So, let us start with some Java basic syntax.

3. Java Basics

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

Basic Java Syntax

Java Syntax – Java Basics

A simple Java program-

Class MyClass
{
public static void main(String[] args )
{      System.out.println( “hello World”);
}
}

a. Identifiers in Java

Identifiers in java language are the names of Java packages, Java classes and objects, interfaces, methods, and variables in Java. They are basically the name of any element. For example, in the program above, String, main, args and println are Java identifiers.

Identifiers in Java are case-sensitive, there are some basic conventions that are to be followed while naming any identifier, they can contain,

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

Java identifiers cannot start with a digit or be the same as a reserved word.

Follow this link to know more about Identifiers in Java

b. Java Keywords

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

In the program above, public, static void and class are java keywords. There are 50 java keyword list:

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 double return type or variable.
float It declares floating return type or variable.
short It declares an short integer return type or variable.
void This data type declares that the method does not have a return type.
int It declares a 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 makes you prematurely exit a loop
continue It makes you prematurely go to the start 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.
else It  executes the other statementif the “if” statement condition is not true.
try It is used for situations where the program may get an exceptional situation.
catch It  is used to handle the exception.
finally It is used to denote that a given block of code is executed regardless of exceptional situations.
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 cannot be sub classed or may not be overridden.
implements It denotes that this class implements this 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 a 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 be 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 threaded 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 be serialized.
volatile It warns that the given variable changes asynchronously to the compiler.

Java 1.2 adds “strictfp” which declares that the method or class should run with exact IEEE 754 semantics. Java 1.4 adds the keyword “assert” to denote assertions while Java 5 adds the keyword “enum” and “assert”.

Follow this link to know more about Java Keyword Part -1

“true” and “false”  are boolean literals. “goto” and “const” are hardly implemented. Let’s revise Java Data types and Java Modifiers

c. Java Literals

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

  • For 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 MyClass
{
public static void main(String[] args )
{  int a = 122;          //decimal form
int b = 5624;       //octal form
int c = 0xFace;   // hexa- decimal form
int d = 0b2222;  // binary form
System.out.println( a);
System.out.println( b);
System.out.println( c);
System.out.println( d);
}
}

Let’s read more about Literals in Java Programming Language

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

int a = 100.888;

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

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

NameDescriptionExample
Single quoteIn this type, the literals can be specified 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 be specified 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 lineffed character.

string I = “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;

d. Code Blocks in Java

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

e. Java Comments

There are 3 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.

Let’s Explore Java Comments in detail 

4. Structure of Java Program

Java Program consists of below 2 parts:

a. Main Method in Java

The main method is the entry point of any program. There can be more than one class in a program with the main method. Java main method should always return no value, that is it should return void. It should always be static.

public static void main(String[] args)

b. Java Packages

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

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

5. Java Operators

There are basically 5 types of Java operators and some miscellaneous type. They are-

Java operators in Java Syntax

Java Syntax- Java Operators

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

Let’s Discuss Pair Class in Java With Techniques

b. 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 equal 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.

c. Bitwise Operators in Java

> Bitwise right shift operator, it shifts the value of 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.
IBitwise 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.
>>

d. Logical Operators in Java

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

Do you know How to Establish Java Socket Connection

e. 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 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 left operator to right and assigns the remainder to left operator.
<<=Left shift AND operator.
>>=Right shift AND operator.
^=Bitwise Exclusive OR operator.
I=Bitwise Inclusive operator.
&=Bitwise assignment AND operator.

f. 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 : " +&nbsp; b );
b = (a == 10) ? 20: 30;
System.out.println( "Value of b is : " + b );
}
}

Output-

Value of b is : 30

Value of b is : 20

6. Control Statements in Java

a. Java Conditional statements in Java

 Java Control Statements in Java Syntax

Java Syntax – Java Control Statements

i. If statement in Java

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

Example-

if (i == 3) action();

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

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 the condition accordingly.

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;
}

b. Iteration statements in Java

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

i. While loop in Java

The condition is checked after every iteration.

Example-

while (i &lt; 10)
{
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 &lt; 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();
}

Read about Island of Isolation in Java with Example

c. 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 &lt; 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;
}

d. 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 object is null
doSomethingWithObject(obj);
}

7. Conclusion

In this Java Syntax tutorial, we learned the basic syntax used in Java programming language, the various java operators, structure of java program and various control statements in java. This will help us write and understand the Java code better in the further tutorials.

Read Also – Is Java An Object-Oriented Language or Not?

For reference


2 thoughts on “Java Syntax to Learn Java Programming

  • Gowsalya

    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 Post author

      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

Comments are closed.