Removing a default Double or int - java

Hello I'm after a cleaner implementation of how to check for a defaulted doubled value such as -1.0
My implementation for strings is:
private static String stringNullChecker(String o)
{
if(o == null || o.equals("?") || o.equals(""))
{
return null;
}
else
{
return o;
}
}
so I can just call it as follows:
obj.setExDestination(stringNullChecker(wrapperObj.getExchange()));
However if I try the same with doubles it will throw a null pointer error.
so the implementation is currently:
if(doubleNullChecker(wrapperObj.getPrcCcy()) != null)
{
obj.setSettlCurrFxRate(wrapperObj.getPrcCcy());
}
But I'm having to do this If statement for every double/int value. Which is a lot of repeated code, I'd like something to push this out into it's own atomic function but other than a Boolean I'm at a loss as what would be nice clean code.
Basically I only want to set the value if it has a non default value.

Primitive double
double as a primitive type cannot hold null value. It only can hold -1.0, 0.0, or even NaN (a special float value, but I'm not very sure of it's behaviour).
So you cannot check if a primitive double variable is null.
Anyway you can do this:
public static double notNaN(double value, double defaultValue) {
return Double.isNaN(value)? defaultValue: value;
}
In case of a java.lang.Double
If your properties are Double (it is... object representation of double) it can be null. Just in this case you can make a defaultValue checker method.
public static double notNull(Double doubleObj, double defaultValue) {
return doubleObj == null? defaultValue: doubleObj.doubleValue();
}
// use this way (getPropertyDouble() returns a java.lang.Double)
notNull(myObj.getPropertyDouble(), -1.0);
Your check
If if(o == null) works it's because Java converts your o primitive double to java.lang.Double and makes an object comparison (check if this autoboxed double is null... but a boxed primitive value always is an existent object).
Checking values for objects
If you have a Double object and want to check it's value I should recommend:
doubleObj.equals(Double.valueOf(1.0D));
It is:
use equals for comparison: you don't want to compare object references but values inside the object.
compare against another Double object: that's why I wrote Double.valueOf(1.0D), to box the value explicitly.
Setting the property
Unluckily in Java there's no simple way of passing a method A by reference to another method B, in order to B executes A if some condition mets. You can use reflection but it's overkill I think. And there's no much sense to use some templating mechanism if what you want to do is reducing your code.
So... What I come up with is simply:
resetting the same value
setting a default known value
In the first case -"let the value as is"- you can do:
obj.setProperty(notNull(objWrapper.getProperty(), obj.getProperty()));
In this code you always set the value. If objWrapper has a null value (or whatever you check) the value to set to obj will be its own current value.
In the second case -"if not setted use a default"- you can do:
obj.setProperty(notNull(objWrapper.getProperty(), HERE_GOES_YOUR_DEFAULT_VALUE));
Keep in mind that if your obj.setProperty is an object you can use null, otherwise you are forced to some constant value.

Related

How to check if an int is a null

I have an object called Person.
it has several attributes in it;
int id;
String name;
i set a person object like Person p = new Person(1,"Joe");.
1.) I need to check if the object is not null; Is the following expression correct;
if (person == null){
}
Or
if(person.equals(null))
2.) I need to know if the ID contains an Int.
if(person.getId()==null){}
But, java doesn't allow it. How can i do this check ?
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.
Integer id;
String name;
public Integer getId() { return id; }
Besides, the statement if(person.equals(null)) can't be true because if person is null, then a NullPointerException will be thrown. So the correct expression is if (person == null)
primitives dont have null value. default have for an int is 0.
if(person.getId()==0){}
Default values for primitives in java:
Data Type Default Value (for fields)
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
boolean false
Objects have null as default value.
String (or any object)--->null
1.) I need to check if the object is not null; Is the following expression correct;
if (person == null){
}
the above piece of code checks if person is null. you need to do
if (person != null){ // checks if person is not null
}
and
if(person.equals(null))
The above code would throw NullPointerException when person is null.
A primitive int cannot be null. If you need null, use Integer instead.
1.) I need to check if the object is not null; Is the following expression correct;
if (person == null){
}
YES. This is how you check if object is null.
2.) I need to know if the ID contains an Int.
if(person.getId()==null){}
NO Since id is defined as primitive int, it will be default initialized with 0 and it will never be null. There is no need to check primitive types, if they are null. They will never be null. If you want, you can compare against the default value 0 as if(person.getId()==0){}.
Compiler won't let you assing value of int to null. It won't run.
So we could say it is already partly solved for you.
You have to access to your class atributes.
To access to it atributes, you have to do:
person.id
person.name
where
person
is an instance of your class Person.
This can be done if the attibutes can be accessed, if not, you must use setters and getters...
In Java there isn't Null values for primitive Data types.
If you need to check Null use Integer Class instead of primitive type. You don't need to worry about data type difference. Java converts int primitive type data to Integer.
When concerning about the memory Integer takes more memory than int. But the difference of memory allocation, nothing to be considered.
In this case you must use Inter instead of int
Try below snippet and see example for more info,
Integer id;
String name;
//Refer this example
Integer val = 0;
`
if (val != null){
System.out.println("value is not null");
}
`
Also you can assign Null as below,
val = null;
You can use
if (person == null || String.valueOf(person.getId() == null))
in addition to regular approach
person.getId() == 0

