Results 1 to 4 of 4
Like Tree2Likes
  • 1 Post By pbrockway2
  • 1 Post By JosAH

Thread: A rather unusual for loop

  1. #1
    Kagiso is offline Member
    Join Date
    Nov 2012
    Location
    Johannesburg, South Africa
    Posts
    92
    Rep Power
    0

    Default A rather unusual for loop

    Given the code. What is the output?
    1. public static void main(String args[]) {
    2. Object myObj = new String[]{"one", "two", "three"};{
    3. for (String s : (String[])myObj) System.out.print(s + ".");
    4. }
    5. }

    it turns out the output is one.two.three
    and I was so convinced it wouldn't compile

    for(String s :(String[] myObj) // can anyone kindly explain this line to me

    because I'm only used to for loops that are written like this:
    for(int i ; i<myObj.length; i++)

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,708
    Rep Power
    13

    Default Re: A rather unusual for loop

    It's called an "enhanced for loop". Although other languages often call it a "for each loop".

    The for Statement (The Java™ Tutorials > Learning the Java Language > Language Basics)

    (Ask if something in that tutorial is unclear.)
    Kagiso likes this.

  3. #3
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    14,044
    Blog Entries
    7
    Rep Power
    23

    Default Re: A rather unusual for loop

    Not that it matter much, but the output is "one.two.three." (a dot after "three").

    kind regards,

    Jos
    Kagiso likes this.
    The only person who got everything done by Friday was Robinson Crusoe.

  4. #4
    Kagiso is offline Member
    Join Date
    Nov 2012
    Location
    Johannesburg, South Africa
    Posts
    92
    Rep Power
    0

Similar Threads

  1. Unusual null pointer error
    By PRW56 in forum New To Java
    Replies: 8
    Last Post: 03-22-2012, 07:58 PM
  2. Replies: 6
    Last Post: 01-13-2012, 01:59 PM
  3. A few unusual jokes
    By tim in forum Entertainment
    Replies: 5
    Last Post: 01-06-2012, 09:52 AM
  4. Replies: 1
    Last Post: 10-01-2011, 02:12 AM
  5. Eclipse Unusual Problem
    By vineet.utd@gmail.com in forum Eclipse
    Replies: 0
    Last Post: 01-27-2011, 10:17 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •