Java Fundamentals  «Prev 

Integer Number Datatype

Integer numbers are whole numbers without fractional parts, and are represented in Java by the following simple data types:
  1. byte,
  2. short,
  3. int,
  4. long.
The difference between each of these integer data types is the memory required for storage, which determines how large (or small) a number each type can store. As an example, the byte data type requires the least memory (8 bits) but can only store numbers in the range -128 to 127.
The int data type requires four times as much memory (32 bits) as byte and can store numbers in the range -2,147,483,648 to 2,147,483,647.
The long data type is the largest of the integer types and can store extremely large numbers.
Practically speaking, the int type is sufficient in most cases for dealing with a wide range of integer numbers.

Converting Java String to Long

The following 2 lines of Java are given?
String mStr = "123";
long m = // 1

Which of the following options when put at //1 will assign 123 to m?
Select 3 options:
  1. new Long(mStr);
  2. Long.parseLong(mStr);
  3. Long.longValue(mStr);
  4. (new Long()).parseLong(mStr);
  5. Long.valueOf(mStr).longValue();


Answers: a, b, e

Explanation:
a) Auto unboxing will occur.
c) longValue is a non-static method in Long class.
d) Long (or any wrapper class) does not have a no-args constructor, so new Long() is invalid.
e) Long.valueOf(mStr) returns a Long object containing 123.
longValue() on the Long object returns 123.