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.

Building Client (JavaScript) Custom Validation in ASP.NET MVC 4 using jQuery

Introduction

I was recently asked by some students of mine how exactly is client custom validation done in ASP.NET MVC (4). I did this once before unobtrusive validation and jQuery in ASP.NET MVC 2.0 but then I lost contact with the implementation details.

In ASP.NET MVC 4 (this started in MVC 3) there is jQuery unobtrusive validation that works hand-in-hand with Data Annotations (a set of validation attributes that can decorate properties or even (view)model classes). I just remembered that you need to create a ValidationAttribute subclass and also implement IClientValidatable on it. Also you must decorate a property of the (View)Model with this attribute.

On the client side you need to write JavaScript code that provides a validation adapter and a validation function.

Let’s suppose we’d want to create an URL shortening service and on the “Add URL” page we’d have three fields :
- Original URL (textbox)
- Use custom slug (checkbox)
- Custom slug (textbox)

The “Original URL” textbox would be mandatory and the input format should be of a fully-qualified URL (for example “http://blog.andrei.rinea.ro” :P )

The custom slug textbox would be mandatory ONLY if the “Use custom slug” checkbox would be checked. This is the tough part since validating this field requires knowledge of another field’s value (the checkbox in this case). And by tough I mean having to write actual code because there is no out-of-the-box validator for this (not on the server-side nor on the client-side).

This small tutorial will asume that you have knowledge of the ASP.NET MVC platform and C#. I will not go into detail on matters such as what is the MVC pattern, what is the controller, view etc.

 

Implementation – server side

Let’s start by creating a new ASP.NET MVC 4 web project (select “Internet site” template).
We’ll create a UrlController controller with an action called Add :

using System.Web.Mvc;

namespace MVC4_jQuery_Unobtrusive_Custom_Validation.Controllers
{
    public class UrlController : Controller
    {
        [HttpGet]
        public ActionResult Add()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Add(AddUrlViewModel userInput)
        {
            if (ModelState.IsValid)
            {
                // store the data
                // ...
                return RedirectToAction("Index", "Home");
            }
            return View();
        }
    }
}

Read more »

Bing it on, Reactive Extensions! – story, code and slides

I held a presentation at UBISOFT Buchares headquarters for the RONUA local programmers user group recently as I’ve announced earlier.
Here’s the contents, step-by-step, final code and slides.

————- [scroll way down for the downloads]

I was recently tasked with rewriting an app component by leveraging Reactive Extensions. I knew little about Rx (the short form of Reactive Extensions) and all I remembered was that it has two interfaces IObservable and IObserver and it seemed dull at that time.

Basically the component enables search without needing to hit ENTER or a “Go!” button, although provides for these. After the user finishes typing an async request goes to the data store and searches for the phrase entered and fetches the results. In the original implementation the component used a lot of timers, event handlers, private fields all making up a nice spaghetti bowl of code.

Let’s do this step by step and see how our little (demo) app develops. Fire up Visual Studio 2012 and start a new WPF project (.NET 4.5 preferrably). The very next thing we’ll install Rx. Right click on the project in the Solution Explorer and select “Manage NuGet Packages” (you can also use the Package Manager Console if you like it better). Search online for “Reactive Extensions”.

In the result lists (this requires a functional internet connection) select ‘Reactive Extensions – WPF Helpers‘ (the nice thing about NuGet packages is that it automatically resolves and installs all the dependencies). Accept the license(s) (you know what’s the most common lie told these days? “I have read and accepted the terms of the license” :P ).

In our demo we will use Bing as the data store which we’ll target through our searches (sorry, Google was too difficult to setup, offered less search requests per month and no C# demo code. Thanks Google, thanks again.). In order to do this you will need a Microsoft Account (I guess we all have one these days). Go to http://www.bing.com/developers/ and then select “Search API” -> Start now (this will lead you to https://datamarket.azure.com/dataset/5BA839F1-12CE-4CCE-BF57-A49D98D29A44 ). There are paid subscriptions and a free subscription. Hit signup and go through the process (leave a comment if you are unable to go through this process).

In the end you will need to obtain the (Primary) Account Key and the Customer ID. These are available under “My Account” -> Account Information ( https://datamarket.azure.com/account ). We’ll use these later so save them. Also, don’t share them with other people because these are your credentials. Also visit “My Data” ( https://datamarket.azure.com/account/datasets ) and click on “Bing Search API”‘s “Use” link (far right, https://datamarket.azure.com/dataset/explore/bing/search ). Capture the “URL for current expressed query” : “https://api.datamarket.azure.com/Bing/Search/v1/Web“. We’ll also need these later.

Read more »

WP Like Button Plugin by Free WordPress Templates