function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
RstrunkRstrunk 

If else in APEX

 

Does whitespace matter between the ELSE and IF keywords?  For example are the two code snips below the same logic wise?

 

if(condition){

}
else if(condition){

}
else{

}

 

if(condition){

}
else 
    if(condition){

}
else{

}

 

kiran2000kiran2000

no

souvik9086souvik9086

Output will be same. 

 

If this post is helpful please throw Kudos.If this post solves your problem kindly mark it as solution.

Thanks

Yoganand GadekarYoganand Gadekar

Both are same....

sfdcfoxsfdcfox

While this has already been answered a few times, perhaps it would be useful to know why. Apex Code, like Java (and C++, C#, etc.) use curly braces to delineate "blocks", such as functions, do-while loops, etc, which also affect "scope" (what data and methods are available in a given line of code), and uses semi-colons to delineate "statements", which are single units of work. Outside of strings, white space may be arbitrarily placed. You could also write your code like this:

 

if
    (
        condition1
    )
    {
        // condition1 true here
    }
    else
    if
        (
            condition2
        )
        {
            // condition2 true here
        }
        else
        {
           // neither condition1 or condition2 true here
        }

or even like this (assuming single-statement blocks):

 

if(cond1)doA();else if(cond2)doB();else doC();