• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

this is weird

 
Ranch Hand
Posts: 89
Eclipse IDE Tomcat Server Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 Tomcat Server Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
oh. Thanks sir Henry.
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic