Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why toBinaryString is not an instance method in Integer class?

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?

like image 660
Quazi Irfan Avatar asked Jul 13 '11 11:07

Quazi Irfan


People also ask

What does Integer toBinaryString do in Java?

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.

Which of the methods of the Java Lang Integer class returns a primitive int type?

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.

What are Integer methods in Java?

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.

Does Integer extend number in Java?

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.


2 Answers

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).

like image 75
Sanjay T. Sharma Avatar answered Oct 25 '22 16:10

Sanjay T. Sharma


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.

like image 22
Jon Skeet Avatar answered Oct 25 '22 16:10

Jon Skeet