Java declaration confusion for datatypes - java

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.

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.

int is a primitive, Integer is a class.
See http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

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.

Related

Delete value for previously assigned int field [duplicate]

Can an int be null in Java?
For example:
int data = check(Node root);
if ( data == null ) {
// do something
} else {
// do something
}
My goal is to write a function which returns an int. Said int is stored in the height of a node, and if the node is not present, it will be null, and I'll need to check that.
I am doing this for homework but this specific part is not part of the homework, it just helps me get through what I am doing.
Thanks for the comments, but it seems very few people have actually read what's under the code, I was asking how else I can accomplish this goal; it was easy to figure out that it doesn't work.
int can't be null, but Integer can. You need to be careful when unboxing null Integers since this can cause a lot of confusion and head scratching!
e.g. this:
int a = object.getA(); // getA returns a null Integer
will give you a NullPointerException, despite object not being null!
To follow up on your question, if you want to indicate the absence of a value, I would investigate java.util.Optional<Integer>
No. Only object references can be null, not primitives.
A great way to find out:
public static void main(String args[]) {
int i = null;
}
Try to compile.
In Java, int is a primitive type and it is not considered an object. Only objects can have a null value. So the answer to your question is no, it can't be null. But it's not that simple, because there are objects that represent most primitive types.
The class Integer represents an int value, but it can hold a null value. Depending on your check method, you could be returning an int or an Integer.
This behavior is different from some more purely object oriented languages like Ruby, where even "primitive" things like ints are considered objects.
Along with all above answer i would like to add this point too.
For primitive types,we have fixed memory size i.e for int we have 4 bytes and char we have 2 bytes. And null is used only for objects because there memory size is not fixed.
So by default we have,
int a=0;
and not
int a=null;
Same with other primitive types and hence null is only used for objects and not for primitive types.
The code won't even compile. Only an fullworthy Object can be null, like Integer. Here's a basic example to show when you can test for null:
Integer data = check(Node root);
if ( data == null ) {
// do something
} else {
// do something
}
On the other hand, if check() is declared to return int, it can never be null and the whole if-else block is then superfluous.
int data = check(Node root);
// do something
Autoboxing problems doesn't apply here as well when check() is declared to return int. If it had returned Integer, then you may risk NullPointerException when assigning it to an int instead of Integer. Assigning it as an Integer and using the if-else block would then indeed have been mandatory.
To learn more about autoboxing, check this Sun guide.
instead of declaring as int i declare it as Integer i then we can do i=null;
Integer i;
i=null;
Integer object would be best. If you must use primitives you can use a value that does not exist in your use case. Negative height does not exist for people, so
public int getHeight(String name){
if(map.containsKey(name)){
return map.get(name);
}else{
return -1;
}
}
No, but int[] can be.
int[] hayhay = null; //: allowed (int[] is reference type)
int hayno = null; //: error (int is primitive type)
//: Message: incompatible types:
//: <null> cannot be converted to int
As #Glen mentioned in a comment, you basically have two ways around this:
use an "out of bound" value. For instance, if "data" can never be negative in normal use, return a negative value to indicate it's invalid.
Use an Integer. Just make sure the "check" method returns an Integer, and you assign it to an Integer not an int. Because if an "int" gets involved along the way, the automatic boxing and unboxing can cause problems.
Check for null in your check() method and return an invalid value such as -1 or zero if null. Then the check would be for that value rather than passing the null along. This would be a normal thing to do in old time 'C'.
Any Primitive data type like int,boolean, or float etc can't store the null(lateral),since java has provided Wrapper class for storing the same like int to Integer,boolean to Boolean.
Eg: Integer i=null;
An int is not null, it may be 0 if not initialized. If you want an integer to be able to be null, you need to use Integer instead of int . primitives don't have null value. default have for an int is 0.
Data Type / Default Value (for fields)
int ------------------ 0
long ---------------- 0L
float ---------------- 0.0f
double ------------- 0.0d
char --------------- '\u0000'
String --------------- null
boolean ------------ false
Since you ask for another way to accomplish your goal, I suggest you use a wrapper class:
new Integer(null);
I'm no expert, but I do believe that the null equivalent for an int is 0.
For example, if you make an int[], each slot contains 0 as opposed to null, unless you set it to something else.
In some situations, this may be of use.

Why does this print exception?

String bob2 = "3";
System.out.println((int)bob2);
I'm unsure of why this causes an exception. Can anyone explain? Pretty sure because of the int on String type, but want to make sure.
Yes you are right its because of typecasting. If u need to convert String to int use below code
Integer.parseInt("3");
You are correct.
You can't just cast a string to an int.
You should convert it using Integer.parseInt()
Use this
Integer.valueOf("3");
or
Integer.parseInt("3");
In Java whenever you are trying to change type of an entity to another, both the types should have some relation. Like if you are trying to caste a sub class object to super class, it will work smoothly. But if you try to compare a Person object with a Lion object, that comparison is meaning less, the same is the logic in casting. We cannot cast a Person object to Lion object.
In your code bob is String type and you are trying to cast it to int and in Java both String and Integer is not having any relation. That's why Java is throwing Exception, Class Cast Exception I guess, this is raised when different types of objects are compared.
But the parseInt(String arg) method in Integer class gives an option to convert numeric String to Integer, given that the argument is a qualified Integer as per Java standards.
Example :-
String numericString = "1234";
int numberConverted = Integer.parseInt(numericString);
System.out.println(numberConverted);
You can also try these which will tell you the precautions before using this method
int numberConverted = Integer.parseInt("1234r");
int numberConverted = Integer.parseInt("1234.56");
int numberConverted = Integer.parseInt("11111111111111111111111111111");
You can't cast String to Integer. Change:
System.out.println((int)bob2);
to:
System.out.println(Integer.parseInt(bob2));
It will create an Integer value from the String provided with bob2 variable. You can also create a reference to int variable like this if you want to store primitive int instead of Integer:
int intBob2 = Integer.parseInt(bob2);

