I'm a beginner in Java and I have a question from the "Head First Java" book. In the book, the author creates a method that takes the number as String and then convert it into int. Why do I need to take the input as a string and convert it rather than directly take it as an int. Below is he screenshot that I'm talking about.
Why Use String Input Instead of Int for Numbers in Java?
java
Related Solutions
I guess it's just consistency, or "principle of least astonishment". String is an object, so it would be surprising if was treated differently than other objects.
At the time when Java came out (~1995), merely having something like String
was total luxury to most programmers who were accustomed to representing strings as null-terminated arrays. String
's behavior is now what it was back then, and that's good; subtly changing the behavior later on could have surprising, undesired effects in working programs.
As a side note, you could use String.intern()
to get a canonical (interned) representation of the string, after which comparisons could be made with ==
. Interning takes some time, but after that, comparisons will be really fast.
Addition: unlike some answers suggest, it's not about supporting operator overloading. The +
operator (concatenation) works on String
s even though Java doesn't support operator overloading; it's simply handled as a special case in the compiler, resolving to StringBuilder.append()
. Similarly, ==
could have been handled as a special case.
Then why astonish with special case +
but not with ==
? Because, +
simply doesn't compile when applied to non-String
objects so that's quickly apparent. The different behavior of ==
would be much less apparent and thus much more astonishing when it hits you.
The returning of null makes sense to me since manipulating a null string should result in a null string, not an error
Well, that is your opinion. Others may argument that String operations on a null object, which does not contain a String, make no sense and hence should throw an Exception
Why "Java designers" did or did not something is difficult to anwer.
There are already libraries out there which can do null-safe String operations, e.g. StringUtils of Apache Commons. You can use that or similar libraries if you need them.
Addition based on your comments
Reading through the comments, it seems like the real problem you face is that you have to check for null
all over your code. That can be an indicator of a bad program design without clearly defined contracts between interfaces. You might want to read Avoiding “!= null” statements in Java?
Best Answer
Simply because the user's guess is most probably entered through a mechanism which only supports entering chars, or strings, but no other types. For example,
most GUIs have a text-input control, but not a numeric input control. So, the user enters text in the control, and then the program must convert the text to a number.System.in.read()