code_junkie

Why does addition of long variables cause concatenation?

Nov 11th, 2011
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. Vector speeds = ... //whatever, speeds.size() returns 2
  2. long estimated = 1l;
  3. long time = speeds.size() + estimated; // time = 21; string concatenation??
  4.  
  5. Vector speeds = ... //whatever, speeds.size() returns 2
  6. long estimated = 1l;
  7. long time = estimated + speeds.size(); // time = 12; string concatenation??
  8.  
  9. Vector speeds = ... //whatever, speeds.size() returns 2
  10. long estimated = 1l;
  11. long size = speeds.size();
  12. long time = size + estimated; // time = 3; correct
  13.  
  14. import java.util.*;
  15.  
  16. public class Test
  17. {
  18. public static void main(String[] args)
  19. {
  20. Vector speeds = new Vector();
  21. speeds.add("x");
  22. speeds.add("y");
  23.  
  24. long estimated = 1l;
  25. long time = speeds.size() + estimated;
  26. System.out.println(time); // Prints out 3
  27. }
  28. }
  29.  
  30. System.out.println("" + size + estimated);
  31.  
  32. "" + size <--- string concatenation, so if size is 3, will produce "3"
  33. "3" + estimated <--- string concatenation, so if estimated is 2, will produce "32"
  34.  
  35. System.out.println("" + (size + estimated));
  36.  
  37. "" + (expression) <-- string concatenation - need to evaluate expression first
  38. (3 + 2) <-- 5
  39. Hence:
  40. "" + 5 <-- string concatenation - will produce "5"
Add Comment
Please, Sign In to add comment