convert Integer to int

I have an Integer value of variable as below:
Integer programNumber= ........
I took the program number as Integer type. However in my other class, I want to check whether this variable, programNumber, equals variable which is the type of int.
To sum up, I want to convert the variable of the of Integer to int primitive value.
I used programno.intValue() but it doesn't work.
Thanks in advance.
I have a two class, BasvuruKisi and Program. the code snippet is below:
BasvuruKisi bsvkisi = (BasvuruKisi) (this.getHibernateTemplate().find("from BasvuruKisi bsv where bsv.basvuruNo=?", basvuruNumaralari.get(i))).get(0);
if (bsvkisi != null) {
int yetkiVarmi = 0;
Integer programno= bsvkisi.getProgramId();
List array =
this.getHibernateTemplate().find("from Program p where p.id=?", programno.intValue());
but
this.getHibernateTemplate().find("from Program p where p.id=?", programno.intValue());
this one doesn't work. return firstly, no table or view is available despite available and then returns null pointer exception.
thanks
The variable name in the initialization block says programNumber, but the variable in the method call is programno. Which is it?
Using the wrong variable name shouldn't give you a null pointer exception, unless you have another variable named programno defined somewhere.
Whatever the variable name is, make sure you initialize it before you get the intValue.
Validate programNumber is null or not?
If the value is null, it throws Exception.
Integer programNumber= null;
System.out.println(programNumber.intValue());

Initialising instance variables as null, "" or 0

When initialising variables with default values:
What is the difference between:
private static String thing = null;
and
private static String thing = "";
I'm not understanding which is better and why nor what is the best way to deal with other data types.
private static int number = 0;
private static double number = 0;
private static char thing = 0;
Sorry I struggle learning new languages.
Except for initializing String to an empty string
private static String thing = "";
the other assignments are unnecessary: Java will set all member variables of primitive types to their default values, and all reference types (including java.String) to null.
The decision to initialize a String to a null or to an empty string is up to you: there is a difference between "nothing" and "empty string" *, so you have to decide which one you want.
* The differences between "nothing" and "empty string" stem from the observation that no operations are possible on a null string - for example, its length is undefined, and you cannot iterate over its characters. In contrast, the length of an empty string is well-defined (zero), and you can iterate over its characters (it's an empty iteration).
When you make:
private static String ptNo = "";
you are creating a variable ptNo and making it to refer an object String "".
When you make:
private static String ptNo = null;
you are creating a variable, but it doesn't refer to anything.
null is the reserved constant used in Java to represent a void reference i.e a pointer to nothing.
In Java null and an empty are not the same thing.
From suns java tutorial
It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type. Relying on such default values, however, is generally considered bad programming style.
The following chart summarizes the default values for the above data types.
Data Type Default Value (for fields)
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
String (or any object) null
boolean false
Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it
is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.
"" is an actual string with empty value.
null means that the String variable points to nothing.
As an example,
String a="";
String b=null;
a.equals(b) returns false because "" and null do not occupy the same space in memory.

Type casting the `Object` type variables

I need to call a function with the following signature.
createColumn (N name, V value, Serializer<N> nameSerializer, Serializer<V> valueSerializer)
I want to pass variables of type Object which might have been assigned values of integer or string, I want the type casting to be performed automatically..according to the values that I assigned to Object type variables instead of explicit cast like this:-
Object object1= "MY_AGE";
// string value assigned to to object type variable
Object object2= 31; // integer value assigned to object type variable
createColumn ((String)object1, (int)object2, ....); // Since the datatype of object1 & object2 would not be same everytime while I am calling this function in a for loop, I want that it should automatically cast according to the value I assign to it.* So I am seeking something like this, if possible:-
createColumn (object1, object2, ....);
You can call the following since you don't want to check at compile time that the types match,
createColumn(object1, object2, (Serializer)serializer1, (Serializer)serializer2);
EDIT: This compiles for me (with an "Unchecked" warning)
interface Serializer<T> { }
public static <N,V> void createColumn (N name, V value, Serializer<N> nameSerializer, Serializer<V> valueSerializer) {
}
public static void main(String[] args) throws NoSuchFieldException {
Object object1 = "hi";
Object object2 = 31;
Serializer<String> serializer1 = null;
Serializer<Integer> serializer2 = null;
createColumn(object1, object2, (Serializer) serializer1, (Serializer) serializer2);
}
As I understand your question is not about casting (which deals with compile-time declared types), but conversion (which deals with runtime type of objects).
Consider using String.valueOf() method for your Object arguments. For both Integer and String it will produce their String representation.
I don't think it is possible, you have given the variable a type object and i'm not aware of any way to determine if it is really an int or string unless you use some ugly logic to see what characters the value consists of but that isn't going to be fool proof unless the value will always be either an integer or a string.
Do you need to pass integers or can everything just be passed as a string?

Categories