aspose file tools*
The moose likes Java in General and the fly likes this is weird Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "this is weird" Watch "this is weird" New topic
Author

this is weird

Alexander Sales
Ranch Hand

Joined: Feb 21, 2011
Posts: 89

//this is weird

public class B{

public static void main(String[] args) {
String lesserThan = "03101800";
int greaterThan = 03112011;

if(greaterThan < Integer.parseInt(lesserThan)){
System.out.println(true);
}else{
System.out.println(false);
}


}
}

//output = true;

//can somebody explain what is happening here?


OCPJP 6, OCEWCD Java EE 6
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40


Basically, the lesserthan is a string that is getting parsed (in base 10) to an integer. The greaterthan is already an int that is being assigned from an literal -- and the octal (base 8) literal is lesser than the value that was parsed from a string.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Alexander Sales
Ranch Hand

Joined: Feb 21, 2011
Posts: 89

oh. Thanks sir Henry.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14269
    
  21

When you start an integer literal with a 0, for example 03112011, then the number is interpreted as a base-8 (octal) number. So 03112011 is the number 824329 (in decimal). When you parse the string "03101800" it is interpreted as a decimal number, so this is the number 3101800.

Because 824329 is less than 3101800, you'll see "true" being printed.

Another remark: Those numbers look like dates. It's not a good idea to store dates as integers in this way. Suppose that you'd do this:


Use the java.util.Date and java.util.Calendar classes if you want to work with dates. Note that those classes contain before() and after() methods to check if one date is before or after another date.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
 
 
subject: this is weird