In this article we will talk about expressions, statements and code blocks in JAVA.
Table of Contents
Expressions are building blocks off all JAVA programs which are made up of variables, operators, and method invocations. The expression are created according to the syntax and evaluates to a single value. For example, if we want to covert miles to kilometre we first need to know a mile is equal to 1.609344km. Now lets suppose we want to convert 50 miles to kilometres.
double kilometres = (50 * 1.609344);
In the above statement kilometres = (50 * 1.609344)
is an expression and data type double is not part of an expression. Typically except data type and ; forms an expression.
Expression Examples In JAVA:
int score = 50; //In bold is an expression
If you are using literal value, then except data type and ; is a part of expression. So score = 50
is an expression.
Another example of expression:
if(score == 50){ System.out.println( “This is also an expression” ); }
If you are using control flow if statements, then component inside bracket is a part of expression. So score == 50
is an expression. Remember here braces ( and ) is not part of expression.
Also for methods component inside bracket is a part of expression. So “This is also an expression”
is an expression. Remember here also braces ( and ) is not part of expression.
Statement forms a complete unit of execution. All statements are terminated with semicolon (;). For example:
int myRoll = 3;
The above complete line is a statement. In JAVA following types form expressions of assignment: any use of ++ or – – , method invocations and object creation expressions can be made into statement by terminating with semicolon(;);
Lets see each type expression made into statement:
Assignment expression made into expression:
int myRoll = 3;
Any use of ++ or — made into expression:
myRoll++; myRoll--;
Method invocations:
System.out.println(myRoll); Object creation expressions made into statements Bike myBike = new Bike();
Important Note: Declaration statements and control flow statements are other two types of statements in JAVA.
A blocks in JAVA is a group of zero or more statements enclosed between braces. The block begins with opening braces ({) and ends with closing braces (}). Even though it is a statement but doesn’t end with semicolon(;). For example:
{ int myRoll = 3; String myName = “Abhishek”; }
It is mostly used with control flow statement. For example:
If (x == 50){ System.out.println(“Example of control flow statement”); x--; }
In the above example all code inside braces {} is part of blocks.
Premium Project Source Code:
Leave a Reply