int g = 269;//1_0000_1101
    System.out.println( length(Integer.toBinaryString(g)));
This will print 18(why?), but I want it to print 9. How can I do that?
  int g = 269;//1_0000_1101
    System.out.println( length(Integer.toBinaryString(g)));
This will print 18(why?), but I want it to print 9. How can I do that?
 
    
    System.out.println(Integer.toBinaryString(g).length());
Would print out the length of the returned String from toBinaryString. You are measuring the length of the statement otherwise.
 
    
    If you use the Integer object for your whole number, the getObjectSize(Object o) method in the Instrumentation library is your guy: http://docs.oracle.com/javase/7/docs/api/java/lang/instrument/Instrumentation.html
There are a few threads on this.
Cheers!
