Java what is the double underscore notation for? - java

I was browsing the web and found this example. Within the public static void main method is this line syntax which I have never seen before __main:
As in:
public class Klass {
public static void main(String[] args) {
// code goes here...
__main:
// and mode code here...
}
}
I tried punching this into eclipse and got a little yellow underline with a tool-tip which said "The label __main is never explicitly referenced".
I can't find anything online and I'm really curious! I've been programming in Java for years and I've never seen this syntax before. What does it do, why would you use it, where can I learn more?

That's a label. You can use it with the break and continue statements. It's not necessary, to use the double underscore.
To be more precise: it is (the first) part of a Labeled Statement (JLS 14.7):
Identifier : Statement

Double underscores in Java have not semantic meaning (the same way that single underscores don't have any semantic meaning).
The only meaning they could have would depend on some naming convention that defines what they are used for.
It looks like the code you look at uses double underscores for labels. Since labels are not frequently used in Java, I wouldn't worry to much about it.

A goto statement in C and its counterparts are accompanied by a Label argument. In a defined method, a goto label; statement will fire the routine proceeding the label. Below is an example demonstrated by Greg Rogers in this Post.
void foo()
{
if (!doA())
goto exit;
if (!doB())
goto cleanupA;
if (!doC())
goto cleanupB;
// everything succeed
return;
cleanupB:
undoB();
cleanupA:
undoA();
exit:
return;
}
A goto can be a very effective tool in Java, but Java does not explicitly support the goto keyword even though the keyword has been reserved by the language. Using a break statement will enable the command jump out of the label to proceed to the statement after the label.
Example:
public class Klass {
public static void main(String[] args) {
// code goes here...
__main:
{
if(args.length==0)
{
break __main;
}
}
//code after label
}
}
The package com.sun.org.apache.bcel.internal.generic.GOTO, I have not used it personally but I think it can aid to achieve the same code structure as demonstrated by Greg Rogers like this:
void foo()
{
if (!doA())
GOTO exit;
if (!doB())
GOTO cleanupA;
if (!doC())
GOTO cleanupB;
// everything succeed
return;
cleanupB:
undoB();
cleanupA:
undoA();
exit:
return;
}
void undoB(){}
void undoA(){}
boolean doC(){return false;}
boolean doA(){return false;}
boolean doB(){return false;}

The double underscores are irrelevant. You are really asking about Labels. Here is some info . Basically they are used for controling breaks. Also a fun trivia question in interviews: Does the following code compile?
public void doSomething(){
http://www.stackoverflow.com
}
Why yes it does and now you know why:D

Java has labels (but no goto). The double underscore has no meaning but it is a legal Java identifier.
From the JLS:
14.7 Labeled Statements Statements may have label prefixes.
LabeledStatement:
Identifier : Statement
LabeledStatementNoShortIf:
Identifier : StatementNoShortIf
The Identifier is declared to be the label of the immediately
contained Statement.
Unlike C and C++, the Java programming language has no goto statement;
identifier statement labels are used with break (§14.14) or continue
(§14.15) statements appearing anywhere within the labeled statement.
The scope of a label declared by a labeled statement is the statement
immediately enclosed by the labeled statement.

It's just a label. you could write bla:, for the same effect.
Labels are generally used with goto statements, but as far as I know, goto is forbidden in java (and greatly discouraged in any other high-level language).
This can also, however, be used inside loops with continue and break, e.g. continue someLabel;, if you want the continue or the break to refer to an outer loop rather than the immediate one you are in right now.

double underscore and labels tend to be used more in C. Perhaps the developer have been writing C recently.
BTW: Labels are rarely used for loops but an even rarer use is to jump out of scope.
scope: {
// some code
if (flag)
break scope; // no loop
// some more code
}
Because labels are rare, they can more confusing than useful. ;)

Nobody seems to have answered EXACTLY what you actually asked (but the "goto" answers are probably what you were really looking for) and they are right about it just being an identifier, but not why they were used in this case.
The double-underscore is typically used within the system to prevent possible collisions with other identifiers... usually it is used in cases where the scope is available to the user. In this case without the underscores you might be prevented from making a "main" variable at some point or another, or perhaps some system-class would be prevented from using the word main.
In this case I'm guessing that if the variable had been named "main" it would conflict with the "public static void main" being defined.
I guess in summary the double-underscore is a form of manual scoping..

Related

Is there a Java built-in construct like vb.net's Do Until Loop?

I am trying to make my code more readable and so it would be useful to use the following (or equivalent)
do
{
...
}
until(Display.isCloseRequested())
rather than
do
{
...
}
while(!Display.isCloseRequested())
but I can't seem to find something like this.
Yes, I don't like the 'java convention' of having the opening brace on the same line as the statement and the final statement on the same line as the closing brace. I prefer that code style.
No, Java doesn't have a do-until loop construct or similar. Just do-while with the opposite test as you indicated in the question, for, and while. All use "positive" tests (loop continues while test is true).
More in the JLS:
Control flow statements
for
while and do-while
If you really want the until syntax, you can cheat a little and create an until() method that negates a boolean expression.
For example...
do {
// something
} while (
until(Display.isCloseRequested())
);
...
public static boolean until(boolean condition) {
return !condition;
}
You can statically import the until method whenever you want to use it.
Although this introduces some issues:
It doesn't look very pretty.
It is unconventional and can cause confusion.

Why does this for loop compile? [duplicate]

Given the following code sample:
public class WeirdStuff {
public static int doSomething() {
while(true);
}
public static void main(String[] args) {
doSomething();
}
}
This is a valid Java program, although the method doSomething() should return an int but never does. If you run it, it will end in an infinite loop. If you put the argument of the while loop in a separate variable (e.g. boolean bool = true) the compiler will tell you to return an int in this method.
So my question is: is this somewhere in the Java specification and are there situation where this behavior might be useful?
I'll just quote the Java Language Specification, as it's rather clear on this:
This section is devoted to a precise explanation of the word "reachable." The idea is that there must be some possible execution path from the beginning of the constructor, method, instance initializer or static initializer that contains the statement to the statement itself. The analysis takes into account the structure of statements. Except for the special treatment of while, do, and for statements whose condition expression has the constant value true, the values of expressions are not taken into account in the flow analysis.
...
A while statement can complete normally iff at least one of the following is true:
The while statement is reachable and the condition expression is not a constant expression with value true.
There is a reachable break statement that exits the while statement.
...
Every other statement S in a nonempty block that is not a switch block is reachable iff the statement preceding S can complete normally.
And then apply the above definitions to this:
If a method is declared to have a return type, then every return statement (§14.17) in its body must have an Expression. A compile-time error occurs if the body of the method can complete normally (§14.1).
In other words, a method with a return type must return only by using a return statement that provides a value return; it is not allowed to "drop off the end of its body."
Note that it is possible for a method to have a declared return type and yet contain no return statements. Here is one example:
class DizzyDean {
int pitch() { throw new RuntimeException("90 mph?!"); }
}
Java specification defines a concept called Unreachable statements. You are not allowed to have an unreachable statement in your code (it's a compile time error). A while(true); statement makes the following statements unreachable by definition. You are not even allowed to have a return statement after the while(true); statement in Java. Note that while Halting problem is undecidable in generic case, the definition of Unreachable Statement is more strict than just halting. It's deciding very specific cases where a program definitely does not halt. The compiler is theoretically not able to detect all infinite loops and unreachable statements but it has to detect specific cases defined in the spec.
If you are asking if infinite loops can be useful, the answer is yes. There are plenty of situations where you want something running forever, though the loop will usually be terminated at some point.
As to your question: "Can java recognized when a loop will be infinite?" The answer is that it is impossible for a computer to have an algorithm to determine if a program will run forever or not. Read about: Halting Problem
Reading a bit more, your question is also asking why the doSomething() function does not complain that it is not returning an int.
Interestingly the following source does NOT compile.
public class test {
public static int doSomething() {
//while(true);
boolean test=true;
while(test){
}
}
public static void main(String[] args) {
doSomething();
}
}
This indicates to me that, as the wiki page on the halting problem suggests, it is impossible for there to be an algorithm to determine if every problem will terminate, but this does not mean someone hasn't added the simple case:
while(true);
to the java spec. My example above is a little more complicated, so Java can't have it remembered as an infinite loop. Truely, this is a weird edge case, but it's there just to make things compile. Maybe someone will try other combinations.
EDIT: not an issue with unreachable code.
import java.util.*;
public class test {
public static int doSomething() {
//while(true);
while(true){
System.out.println("Hello");
}
}
public static void main(String[] args) {
doSomething();
}
}
The above works, so the while(true); isn't being ignored by the compiler as unreachable, otherwise it would throw a compile time error!
Yes, you can see these 'infinite' loops in some threads, for example server threads that listen on a certain port for incoming messages.
So my question is: is this somewhere in the Java specification
The program is legal Java according to the specification. The JLS (and Java compiler) recognize that the method cannot return, and therefore no return statement is required. Indeed, if you added a return statement after the loop, the Java compiler would give you a compilation error because the return statement would be unreachable code.
and are there situation where this behavior might be useful?
I don't think so, except possibly in obscure unit tests.
I occasionally write methods that will never return (normally), but putting the current thread into an uninterruptible infinite busy-loop rarely makes any sense.
After rereading the question....
Java understands while(true); can never actually complete, it does not trace the following code completely.
boolean moo = true;
while (moo);
Is this useful? Doubtful.
You might be implementing a general interface such that, even though the method may exit with a meaningful return value, your particular implementation is a useful infinite loop (for example, a network server) which never has a situation where it should exit, i.e. trigger whatever action returning a value means.
Also, regarding code like boolean x = true; while (x);, this will compile given a final modifier on x. I don't know offhand but I would imagine this is Java's choice of reasonable straightforward constant expression analysis (which needs to be defined straightforwardly since, due to this rejection of programs dependent on it, it is part of the language definition).
Some notes about unreachable statements:
In java2 specs the description of 'unreachable statement' could be found. Especially interesting the following sentence:
Except for the special treatment of while, do, and for statements whose condition expression has the constant value true, the values of expressions are not taken into account in the flow analysis.
So, it is not obviously possible to exit from while (true); infinite loop. However, there were two more options: change cached values or hack directly into class file or JVM operating memory space.

Why can't you create a 1 statement function without curly braces?

So, in most programming language, if you are using a loop or an if, you can do it without curly braces if there is only a single statement in it, example:
if (true)
//Single statement;
for (int i = 0; i < 10; i++)
//Single Statement
while (true)
//Single statement
However, it doesn't work for functions, example:
void myFunction()
//Single Statement
So, my question, why doesn't it work for functions?
C++ needs it to disambiguate some constructs:
void Foo::bar() const int i = 5;
Now does the const belong to bar or i ?
Because language grammar forbids you to do that.
The Java grammar defines a method as following:
MethodDeclaration:
MethodHeader MethodBody
Methodbody as:
MethodBody:
Block
;
Which means either a Block (see below) or a single semicolon
Block:
{ BlockStatementsopt }
And a block as one or more statements within curly brackets.
However an if is defined as:
IfThenStatement:
if ( Expression ) Statement
Where no block is needed after the closing ) and therefore a single line is ok.
Why they chose to define it that way? One can only guess.
Grammar can be found here: http://docs.oracle.com/javase/specs/jls/se7/html/index.html
This is not a rule, in some languages you can (Python? Yes, I know that's really contrived example :)) ), in other you cannot.
You could very well extend your question for example to class and namespaces, for example, why not:
namespace Example
class Foo : public Bar
public: std::string myMethod()
return "Oh noes!";
right? At each level, that's just a single item, so why not skip the braces everywhere?
The answer is at the same time simple and complex.
In simple terms, it's about readability. Remember that you can layout your code as you like, since whitespaces are usually discarded by the compiler:
namespace Example class Foo : public Bar public: std::string myMethod() return "Oh noes!";
Well, that starts looking unreadable. Notice that if you add the braces back
namespace Example { class Foo : public Bar { public: std::string myMethod() {return "Oh noes!";}}}
then it, strangely, becomes somewhat comprehensible.
The actual problem is not readability (who cares anyways? I'm joking of course) but in the latter: comprehension. Not only you must be able to comprehend the code - the compiler must. And for the compiler there is no such thing as "oh, this looks like function". The compiler must be absolutely sure that it is a function. Also, it must be completely sure about where it starts, where it ends, and so on. And it must do that without looking at whitespaces too much, since C-family languages allow you to do add them in any quantities you like.
So, let's look again at the packed-up no-braces example
namespace Example class Foo : public Bar public : std::string myMethod() return "Oh noes!";
^ ^ ^^
I've marked some problematic symbols. Assuming you could define a grammar that handles it, please note how the meaning of ":" character changes. At one time it's denoting that you're specifying inheritance, at other point it's specifying access modifier to a method, at third place it's just namespace qualifier. Ok, the third one could be discarded if you were smart and noticed it's actually '::' symbol, not just a ':' character.
Also, meaning of keywords can change:
namespace Example class Foo : public Bar public : std::string myMethod() return "Oh noes!";
^^^^^^ ^^^^^^
At first place, it defines access modifier for inherited base class, at second place it defined access modifier for a method. What's more, at first place it's not meant to be followed by a ":" and at second place it's required to be followed by it!
So many rules, exceptions and corner cases, and we covered just 2 simple things: public and ':'. Now, imagine you are to specify the grammar for the whole language. You describe everything in the way you'd like to have. But, when you gather all the rules together, they at some point may start overlap and collide with each other. After adding Nth rule, it may happen that your 'compiler' would be unable to tell whether the 'public' actually marks inheritance, or starts a method:
namespace Example class Foo : public ::Bar public : std::string myMethod() return "Oh noes!";
^^^^^^^^ ^^^^^^^^
Note that I only changed the Bar to ::Bar. I only added a namespace qualifier, and now our rule of "public is followed by a colon" is trashed. As I now added a rule that "base class names may have namespace qualifiers", I also must add more rules to cover yet another corner cases - to remove the ambiguity of the meaning of "public" and ":" in this place.
To cut the long talk: the more rules, the more problem you have. The "compiler" grows, gets slower, eats more resources to work. This results in inability to handle large code files, or in frustration when the user must wait oh-so-long for that module to compile.
But what's worse for the user is, the more complex or ambiguous, the worse error messages are. Noone wants to use a compiler that is unable to parse some code and also unable to tell you what's wrong with it.
Remember in C++ what happens when you forget some ';' in a .h file? Or when you forget some }? Compiler reports you an error 30 or 300 lines farther. This is because the ';' and '{}' can be ommitted in many places, and for that 30 or 300 lines, the compiler simply does not yet know that's something wrong! Were the braces required everywhere, the point of error could be pinpointed faster.
The other way: making them optional at namespace, class, or function level, would remove the basic block-starts/block-ends markers and, at least:
could make the grammar ambiguous (and hence force to add more rules)
could hurt detecting (and reporting!) errors
any part of which noone really wants.
The C++ grammar is so complex, that it actually might be not possible to omit the braces at those places at all. For Java or plain C, I think it could be possible to make a grammar/compiler that would not require them, but would it would still hurt error reporting much. Especially in C which allows to use #include and macros. In early Java, the impact might be lesser, as the grammar is relatively simple, compared i.e. to current C++..
Probably the simplest, fastest, easiest to implement, and probably easiest to learn grammar would .. require braces (or any other delimiters) just about everywhere. Check LISP for example. But then, large part of your work would consist of constantly writing the same required markers, which many language-users simply does not like (i.e. I get nauseous when I need to work on some old code in VisualBasic with its "if then end if" yuck)
Now, if you look at brace-less language like Python - how does they solve it? They denote the block-starts/block-ends by .. intendation. In this language you must indent your code properly. If you don't indent it correctly, it will not compile at all, or it the loops/functions/etc will silently get their code messed up, because the compiler will not know what part does belong to which scope. No free lunch here again.
Basically a method(function) is a collection of statements that are grouped together to perform an operation. We group the statements for reusable. That is if you know that a set of instructions will used often in that case we create it as a separate function.
If you can perform the task in a single line of code, then why do you need to write a function?
Because the grammar of the language doesn't allow you to.
Here is the grammar for a function in C taken from the ISO/IEC 9899-1999 specification:
6.9.1 Function definitions
Syntax
1 function-definition:
declaration-specifiers declarator declaration-listopt compound-statement
The compound-statement part is the body of a function, and a compound statement is declared as
compound-statement:
{ block-item-listopt }
i.e. it starts and ends with braces.
An if, while or similar body can have a statement as its body.
(6.8.5) iteration-statement:
while ( expression ) statement
A statement can be one of several constructs.
statement:
labeled-statement
compound-statement
expression-statement
selection-statement
iteration-statement
jump-statement
of which only compound-statement requires the braces.
In c++ you need a compound statement to make a function body - which is actually surrounded with curly barces. It does not mean you need to have curly braces right immediately, following will compile just fine:
int foobar()
try {
return 1;
}
catch (...){return 0;}
You can't precisely say there are no one statement functions in C#. Anonymous methods could be one of them. Without single line statements we could not have Lambda expression in c#. The C# 3.0 wouldn't be exist.
There is no reason to add that extra parsing code in the compiler because the functionality is really useless, how many one line methods have you written that are not accessors or mutators? This has been dealt with in C# via properties but not yet in Java.
So the reason is, it's unlikely to be used considering most developers discourage leaving out optional bracket blocks anyway.

Why does Java allow for labeled breaks on arbitrary statements?

I just learned today that the following Java code is perfectly legal:
myBlock: {
/* ... code ... */
if (doneExecutingThisBlock())
break myBlock;
/* ... more code ... */
}
Note that myBlock isn't a loop - it's just a block of code I've delimited with curly braces.
This seems like a rather strange feature to have. It means that you can use a named break to break out of an if statement or anonymous block, though you can't normally use a break statement in these contexts.
My question is this: is there a good reason for this design decision? That is, why make it so that you can only break out of certain enclosing statements using labeled breaks but not regular breaks? And why allow for this behavior at all? Given how (comparatively) well-designed Java is as a language I would assume there's a reason for this, but I honestly can't think of one.
It is plausible that this was done for simplicity. If originally the labeled break can only break loop statements, then it should be immediately clear to language designer that the restriction isn't necessary, the semantics work the same for all statements. For the economics of the language spec, and simpler implementation of compilers, or just out of the habit towards generality, labeled break is defined for any statement, not just loop statements.
Now we can look back and judge this choice. Does it benefit programmers, by giving them extra expression power? Seems very little, the feature is rarely used. Does it cost programmers in learning and understanding? Seems so, as evidenced by this discussion.
If you could go back time and change it, would you? I can't say I would. We have a fetish for generality.
If in a parallel universe it was limited to loop statements only, there is still a chance, probably much smaller, that someone posts the question on stackoverflow: why couldn't it work on arbitrary statements?
Think of it as a return statement that returns from the block instead of from the entire function. The same reasoning you apply to object to break being scattered anywhere can also be applied to return being allowed anywhere except at the end of a function.
The issue with goto is that it can jump forward, past code. A labeled break cannot do that (it can only go backwards). IIRC C++ has to deal with goto jumping past code (it is been over 17 years since I cared about that though so I am not sure I am remembering that right).
Java was designed to be used by C/C++ programmers, so many things were done to make it familiar to those developers. It is possible to do a reasonable translation from C/C++ to Java (though some things are not trivial).
It is reasonable to think that they put that into the language to give C/C++ developers a safe goto (where you can only go backwards in the code) to make it more comfortable to some programmers converting over.
I have never seen that in use, and I have rarely seen a labeled break at all in 16+ years of Java programming.
You cannot break forward:
public class Test
{
public static void main(final String[] argv)
{
int val = 1;
X:
{
if(argv.length == 0)
{
break X;
}
if(argv.length == 1)
{
break Y; <--- forward break will not compile
}
}
val = 0;
Y:
{
Sysytem.out.println(val); <-- if forward breaks were allowed this would
print out 1 not 0.
}
}
}
Why make it so that you can only break out of certain enclosing statements using labeled breaks but not regular breaks
Consider:
while (true) {
if (condition) {
break;
}
}
If the break did as you suggest, this code would perform unexpectedly. Breaks would become a lot more difficult to use.
And why allow for this behavior at all?
I don't use it, but it is a feature and allows for certain unique control-flow constructs. I'd ask you, why not allow it?
is there a good reason for this design decision?
Yes. Because it works.
In the labelled break case, the fact that you don't need to be inside a loop or switch lets you to express things that are harder to express in other ways. (Admittedly, people rarely do use labelled break this way ... but that's not a fault of the language design.)
In the unlabelled break case, the behavior is to break out of the innermost enclosing loop or switch. If it was to break out of the innermost enclosing statement, then a lot of things would be much harder to express, and many would probably require a labelled block. For example:
while (...) {
/* ... */
if (something) break;
/* ... */
}
If break broke out of the innermost enclosing statement, then it wouldn't break out of the loop.
There is another possible reason / rationale. Remember that Java was a brand new language and a relatively early adopter of exceptions and exception handling.
Consider this:
try {
/* ... code ... */
if (doneExecutingThisBlock())
throw new OuttaHere();
/* ... more code ... */
} catch (OuttaHere e) {
/* do nothing */
}
According to the dogma, that is bad code. You shouldn't use exceptions for "normal" flow control.
(Pragmatically, that it also very inefficient due to the overheads of exception creation and handling. Exceptions performance was improved significantly in Java 8, I think, but that was ~20 years later.)
Now imagine that you are a language designer, and you feel that you have to provide an alternative to the "exceptions as flow control" anti-pattern. The "break to label" construct does exactly that. Compare the above with the example in the question.
In hindsight, this is unnecessary. The above can be done in other ways; i.e. without labelled break. In practice this construct is used so rarely that many (maybe most) programmers don't even know it exists in Java.
The ability to leave a sequence of statements has been implemented in several programming languages before Java. Two examples:
Algol-68 had exit to terminate the execution of the smallest closed-clause (very loosely speaking, a begin ... end sequence).
BLISS had labelled BEGIN … END blocks, with a LEAVE statement to terminate execution.
Implementations with labels (as in Java) are more flexible in that they can exit nested blocks (or compound statements, or whatever you call them in your language of choice); without the label, you're limited to exiting a single "level" only.
Answering the direct question, "why" -- because it's been found to be a useful construct in other, prior, languages.
Adding to Stephen C's answer, if (something) you cannot break out of a nested loop. These situations do happen in numerical algorithms. One simple example here - you cannot break out of the i-loop without the named for. Hope this helps.
public class JBreak {
private int brj;
public JBreak (String arg) {
brj = Integer.parseInt (arg);
}
public void print () {
jbreak:
for (int i = 1 ; i < 3 ; i++) {
for (int j = 0 ; j < 5 ; j++) {
if ((i*j) == brj)
break jbreak;
System.out.println ("i,j: " + i + "," + j);
}}}
public static void main (String[] args) {
new JBreak(args[0]).print();
}}
It's the "structured" equivalent to a goto, useful in certain circumstances.
I quite often use such a label create named sub-blocks in a method to tightly limit scope of variables or to simply label a block of code which is not appropriate to break out into a separate function. That is, I use it to label a block so that the code structure around braces is preserved. Here's an example in C for a JNI call, and I do the same in Java:
JNIEXPORT void JNICALL Java_xxx_SystemCall_jniChangePassword(JNIEnv *jep, jobject thsObj,
jlong handle, jbyteArray rndkey, jbyteArray usrprf, jbyteArray curpwd, jbyteArray newpwd, jint pwdccs, jint tmosec) {
Message rqs,rpy;
thsObj=thsObj;
SetupRequest: {
memset(&rqs,0,sizeof(rqs));
setOpcode(&rqs,"CHGPWD");
if(!setField(mFldAndLen(rqs.rnd ),null ,jep,rndkey,"Random Key")) {
return;
}
if(!setField(mFldAndLen(rqs.dta.chgpwd.user ),&rqs.dta.chgpwd.userLen ,jep,usrprf,"User Profile")) {
return;
}
if(!setField(mFldAndLen(rqs.dta.chgpwd.curPass),&rqs.dta.chgpwd.curPassLen,jep,curpwd,"Cur Password")) {
return;
}
if(!setField(mFldAndLen(rqs.dta.chgpwd.newPass),&rqs.dta.chgpwd.newPassLen,jep,newpwd,"New Password")) {
return;
}
rqs.dta.chgpwd.ccsid=pwdccs;
}
...
The break statement terminates the labeled statement; it does not transfer the flow of control to the label. Control flow is transferred to the statement immediately following the labeled (terminated) statement.
It seems to be useful to exit nested loops. See http://download.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
It's semantically the same as is there a equivalent of Java's labelled break in C# or a workaround

java just curly braces

I was reading a book and there were a few example with programs that has just curly braces
for example
public static void main(String args[]){
//what is the uses of curly braces here.
{
//some code
}
}
It's a code block. The variables declared in there are not visible in the upper block (method body outside of these curlies), i.e. they have a more limited scope.
Be careful, it is NOT ALWAYS an initialisation block as others have suggested. In your case it is a variable scoping mechanism called a Code Block or block.
If it is outside of a method, then it is!
Example
public class MyClass {
{
// this is an initialisation block
}
}
However, if it is inside a method, it is NOT!
In this case (which is the case in your example), it is a code block. Anything initialised inside the curly braces is not visible outside
Example
public static void main(String args[]){
{
String myString = "you can't see me!";
}
System.out.println(myString); // this will not compile because myString is not visible.
}
This idea of how to use curly braces as a coding construct is a debated issue in the Java world . There are several explanations people come up with when they see curly braces by themselves. So Im going to try to answer your question from a practical perspective.
The implied question in your post here is, really - when/why are these used ? Practically speaking, the following cases might result in a lone code block :
1) The programmer wanted additionally scoping to reuse variable names without fear of collisions for clarity (i.e. making several objects of the same type in a unit test or database insertion block).
other possible reasons :
2) Forgotten if/else/for/while loop code that is under development.
3) Remaining artifact of a removed if/else/for/while clause.
4) Autogenerated code uses scoping to simplify the creation of several similar components with identical variable names (i.e. consider a gui generator that needed to make code for 100 radio buttons - rather than incrementing variable names per button, it could use scoping).
5) As a tiny, reusable, pastable logical block with minimal side effects : the programmer felt like a block of code in a method was so obscure, its variables and internal side effects should have minimal visibility to the outside world. That is, the programmer has used a code block as a poor-man's anonymous lambda function (albeit, one without a return value). In this pattern one might do something akin to the below :
//lets say I want to make a primary key for a dogs name in a database.
String dogNameKey=null;
{
long time = System.currentTimeInMilliseconds();
String theName = "spot";
dogName=theName+"_"+time;
}
Clearly, the simple strategy for naming this record (dogNameKey) is not worthy of an external method - its too simple. But at the same time, the "time" variable should have no bearing or accessibility outside the logic for making this name up - i.e. it shouldn't even be relevant to the method which contains this tiny key generating block. So, by using braces, I've scoped it out . If a labmda were possible, than all of this scoping could be wrapped in a single, anonymous function.
Now - I could paste several of these blocks, and the variable names would be identical, so it would be easy to scan them by eye.
*Thus, when you see curly braces by themselves - they usually are pretty important - either they implement a specific custom-scoping, or they are an artifact of an error or potentially of autogenerated code. Scoping can also be used to "start" the refactoring of a method without actually writing a new method, by separating out its independant parts ... although IDEs are much better at this than humans. *
You can logically separate your code by this in some cases, and in fact there's one use case I apply very often: demo data. E.g., you have some demo data generation class that creates demo data entries and inserts into your database. You place each single item in such a block, and can do copy-paste without changing variable names.
It is called Block
A block is a sequence of statements, local class declarations and local variable declaration statements within braces.
Also See:
Documents

Categories

Resources