0

I have a doubt about null assigning to variable in Java. In my program I have assigned null to String variable as String str_variable = null;. For the learning purpose i assigned null integer variable as int int_variable = null; It shows error Add cast with Integer. So that rewrite the above int declaration as Integer int_variable = null;. This does not shows errors. I do not know the reason of these two kind of declaration.

Please the difference between to me.

String str_variable = null;

int int_variable = null; // error.

Integer int_variable1 = null; // no error.

3 Answers 3

1

String and Integer are both classes, in a way they are not native data types that is why it is always okay for you to set null as an initial value, however for int you must always initialize it with a number, one good way to find out their appropriate initialization value is to create variables outside your main(), example String var1; int var2; then use System.out.println(var1); System.out.println(var2); within the main() to see what was placed as an initial value when you run the program.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks i get idea of it. what is wrapper class? what is the different between other class and wrapper class in java?
when you try to picture a wrapper class a simple analogy can be formed, native data type -> Class -> Wrapper Class, simply put a wrapper class is a class built over another class, or it is an expansion of a class built to serve another purpose
1

int is a primitive, Integer is a class.

See http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

Comments

1

int is a primitive type, Integer is a wrapper class type extending Object class. Non-referencing objects can be null but primitives cannot. That's why you get an error message saying you need casting.

You can use a line like int num = (Integer) null;, this is how casting is done, however you will get NullPointerException when you try to use num anywhere in your code since a non-referencing(null) Integer object doesn't hold / wrap a primitive value.

2 Comments

thanks. what is wrapper class? what is the different between other class and wrapper class in java?
Wrapper classes are used to represent primitive values (int, long, boolean, ..) when you need an object of them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.