Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Java automatically save an 'evaluate' statement in a predefined Java variable?

Say I perform a simple add/concatenation statement:

variable + newInput

Without setting the calculated value to a new variable, as in:

variable = variable + newInput

or

variable += newInput

Does Java have some sort of specifier to be able to use the computed sum or concatenated string?

Apparently in Python it is automatically saved in the implicit global variable _ -which is implementable like

Print(_)

Is there anything like this in Java?

like image 677
Jason V Avatar asked Jun 06 '17 13:06

Jason V


Video Answer


2 Answers

No. It does not have anything like this. You have to assign the computed value to a variable, otherwise it will be lost and consequently collected by the garbage collector.

The best option is to use a special operator so not to use an extra variable but assign the result to an old one. This is a Shorthand operator.

Variable += NewInput
like image 190
Vasiliy Vlasov Avatar answered Oct 12 '22 23:10

Vasiliy Vlasov


More than just not saving the result, Java will outright refuse to compile your program if it contains such a line, precisely because the result would be unsaved and unusable if it was allowed:

public class Main
{
    public static void main(String[] args)
    {
        1+2;
    }
}

Result:

Main.java:5: error: not a statement
        1+2;
         ^
1 error

Java does not allow arbitrary expressions as statements, and addition expressions are not considered valid Java statements.

The expressions that are allowed as statements by themselves are listed in the JLS:

ExpressionStatement:
  StatementExpression ;

StatementExpression:
  Assignment 
  PreIncrementExpression 
  PreDecrementExpression 
  PostIncrementExpression 
  PostDecrementExpression 
  MethodInvocation 
  ClassInstanceCreationExpression

Assignment, increment, decrement, method calls, and new Whatever(), all things with side effects or potential side effects. Barring possible side effects of an implicit toString() call, + cannot have side effects, so to catch probable errors, Java forbids addition expressions from being statements.

like image 40
user2357112 supports Monica Avatar answered Oct 13 '22 00:10

user2357112 supports Monica