Changing boolean value in class function in java

Can we modify a Boolean value in class function in java, something like this wont work as the change is local to function. How can we make the following change passed variable reflect outside the method call?
public void changeboolean(Boolean b)
{
if( somecondition )
{
b=true;
}
else
{
b=false;
}
}
EDIT
The code could be like this:
public String changeboolean(Boolean b,int show)
{
if( somecondition )
{
b=true;
show=1;
return "verify again";
}
else
{
b=false;
show=2;
return "Logout";
}
show=3;
return verifed;
}
I'm searching for something like this
b.setvalue(true);
Is it possible?
Can we modify a Boolean value in class function in java
No, Boolean is immutable, like all the wrappers for the primitive types.
Options:
Return a boolean from your method (best choice)
Create a mutable equivalent of Boolean which allows you to set the embedded value. You would then need to modify the value within the instance that the parameter refers to - changing the value of the parameter to refer to a different instance wouldn't help you, because arguments are always passed by value in Java. That value is either a primitive value or a reference, but it's still passed by value. Changing the value of a parameter never changes the caller's variable.
Use a boolean[] with a single element as the wrapper type
Use AtomicBoolean as the wrapper type
Boolean is immutable, like all the wrappers for the primitive types.
Soln:
Trying using MutableBoolean of apacheCommon
http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/mutable/MutableBoolean.html

The equals() method in Java works unexpectedly on Long data type

Let's first consider the following expressions in Java.
Integer temp = new Integer(1);
System.out.println(temp.equals(1));
if(temp.equals(1))
{
System.out.println("The if block executed.");
}
These all statements work just fine. There is no question about it. The expression temp.equals(1) is evaluated to true as expected and the only statement within the if block is executed consequently.
Now, when I change the data type from Integer to Long, the statement temp1.equals(1) is unexpectedly evaluated to false as follows.
Long temp1 = new Long(1);
System.out.println(temp1.equals(1));
if(temp1.equals(1))
{
System.out.println("The if block executed.");
}
These are the equivalent statements to those mentioned in the preceding snippet just the data type has been changed and they behave exactly opposite.
The expression temp1.equals(1) is evaluated to false and consequently, the only statement within the if block is not executed which the reverse of the preceding statements. How?
You're comparing a Long to an int. The javadoc for java.lang.Long#equals says that the equals method
Compares this object to the specified object. The result is true if and only if the argument is not null and is a Long object that contains the same long value as this object.
Instead try System.out.println(new Long(1).equals(1L)); Now that you're comparing a Long to a Long instead of a Long to an Integer, it will print true.
The reason you can do that comparison is because of autoboxing in Java.
The actual method you are calling is this:
http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Long.html#equals(java.lang.Object)
which is comparing your Long object to some other Object, not to an actual primitive int.
What happens when you call the method is that your primitive integer(1) is being autoboxed into an Object(Integer) so then you are effectively calling:
new Long(1).equals(new Integer(1));
which is why it fails.
This is why if you call
new Long(1).equals(1L)
this would work, because Java will autobox the 1L (primitive long, not int) into a Long object, not an Integer object.
The literal value 1 is not a long, it's an int. Try the above code with this instead:
System.out.println(temp1.equals(1L));
And
if (temp1.equals(1L))
As you can see, putting an L after the literal value 1 indicates that it's a long, and then the comparisons work as expected.
Java is being lazy.
When you perform the following comparison java will automatically cast the int to a long (as a long can contain any value an int can contain). And the comparison is between two longs and not two ints.
int i = 1;
long l = 1L;
boolean b = i == l;
Java is able to do this because the type information about i and l is known at compile time and when performing the comparison. However, when you use the boxed version the type can be known at compile time, but not when performing the comparison. This is because the comparison has to done within an equals method, and since equals takes Object as a parameter the type information is lost. Thus Java is lazy and only checks to see if two boxed numbers are equal if they are both of instances of same Number class (eg. both Integer, or both Long, or both Double, etc...).
Turns out the only fully reliable way to compare two numbers of unknown type at runtime is to convert both to strings and both to BigDecimal and then to use the method compareTo (and not equals). Though if you know you are only ever going to get longs and ints then life is simpler as you can just do the following.
Number n0 = new Long(1L);
Number n1 = new Integer(1);
boolean equal = n0.longValue() == n1.longValue();
According to Javadoc's page on Long, the .equals method evaluates to true only if
The argument is a Long object
If (1) is true, then the Long objects must have equal values
In your scenario, 1 is an int, not a Long object, so it fails (1), and therefore, evaluates to false. If you need to test to a long, use 1L instead.
That behaviour is consistent with autoboxing converting the 1 to an Integer which then compares equal to another Integer(1). Comparing a Long to an Integer yields false.
If you would use 1L to compare against Long it would yield true.
Long temp1 = new Long(1); System.out.println(temp1.equals(1));
if(temp1.equals(1)) {
System.out.println("The if block executed."); }
in this code temp1.equals(1) is comparing a Long object to Integer object which gives the result false ,we can correct it by using 1L instead of 1 ,,,eg temp1.equals(1L), by doing this we are comparing Long object with a Long and gives result TRUE
The implementation of equals() method of class Long illustrates why:
public boolean equals(Object obj) {
if (obj instanceof Long) {
return value == ((Long)obj).longValue();
}
return false;
}
The equals method in Java.lang.Long initially starts with an instanceOf Long check only after that the value is compared.
public boolean equals(Object obj) {
if (obj instanceof Long) {
return value == ((Long)obj).longValue();
}
return false;
}
So if you are going to use and Integer Value int the place of a Long value then the first check fails and hence you will get false as the result .
You can compare Long/integer values without uting equals(). This is only needed when you are comparing strings as far as I know.

Can't check if int is null

I'm trying to use a dictionary. Whenever I want to check if an element is present in the dictionary, I do this:
int value = results.get("aKeyThatMayOrMayNotBePresent");
if (value != null)
// ...
But then the compiler says I can't compare an int to a <nulltype>. What's the correct way to check for null in this case?
You're comparing a primitive value (int) to null. Since primitives cannot be null, you should use a corresponding object, such as Integer in this case. So, you should write
Integer value = results.get("aKeyThatMayOrMayNotBePresent");
Your null check is too late.
int value = results.get("aKeyThatMayOrMayNotBePresent");
This line already converts the reference to a primitive int. It will throw a NullPointerException if the return value of get is null.
The correct way would be to use Integer instead of int.
Integer value = results.get("aKeyThatMayOrMayNotBePresent");
This way value wont be a primitive type and your null check is valid.
int is a primitive type; you can compare a java.lang.Integer to null.
You should use Map instead of Dictionary, Dictionary is obsolete.
With Map you can use containsKey() instead, which in my opinion is more readable:
if (results.containsKey(key))
{
int value = results.get(key);
[...]
}
In my experience this is not slower than your approach, despite the apparent double access to the map. If this is executed often enough for performance to matter then it is optimized away.
Get the Object and check if that is null.
Object valueObj = results.get("...");
if ( valueObj != null )
{
Integer value = (Integer)valueObj;
}

Can an int be null in Java?

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.

Categories

Resources