Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

This is one (of many) reasons I have a dislike for Java:

    String myString = null;
    if (myString.equals("foobar")) { /* ... */ }
    // This causes a NullPointerException in Java
Here is some equivalent C# code:

    using System;
    
    namespace SampleApplication
    {
        static class Program
        {
            static void Main(string[] args) {
                String myString = null;
    
                if (myString == "foobar") {
                    Console.WriteLine("???");
                }
                else {
                    Console.WriteLine("No good!!");
                }
            }
        }
    }
and sure enough it produces what I consider the correct logical output:

    No good!!


[deleted]


No, jussij is right. It is your code which is not equivalent.

Your Java code is checking reference equality while the C# code is checking string value equality. The == operator works differently between strings in C# compared to Java. The only reason the Java code you wrote might "work" is due to Java interning strings so the references could be the same.


With java 7 and java.util.Objects there is a static helper method. Nice to have in the favourites in Eclipse.

    import static java.util.Objects.equals;

    if(equals(myString, "foobar")) { ... }


So rather than fix the obvious problems in the language they resort to a standard library work around?

I'm an experienced programmer and in my time I've only ever worked two big Java projects. Those two projects left me feeling like an idiot!

Not long after I started work on my first C# project and while it felt a lot like Java, it was clear the designers of that language had created a Java like language that was so much better than Java. It just felt right!

So is C# better than Java?

Based on my experience with both languages I would say yes.

Does my opinion matter. No!

But to me Java had the lead and it let it go.

With the lead gone it is now trying desperately to play catch up to C# which is progressing leaps and bounds.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: