Ternary if-else operator in Java

29 Mar

This post is written because something I didn’t know about ternary if-else operator. After some debugging I  finally realized the cause of the outcome.

A basic situation could be as follows:

  • A class called MyClass with a long attribute with a specific constructor.
  • public class MyClass {
    	private long value;
    		public MyClass(long value) {
    		this.value = value;
    	public long getValue() {
    		return this.value;
  • Another class that creates an instance of the previous class in its main method.
  • public class Example {
    	public static void main(String[] args) 
    		MyClass myClass = new MyClass((3>1) ? null : 3);

Try to find the answer out. If you are not sure of it, just copy the code, compile it and execute it … if you are able to. There’s some nice post about this situation in stackoverflow. This is my prefered one.

It seems java compiler tries to evaluate the type of both branches (if-else). It realizes and int value and a null(object) value which might reference to a integer value. Because of that Java compiler doesn’t complain about it. The problem is shown in executing time as long as null value can’t be parsed to a correct integer value.

Deja un comentario

Publicado por en 29 marzo, 2012 en Java


Etiquetas: ,


Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de

Estás comentando usando tu cuenta de Cerrar sesión /  Cambiar )

Google photo

Estás comentando usando tu cuenta de Google. Cerrar sesión /  Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión /  Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión /  Cambiar )

Conectando a %s

A %d blogueros les gusta esto: