Category Archives: Basics

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 »

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 »

Type check and inheritance – and a nice ReSharper tip

Let’s suppose you have three classes in a simple hierarchy :

public class A
{
}

public class B : A
{
}

public class C : A
{
}

Now suppose you receive an instance of one of these classes (you don’t know the exact type to which this instance belongs). How can you determine programatically if the instance is of a type inheriting from A or it is of type A exactly?

Normally I would do the following :

var instance = ObtainInstanceFromSomeWhere(); // this method will not return null
var instanceIsExactlyOfTypeA = typeof(A) == instance.GetType();
var instanceIsOfTypeAOrAnInheritingType = typeof(A).IsAssignableFrom(instance.GetType());

All these work and are nice and dandy. However ReSharper showed me a nicer alternative to the last statement :

var instanceIsOfTypeAOrAnInheritingType = typeof(A).IsInstanceOfType(instance);

Now, pro’lly, many of you knew about this method but I didn’t! 🙂
Hopefully it will help someone..

Back to basics – object equality

What do you think this piece of code will output?

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(GetValue() == (object)true);
            Console.WriteLine(object.Equals(GetValue(), true));
        }

        static object GetValue()
        {
            return true;
        }
    }

I won’t be like others and ask you not to run the code. Run the code if you feel like it. I’ll wait here.

Back already? Surprised?
I surely have been.. I’ve found a piece of code similar to this as I was cleaning up code in our repository. You have a method that is required to return object (as in System.Object) and you want to check if, unboxed, it holds the value of true (or not).

Why exactly does

    GetValue() == (object)true

return false considering that GetValue() returns always a true value? Well… because you are comparing two instances of a System.Object and the ‘==’ operator is coded in a way that uses the ReferenceEquals (and not Equals) method on System.Object.

The author could have unboxed it to a local variable and do the check after but the speed of coding is so much important for some of us.. Thank you ReSharper for pointing this to us and fixing a potentially subtle bug.