Setting null value to integer
How can i set null to integer variable initially instead of «0». I know already by default all int value is «0». I used String.valueOf() method etc. I dont want to print as «null». I want to print blank like » «. I get number format exception. Please give one solution for that. Thanks in advance Here is the code
8 Answers 8
I am sure you are over-complicating the problem, it is a real simple thing to do. Check the code below:
Integer i = null; System.out.println(i == null ?"":i);
Use Integer wrapper class instead of primitive
For object references you can set null.But you cannot to primitives .
Creating an instance of Integer with its primary value as null is meaningless, but you can do this on declaration:
Integer >The reason you're getting NumberFormatException is laid out in the documentation:
- The first argument is null or is a string of length zero.
- The radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX.
- Any character of the string is not a digit of the specified radix, except that the first > character may be a minus sign ‘-‘ (‘\u002D’) or plus sign ‘+’ (‘\u002B’) provided that the string is longer than length 1.
- The value represented by the string is not a value of type int.
You can’t call Integer.parseInt(«») or Integer.parseInt(null) , with that limitation.
If you parse null or blank as int it will throw numberFormatException . Check for that before parsing:
try < System.out.println(StringUtils.isNotBlank(id)?Integer.parseInt(id):""); >catch(NumberFormatException e)
Also be sure if string has not number by catching exception. StringUtils.isNotBlank() will check for both null as well as blank .
You would have to stick with the java.lang.Integer class.
String Integer test = null; if (!"".equals(id))
Instead of parse, we can use Integer.valueOf(null);
ints are primitives, they have default values different from null.
int is a reserved keyword; this isn’t valid Java syntax. Besides, the OP isn’t referring to primitives.
The simple boxed Integer Integer i = null; has already been supplied. Here is an alternative:
class NullableInt < private int value; private boolean isNull; public NullableInt() < isNull = true; >public NullableInt(int value) < this.value = value; isNull = false; >public NullableInt(String intRep) < try < value = Integer.parseInt(intRep); >catch (NumberFormatException) < isNull = true; >> boolean isNull() < return isNull; >void setNull(boolean toNull) < isNull = toNull; >void setValue(int value) < this.value = value; >int getValue() < return value; >@Override public String toString() < return isNull ? "" : value; >> NullableInt integer1 = new NullableInt(56); NullableInt integer2 = new NullableInt(); System.out.pritnln(integer1); // >> "56" System.out.println(integer2); // >> "" // and finally, to address the actual question: String ; System.out.println(new NullableInt(id)); // >> ""
Why cast null to Object?
I found a spot in some code I’m working on where null is cast to Object as it is passed to a method. Why would this be done? I am aware of this question which deals with overloaded methods, and using the cast to determine which version of the method to call. But if the cast were not performed, wouldn’t an overloaded method with a parameter typed as Object be chosen over any other matching version of the method if the method is called with a null argument? So what else does the cast accomplish?
4 Answers 4
If the cast where not performed, then the most specific version would be chosen.
null could be a null-reference of type String or of type Object . So if those two methods are available, then the String method will be called.
If you have methods with Object , Integer and String then calling that with null (and no cast) would give a compilation error because Integer and String are both valid and equally specific (i.e. none is a specialization of the other). In that case you would have to cast null to specify which method to call.
Though I agree with your answer but I believe the first statement is not correctly put i.e. compiler always try to locate the most specific match if more than one method is applicable, for example, if you cast null to say Integer and you have overloaded method with Object type and Number type argument respectively then it will resolve to one with Number type (i.e. the most specific one).
The » Object method» is always the «least specific» method among all «applicable methods». That’s why it wouldn’t be chosen by the compiler.
Then the compiler has the choice of two «applicable methods». You’re actually calling the more specific method
Which will give you a NullPointerException . In order to call the other method, write
In this case, you remain with only one «applicable method», so you don’t have the problem of a different, overloaded method being «more specific».
+1 for String.valueOf(Object o) is «least specific» match among all possible matches. However, it would make sense to also mention that in case of String if no specific cast is done then the «most specific» match we are left with is String.valueOf(Char [] c) and thus it gets called. Note: java compiler always resolves overloaded methods to the one with «most specific» match and if it fails to do so it will give ‘reference to method is ambiguos’ compilation error.
Though previous answers already explains what happens if you cast null to Object vs. if you don’t cast null to Object, but I would still like to add few missing points.
So in Java, ‘arrays’ are objects which means they can be assigned to Object type i.e. if you do new char[0].getClass().getSuperclass() it gives java.lang.Object and therefore in case when null is not explicitly cast compiler chooses valueOf(char[]) over valueOf(Object) as the most applicable method.
However, here comes the missing part, had there been another overloaded method that was accepting a interface type param (remember interface don’t extend Object class so they too cause ambiguity in most specific method selection) e.g. valueOf(CharSequence) then this would have lead to compile time error (i.e. reference to valueOf is ambiguous) because then compiler could’t pick the most applicable method.
So the bottom line is avoid passing raw null as arguments to methods rather always cast them to param type of the method being called. 🙂
Conversion from null to int possible?
I know that when I read the answer to this I will see that I have overlooked something that was under my eyes. But I have spent the last 30 minutes trying to figure it out myself with no result. So, I was writing a program in Java 6 and discovered some (for me) strange feature. In order to try and isolate it, I have made two small examples. I first tried the following method:
and the compiler refused it: Type mismatch: cannot convert from null to int. This is fine with me and it respects the Java semantics I am familiar with. Then I tried the following:
private static Integer foo(int x) < if (x < 0) < return null; >else < return new Integer(x); >> private static int bar(int x) < Integer y = foo(x); return y == null ? null : y.intValue(); >private static void runTest() < for (int index = 2; index >-2; index--) < System.out.println("bar(" + index + ") main" java.lang.NullPointerException at Test.bar(Test.java:23) at Test.runTest(Test.java:30) at Test.main(Test.java:36)
Can you explain this behaviour? Update Thank you very much for the many clarifying answers. I was a bit worried because this example did not correspond to my intuition. One thing that disturbed me was that a null was being converted to an int and I was wondering what the result would be: 0 like in C++? That would hae been very strange. Good that the conversion is not possible at runtime (null pointer exception).
How to Pass NULL Data Type?
There is NO data type of NULL. NULL itself means ABSENCE of data. When there is no data, how can it have type?
Yeah, this is what I had to be taught when I joined my company. NULL is the absence, it is not a type, however it can be represented by types (i.e. the .NET framework has DBNull.Value as a representation of the NULL value).
Yes I agree. In any technology you must have something to represent it. (You cant represent nothing with nothing). But as a concept, NULL means "nothing". Literally!
@Hemant, while that is a good database definition of NULL, that abstract concept is represented by an actual value. Assuming that Prabhahar wants to pass the value in some programming language to the database, there will be an associated database driver API which will have an implementation of passing NULL.
I don't agree that Null means "an absence of a value". Rather, it is a special value (in addition to any ordinary possible value associated with the datatype) which is subject to special logic and handling. It is possible to explicitly record that a normal input to the computer system was not available at the time the record was made - and that record is then a present record with a present Null value.
Null does not have a specific data type in SQL. Any nullable column or variable can contain null. Null is never equal or unequal to anything. You can cast a variable holding null to another variable and get null, for example:
declare @a integer set @a = null select convert (float, @a) ---------------------- NULL (1 row(s) affected)
Usually NULL is its own datatype - the type of 1 is "INTEGER", the type of the type of NULL is "NULL"
Datatype for NULL is as meaningless as datatype for 0 : it can be INTEGER , FLOAT or a VARCHAR . You cannot tell it just from the value.
NULL is legitimate value in almost every datatype domain, which means the absence of actual value.
It's also meaningless to discuss datatypes out of context of certain RDBMS .
In SQLite , for instance, datatypes are value-bound, not column-bound, and NULL is a first-class datatype per se.
In Oracle , the datatypes are more strictly defined. For instance, this query works:
SELECT COALESCE(dt, i) FROM ( SELECT CAST(NULL AS DATE) AS dt, CAST(NULL AS DATE) i FROM dual ) q
SELECT COALESCE(dt, i) FROM ( SELECT CAST(NULL AS DATE) AS dt, CAST(NULL AS NUMBER) i FROM dual ) q
, because the latter query returns two columns of different datatypes, both of them having values of NULL , and COALESCE requires both arguments to have same datatype.
It's better to say that a NULL of any datatype can be implicitly converted to a NULL on another datatype.
For instance, a VARCHAR can be implicitly converted to a INTEGER if it has value of 0 , but cannot if it has value of 'some_string' .
For NULL 's, any datatype can be implicitly converted to any other datatype, if the implicit conversion between them is allowed at all.