4

Hi I'm having trouble understanding why this isn't working

if(Long.parseLong(morse) == 4545454545){
     System.out.println("2");
}

Where morse is just a String of numbers. The problem is it says Integer number too large: 4545454545, but I'm sure a Long can be much longer than that.

Raedwald
  • 46,613
  • 43
  • 151
  • 237
Strife
  • 59
  • 1
  • 1
  • 5
  • I am sure you must have realized the mistake till now.. You are comparing an integer and a Long. The max value of Integer is 2147483647, which is approximately half of what you have typed there. – dharam Jul 13 '13 at 18:26
  • yup never knew about the L in the end to qualify as Long thanks – Strife Jul 13 '13 at 18:57

3 Answers3

18

You need to use 4545454545l or 4545454545L to qualify it as long. Be default , 4545454545 is an int literal and 4545454545 is out of range of int.

It is recommended to use uppercase alphabet L to avoid confusion , as l and 1 looks pretty similar

You can do :

if(Long.valueOf(4545454545l).equals(Long.parseLong(morse)) ){
     System.out.println("2");
}

OR

if(Long.parseLong(morse) == 4545454545l){
   System.out.println("2");
}

As per JLS 3.10.1:

An integer literal is of type long if it is suffixed with an ASCII letter L or l (ell); otherwise it is of type int (§4.2.1).

AllTooSir
  • 48,828
  • 16
  • 130
  • 164
  • 3
    Since `parseLong()` returns a primitive long, there's no need to use `.equals()` - `==` will work just fine. – Michael Berry Jul 13 '13 at 18:21
  • *Don't* use `l`, use `L`. Both mean the same thing but the former can cause confusion as it can look like a `1`. – arshajii Jul 13 '13 at 18:49
4

If your integer value is larger than 2147483647, as your literal is then you need to use a long literal:

4545454545L

...note the L at the end, which is the difference between a long and an int literal. A lower case l works too, but is less readable as it's easily confused with a 1 (not a great thing when you're dealing with a number!)

Michael Berry
  • 70,193
  • 21
  • 157
  • 216
2

You need to use 4545454545L or 4545454545l to qualify it as long.

nachokk
  • 14,363
  • 4
  • 24
  • 53