File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Java » Java in General
Bookmark "this is weird" Watch "this is weird" New topic

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)){


//output = true;

//can somebody explain what is happening here?

Henry Wong

Joined: Sep 28, 2004
Posts: 20535

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.


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

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
I agree. Here's the link:
subject: this is weird
It's not a secret anymore!