I have a problem with the method that aims to print a hypothetical new hashCode for my class. I am trying to create for each object a hashcode that will be composed of the hashCodes of two String variables of my class. That's my code:
public void printHashCodes(){
String plateNumber = String.valueOf(this.liNumber.hashCode()) + String.valueOf(this.country.hashCode());
int hashCodeToConvert = Integer.valueOf(plateNumber);
System.out.println(hashCodeToConvert);
System.out.println(plateNumber);
}
Whenever I delete "hashCodeToConvert" lines and print a String called "plateNumber" method works fine. From that I understand that conversion of joined hashCodes to String was succesful.
Whenever I replace the content of the "plateNumber" String with some constant value like "123456789" the method works fine too so the code must be working well but in the form above it just doesn't work.
I assume there must be some limitation in conversion of potentially unlimited String into limited primitive int but what is the actual reason and what is the solution for that problem?
Clarification: My actual aim is to make a hashCode for an object but I am using printHashCodes method to verify those hashCodes. Since hashCode must be an int I have to reconvert it into int. It cannot stay as String(as farest I know)
I can see two reasons why your code is failing.
First, the result of String.valueOf(this.liNumber.hashCode()) + String.valueOf(this.country.hashCode()) could be too big.
The maximum value for an integer is 2147483647.
Secondly, the output of the hashCode() method could be below zero, and the value of plateNumbercould be 2147483647-1164645587, which is not easy to transform into an integer.
In both cases, it will throw a java.lang.NumberFormatException.
For me, the easiest solution would be to create a hashcode for an object that would contain these two values.
Or to use this:
return Objects.hash(liNumber, country);
I can't figure out what this lines do:
this.value = "".value;
and
int len2 = anotherString.value.length;
There is an array called "values" in the beginning of the class. It's something like String.Array (Array of chars).
How does it work?
Since the value field contains the characters for the String instance, what you see is the constructor using the value field of the (usually) interned empty string constant.
This way, an empty string created with the empty constructor will all use the same instance of the array. Strings are immutable, so they can and usually do, share the underlying char array to save on memory usage.
In terms of instances of wrapper classes, does the instance behave differently when the instance is created via a String arg in the constructor in comparison to an int, double etc.
E.g is there a difference in:
Integer wrapperInt= new Integer(33);
Integer wrapperInt2= new Integer("33");
The end result will be the same - you'll have an Integer object with the value 33.
The version that takes a String will throw a NumberFormatException if the input string cannot be parsed.
Note: There's no need to write a statement like Integer wrapperInt = new Integer(33);. Let the compiler do it for you (auto-boxing):
Integer wrapperInt = 33;
If, for some reason, you do not want to use auto-boxing, then at least use Integer.valueOf(...) instead of using the constructor:
Integer wrapperInt = Integer.valueOf(33);
This is more efficient; the valueOf method can return a cached object (so that it's not necessary to create a new Integer object).
No, it doesn't. Both instances represent the integer 33. If there was a difference, it would be written in the javadoc.
Note that you should favor the usage of the factory methods instead:
Integer i = Integer.valueOf(33);
i = Integer.valueOf("33");
The only difference is you will be creating a string object unnecessarily in the second approach and it will try to parse the string you have passed to the constructor, If it couldn't parse the string then it will throw NumberFormatException.
The answer is that yes, there can be a difference between the two syntaxes. Specifically, the syntax
new Integer(33);
results in the value 33 being interpreted as an integer constant by the compiler and stored as a literal in the code. By contrast, the syntax
new Integer("33");
results in a call that routes the string value through Integer.parseInt(s, 10). This matters if the value in question has a leading zero character; in the case of an int literal, the compiler will evaluate the literal as octal:
new Integer(010); // equals 8
By contrast, the string constructor will always evaluate the value as base 10:
new Integer("010"); // equals 10
In any case, you should almost always be using Integer.valueOf(), as it is usually more efficient.
There are a lot of questions about null and in java.
What I am failing to grasp is what people mean by null is pointing to nothing or why to use null at all.
I can't understand the difference between
String thing = null;
and
String thing = "";
This question has detailed answers What is null in Java?, but I just can't wrap my head around it.
What am I missing?
languages I've studied (no expert)
Python, vb (vb.net), web programming (html, css, php, bit of js), sql
I should add, it is this answer https://stackoverflow.com/a/19697058/2776866 which prompted me to write this.
String str = null;
means a String reference, named str, not pointing to anything
String str = "";
means a String reference, named str, pointing to an actual String instance. And for that String instance, it is a zero-length String, but it is still an actual object.
Just a little update with some diagram which hopefully can help you visualize that:
assume I have
String nullStr = null;
String emptyStr = "";
String myStr = "ab";
What it conceptually is something look like:
// String nullStr = null;
nullStr ----------> X pointing to nothing
// String emptyStr = "";
+------------------+
emptyStr ---------> | String |
+------------------+
| length = 0 |
| content = [] |
+------------------+
// String myStr = "ab";
+------------------+
myStr ------------> | String |
+------------------+
| length = 2 |
| content = [ab] |
+------------------+
(of course the internal structure of the String object is not the real thing in Java, it is just for giving you an idea)
More edit for the rationale behind NULL:
In fact in some language they do not provide concept of NULL. Anyway, in Java (or similar language), Null means semantically different from "empty" object. Use String as an example, I may have a People class with a String preferedTitle attribute. A Null preferedTitle means there is NO preferred title for that people (so that we need to derive and show the title for it, maybe), while a preferedTitle being an empty string means there IS a preferred title, and that's showing nothing.
Btw, although a bit off topic: concept of Null is seen as problematic for some people (because all those extra handling it need etc). Hence some languages (e.g. Haskell) are using some other ways to handle the situation where we used to use Null.
String str is a reference to an object. That is, it's not an actual object, but a variable which can contain the address of an object. When you assign a value to str you are changing the address stored within and changing which object it addresses.
null is reference value which points to no object. It's about as close to nothing as you can get. If you assign null to a String reference (String str = null;), you cannot then invoke any method of String using that reference -- all attempts will result in NullPointerException.
"" is a character String which contains no characters -- zero length. It is still an object, though, and if you assign its address to your String reference variable (String str = "";) you can then take its length, compare it to another String, extract its hashCode, etc.
Java doesn't really expose pointers, instead it deals with references.
When you say
String thing = null;
You are saying that there is a reference (of type string) called thing, which isn't referencing anything.
When you say
String thing = ""
This is shorthand for,
String thing = new String("");
Now you have an actual object initialized and ready to be used. You told the compiler to create a string and now your "thing" references the new string.
If you want to know the length of your initialized string, you can go;
thing.length
Which is zero. The string exists, but is zero length.
Trying string.length on the null version causes a NullReferenceException, which is the compiler saying
"I tried to find out about the length of your string, but I couldn't find it!"
Practically speaking, null means "not available for calling methods". If an object is allowed to be null, you must always check it for null before calling method on it.
An attempt to call any method on a null object is unconditionally an error. In nearly all cases it's a programming error, too, because you are supposed to either
Ensure that a variable is always non-null, or
Check a variable that could legally be null before calling methods on it.
On the other hand, an empty object lets you call methods. For example, you can find the length of an empty string - it is zero. You could also iterate a string, pass it to methods that expect non-null strings, and so on.
To visualize this, consider a Boolean object instead of a String. Unlike the primitive boolean that has only two states, namely true ("yes") and false ("no"), the Boolean object has three states:
Yes
No
Don't know
This third "don't know" state corresponds to null. It's neither true nor false state. Your program can use this third state to its advantage - for example, you can use comparison to null to see if a value has been set, or set a value to null to "unset" its value.
In Java null and an empty String are two different things.
If an String is null then you can not access its methods as it will throw a NullPointerException, however if a String is "" then the String object is valid and you can access its methods.
For example
String a = null;
String b = "";
System.out.println (a.length()); // No Good
System.out.println (b.length()); // Prints 0
Let's compare this to Python. In Python, the equivalent to null is None.
>>> test = ""
>>> test1 = None
This is setting an empty string and a "null" string.
>>> test
''
>>> test1
None
In Python we can test nullity using is
>>> test is None
False
>>> test1 is None
True
We can test for empty strings using ==
>>> test == ""
True
>>> test1 == ""
False
null (like None) is the absence of a value.
Conceptually null is a special value which means that the variable points to an invalid object, so it doesn't refer to anything valid in the sense that you can't access its content (variables or methods).
You can see it as a sort of special condition which has been added to languages because it was useful to be able to have pointers that refer to nothing. But there is some discordance here, in fact some languages prevent the necessity of a null value by forcing you to have just inizialized (meaningful) values.
There is difference in your example, "" is a valid object: it's an empty string while null is not a valid object.
Although many object-oriented frameworks implement references with pointers, it is better to think of references not as "pointing to" objects, but rather as "identifying" them [personally, I like the term "object identifier" to describe references, since the term "reference" is somewhat overloaded in different contexts]. Although object identifiers are not human readable, one can imagine the system as giving each object an associated number starting at 1, and each class-type variable as either having an object number or a zero written on it. Since class-type variables and array slots default to holding zero, and there will never be a zeroth object, there's no danger that the default-valued variable of an uninitialized variable or array slot will identify a valid object.
I prefer using the concept of containers/boxes to understand this concept
Let's start with this
String thing = "";
Imagine you have a container/box where you can store any value as long as you put the value between double quote marks "", if you decide to just put the double quotation mark without a value inside the box there is absolutely nothing wrong with that and any time you open your box you still see something inside (The double quotation mark )
Now This big man over here called null
String thing = null;
In simple terms look at null as being absolutely nothing
What does all this mean?
When you open the first box you see the double quotation ""
When you open the second box you see nothing (it's just an empty box)
What is the difference between getString() and optString() in JSON?
As Diego mentions, it's a good idea to check the documentation (this link is now out of date - good thing we have the Wayback Machine!) before posting a question here, but now that you have:
The difference is that optString returns the empty string ("") if the key you specify doesn't exist. getString on the other hand throws a JSONException. Use getString if it's an error for the data to be missing, or optString if you're not sure if it will be there.
Edit: Full description from the documentation:
Get an optional string associated with a key. It returns an empty string if there is no such key. If the value is not a string and is not null, then it is converted to a string.
If you want to avoid NullPointerException you better make use of optString()
If you are fetching the data from JSON at any time, you might have null data for a particular Key value, at that time instead of implementing Null conditions, better make use of this optimized method optString("<keyname>")
public java.lang.String optString(int index)
Get the optional string value associated with an index. It returns an empty string if there is no value at that index. If the value is not a string and is not null, then it is coverted to a string.
Parameters:
index - The index must be between 0 and length() - 1.
Returns:
A String value.
1) getString (String name):- This method Returns the String value mapped by name if it exists, coercing it if necessary, or throws JSONException if no such mapping exists.
2)optString (String name):- This method Returns the String value mapped by name if it exists, coercing it if necessary, or the empty string ("") if no such mapping exists.
optString() is used to overcome NullPointerException, which we get while using getString() when the required key doesn't exists in json it basically replaces with the default value.
example let the input Json be
{
"name":"abhi",
"country":"india"
}
now in java when you execute
String city = json.getString("city");
it will throw a NullPointerException.
by using optString(String key, String default) we can overcome the above problem.
String city= json.optString("city","default");
System.out.println(city);
Output: default