Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

this is weird

 
Alexander Sales
Ranch Hand
Posts: 89
Eclipse IDE Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
//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?
 
Henry Wong
author
Marshal
Pie
Posts: 21112
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
 
Alexander Sales
Ranch Hand
Posts: 89
Eclipse IDE Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
oh. Thanks sir Henry.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15272
37
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic