This question already has answers here:
Why does int num = Integer.getInteger("123") throw NullPointerException?
(3 answers)
Closed 7 years ago.
According to definition
The java.lang.Integer.getInteger(String nm) method determines the integer value of the system property with the specified name.
Can someone describe me the definition in simple terms.
Where is Integer.getInteger needed. Where can i use it. Why does the below program prints different outputs.
String str1 = "sun.arch.data.model";
System.out.println(Integer.getInteger(str1,5));
System.out.println(Integer.getInteger(str1));
String str2 = "com.samples.data.model";
System.out.println(Integer.getInteger(str2,5));
System.out.println(Integer.getInteger(str2));
Output:
32
32
5
null
The Integer.getInteger(String) method states the following:
The first argument is treated as the name of a system property. System properties are accessible through the System.getProperty(java.lang.String) method. The string value of this property is then interpreted as an integer value using the grammar supported by decode and an Integer object representing this value is returned.
If there is no property with the specified name, if the specified name is empty or null, or if the property does not have the correct numeric format, then null is returned.
The other method, with two parameters, has a default value that is returned instead of null, if the parameter is not set or is an invalid integer.
Since sun.arch.data.model is a valid property with a numeric value, its value is returned both times (it is 32). com.samples.data.model is either non-existent or non-numeric and so the invalid handling logic is invoked instead, returning the default of 5 when specified, and null in the second call, where the default isn't specified.
Related
This question already has answers here:
Why does null reference print as "null"
(3 answers)
Closed 6 years ago.
In Java, if I write:
System.out.println((String) null);, I get "null".
This seems weird. Does anyone know why the designers chose this approach? It seems to me that this is a case of "creating something out of nothing". I've read the JLS entry on cast operators, and it says:
The type of a cast expression is the result of applying capture conversion (§5.1.10) to the type whose name appears within the parentheses.
The result of a cast expression is not a variable, but a value, even if the result of the operand expression is a variable.
Jumping to the entry on capture conversion, I see capture conversion defined for generic types, but the entry adds:
Capture conversion on any type other than a parameterized type (§4.5) acts as an identity conversion (§5.1.1).
Okay! On to the entry on identity conversion and there's this:
A conversion from a type to that same type is permitted for any type.
In this case, the type is String but the thing to be converted is null and that left me confused. However, it turns out that Java is actually using String conversion for (String) null. The JLS entry on String conversion says:
Any type may be converted to type String by string conversion...
If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l).
One problem that this raises is this:
HashMap map = new HashMap();
System.out.println((String)map.get("something"));
The program prints "null". How do I know whether it was that because entry was null versus the String in the HashMap has value "null" (four ASCII characters 'n', 'u', 'l', 'l')? Now I know someone will say that Java discourages the use of raw types, and that the type HashMap should be parameterized but is that the solution?
You are overthinking this. Java is not casting (the value) null to (the string) "null". The correct answer is that this is merely an explicit behavior of the PrintStream.println(String) method:
Prints a String and then terminate the line. This method behaves as though it invokes print(String) and then println().
Next we consult what PrintStream.print(String) has to say:
Prints a string. If the argument is null then the string "null" is printed. Otherwise, the string's characters are converted into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.
(Remember, the type of System.out is PrintStream.)
HashMap map = new HashMap();
System.out.println((String)map.get("something"));
The program prints "null". How do I know whether it was that because
entry was null versus the String in the HashMap has value "null"
(four ASCII characters 'n', 'u', 'l', 'l')?
There's still a difference between null and "null", you just can't see that when you print them out with System.out.println. They're different values, and they do compare differently:
HashMap map = new HashMap();
map.put("foo", "null");
String something = (String) map.get("something");
String foo = (String) map.get("foo");
System.out.println(something == null); // true
System.out.println(foo == null); // false
System.out.println("null".equals(something)); // false
System.out.println("null".equals(foo)); // true
It does nothing to do with casting, but with printing: If you cast a null to String, it is still a null:
String s=(String)null;
if (s==null)
{
System.out.println("It is still a null");
}
else
{
throw new RuntimeException("This won't happen");
}
So you shouldn't have any difficulties to check if a value returned by a Map, Collection, or whatever API is null or not, simply performing a direct comparation by program.
In the other hand, never trust the result printed directly to the standard output by a PrintStream (as System.out). See the documentation of PrintStream.print(String).
Moreover: The same ambiguity happens when printing a number or a boolean: If you see on the standard output "123", is it a number value or a string value? I insist: To check values, never trust the appearance of a string printed out to a PrintStream.
This question already has answers here:
Extract Integer Part in String
(9 answers)
Closed 7 years ago.
Is there a way to get a Integer variable from a String object, something like:
String string = "Render.SCREEN_WIDTH_TILES";
// SCREEN_WIDTH_TILES is a Render Integer value referenced in other class
I want the string variable to hold the reference to the specified int.
What I want from that string value is to "transform it" into a int value,
Is it possible to do this?
I can't find a way to handle an integer value as a variable in a string.
You seem to be misunderstanding how Integer.parseInt(s) works. The documentation clearly states:
Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign - (\u002D) to indicate a negative value or an ASCII plus sign + (\u002B) to indicate a positive value.
The parameter to Integer.parseInt(s) must be a string that contains a number. Such as:
Integer.parseInt("12345")
Integer.parseInt("-45")
But not:
Integer.parseInt("Hello world")
Integer.parseInt("this will not work 4 you")
And certainly not: Integer.parseInt("Render.SCREEN_WIDTH_TILES - 1");
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
my case:
I try to get a value from my MySQL database. This data is defined as a VARCHAR.
This is done in java with a prepared statement and resultset.
String add1 =rs.getString("include");
according to this website table 5.1 states "Can always be converted to these Java types".
therefore a VARCHAR should be able to be converted in a java.lang.string.
When i check the data type in java it indeed gives java.lang.string. So for so good.
My issue is when i try to compare this obtained "String" value to a in java defined String value they don't seem to be equal.
Let's give a simple example.
I get the (VARCHAR) value "1" from the database and store in in String add1
I want to check if this value is indeed "1" and therefore I use the following statement
if(add1=="1")
{
/* do something */
}
Only the values are , according to java, not the same. So I was curious about why this is.
I started searching why those two "Strings" are not equal.
First of I checked the length of both strings. Both came out to be 1 in length as expected.
Afterwards I checked the value of both. To see if both values where indeed the same i wanted to check their hexadecimal representance.
Both came out with the value 0x31. Still as expected.
But then why isn't my if statement accepted by java if both seem to represent the same string-hex-bin-you name it value.
In short: Why is my VARCHAR "String" obtained from a MySQL databse in java not the same as a String defined in java.
Compare values, not memory references:
if(add1.equals("1"))
{
/* do something */
}
Please see this post best answer.
You must always compare strings with the .equals method in your case it will be
add1.equals("1")
"==" or equality operator in Java is a binary operator It is good for compairing primitives like boolean, int, float "==" works fine but when it comes to compare objects it creates confusion with equals method in Java. "==" compare two objects based on memory reference. so "==" operator will return true only if two object reference it is comparing represent exactly same object otherwise "==" will return false.
String comparison is a common scenario of using both == and equals method. Since java.lang.String class override equals method, It return true if two String object contains same content but == will only return true if two references are pointing to same object.
Read more: http://javarevisited.blogspot.com/2012/12/difference-between-equals-method-and-equality-operator-java.html#ixzz3PdLbOre0
You need to compare the Strings with .equals() method. because == checks for object reference.
What is the difference between == vs equals() in Java?
This question already has an answer here:
How does java.awt.Color.getColor(String colorName) work?
(1 answer)
Closed 8 years ago.
I would like the user to import a string such a "Red" then be able to pass it to the code below.
String red = "Red";
Color color = Color.getColor(red);
System.out.println(color);
output:
null
How would I get it to output Red. If that is possible.
Look at the JavaDoc what Color.getColor() says:
Finds a color in the system properties.
The argument is treated as the name of a system property to be obtained. The string value of this property is then interpreted as an integer which is then converted to a Color object.
If the specified property is not found or could not be parsed as an integer then null is returned.
Parameters:
nm - the name of the color property
Returns:
the Color converted from the system property.
"Red" is not defined as system property.
This is already answered in How does java.awt.Color.getColor(String colorName) work?
You expect the method to do something else than it does. Maybe you also want to use
Color.RED
instead.
What is the best way to assign a value with type conversion to a property of an object in Java.
For eg: A Person class with age field as an integer. If the following statement has to assign integer 21 to age field, then what should be the implementation of set method? [Note: 21 is passed as string]
ObjectUtils.set(person, "age", "21");
One way is to get the type of the field and type cast explicitly. Is there any better approach or library utility available to achieve this?
Take a look at BeanUtils.setProperty():
Set the specified property value, performing type conversions as required to conform to the type of the destination property.
You can achieve this by using reflexion:
using this you can get the attribute type dynamically, something like this:
Person p = ...; // The object you want to inspect
Class<?> c = p.getClass();
Field f = c.getDeclaredField("age");
f.setAccessible(true);
String typeOfAge = (String) f.getType(p);
After you have the attribute type its easy to cast the value.
use Integer.parseInt(String) in your set method. Make sure you catch the exception for an invalid number. Here is hte javadoc for parseInt
parseInt
public static int parseInt(String s) throws NumberFormatException Parses the string
argument as a signed decimal integer. The characters in the string
must all be decimal digits, except that the first character may be an
ASCII minus sign '-' ('\u002D') to indicate a negative value. The
resulting integer value is returned, exactly as if the argument and
the radix 10 were given as arguments to the parseInt(java.lang.String,
int) method. Parameters: s - a String containing the int
representation to be parsed Returns: the integer value represented by
the argument in decimal. Throws: NumberFormatException - if the string
does not contain a parsable integer.