Java 1.5 Samples: Like kids in a sandbox

Discussions

News: Java 1.5 Samples: Like kids in a sandbox

  1. Java 1.5 Samples: Like kids in a sandbox (34 messages)

    Since there are so many language changes in Tiger, people are having fun with seeing what they can do, and creating examples. Checkout some samples that come from Josh Bloch and others. What are you excited about? What do you wish was in there?

    You can see mini programs such as the word frequency counter, and grep... or just view code snippets of the new features.

    View JDK 1.5 Sample Code

    Threaded Messages (34)

  2. I once attended a conference when James Gosling what talking on the Java Technology. At that time he seemed not to like the idea of C++ templates. Someone suggested to include templates in Java and he strongly opposed that. I looked at one of the examples of Java 1.5 and surprised to see something similar to C++ templates. I guess, he has agreed to include them. The example I am referring is on Collection (Generic collection). God job done by Sun in implementing those new features.


    Thanks,
    Godfrey Nangoma
  3. Just I tried all the examples, they simply explains what you can do in 1.5. Excellent.
  4. Am I wrong or Wrong answer?[ Go to top ]

    In these, I tried enum examples (the first one) and I got the following result instead of

    Given answer in the link

    1
    2
    3
    4


    Actual answer (from the command line as well as from "Run It" in the link).

    clubs
    diamonds
    hearts
    spades

    Any ideas?
  5. Am I wrong or Wrong answer?[ Go to top ]

    In these, I tried enum examples (the first one) and I got the following result instead of

    >
    > Given answer in the link
    >
    > 1
    > 2
    > 3
    > 4
    >
    >
    > Actual answer (from the command line as well as from "Run It" in the link).
    >
    > clubs
    > diamonds
    > hearts
    > spades
    >
    > Any ideas?

    It must just be that way when the enums are sent to console. Check out this code which proves how enums are used in a switch statement - this is very useful.


    enum Suit { clubs, diamonds, hearts, spades };
    for (Suit suit : Suit.values())
    {
        System.out.println(suit);
        switch (suit)
        {
            case clubs:
                System.out.println("case clubs");
                break;

             case diamonds:
                System.out.println("case diamonds");
                 break;

              default:
                   System.out.println("Case Default");
                   break;
        }
    }
  6. Expected[ Go to top ]

    The author assumed the enum is going to be converted to an int but it seems the toString is invoked which prints the enum names.
  7. Wrong answer is fixed now[ Go to top ]

    I am the author of the code example. I used JDK 1.5 alpha to write the narrative, and that version of the JDK didn't quite work properly. I've corrected the documentation. Sorry for the confusion.

    You might like to try an interactive version of the same page:
    http://zamples.com/JspExplorer/samples/samplesJDK1_5.jsp
  8. Actually Gosling is still opposed to C++ templates. Java generics are much less powerful (and complex) than C++ templates. C++ templates are actually a Turing-complete functional programming language that gets executed by the compiler (don't believe me? Google for "C++ generative programming"). Java generics are a much more straightforward type-parameterization mechanism.
  9. Gosling also does not like the idea of leaving memory control to the progammer, which is why Java has a garbage collector. But if you look at the real time version of Java he's been working on, it becomes apparent that in real time applications, garbage collection just isn't going to cut it - so he 'invented' this notion of "ImmortalMemory" where you basically allocate memory that is never deallocated. Goes to show you that Java still is quite immature as a language and is slowly (albeit not completely) gone back home to roost (C++, Stroustroup) :). I'm not flaming Java - it's just that it has its purposes and is good for maybe most user-centric applications. But when you need absolute control of everything, including memory, C/C++ becomes your friend.. all over again :).
  10. gone back home to roost (C++, Stroustroup)


    Actually, the roots of Java is much more Objective-C rather than C++, at least semantically. Syntactically it borrowed from C++ though.

    Have a look at this comment from Patrick Naughton, one of the designers:
    http://cs.gmu.edu/~sean/stuff/java-objc.html

    /Håkan
  11. Anyone know if reflection works with generics?

    I guess not, if generics isn't implemented at the JVM level.
  12. metadata[ Go to top ]

    Apparently the spec states that metadata tags are inserted into the bytecode to preserve type information.
  13. Anyone know if reflection works with generics?

    >
    > I guess not, if generics isn't implemented at the JVM level.

    See "Comparing C# and Java Generics") in this article.

    http://www.artima.com/intv/generics2.html

    "When you apply reflection to a generic List in Java, you can't tell what the List is a List of. It's just a List."
  14. Anyone know if reflection works with generics?

    > >
    > > I guess not, if generics isn't implemented at the JVM level.
    >
    > See "Comparing C# and Java Generics") in this article.
    >
    > http://www.artima.com/intv/generics2.html
    >
    > "When you apply reflection to a generic List in Java, you can't tell what the List is a List of. It's just a List."

    This lame article is a plain crap. See API java source code or API documentation.
  15. I realy do not see that any of new enhancements in J2SE 1.5 is bad for Java. All of the enhancements are pretty simple and follow the simplicity of the original Java language, although some of them may sime somewhat complex (like generics or metadata).
    But I have some concerns about how generics is implemented in Java.
    Type erasure is very nice idea that enables backward compatibility at the JVM level in an elegant way, but I am warried that it will harm performance, at least when comparing with C# 2.0 generics, that do not try to be compatible and implements generics at the CLR level too. The result is that C# 2.0 generics do not need type erasure (inserting type casts in particular) and even enables collections of primitive types that do not contain boxed primitives, but actual primitives as value types. This way C# 2.0 collections of primitives are far ahead Java boxed primitives collections.

    I hope that this will be addressed in some future versions even at the cost of backward compatibility. Maybe a compiler switch can be added to generate generic code using type erasure or by using newly added JVM features to evoid type casts. This way we will have best of both worlds, backward compatibility for the ones who need it, and performance fot the others.

    At the end I have a suggestion for one more language enhancement, regarding making checked exceptions less painfull and thus more usefull.

    for example whe could have following language construct:

    public void aMethod() throws ExceptionTypeA chains ExceptionTypeB, ExceptionTypeC {
      ...
    }

    intead of:

    public void aMethod() throws ExceptionTypeA {
      try {
        ...
      }
      catch (ExceptionTypeB exB) {
        throw new ExceptionTypeA(exB);
      }
      catch (ExceptionTypeC exC) {
        throw new ExceptionTypeA(exC);
      }
    }

    This is just a synthax sugar and only needs compiler changes. If 'chains' could not be added as reserved word because of backward compatibility maybe some other syntax could be used like using some existing reserved word, for example 'catch'.
    This change could be usefull in writing EJBs where no more all exceptions should be explicitely (with try-catch) wrapped with EJBExceptions but implicitely using new syntax.

    What do you think ?
  16. or construction of :
    wait (500) {
      someclass.someMethod();
    }

    instead of :

    Thread _thread = new Thread() {
      public run() {
       someclass.someMethod();
      }
    }

    _thread.start();
    _thread.join(500);

    :))
  17. Templates v. generics[ Go to top ]

    C++ templates and Java generics may look similar, but are really quite different.

    Templates are a way of saying to the compiler, "generate me a distinct version of this code by textual substitution of this parameter, once for each distinct parameter I use (statically) in the source". You have to recompile the template class for each distinct parameterized use, even if it's in a separate library. Basically its just a macro system with a little bit of cooperation from the linker.

    Generics are simply an extension to the type system, so that the compiler can do more fine-grained type checking. Because the runtime isn't involved in this enhancement to the type system, the compiler also has to add redundant type-casts to the bytecode to please the bytecode verifier. Or perhaps the 1.5 runtime is enhanced to know about statically checking generic types?

    The big advantage of generics is that only one copy of the bytecode is needed for a generic class, however many ways you use it. In a template language each different use of a template compiles a full copy of the code (although a good compiler might be able to avoid this for "similar" uses). Used liberally this can lead to object code bloat, especially for a library with many clients.

    This is why Gosling (and any right-thinking language designer?!?) would baulk at the prospect of templates.

    __Mark Tillotson
  18. Importing Static Members

    With this feature java imports could be safely considered as c++ namespaces :)
  19. Went a Little Too Far?[ Go to top ]

    Am I the only one who thinks they went a little too far on some of the changes? One that particularly threw me off was the formatted output. I fear some of these changes will give easy outs away from nice OO-design.

    Most of the changes are great though. I'd like to learn a little more about the metadata.
  20. Went a Little Too Far?[ Go to top ]

    Am I the only one who thinks they went a little too far on some of the changes? One that particularly threw me off was the formatted output. I fear some of these changes will give easy outs away from nice OO-design.

    >
    It can be more features to "easy out away from nice OO-design" like lambda functions. I think pragmatic language features are more usefull than OO.
  21. Metadata[ Go to top ]

    Anyone care to explain what was going on with the Metadata example?
  22. Metadata[ Go to top ]

    Metadata extends Reflection by allowing for the inclusion of custom attributes. It appears to be a language feature 'inspired' by .NET. I think that .NET custom attributes facilitate some of the tool support built into .NET such as client-proxy generation and server interface generation. In retrospect Sun probably should have just named the feature Custom Attributes.
  23. "We took all the good things we could take from C++" seemed to be a slogan of Java world. Well, now it looks like "let's take the rest".

     I've started as a C++ programmer. I've used these features there. Some say "laziness of people drives the progress". I think I will use them here as well, cause as all of us I am lazy. Just a little less to type, isn't it cool [I am trying to put sarcasm here]. I've never used plain C a lot, because when I started it was already considered "archaic", C++ was the hype. I've switched from C++ to Java, not because the former one was hard, or the latter one was easy - because C++ was so damn ugly. Even the worst written code in Java made my heart sing.

     I was always interested why Java was so successful in winning the souls and minds of so many people. The answer was always there, I finally phrased it today to myself:

     In all it's power and all it's limitations Java _was_ a beautiful language.

     I look at the examples and the only thought that buzzers in my mind is "The beautiful language I fell in love with... is gone".
  24. I do think that there are some new features in Tiger that are really a bad idea (like variable arguments), some that are questionable (like enhanced for loop) but a lot of features that are really useful:
    - on top of all generics: I never liked how I had to cast objects when I got them from collections
    - metadata
    - autoboxing: ok, a real clean OO-way would have been to throw away all primitves and make them objects, but that is probably unrealistic
    ...

    I don't see why these features should make Java less "beautiful"
  25. Importing Static Members[ Go to top ]

    I was looking at the 'Importing Static Members' example in the article and is it me or does this break every OO Java principle to date? I really look forward to using some of the new features Sun is offering (i.e. generics) but I'm not sure it is worth the damage some other changes will cause.
  26. Importing Static Members[ Go to top ]

    I was looking at the 'Importing Static Members' example in the article and is it me or does this break every OO Java principle to date? I really look forward to using some of the new features Sun is offering (i.e. generics) but I'm not sure it is worth the damage some other changes will cause.
    In what way do static imports break Java OO principles that regular imports weren't breaking already?

    --
    Cedric
  27. Importing Static Members[ Go to top ]

    I was looking at the 'Importing Static Members' example in the article and is it me or does this break every OO Java principle to date? I really look forward to using some of the new features Sun is offering (i.e. generics) but I'm not sure it is worth the damage some other changes will cause.


    How language features can break OOP in your code ? Do you think language feature is broken if it is not an OO principle ?
  28. Importing Static Members[ Go to top ]

    "System.out.println(abs(x));"

    Maybe I'm all wet but it just seems like a line of code like the above implies that the method 'abs' belongs to the current class. That bothers me for some reason. What happens if you import multiple static classes. How do you know where abs() is coming from?
  29. Importing Static Members[ Go to top ]

    "System.out.println(abs(x));"

    >
    > Maybe I'm all wet but it just seems like a line of code like the above implies that the method 'abs' belongs to the current class. That bothers me for some reason. What happens if you import multiple static classes. How do you know where abs() is coming from?

    Do not use it if it is not clear form context. It is possible to write unreadable code with objects too, doe's it makes OOP useless ?
  30. Importing Static Members[ Go to top ]

    "System.out.println(abs(x));"

    >
    > Maybe I'm all wet but it just seems like a line of code like the above implies that the method 'abs' belongs to the current class. That bothers me for some reason. What happens if you import multiple static classes. How do you know where abs() is coming from?

    How is that at all different than if I type:

       XYZ.abs()

    How do you know where class XYZ is? What if you have more that one class XYZ in your application (in different packages)?

    This is basically called namespace management. I don't see how the introduction of static imports really changes things substantially. You still don't /really/ know where something is defined unless you have good tool support and good coding conventions.
  31. Importing Static Members[ Go to top ]


    > This is basically called namespace management. I don't see how the >introduction of static imports really changes things substantially. You still >don't /really/ know where something is defined unless you have good tool >support and good coding conventions.

    I wasn't really referring to namespace problems. Say your reading someone's code and you come across a method call 'calculate(y);'. Obviously if both classes you imported have a method called 'calculate(..)' you would get a compile time error. However say the method only exists in one of the static classes. Which class is it? Really this isn't the thing I'm most concerned about. I just think that up to now in Java you cant call a method in a different class w/ out reference to the object. Static imports have changed that and I think it has taken away from the OO flow of things.
  32. RE: Importing Static Members[ Go to top ]

    I see the feature as really handy to get static variables into a class without having to prefix them with the class name.

    I may also agree that importing static methods may be more confusing than using the old ClassName.staticMethod(x) way.

    Again, this is just another tool to be used wisely. If I was doing a lot with the math package I'd be very tempted to import the static methods.

    Finally, our coding convention shuns imports like java.io.* in favor of naming each class individually. If your coders adopted this convention it would be simple to know where a static method was imported from. The best IDEs and java pretty printers can automatically force this convention.

    I don't see anything wrong with new syntax-candy that makes the intent of a method more easily readable and I'm looking forward to using Tiger (once it is available inside a J2EE container that is).



    > >
    > > This is basically called namespace management. I don't see how the >introduction of static imports really changes things substantially. You still >don't /really/ know where something is defined unless you have good tool >support and good coding conventions.
    >
    > I wasn't really referring to namespace problems. Say your reading someone's code and you come across a method call 'calculate(y);'. Obviously if both classes you imported have a method called 'calculate(..)' you would get a compile time error. However say the method only exists in one of the static classes. Which class is it? Really this isn't the thing I'm most concerned about. I just think that up to now in Java you cant call a method in a different class w/ out reference to the object. Static imports have changed that and I think it has taken away from the OO flow of things.
  33. Importing Static Members[ Go to top ]

    I think that the real benefit here is the possibility to refer to static constants from a class without needing to inherit from it. Instead of MyClass.MY_CONSTANT, or even worse, extend MyClass, you can simply refer to MY_CONSTANT.

    This way, you dont have to create interfaces with static constants and implement them, but classes with a private constructor and import the static members, wich is far more elegant, IMHO.
  34. Importing Static Members[ Go to top ]

    Do you think language feature is broken if it is not an OO principle ?

    No, but it is a slippery slope. IMHO
  35. Importing Static Members[ Go to top ]

    It's not a slippery slope. If you have two imported static methods of the same name, then you should get a compile time error. Try to import java.sql.* and java.util.*. Then do a Date testDate = new Date(); The compiler will tell you that the Date reference is ambiguous.