The expression statement in java is a one kind of statement that usually created to produce some new value. Expressions are built using values, variables, operators and method calls. Although, Sometimes an expression assigns a value to a variable .
Types of Expressions
While an expression frequently produces a result, it doesn’t always. There are three types of expressions in Java:
- Expression that produce a value
(4 + 5);
- Expression that assign a variable
result=(4 + 5);
- Expression that have no result but might have a “side effect” because an expression can include a wide range of elements such as method invocations or increment operators that modify the state (i.e., memory) of a program. A method invocation that declared as void.
i++; k--; ++i; --k; exception.printStackTrace();
Expression that produce a value
Expressions that produce value use wide range of operators to generate result.
- Arithmatic Operators : +,-,*,/,%
- Conditional Operators :||,&&, ? :
- Comparison Operators : ==, !=, > , >=, <, <=,
These expressions produce a value:
4*5 5/3 5% 2 pi + (20 * 3)
Expressions that assign a value
While some expressions produce no result, they can have a side effect which occurs when an expression changes the value of any of its operands or methods with return type as void.
//Declaration statements with assignment; int secondsInDays=0; int daysInWeek=7; int hoursInDay=24; int minutesInHour=60; int secondsInMinute=60; boolean calculateWeek=true; //Varible assignment expression int secondsInDays=secondsInMinute * minutesInHour * hoursInDay; System.out.println("The number of seconds in a day is: " + secondsInDay);
Here in the first six lines of the code, are expression with assignment operator where assign value on the right side variable of the left. After that where calculating value for variable secondsInDays is an expression statement which is built up through use of more than one operator.
Expressions with no Result
try{ int k=0; int x=0; //expressions not return any value or assign variable //but side effects are more x++; ++x; //expression statement with operator k=(x/k); } catch(Exception ex) { //expression not returning any value //because method return type is void ex.printStackTrace(); }
In above example using prefix and postfix increment that changing it’s own value but not returning or assigning any variable. Same as in catch block method printStackTrace() return type is void but it’s print exception stack trace in console logs.
References
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/opsummary.html
https://www.thoughtco.com/expression-2034097
You must log in to post a comment.