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 15 of 15

Thread: Lazy Thursday Question: Weird Syntax You've Seen?

  1. #1
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Question Lazy Thursday Question: Weird Syntax You've Seen?

    Hey all,

    We all know that Java is the best language ever and it always makes absolute syntactic and semantic sense, but occasionally I'll come across some syntax that makes me say, "huh?".

    These often turn out to be awesome learning exercises, showing functionality I didn't know about before.

    So I'd love to hear about syntax that threw you off or made you say "wtf, is this even Java...". I'll start with a few of mine.

    The first one is pretty basic, operating on an array returned from a method directly instead of using a variable to reference the array first:

    public class ArrayTest {
     
    	public static int[] getArray(){
    		return new int[]{0, 1, 2, 3, 4, 5};
    	}
     
        public static void main(String[] args) {
     
        	int[] array = getArray();
        	System.out.println(array[2]);
     
        	System.out.println(getArray()[2]);
        }
    }

    Specifically, I had to think about this line for a second before realizing what was going on:
    System.out.println(getArray()[2]);
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!


  2. #2
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Lazy Thursday Question: Weird Syntax You've Seen?

    I stumbled across another example when a coworker of mine asked why his static block wasn't working (he was missing the static keyword):

    public class BlockTest {
     
    	public static int x = 0;
     
    	static{
    		x = 2;
    	}
     
    	{
    		x = 4;
    	}
     
    	public BlockTest(){
    		x++;
    	}
     
    	public static void main(String... args){
    		new BlockTest();
    		System.out.println("X: " + x);
    	}
     
    }

    Specifically, when does the non-static block at the top of the class happen? What if the class is never instantiated and only contains static methods? The answer is actually in the basic tutorials, and it's called an initializer block. It gets copied into every constructor. Weird, but useful when you want to initialize stuff in every constructor but want to use code that can't be at the top with the declarations.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  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: Lazy Thursday Question: Weird Syntax You've Seen?

    I remember Json posting some funny allowable names for classes/fields/methods.

    http://www.javaprogrammingforums.com....html#post4807

    Brief code snippets:

    public class _ {
     
        public int _ = 0;
     
        public final int __;
     
        public _() {
            this._++;
            this.__ = 5;
        }
     
        public static void main(final String... arguments) {
            final _ _ = new _();
            System.out.println("_ = " + _._);
        }
    }

    public class $ {
     
        public final int £;
     
        public int $ = 0;
     
        public $() {
            this.$++;
            this= 5;
        }
     
        public static void main(String... arguments) {
            final $ $ = new $();
            System.out.println("$ = " + $.$);
        }
    }

  4. #4
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Lazy Thursday Question: Weird Syntax You've Seen?

    And finally, how do you create an instance of a public non-static inner class? This is how:

    public class InnerClassTest {
     
    	public InnerClassTest(){
    		OuterClass oc = new OuterClass();
    		OuterClass.InnerClass ic = oc.new InnerClass();
    	}
     
    	public class OuterClass {  
    				public class InnerClass{
    					//inner class
    				}
    	}  
     
    	public static void main(String... args){     
    		new InnerClassTest();
    	}  
    }

    The answer is you use the reference to the outer class, then call .new InnerClass().

    What. That's so gross looking to me. In my brain, it would make more sense if it looked like this:

    new oc.InnerClass();

    But I'm sure there's a reason for the syntax looking the way it does.

    Anyway, those are the three weird syntax examples I've seen lately that made me stop and think for a second. Does anybody else have any others? I'd love to see them!
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  5. #5
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Lazy Thursday Question: Weird Syntax You've Seen?

    Quote Originally Posted by helloworld922 View Post
    I remember Json posting some funny allowable names for classes/fields/methods.
    Hahahaha. Those are awesome. I'm going to start using them as often as possible at work and just wait for a code review...
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  6. #6
    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: Lazy Thursday Question: Weird Syntax You've Seen?

    Not necessarily weird syntax, but an abuse of Java's arrays to get pass-by-reference(ish) for primitives:

    public class PrimitivesAbuse
    {
        public static int factorial(int n, boolean[] success)
        {
            if(n < 0)
            {
                success[0] = false;
                return 0;
            }
            int answer = 1;
            for(int i = 1; i <= n; ++i)
            {
                answer *= i;
            }
            success[0] = true;
            return answer;
        }
     
        public static void main(String... args)
        {
            boolean[] success = new boolean[1];
            int f = factorial(3, success);
            if(success[0])
            {
                System.out.println("was able to compute 3!");
            }
            else
            {
                System.out.println("can't compute 3!");
            }
        }
    }
    Last edited by helloworld922; April 21st, 2011 at 11:22 AM.

  7. #7
    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: Lazy Thursday Question: Weird Syntax You've Seen?

    And who can forget the abuse of =, +=, ++/--, ... etc?

    		public static void main(String[] args)
    	{
    		int a = 1, b = 2, c = 3;
    		c += b = a++;
    		System.out.println(a + " " + b + " " + c);
    	}

  8. #8
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 294 Times in 227 Posts
    Blog Entries
    4

    Default Re: Lazy Thursday Question: Weird Syntax You've Seen?

    This is pretty interesting

    public class Foo {
     
    	static int fubar = 420;
     
    	Foo getFoo() {
    		return null;
    	}
     
    	public static void main(String args[]) {
    		Foo foo = new Foo();
    		System.out.println(foo.getFoo().fubar);
    	}
    }
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

  9. #9
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Lazy Thursday Question: Weird Syntax You've Seen?

    Nice examples guys. I just thought of another one, referring to an outer class's "this" reference from an inner class:


    public class InnerClassTest {
     
    	public InnerClassTest(){
    		OuterClass oc = new OuterClass();
    		OuterClass.InnerClass ic = oc.new InnerClass();
    	}
     
    	public class OuterClass {  
     
    		public int getInt(){
    			return 1;
    		}
     
    		public class InnerClass{
    			//inner class
     
    			public InnerClass(){
    				System.out.println(getInt());
    				System.out.println(OuterClass.this.getInt());
    			}
     
    			public int getInt(){
    				return 2;
    			}
    		}
    	}  
     
    	public static void main(String... args){     
    		new InnerClassTest();
    	}  
    }

    It took me a minute to figure out how to get to the outer class's "this".
    System.out.println(OuterClass.this.getInt());
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  10. #10
    Member
    Join Date
    Mar 2011
    Location
    Earth!
    Posts
    77
    Thanks
    2
    Thanked 1 Time in 1 Post

    Default Re: Lazy Thursday Question: Weird Syntax You've Seen?

    EDIT: Lol, I duplicated the one posted right above this post. It actually took me a ages to figure that one out, if I remember correctly. In any case, inner classes seems to be the source of many weird syntax examples .
    Last edited by Kerr; April 24th, 2011 at 02:57 PM.

  11. #11
    Member
    Join Date
    Mar 2011
    Location
    Earth!
    Posts
    77
    Thanks
    2
    Thanked 1 Time in 1 Post

    Default Re: Lazy Thursday Question: Weird Syntax You've Seen?

    I encountered this the other day. Appearently even anonymous inner classes can have some form of constructor like functionality. It just looks really weird, lol. For example:
    public class Program
    {
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args)
        {
            List<String> strs = new ArrayList<String>(){{add("b"); add("a"); add("z");}}; // <-- Who gets this just by looking at it? I sure didn´t when I saw it, lol.
            for (String s : strs)
                System.out.println( s );
        }
    }

  12. #12
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Lazy Thursday Question: Weird Syntax You've Seen?

    Quote Originally Posted by Kerr View Post
    I encountered this the other day. Appearently even anonymous inner classes can have some form of constructor like functionality. It just looks really weird, lol.
    Nice. Yeah, that's using an anonymous inner class along with the "initializer block" I posted in one of my examples. With formatting, that translates into this:

    import java.util.ArrayList;
    import java.util.List;
     
    public class Main
    {
    	public static void main(String[] args)
    	{
    		List<String> strs = new ArrayList<String>(){
                            //initializer block
    			{
    				add("b"); 
    				add("a"); 
    				add("z");
    			}
    		};
     
    		for (String s : strs){
    			System.out.println( s );
    		}
    	}
    }

    What makes it more interesting is that you can't have a normal constructor in an anonymous inner class!
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  13. #13
    Member OutputStream's Avatar
    Join Date
    Apr 2011
    Posts
    32
    My Mood
    Fine
    Thanks
    1
    Thanked 4 Times in 3 Posts

    Default Re: Lazy Thursday Question: Weird Syntax You've Seen?

    Not necessarily weird syntax, but abusing the finally clause can produce some really weird results:

    try {
        return true;
    } finally {
        return false;
    }
    The above code actually returns false...

    This one however returns true:
    for(int i=0;i<10;i++) {
        try {
            return false;
        } finally {
            continue;
        }
    }  
    return true;

  14. #14
    Member
    Join Date
    Mar 2011
    Location
    Earth!
    Posts
    77
    Thanks
    2
    Thanked 1 Time in 1 Post

    Default Re: Lazy Thursday Question: Weird Syntax You've Seen?

    Found this on the internet.
    public class JTest
    {
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args)
        {
            System.out.println( "Hello" );
            http: //www.javaprogrammingforums.com/forum.php
            System.out.println( "World" );
        }
    }
    This actually compiles. Can you see why? It is pretty easy to understand, just a case of when we humans see one thing and the compiler sees another. Had to read the explanation myself before I got it xD.

    Also, this looks kind of weird, but it is valid code for returning an array.
    public class JTest
    {
        private String getSomeStrings()[]
        {
            return new String[]{"a", "b", "c", "d"};
        }
     
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args)
        {
            JTest var = new JTest();
            String[] strs = var.getSomeStrings();
            for (String tmp : strs)
                System.out.println( tmp );
        }
    }
    Last edited by Kerr; May 11th, 2011 at 04:01 AM.

  15. #15
    Member
    Join Date
    Mar 2011
    Location
    Earth!
    Posts
    77
    Thanks
    2
    Thanked 1 Time in 1 Post

    Default Re: Lazy Thursday Question: Weird Syntax You've Seen?

    Lol, yeah, it would actually have been better with normal compilers in my opinion. This just seems so weird when you first look at it.

Similar Threads

  1. ClassNotFoundException (bit weird)
    By chronoz13 in forum Exceptions
    Replies: 1
    Last Post: April 26th, 2011, 02:15 AM
  2. syntax question
    By surfbumb in forum What's Wrong With My Code?
    Replies: 2
    Last Post: March 9th, 2011, 04:01 PM
  3. [SOLVED] Weird calendar.
    By javapenguin in forum What's Wrong With My Code?
    Replies: 7
    Last Post: January 3rd, 2011, 08:19 PM
  4. How do you read this syntax?
    By meowCat in forum Java Theory & Questions
    Replies: 5
    Last Post: August 8th, 2010, 03:09 PM
  5. Jsp weird problem
    By johniem in forum JavaServer Pages: JSP & JSTL
    Replies: 1
    Last Post: February 5th, 2010, 06:46 AM