I have a class as below, before I set the data I need to check whether getValue() is present and it's value is empty.
public class Money {
{
private String value;
private String currency;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getCurrency() {
return currency;
public void setCurrency(String currency) {
this.currency = currency;
}
}
//JSON is like this
"money": {
"currency": "USD",
"value": ""
}
I want to check whether this getValue() is present or not like obj.getMoney().getValue() != null,
and then I need to check it's value is empty... obj.getMoney().getValue().equals("") but it fails on this condition obj.getMoney().getValue() != null as null.
If the following check fails
if (obj.getMoney().getValue() != null) { ... }
then it implies that the money object itself is null. In this case, you can slightly modify your if condition to check for this:
if (obj.getMoney() != null && obj.getMoney().getValue() != null) { ... }
You said that first you need to check whether value is null or not and then also check whether the value is empty or not,
You can do the following
if (obj.getMoney() != null && obj.getMoney().getValue() != null && !obj.getMoney().getValue().isEmpty()) {
// rest of the code here
}
obj.getMoney().getValue() will give you null pointer exception. You should check for null object before using . after it. Example code:
Below code looks huge but it's actually readable and it will be optimized by compiler.
if(obj != null){
Money money = obj.getMoney();
if(money != null) {
String value = money.getValue();
//Add you logic here...
}
}
I think you are getting null point exception. You are facing this exception because obj.getMoney() is already null. Since you are trying to get a null object's value, so you are getting this exception. Correct code will be
if ((obj.getMoney() != null) && (obj.getMoney().getValue().trim().length() > 0)) {
// Execute your code here
}
When instantiating your obj, gives a new. The form of validation is correct, the problem is in the obj that was not initialized. (I believe)
Related
In the Commercial Paper example of Hyperledger Fabric, there is a StateListImpl class that implement getState like this:
#Override
public State getState(String key) {
CompositeKey ledgerKey = this.ctx.getStub().createCompositeKey(this.name, State.splitKey(key));
byte[] data = this.ctx.getStub().getState(ledgerKey.toString());
if (data != null) {
State state = this.deserializer.deserialize(data);
return state;
} else {
return null;
}
}
But, when I call this StateListImpl.getState function with a Key that doesn't exists, the condition data != null its true (and an exception is ocurring inside deserializer), so it seems that ctx.stub.getState(ledgerKey) is not returning null. I've searched in fabric documentation (and in its javadocs) and doesn't say anything about what happens when key isn't in the ledger.
Well, what returns ctx.stub.getState(KEY) if KEY state is not in the ledger?
In Java is not enough checking for null, you have to check also for the length of the byte array, I'm using the following code:
final String data = stub.getStringState(id);
if (StringUtils.isEmpty(data)) {
throw new RuntimeException(
String.format("The item %s doesn't exist", id)
);
}
If we look closer at StringUtils.isEmpty it checks for the length
public static boolean isEmpty(CharSequence cs) {
return cs == null || cs.length() == 0;
}
It is because the getState does not return a null value. Instead, it returns an object that is 'undefined'.
So if you change your code to getState(key)===undefined then it should work fine.
I have a POJO looking like this:
public class Pojo implements Comparable<Pojo> {
private String type;
private String journalId;
private Date bookingDate;
private Long account;
private String description;
private BigDecimal debit;
private BigDecimal credit;
....
}
and I want to sort a list of these POJOs. Currently my compareTo method looks like this:
#Override
public int compareTo(EfdisJournal other) {
int i = this.type.compareTo(other.type);
if (i != 0)
return i;
if (this.bookingDate != null && other.bookingDate != null)
i = this.bookingDate.compareTo(other.bookingDate);
if (i != 0)
return i;
if (this.journalId != null && other.journalId != null)
i = this.journalId.compareTo(other.journalId);
if (i != 0)
return i;
return this.account.compareTo(other.account);
}
If I run a sort with this compareTo method, I get this java.lang.IllegalArgumentException: Comparison method violates its general contract error. I did google a bit and I think it happens because some of the fields are null on comparison. Yet I have no idea how to solve this or if I am right why that error appears.
The comparison should work like this: 1st compare by type, then compare by bookingDate, as 3rd compare by journalId and at last compare by account. All comparisons should be ascending.
type is never null
bookingDate may be null
journalId may be null
account is never null
EDIT:
Sadly I was not able to implement the method, so that the order is as needed. Yet, i solved the problem I had, because the stored procedure yielded 2 resultsets, of which the second was order as needed, so the only thing I had to do was to use the 2nd resultset instead of the first.
You need to deal with the case where one instance has a null bookingDate, and the other has a non-null bookingDate.
You should decide whether things with null bookingDate should be sorted before or after things with a non-null bookingDate, and write your compareTo appropriately. (And then journalId too.) Then you can get an order that sorts consistently.
For instance:
#Override
public int compareTo(EfdisJournal other) {
int i = this.type.compareTo(other.type);
if (i != 0) {
return i;
}
if ((this.bookingDate==null) ^ (other.bookingDate==null)) {
return (this.bookingDate==null ? -1 : 1);
}
if (this.bookingDate != null && other.bookingDate != null) {
i = this.bookingDate.compareTo(other.bookingDate);
}
if (i != 0) {
return i;
}
if ((this.journalId==null) ^ (other.journalId==null)) {
return (this.journalId==null ? -1 : 1);
}
if (this.journalId != null && other.journalId != null) {
i = this.journalId.compareTo(other.journalId);
}
if (i != 0) {
return i;
}
return this.account.compareTo(other.account);
}
You're ignoring situations where bookingDate and/or journalId is null with one and non-null with the other.
I am trying to validate some input from a Swing form by checking for null values. However the checkFirstName method is always returning true. So for example if i leave the firstname blank on the form it will return true even though the field is null.
Here is my two methods, the first one is fired when the user clicks the save button.
public void saveNewCustomer() throws SQLException, ClassNotFoundException {
boolean dbOK = false;//boolean to check if data input is not null
System.out.println(dbOK);
String firstName = txtNCustomerFirstName.getText();
String lastName = txtNCustomerLastName.getText();
if (checkFirstName(firstName)) {
dbOK = true;
} else {
lblNCustFirstNameError.setText("First Name Must be Entered");
dbOK = false;
}
System.out.println(dbOK);
if (dbOK) {
dbConnector.insertSignup(firstName, lastName);
System.out.println("Success");
} else {
System.out.println("Error");
}
}
public boolean checkFirstName(String firstName) {
boolean allOK = false;
System.out.println(allOK);
if (firstName != null) {
allOK = true;
} else {
allOK = false;
}
return allOK;
}
Have i done something wrong cause this to me should be return false cause the firstname field is null.
The String will never be null, the String will be empty. Check firstName.isEmpty(). Still I suggest you keep the check for null too:
public boolean checkFirstName(String firstName) {
boolean allOK = false;
System.out.println(allOK);
if (firstName != null && !firstName.isEmpty()) {
allOK = true;
} else {
allOK = false;
}
return allOK;
}
EDIT: as pointed out by Windle you probably would like to check if the String has at least one non-whitespace:
if (firstName != null && !firstName.trim().isEmpty())
Also you may perform more complex verification - for instance if you want to make sure there are no whitespaces in the username after you trim it.
So for example if i leave the firstname blank on the form
You are just checking for null, you need to do empty ("") String check also.
It should be something like:
if (firstName != null && !"".equals(firstName.trim()) {
The txtNCustomerFirstName.getText method is returning an empty string. You might change your checkFirstName method's if statement to check for an empty string:
if (firstName != null && !firstName.isEmpty()) {
If you don't have Java 6+, you can use firstName.length() > 0 instead of isEmpty.
As far as I'm aware, the getText() method you're calling in the saveNewCustomer() will return an empty string rather than null.
So for example if i leave the firstname blank on the form it will
return true even though the field is null.
This is where your reasoning is wrong. When you leave a text field blank, getText() returns an empty string i.e. "" which is not null. You should check for emptiness instead of null.
if (!firstName.isEmpty()) { ... }
If firstName may also be null (e.g. when it comes from another source), you should check that beforehand:
if (firstName != null && !firstName.isEmpty()) { ... }
As other answers have suggested do a null check with an empty string check. I'd say trim the leading and trailing whitespaces also before doing an empty check because in reality you want to avoid such situation.
if (firstName != null && !firstName.trim().isEmpty()) { ... }
I have a simple dataset class similar to:
class DataSet {
private String value;
private String additionalValue;
public DataSet(String value, String additionalValue) {
this.value = value;
this.additionalValue = additionalValue;
}
public String getAdditionalValue() {
return this.additionalValue;
}
}
Then I have created an ArrayList<DataSet> and added a new element DataSet("Value1", null).
Now at some point I need to check if the entry with value "Value1" has additionalValue and if it does, what it is.
I do a simple loop checking if value.equals("Value1") == true, then I do:
if (element.getAdditionalValue() != null) {
return element.getAdditionalValue();
}
However, as soon as it gets to the if statement, it throws an error saying that the value is null.
How can I make it so that it doesn't throw an error and just skips the return statement if additionalValue is null?
EDIT:
But the thing is that the element cannot be null at the point where it checks additionalValue as it passed through the element.getValue.equals("Value1") condition.
for (DataSet element : dataSet) {
if (element.getValue.equals("Value1")) {
if (element.getAdditionalValue() != null) {
return element.getAdditionalValue();
}
}
}
I think the problem is that your element object is null, so you have to check it before checking additionalValue.
if (element != null && element.getAdditionalValue() != null){
return element.getAdditionalValue();
}
This will sort you out:
if (element != null && element.getAdditionalValue() != null) {
return element.getAdditionalValue();
}
Is it possible to nest more than 5 'Conditional Operators' in Java. I ask because it seems that I cause a compiler exception when I try to compile this code:
public Object getValue() {
return
number != null ? number :
string != null ? string :
bool != null ? bool :
date != null ? date :
list != null ? list :
null;
}
I have narrowed it down to this code because if I comment out the last line it seems to compile fine.
public Object getValue() {
return
number != null ? number :
string != null ? string :
bool != null ? bool :
date != null ? date :
// list != null ? list :
null;
}
Does anybody else know if this is a limitation of the java compiler or am I jumping to false conclusions, it would be great if someone else could try to reproduce this. If anybody is interested I have reproduced and posted the Stack Trace from the compiler here https://gist.github.com/919284.
Note that it is very likely a bug in the compiler not my code, as the output said "Please File a Bug at Java Developer Connect site" (or something similar). I am asking here because I am not sure what that bug report would contain.
EDIT:
Chris L has reproduced this, see his answer
I reproduced your error (using Sun JDK 1.6.0_24 on Mac). I simplified your class a little bit to:
import java.util.ArrayList;
import java.util.Date;
public class Test3 {
private Number number;
private String string;
private Boolean bool; // Replace Boolean with Object, and it compiles!
private Date date;
private ArrayList<String> list; // Replace ArrayList with List, and it
// compiles!
public Object getValue() {
return number != null ? number :
string != null ? string :
bool != null ? bool :
date != null ? date :
list != null ? list :
null;
}
}
My stack trace is basically the same as yours. (It has nothing to do with GWT, by the way.)
An exception has occurred in the compiler (1.6.0_24). Please file a bug at the Java Developer Connection (http://java.sun.com/webapps/bugreport) after checking the Bug Parade for duplicates. Include your program and the following diagnostic in your report. Thank you.
java.lang.AssertionError
at com.sun.tools.javac.jvm.Code$State.forceStackTop(Code.java:1688)
at com.sun.tools.javac.jvm.Gen.visitConditional(Gen.java:1679)
at com.sun.tools.javac.tree.JCTree$JCConditional.accept(JCTree.java:1021)
at com.sun.tools.javac.jvm.Gen.genExpr(Gen.java:818)
at com.sun.tools.javac.jvm.Gen.visitConditional(Gen.java:1678)
at com.sun.tools.javac.tree.JCTree$JCConditional.accept(JCTree.java:1021)
at com.sun.tools.javac.jvm.Gen.genExpr(Gen.java:818)
at com.sun.tools.javac.jvm.Gen.visitConditional(Gen.java:1678)
at com.sun.tools.javac.tree.JCTree$JCConditional.accept(JCTree.java:1021)
at com.sun.tools.javac.jvm.Gen.genExpr(Gen.java:818)
at com.sun.tools.javac.jvm.Gen.visitReturn(Gen.java:1626)
at com.sun.tools.javac.tree.JCTree$JCReturn.accept(JCTree.java:1138)
at com.sun.tools.javac.jvm.Gen.genDef(Gen.java:665)
at com.sun.tools.javac.jvm.Gen.genStat(Gen.java:700)
at com.sun.tools.javac.jvm.Gen.genStat(Gen.java:686)
at com.sun.tools.javac.jvm.Gen.genStats(Gen.java:737)
at com.sun.tools.javac.jvm.Gen.visitBlock(Gen.java:1013)
at com.sun.tools.javac.tree.JCTree$JCBlock.accept(JCTree.java:739)
at com.sun.tools.javac.jvm.Gen.genDef(Gen.java:665)
at com.sun.tools.javac.jvm.Gen.genStat(Gen.java:700)
at com.sun.tools.javac.jvm.Gen.genMethod(Gen.java:893)
at com.sun.tools.javac.jvm.Gen.visitMethodDef(Gen.java:866)
at com.sun.tools.javac.tree.JCTree$JCMethodDecl.accept(JCTree.java:639)
at com.sun.tools.javac.jvm.Gen.genDef(Gen.java:665)
at com.sun.tools.javac.jvm.Gen.genClass(Gen.java:2198)
at com.sun.tools.javac.main.JavaCompiler.genCode(JavaCompiler.java:617)
at com.sun.tools.javac.main.JavaCompiler.generate(JavaCompiler.java:1289)
at com.sun.tools.javac.main.JavaCompiler.generate(JavaCompiler.java:1259)
at com.sun.tools.javac.main.JavaCompiler.compile2(JavaCompiler.java:765)
at com.sun.tools.javac.main.JavaCompiler.compile(JavaCompiler.java:730)
at com.sun.tools.javac.main.Main.compile(Main.java:353)
at com.sun.tools.javac.main.Main.compile(Main.java:279)
at com.sun.tools.javac.main.Main.compile(Main.java:270)
at com.sun.tools.javac.Main.compile(Main.java:69)
at com.sun.tools.javac.Main.main(Main.java:54)
I can only confirm that this compiles without error for me in both eclipse 3.5 and javac 1.6.0_u24:
public class Test {
Object number=null, string=null, bool=null, date=null, list=null;
public Object getValue() {
return
number != null ? number :
string != null ? string :
bool != null ? bool :
date != null ? date :
list != null ? list :
null;
}
}
This compiles fine on ideone:
public static void main (String[] args) throws java.lang.Exception
{
Object number = null;
Object string = null;
Object list = null;
Object bool = null;
Object date = null;
Object o =
number != null ? number :
string != null ? string :
bool != null ? bool :
date != null ? date :
list != null ? list :
null;
}
Double check that list is declared in a way that it is accessible inside the method.
May be a bug in your java compiler. I suggest you update your java to the latest and greatest (if there is one) and reproduce. You can install as many different versions of Java as you like.
I don't think there is a limitation while it is syntactically correct. I would guess the java compiler just will expand its parse tree like for a deep if/else if - nesting.
There is no limit as low as this. A method must compile to less than 64KB of byte code.
I compiled your example fine. Is there any reason you don't have just one field?
EDIT: Added setters to check valid types.
public class Holder implements Serializable {
Serializable value;
public void setValue(Number value) {
this.value = value;
}
public void setValue(String value) {
this.value = value;
}
public void setValue(Boolean value) {
this.value = value;
}
public void setValue(Date value) {
this.value = value;
}
public <L extends List & Serializable> void setValue(L value) {
this.value = value;
}
public Serializable getValue() {
return value;
}
}
I know this is an old post, but my recent experiance might shed some light on the subject for those of you who are interested. It's something to be aware of.
Basically, I "broke" some existing code by implementing Comparable in one of my other classes. Here's a stripped down version that generates the same "An exception has occurred in the compiler..."
If there are fewer than 5 expressions in the nested conditional, or if the USDollars class does not implement Comparable this code compiles.
public class TestHit
{
protected final String fSymbol;
protected final long fTime;
protected final USDollars fBasePrice;
public TestHit(String aSymbol, long aTime, int aBasePrice)
{
fSymbol = aSymbol;
fTime = aTime;
fBasePrice = new USDollars(aBasePrice);
}
public Object field(int aIndex)
{
return (aIndex == 0)? fSymbol
: (aIndex == 1)? fTime
: (aIndex == 2)? fBasePrice
: (aIndex == 3)? new Integer(4) // comment out this line and it compiles
: "?";
}
}
final class USDollars
implements Comparable<USDollars> // comment out this line and it compiles
{
private int cents;
public USDollars() { this(0); }
public USDollars(int cents) { this.cents = cents; }
public USDollars(int dollars, int cents) { this(cents + 100*dollars); }
public int cents() { return cents; }
// #Override
public int compareTo(USDollars other) { return this.cents - other.cents; }
}
By the way, a quick fix was to modify the code as follows (ugly but it works):
public Object field(int aIndex)
{
if (aIndex == 2)
return fBasePrice;
return (aIndex == 0)? fSymbol
: (aIndex == 1)? fTime
: (aIndex == 3)? new Integer(4) // comment out this line and it compiles
: "?";
}