What does the semicolon actually do?

LT_ichinen

I was looking at a typical for loop:

class ForDemo {
    public static void main(String[] args){
         for(int i=1; i<11; i++){
              System.out.println("Count is: " + i);
         }
    }
}

I am happy with the semicolons after int i=1: it is a statement which declares the new variable i. If i++ is also a statement, why doesn't it have a semicolon after?

Another example. I opened the Jshell and put the following:

jshell> int a=1;
a ==> 1
jshell> a++
$2 ==> 1
jshell> a
a ==> 2
jshell> int b=1;
b ==> 1
jshell> b++;
$5 ==> 1
jshell> b
b ==> 2

In other words the command ++ works, independently from whether there is a semicolon or not. I expected not to work without it.

Last example (adapted from a presentation about the difference between = and ==):

jshell> boolean x = false;
x ==> false
jshell> if (x = true) System.out.println("Sorry! This is wrong ...");
Sorry! This is wrong ...
jshell> boolean x = false;
x ==> false
jshell> if (x = true;) System.out.println("Sorry! This is wrong ...");
|  Error:
|  ')' expected
|  if (x = true;) System.out.println("Sorry! This is wrong ...");
|              ^

I get the point about the difference between = and ==. My question is why it works in the first half (if (x = true) without ;), and not with a ; (if (x = true;)).

Apologies for the several examples, but I think the question is relatively straightforward: if there are instances where an expression (without ;) works as a command statement (with ;), what is the function of semicolons?

delvh

The semiccolon is a separator of stack calls. The inside of if() wants a boolean, not a stack call. Only inside the {} are statements expected.

The inside of for() expects three stack calls: One defining the loop variable, one defining the breaking clause and one defining what happens after each loop.

Example: The construct for(;;); is a valid java construct. But you should never use it as the only thing it would do is loop over nothing forever: You don't define a variable, a breaking condition or something that gets executed after each call. During the loop you also just do nothing.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related