Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Final For If Conditional

Tags:

java

I know how to use final to set an int, like this:

final int junk = whatever ? 1 : 2;

But, how to do this in more complicated if statements?

like image 662
Irving Avatar asked Feb 17 '23 00:02

Irving


1 Answers

How to use Java "final" To Set a Value in an if() Conditional

Example:

final int junk;
if(whatever) {
    junk = 1;
} else {
    junk = 2;
}

You can nest final value setting to any depth, and Java will flag an error if you make any duplicates or skip any paths.

Example:

final int junk;
if(whatever) {
    junk = 1;
} else {
    if(however) {
        junk = 2;
    } else {
        junk = 3;
    }
}

I use final for local variable closure whenever possible to insure that I don't accidentally reuse variables unexpectedly.

like image 130
David Manpearl Avatar answered Feb 26 '23 21:02

David Manpearl