Reputation: 9765
public static void main(String[] args) {
File dir = new File("dir");
dir.mkdir();
File file = new File(dir,"file.txt");;;;;
;
;
;
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
;
;
;
;
}
}
Compiler shows no error for the extra semi-colons. And code runs as if nothing wrong happened. I want to know what happens behind scene ? Does including such semi-colon consume more of stack memory , and thus require more processor cycles to run ?
Upvotes: 1
Views: 395
Reputation: 421100
I want to know what happens behind scene ?
An extra ;
turns up as a skip statement in the AST.
They are typically used instead of empty bodies in for instance while loops:
while (expression)
;
Does including such semi-colon consume more of stack memory , and thus require more processor cycles to run ?
No, it does not show up in the byte code. (Which is why they typically can't be used as break statements when debugging.)
Some trivia:
You may actually have skip statements outside of classes:
class MyClass {
// ...
}
;;;;;
These are ignored, and allowed simply to not annoy people coming from C++ and are used to put ;
after a class:
class MyClass {
// ...
};
Upvotes: 10
Reputation: 68975
They are removed by compiler just like comments. You can see the bytecode -
public class Test
{
public static void main(String args[])
{
System.out.println("Hi there!");
;
//this is a comment
System.out.println("Bye there!");
}
}
and bytecode is
Compiled from "test.java"
public class Test extends java.lang.Object{
public Test();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream;
3: ldc #3; //String Hi there!
5: invokevirtual #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
8: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream;
11: ldc #5; //String Bye there!
13: invokevirtual #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
16: return
}
As it does not every generate a byte code no extra memory is taken by it.
Upvotes: 1