A simple design question.
Sample code:
Integer int1 = new Integer(20);
System.out.println(Integer.toBinaryString(int1));
Why JDK design is not something like the following? so, toBinaryString function returns the the desired result?
System.out.println(int1.toBinaryString());
Aside for wide usability of a static function, what are the other reasons for this design approach? Are they using any particular design pattern? If it is then, which pattern?
toBinaryString. Returns a string representation of the integer argument as an unsigned integer in base 2. The unsigned integer value is the argument plus 232 if the argument is negative; otherwise it is equal to the argument.
parseInt() : returns int value by parsing the string in radix provided. Differs from valueOf() as it returns a primitive int value and valueOf() return Integer object.
Java Integer Methods. It returns the number of 1-bits in the 2's complement binary representation of the specified int value. It converts the given number into a primitive byte type and returns the value of integer object as byte. It compares two int values numerically and returns the result in integer equivalent.
You obviously can't write Integer instances to a List<Double>, since Integer doesn't extend Double. more precisely if both Integers and Double are Extended from Number, it means we can create one method lets say AddIntoList(List<Number> data) { data.
This is because you can't have two methods with the same name, one static and one instance. Having two different method names for the same functionality again would have been confusing.
Putting in a static method seemed more logical since in that case you wouldn't have to "wrap" an int into an Integer before getting its binary representation and it serves both the purposes (binary string for int
and for Integer
).
Your sample code creates an instance of Integer
and then unboxes it. There's no need for that:
int int1 = 20;
String binary = Integer.toBinaryString(int1);
If it were an instance method, you'd be forced to create an instance of Integer
solely to convert an int
to its binary representation, which would be annoying.
In other words: to avoid creating objects unnecessarily.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With