Number

5 0 0
                                    

Number is a mother class of the following subclasses: Byte, Short, Integer, Long, Float, Double. These subclasses are used for wrapping and unwrapping of primitive data types. Wrapping is like a gift wrap but just in code.

Note: The subclasses above is different from the primitive bytes, short, int, long, float, double.

Why do we need to wrap?

1. When a method has an object parameter, you cannot just put a primitive type as an argument because they are not the same. So, you need to wrap that primitive type into an Object to make it an object type before you are allowed to use that method. 

2. To use static constants MIN_VALUE and MAX_VALUE given by the class above.

3. In some cases where you need convert it to primitives or strings.

=====================

import java.util.Scanner;
class Class2 {
static double doubleThatNumber(Number obj){
return obj.doubleValue() * 2;
}

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number");
String input = scan.next();

Double dWrap = Double.valueOf(input);
System.out.println(doubleThatNumber(dWrap));
System.out.println("min: " + Double.MIN_VALUE);
System.out.println("max: " + Double.MAX_VALUE);
}
}

=====================

Result:

Enter a number1020.0min: 4.9E-324max: 1.7976931348623157E308


NOTE: As you notice that System.out is where we use to output our values to the console while System.in is the opposite which is to input a value to the console. A Scanner class was used to scan an input of stream of values this time coming from the system console. The method next() was used to get that string input but take note that the Scanner class will produce only the very first value before it reach a space. So, if you type in a name for example "Uzumaki Naruto", it will input only Uzumaki. The above result is 6.0 which is a double of the number i input which is 3.

Java ProgrammingWhere stories live. Discover now