RSS

Archivos diarios: 29 marzo, 2012

Ternary if-else operator in Java


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);
    		System.out.println(myClass.getValue());
    	}
    }
    

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: ,

 
Seguir

Recibe cada nueva publicación en tu buzón de correo electrónico.

Únete a otros 69 seguidores

%d personas les gusta esto: