Category Archives: Java

Overriding and overloading in Java and .NET – differences, changes and gotchas

Foraying even more in the fundamentals of Java (coming from a .NET background) I’ve come across some interesting things, along with changes in Java SE 5. But first let’s clear up a bit these two notions (overloading and overriding).

Overriding

Is a language feature that allows a subclass/inheriting class to have a method identical (we’ll later see a slight exception to this) to the one in the base class/superclass in every way except the implementation. That is, to have the same return type, the same name, same paramater types, same parameter order, just the code (and the parameter names) can differ.

This is by no means a definitive definition, Wikipedia, .NET CLS’s and JLS may very well differ slightly.

A typical C# overriding example (yes, I also dislike animal examples but they are so eaaaasyyyy to come up with) :

public class Dog 
{
    public virtual void MakeSound()
    {
         Console.WriteLine("Bark.");
    }
}

public class Hound : Dog
{
    public override void MakeSound()
    {
         Console.WriteLine("Wooofff!!!");
    }
}

Java developers unaware of the intricacies of C# will wonder what is that “virtual” thing. In C# all methods are “final” (sealed) by default unlike Java where methods are “virtual” (non-final / non-sealed) by default. This is a profound difference which we’ll discuss later. The “:” stands for “extends”. We’ll discuss the “override” keyword soon, also.

The equivalent piece of code in Java would look like :

public class Dog {
    public void makeSound() {
        System.out.println("Bark.");
    }
}

public class Hound extends Dog {
    public void makeSound() {
        System.out.println("Woofff!!!");
    }
}

Read more »

Numeric literals in Java 7 and in C#

In both Java and C# it’s quite easy to express integer numerical literals. You can use both decimal and hexadecimal base to represent the value. Only for the hexadecimal base you need to prefix the value with 0x. For decimal base values that exceed 2^31-1 you need to provide a suffix (typically L) specifying this fact so the compiler will treat it like a long integer value. C# also provides unsigned long values (U prefix). In both languages the casing of the suffix does not matter.

Java : (notice, there are no unsigned primitives in Java)

int i1 = 23; // integer, decimal
int h1 = 0x17; // integer, hexadecimal
long i2 = 12345678900L; // long integer (64 bit signed integer)

C# :

int i1 = 23;
int h1 = 0x17;
ulong u1 = 12345678900U;
long i2 = 12345678900L;

As you might have read in Beginning Java for .NET developers on slide 14, beginning in Java 7 you can also use two more features, that are not present in C# (at least at the time of this writing) :

Binary base :

int b1 = 0b11001010;

Underscores in literals (no matter which base) :

int b1 = 0b1100_1010;
long myCardNumber = 2315_2432_2111_1110;
int thousandsSeparated = 123_456_000;

The restrictions on the underscore placing is that you may not place it at the beginning of the value (prefix) or at the end (suffix). Also, for non-integer literals, you may not place it adjacent to the decimal separator.

For floating-point literals you must use the dot as decimal separator (if you need to specify a fraction, if not, you’re not required). You must use F for float-single-precision (32 bit) and D for float-double-precision (64 bit). Moreover in C# you have also the M suffix corresponding to the decimal (128 bit) value type.

C# :

float x1 = 0.001F;
double x2 = 12.33D;
decimal x3 = 111.2M;
float x4 = 33F;

Java :

float f1 = 0.001F;
double f2 = 12.31D;
float f3 = 123F;

Enum – comparison of Java and .NET

A useful feature added in Java 1.5 (also known as J2SE 5.0, 2004) is the enum. In .NET enums have been present since the very first version (2002, and as a beta since 2000) but the engineers at Sun managed to learn something from the shortcomings of the enums in .NET and provided more flexibility.

Let’s start with the simplest, the .NET implementation. In .NET all data types, including value types (equivalent of the primitive types) are part of the type hierarchy, being, indirectly inherited from System.Object (equiv. of java.lang.Object). The enums are just a specialization on top of exact numeric types, by default int (System.Int32). A typical declaration :

public enum Month
{
    January,
    February,
    March,
    April,
    May,
    June,
    July,
    August,
    September,
    October,
    November,
    December,
}

Notice that the compiler is forgiving and doesn’t complain that after the last element we forgot to not place a comma. It will also work, of course, if we don’t place a comma after the last element. Behind the scenes the compiler will generate a value-type inheriting from System.Enum that will have 12 constants. By default these constants we’ll be of type Int32 and their value, again, by default, will start from 0 and increase by 1 for each member. January will be 0 and December will be 11. Casts between the backing type (Int32 in this case) and the Months type will be allowed both at design time and at runtime.

You can also force individual values for each member

public enum Month
{
    January = 3,
    February = 33,
    March = 222,
    April = 14,
    May = 20,
    June = 23,
    July,
    August,
    September,
    October,
    November,
    December,
}

In this case January will be equal to 3, February 33, …, June 23, July 24 (not specified but after a value-specified member, the next member will be the last value + 1 if specific value is not present. You can even force things into a bad situation like so :

public enum Months
{
    January = 1,
    February,
    March,
    April,
    May,
    June,
    July = 1,
    August,
    September,
    October,
    November,
    December,
}

Guess what, not only this is completely valid, but there won’t be just two duplicate values (January and July being equal to themselves, and equal to 1) but also February will be 2, just like August and so on. Of course, this is not recommended. The compiler and the runtime will happily apply your stupid scheme but the humans will be confused. This excess of freedom is not to my liking but I can’t do much about it except counter-recommend it. Ideally you should not have to specify values for typical enums. Except for…
Read more »

Beware of primitive wrappers in Java

A .NET developer can be tricked into thinking that, for example, Integer is the same with int in Java. This is dangerous, in particular for a C# developer, because in C# System.Int32 is absolutely equivalent to int. “int” is just an alias.

In Java there are 8 primitive data types :

  • byte (this is equivalent to sbyte in C#)
  • short (just like short / Int16 in C#)
  • int (just like int / Int32 in C#)
  • long (equivalent to long / Int64)
  • float (similar to float / Single)
  • double (similar to double / Double)
  • boolean (equivalent to bool / Boolean)
  • char (equivalent to char / Char)

Now, these primitive types are not part of the Java Type System, as you might have seen in Beginning Java for .NET developers in the slides, at page 21. These primitives (“value types”) have reference-type peers that are typically spelled the same (except int/Integer, char/Character) and just have the first letter capitalized.

Just like you should avoid comparing strings with == in Java, you should avoid declaring variables and fields of the reference-type peers, unless for a good reason.
The main danger lies in the fact that being reference types and Java not having operator overloading (see Beginning Java for .NET developers, slide 15) comparing two instances with the == operator will compare the instances and not the values.

“Oh, but you’re wrong!”, some of you might say, “I’ve written code like this and it worked!”. Code like this :

public class Main {

    public static void main(String[] args) {
        Integer i1 = 23;
        Integer i2 = 23;

        System.out.println("i1 == i2 -> " + (i1 == i2));
    }
}

Yes, it does print

i1 == i2 -> true

It will work to values up to 127 inclusive. Just replace 23 with 128 (or higher) and see how things go. I’ll wait here.
Surprised? You shouldn’t be. This thing works because of a reason called integer caching (and there are ways to extend the interval on which it works – by default -128 up to 127 inclusive) but you shouldn’t rely on it.

Just use int where available or at least use the .intValue() method.

You might wonder what is the Integer (and the rest of the reference-type wrappers) there for? For a few things where they are needed. Once, because the generics in Java are lacking and you can’t define a generic type with primitive type(s) as type arguments. That’s right, you can’t have List. Scary? Yes, especially when coming from .NET where generics are not implemented with type erasure. So you need to say List and then watch out for reference comparison instead of value comparison, autoboxing performance loss and so on.

The other reason why you need these wrappers is because there is no nullable-types support in Java. So if you need to have a variable or a field that can store a primitive type but might also have to store a null then Integer will be better for you than int.

Just make sure you understand these implications and … be (type :P) safe!

Avoid comparing strings with == in Java

While beginning development in Java, especially if coming from a .NET background (but not necessarily) you might do string comparison with == in Java. Don’t do it. It will compare the string instances and not their effective value.
You might even try it first to check if == really works, testing it in a wrong manner like so :

public static void main(String[] args) {

    String s1 = "Abc";
    String s2 = "Abc";

    System.out.println("s1 == s2 -> " + (s1 == s2));
}

This will output

s1 == s2 -> true

.. which might lead you to believe this works. This does return the correct value because of a feature present in Java and .NET called string interning (not specific to Java or .NET).

Try to obtain a string instance dynamically like concatenating two existing instances and see how things don’t work anymore :

public static void main(String[] args) {

    String s1 = "Abc";
    String s2 = "Abc";

    // new lines :
    String capitalA = "A";
    String bc = "bc";
    String s3 = capitalA + bc;

    System.out.println("s1 == s2 -> " + (s1 == s2));
    // new line :
    System.out.println("s1 == s3 -> " + (s1 == s3));
}
s1 == s2 -> true
s1 == s3 -> false

Weird, huh? That’s because at compile time there are four distinct strings generated : “Abc” (once, even if referred twice), “A” and “bc”. The “Abc” instance obtained by joining “A” and “bc” will be generated at runtime and, of course, it will be a different instance than the first “Abc” instance. That’s why the result of the == operator comparison will be false.
Read more »

Simulating C# ref parameter in Java

As I was saying a few posts ago (Beginning Java for .NET Developers), on the 8th slide, there are no ref and no out method parameter modifiers.

These are rarely used in .NET anyway so you can’t really complain of their lack in Java. Furthermore, some of their legitimate uses, such as the static TryParse methods on value types are not applicable in Java. Why? Because in Java the primitives (int, long, byte etc. – the equivalent of the basic value types in .NET) are not part of the type hierarchy and they have reference-type wrappers (Integer etc.) which would solve the issue of returning the result in case of ‘TryParse’ style of parsing. How’s that? It’s like :

public static Integer tryParseInt(String intString) {
    try {
        return Integer.parseInt(intString);
    } catch (NumberFormatException e) {
        return null;
    }
}

No need for a ‘out’ parameter or ‘ref’. But! Let’s try and simulate ‘ref’ using a generic class written this way :

public class Ref<T> {
    private T value;

    public Ref() {
    }

    public Ref(T value) {
        this.value = value;
    }

    public T getValue() {
        return value;
    }

    public void setValue(T value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return value == null ? null : value.toString();
    }
}

Read more »

Preparing the development environment for Java – Windows and Ubuntu

Unlike .NET development where everything is streamlined and well-aligned, starting from the OS, the framework, the tools, the IDE and all others being written by one company, in Java development you’ll experience “freedom”(1) of choice. I’ll start with a gentle introduction which the experienced may very well skip to avoid getting bored.

In order to get started developing in Java we’ll need the following :

  1. An OS. I’ll showcase Windows and Ubuntu (Linux).
  2. A Java JRE. This is the most basic component required to run Java programs.
  3. A Java JDK. The JDK or Java SDK (IBM calls it that way) typically includes the JRE plus a compiler, tools for running various types of Java programs, packaging tools, extra class libraries and many more.
  4. An IDEIntegrated Development Environment. This is typically an MDI (Multi-Document Interface) application which provides certain convenience features for the developer :
    • Syntax highlighting – keywords are displayed in a certain color, local variables in another etc.
    • Code completion – instead of having to type the whole keyword, or class identifier, a member and so on, an autocompletion prompt will appear (usually triggered by the user typing a dot or other notable event) easing your typing and avoiding typos.
    • Interactive debugging – Allowing the user to control the execution of the program by inserting breakpoints, stepping over, into or out of code, watching expressions (variables, fields etc.), modifying internal data or even (very few IDEs allow) stepping back.
    • Tracing – in case you need to inspect internal data but breaking into the debugger cancels the bug or triggers other unwanted condition or the data changes too fast, you can watch expressions in a specially designed tool window without interrupting the flow of the debugged program
    • Source control integration – allows the user to send/push/checkin/etc changes to file(s) into a repository, obtaining the latest version, comparing versions, merging, branching and many more operations
    • Visual designers – For UI modules or elements most IDEs offer some kind of preview of the developed interface, showing the developer pretty much how things will look and behave without needing to recompile, run and browsing to that particular interface
    • Packaging and deployment – Features for creating a package of the application, be it JAR, WAR, DLL, ZIP, APK etc. Furthermore many IDEs will help you push a site to a webhosting provider, cloud service and so on.
    • .. and a whole lot more but let’s try to keep things shorter

Read more »

Beginning Java for .NET Developers

I’ve always wanted to learn another language and platform and being a long-time .NET developer Java seemed the closest to my knowledge and one which would seem easy to learn based on what I already knew.

I’ve put off this for various reason along the last 3-4 years, most of which laziness was chief.

Recently some colleagues moved from our project to another project that involves Java modules and since .NET is not a first-class citizen in my employer’s eyes I thought maybe it could serve me as a kind of an ‘insurance’ – to learn Java.

I’ve obtained (..) some ebooks (Effective Java and Thinking in Java), downloaded JDK, a few IDEs (IntelliJ IDEA and NetBeans, no Eclipse for me, thanks) and started doing HelloWorld’s and stuff like that. I noticed JavaFX (which is quite similar to WPF on which I currently work)

I’ve came across two nice comparisons of Java and .NET, written in a constructive manner (i.e. not “mine is better, na nanana”) :

Using these two articles I compiled (yes, that’s the original meaning of the word :P) a PowerPoint slideshow.

Then I thought there might be other (.NET developer) colleagues that might be interested in my research and gave an internal presentation based on the slideshow and expanding each item by talk.

I thought I should share it with everyone so here it is (download here) :

I’ve written about Java / C# differences before, and I might continue that series in the near future, with practical examples and counter-examples.

Some more Android development peculiarities

There is a baked in logging class called, intuitively, Log. For some strange reason the authors chose to name its methods, most of them, with one letter. That is :

Log.d(..); // debug level
Log.e(..); // error level
...

Until you hit

...
Log.wtf(..);
...

This one’s funny and I appreciate their sense of humor as it goes up to renaming WTF to “What a Terrible Failure”. Like we’re so dumb that we can’t figure what they really had in mind 😛

Another peculiarity is that in an activity (this akin to a Page / Form / whatever) you have some methods that you can/should override such as onCreate(). Everywhere is stated that the first thing you should write in the overriding method is a call to the super (that is base) class’s method. If it is really all that important and vital why didn’t the class designers go with a template method in first place?

That is a design pattern, that in this case, would go like so :

public class Activity {

    // ...

    private void onCreateInternal(Bundle savedInstanceState) {
        //vital stuff
        onCreate(savedInstanceState);
    }

    protected void onCreate(Bundle savedInstanceState) {
    }

    // ...

}

Take note of another difference between C# and Java : the methods and classes are virtual/unsealed by default. So the onCreate method in my example above is overrideable in any subclass. Also in Java terminology the base class is called the superclass.

Other differences of terminology include :

  • A namespace is called a package
  • By default an import (which is akin to a using directive) imports by default just the specified type and not the whole package (namespace). You need to use a wildcard to import the whole package
  • The closest thing to an assembly is called a JAR (Java ARchive).
  • Eclipse by default is set to autocompile. That is whenever you hit CTRL-S (Save) to a Java file the project is (re)compiled. This sounds terrible but it isn’t! You can’t even notice. Either there is an incremental compilation either the performance of the compiler is incredible.
  • Unlike Visual Studio, Eclipse presents the import block collapsed by default. I wish I had this in VS… Just like a mobile app fan would say “there’s an app for that”, I bet for VS “there’s a plugin for that” 😛
  • In Java if you want to call the super (base) class’s constructor from the current class’s constructor you will write “super(…);” in the constructor’s body. When I first saw this I said to myself Fu-Kin-Su-Pa (er… “great”, that is). “Now I have the liberty to call the base/super constructor from wherever inside the constructor I want”. Well, no. It’s either the first line or it isn’t.

Well, I’ll rant more as I go learning Android development.

My goal is to get to know enough so I can do it in Xamarin via C# but first I must understand the underlying things in order to go a level of abstraction above.

In the next episode(s) : I am indebted with a follow-up from my presentation held at RONUA last year.

Java / C# differences part 1 of n

Recently I’ve been toying around with Android development (since I own an Android “smart” phone for over 2 years now) and mobile development is all the rage now. Moreover, I’ve been trying to do new things lately since even the pragmatic programmer guide advises us to learn a new language each year (kind of aggressive if you ask me).

Anyway I will try to show what a C# developer (almost 8 years now) discovers by doing Java development on Eclipse for Android.

For today :

leaving a member of a class without an access modifier defaults to internal instead of private :

// C#
void Test() // private method
{
}
// Java
void test() { // internal method
}

Overriding a method does not require any kind of keyword or special ceremony. You can use the @Override annotation but this is optional. You can get burned this way easily.

// C#
public override bool Equals(object other)
{
    return _id == other._id;
}
// Java; WRONG! DO NOT USE
public bool equals(Person other) {
    return this.id == other.id;
}

//Correct
public bool equals(Object other) {
    return this.id == other.id;
}

Overriding requires that you use the same method signature (that is, the same return type, the same parameter types and order). If you accidentally mistake the signature (Person instead of Object) you will overload instead of overriding with unknown effects.

Read more »