Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 9 of 9

Thread: BEGINNER! use of {} and ;

  1. #1
    Member
    Join Date
    Dec 2013
    Posts
    51
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Question BEGINNER! use of {} and ;

    OK, just a basic question (I'm expecting to have a bit of a search once I get a bit of info....)

    Sometimes code lines need to be ended with ; and sometimes (like after a for statement) then have a { after them (and the relative code is planted within these curly parentheses.

    Just curious as to what the official kind of line was with this... thanks


  2. #2
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: BEGINNER! use of {} and ;

    Curly brackets are used to signify "code blocks", where the semicolon indicates the end of a line of code.

    In a for loop, you determine which "block-of-code" should be looped by surrounding it with curly brackets. I don't know the exact technical phrasing for why there isn't a semicolon at the end of loop conditions, but the best way I can put it is by thinking of it as: a loop condition isn't really the end of a line of code, since it is immediately followed by the block which should be looped.

    Interestingly enough, if you do put a semicolon at the end of a for loop, you will get a loop which does nothing but iterate the determined number of times. This is because curly brackets are not required for for loops if you intend to only loop one line of code. And since the semicolon indicates a single line of code, the following code examples would all do the same thing (a loop which does nothing but iterates the determined number of times):
    for(int i=0;i<10;i++);
    for(int i=0;i<10;i++) {
         ;
    }
    for(int i=0;i<10;i++)
         ;

    EDIT: made a small mistake, which I fixed.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  3. #3
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: BEGINNER! use of {} and ;

    curly braces in Java are used to denote blocks. Semi-colons are used to denote the end of a single statement. A for loop has syntax like this:

    for(initialize; condition; increment)
        statement

    If you only want to execute a single statement, you could get away without using the curly braces.

    // print out numbers 1 to 10
    for(int i = 1; i <= 10; ++i)
        System.out.println(i);

    However, Java is very strict about what statements will be executed by the for loop. It is exactly the first statement block (either a single statement, or group of statements surrounded by curly braces) and only the first statement block which is executed. Tabbing makes no difference.

    Common issues encountered by programmers:

    int value = 0;
    // the tabbing suggests that at each iteration value should be printed out, but this is not what happens!
    for(int i = 1; i <= 10; ++i)
        value += i; // this gets run 10 times
        System.out.println(value); // this gets run exactly once after the loop

    int value = 0;
    // An even more subtle typo: the for loop on each iteration will execute the empty statement, not the block we wanted!
    for(int i = 1; i <= 10; ++i);
    {
        // this is executed after the loop exactly once
        value += value;
        System.out.println(value);
    }

    Similar problems exist with while loops and if/else clauses.

    Because of these very subtle typos, it is always recommended you follow the following pattern (pick one of the two and don't mix them):

    // how I prefer to write control flow statements: curly braces on its own line
    for(initializer; condition; increment)
    {
        // loop code in here
    }
     
    // also very popular: curly brace on the same line as control flow
    for(initializer; condition; increment) {
        // loop code in here
    }

    Both are equally valid and work well, depending on who you ask they will prefer one or the other. Notice that if you have a single statement to loop over, this is technically more typing than necessary, but it is very resilient against bugs. It also establishes a fundamental pattern to look for which makes reading your code much easier without the reader having to reason too deeply about what is going on (always a good thing).

    // I had to type literally 2 extra characters, or 4 if you count the newlines
    for(int i = 1; i <= 10; ++i)
    {
        System.out.println(i);
    }

  4. The Following User Says Thank You to helloworld922 For This Useful Post:

    GregBrannon (December 23rd, 2013)

  5. #4
    Member
    Join Date
    Dec 2013
    Posts
    51
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: BEGINNER! use of {} and ;

    Quote Originally Posted by helloworld922 View Post

    Both are equally valid and work well, depending on who you ask they will prefer one or the other. Notice that if you have a single statement to loop over, this is technically more typing than necessary, but it is very resilient against bugs. It also establishes a fundamental pattern to look for which makes reading your code much easier without the reader having to reason too deeply about what is going on (always a good thing).

    // I had to type literally 2 extra characters, or 4 if you count the newlines
    for(int i = 1; i <= 10; ++i)
    {
        System.out.println(i);
    }
    Thanks both for the replies! HelloWorld - I'm not sure that I follow the last part of your reply about it being technically more typing than necessary, by this do you mean that there's a more short hand way than using a for loop?

    cheers

  6. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: BEGINNER! use of {} and ;

    Saving a few keystrokes by skipping the use of {}s will make it easier to add bugs to code when updating it. You'll spend more time finding those bugs than you'll save by not typing the {}s.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #6
    Member andbin's Avatar
    Join Date
    Dec 2013
    Location
    Italy
    Posts
    443
    Thanks
    4
    Thanked 122 Times in 114 Posts

    Default Re: BEGINNER! use of {} and ;

    Quote Originally Posted by Scren View Post
    do you mean that there's a more short hand way than using a for loop?
    For a single System.out.println statement all the following four are perfectly equivalent.

    1)
    for (int i = 1; i <= 10; i++)
        System.out.println(i);

    2)
    for (int i = 1; i <= 10; i++) {
        System.out.println(i);
    }

    3)
    for (int i = 1; i <= 10; i++)
    {
        System.out.println(i);
    }

    4)
    for (int i = 1; i <= 10; i++) { System.out.println(i); }

    What changes is only the writing style (for the compiler they are equal). The most preferable are 2) and 3). Many in the Java community (even Oracle, and also me) prefer 2)

    Less than this is not possible, if you want a for cycle to print numbers from 1 to 10.
    Andrea, www.andbin.netSCJP 5 (91%) – SCWCD 5 (94%)

    Useful links for Java beginnersMy new project Java Examples on Google Code

  8. #7
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: BEGINNER! use of {} and ;

    By "more typing", I think he is talking about having the curly brackets, verse not having them.

    With that said, there is a shorter way of writing a for loop, which are best used whenever you don't directly need the index number.
    For example, if you had something like this:
    int[] array = new int[]{1,2,3,4,5}; // This creates an array with the numbers 1, 2, 3, 4, and 5
    for(int i=0;i<array.length;i++) {
         int number = array[i];
         System.out.println(number);
    }
    You can shorten the for loop by combining the iteration and the line where you are setting the number variable. The above for loop does the same as this for loop:
    int[] array = new int[]{1,2,3,4,5}; // This creates an array with the numbers 1, 2, 3, 4, and 5
    for(int number : array) {
         System.out.println(number);
    }
    This for loop, just like the previous one, will go through each index of the array and set the number variable. This way of writing the for loop cannot be used if you increase or decrease the size of the array during the loop (a runtime exception will be thrown). You can modify the array, but you cannot modify the size of the array. If you intend on modifying the size of the array while looping it, you need to use the first for loop example.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  9. #8
    Member
    Join Date
    Dec 2013
    Posts
    51
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: BEGINNER! use of {} and ;

    Right OK, I guess what norm said made sense. Especially seeing as I'm only learning.

    Thanks for the replies, much appreciated.

  10. #9
    Junior Member
    Join Date
    Dec 2013
    Posts
    7
    My Mood
    Cheerful
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: BEGINNER! use of {} and ;

    Quote Originally Posted by andbin View Post
    For a single System.out.println statement all the following four are perfectly equivalent.

    1)
    for (int i = 1; i <= 10; i++)
        System.out.println(i);

    2)
    for (int i = 1; i <= 10; i++) {
        System.out.println(i);
    }

    3)
    for (int i = 1; i <= 10; i++)
    {
        System.out.println(i);
    }

    4)
    for (int i = 1; i <= 10; i++) { System.out.println(i); }

    What changes is only the writing style (for the compiler they are equal). The most preferable are 2) and 3). Many in the Java community (even Oracle, and also me) prefer 2)

    Less than this is not possible, if you want a for cycle to print numbers from 1 to 10.
    prefer 2 !

Similar Threads

  1. Looking for some help! (BEGINNER)
    By Graveyard22 in forum What's Wrong With My Code?
    Replies: 6
    Last Post: October 13th, 2013, 11:17 AM
  2. i'm a beginner
    By so hat in forum What's Wrong With My Code?
    Replies: 1
    Last Post: June 24th, 2013, 12:42 AM
  3. BEGINNER
    By cephy in forum Member Introductions
    Replies: 2
    Last Post: May 23rd, 2013, 03:27 PM
  4. Beginner Help
    By Hawks in forum What's Wrong With My Code?
    Replies: 5
    Last Post: February 6th, 2013, 09:33 PM
  5. beginner
    By reginakanje in forum Object Oriented Programming
    Replies: 2
    Last Post: January 12th, 2013, 06:09 AM