Q:

Java: Initialize condition in If construct (performance)

I am looking for a possibility to initiate a variable in the if condition, so it is only valid in the scope of the condition.
Example: I want to transform this:
String tmp;
if ((tmp = functionWithALotOfProcessingTime()) != null)
{
    // tmp is valid in this scope
    // do something with tmp
}
// tmp is valid here too

Into something similar like this:
if ((String tmp = functionWithALotOfProcessingTime()) != null)
{
    // tmp is *ONLY* in this scope valid
    // do something with tmp
}

A:

I can think of two ways to do it:

You need an extra scope, {...} or try{...}catch... and declare the tmp in that scope.
wrap your if logic in a private method, and declare the tmp in the method, so that in your main logic, you cannot access tmp

A:

Try something like this:
{
    /*
     * Scope is restricted to the block with '{}' braces 
     */
    String tmp; 
    if ((tmp = functionWithALotOfProcessingTime()) != null) {
        // tmp is valid in this scope
        // do something with tmp
    }
}

tmp = "out of scope"; // Compiler Error - Out of scope (Undefined)

