I need the String receive the null value if it is not found in mapper.getChave is what is returned. What I do? If I only get nullPointerException
for(String chave : linha.keySet()) {
//Processa chave
String novaChave = mapper.getChave(chave.trim());
if (!(novaChave == null || novaChave.isEmpty())) {
//Processa valor
String novoValor = linha.getString(chave);
temp.append(novaChave, novoValor);
}
else {
extras.append(chave, linha.getString(chave));
}
}
Log
java.lang.NullPointerException
at oknok.validacao.readers.PlanilhaReader.processaAtributosPlanilha(PlanilhaReader.java:237)
Line 237 is
String novaChave = mapper.getChave(chave.trim());
**UPDATE: The first time the loop runs, i have a Nullpointer and chave contains a value
System.out.println(chave.isEmpty() + "\t" + chave + "\t" + chave.trim());
Output
false Veículo Veículo
You need to add null check for mapper as well as chave.
if (mapper!= null && chave != null && !"".equals(chave) {
// do something
}
mapper.getChave(chave.trim())
^ ^ possible places for NPE.
Most probably value of chave or mapper would be null and you are calling trim() and .getChave() on them respectively causing nullpointer
You need to check whether chave is null before trimming it or doing anything else (I'm assuming that mapper is pre-initialised and not null, but you should check that too)
e.g.
if (chave != null && !"".equals(chave.trim()) {
// now do something
}
You may find it easier (more intuitive) to use something like Apache Commons StringUtils.isNotBlank(String). See here for the doc.
There is a null string reference in linha.keySet().
Follow code change null string to "" : you can change "" to anything you like
String novaChave = mapper.getChave((chave == null ? "" : chave).trim());
Related
Spring Street, 101/12
Postal Code: 8001
State: Washington
How can I separate line by line as in the example above?
address.setAddress(MessageFormat.format(
"{0} {1} Postal Code: {2}, State: {3}",restSmeApplication.getAddress(),restSmeApplication.getStreet() != null ? restSmeApplication.getStreet(): "",restSmeApplication.getPostalCode(),restSmeApplication.getState() != null ? restSmeApplication.getStreet(): "")
);
\n will work for you -
address.setAddress(MessageFormat.format(
"{0} \n {1} Postal Code: {2}, \n State: {3}",restSmeApplication.getAddress(),restSmeApplication.getStreet() != null ? restSmeApplication.getStreet(): "",restSmeApplication.getPostalCode(),restSmeApplication.getState() != null ? restSmeApplication.getStreet(): "")
);
This may help.
address.setAddress(String.format(
"%s %s \n Postal Code: %s,\n State: %s",
restSmeApplication.getAddress(),restSmeApplication.getStreet() != null ? restSmeApplication.getStreet(): "",restSmeApplication.getPostalCode(),restSmeApplication.getState() != null ? restSmeApplication.getStreet(): "")
);
MessageFormat is a heavy object.
For the intent of formatting the string one could use a static method String.format() which follows a printf() syntax and allows more options for formatting.
%n or \n can be used to make a new line.
String addressAsString =
String.format("%s %s%nPostal Code: %s,%nState: %s",
restSmeApplication.getAddress(),
restSmeApplication.getStreet() != null ? restSmeApplication.getStreet(): "",
restSmeApplication.getPostalCode(),restSmeApplication.getState() != null ? restSmeApplication.getStreet(): "");
address.setAddress(addressAsString);
Keep in mind that line is not synonym to string. And the resulting sting is still one single string. We just insert some additional formatting into it so to make it's representation to be multi-line.
This question already has answers here:
Java null check why use == instead of .equals()
(16 answers)
Closed 5 years ago.
I want to initialize a String variable and later assign a value to it using
if (){} else if(){}
This is what I have done:
String roleName;
// A and B are string constants
if (userRoleslist.contains(A)) {
roleName = A;
} else if (userRoleslist.contains(B)) {
roleName = B;
}
if (!roleName.equals(null)) {
audit.info("User: " + userName + " successfully authorized as " +
roleName + " to perform JMX operations.");
return roleName;
} else {
String msg = "User: " + userName + " not authorized to perform JMX operations.";
log.error(msg);
throw new NullPointerException();
}
The problem is that the error is not logged to the console. Only the NullPointerException is thrown and point the line if
(!roleName.equals(null)) {
Also, additionally can I leave out the NullPointerException and a log.error only?
if (!roleName.equals(null)) {
must be
if (roleName != null) {
When you do a null check you should do like this.
As roleName is null, calling a method on it will give you a null pointer exception.
roleName.equals(null) will give you nullpointer exception instead use roleName!=null .
I'm trying to parse a file listed with applicable regex, accepting the regex string to a variable and then use it in a expression. But while in doing so I'm facing troubles with \ and could not use them. Below is the block which is using the code. Can you tell me why it is working for ""©?.*"" and not for ""©?\\s*\\w+.*"". The expression is valid otherwise.
String valuePattern = attrs.getNamedItem("valuePattern").getTextContent();
if (newNodeName == "") {
System.out.println(valuePattern);
// System.out.println("Inside Delete node...");
if (valuePattern == ""
|| (valuePattern != "" && node.getTextContent().matches(valuePattern))) {
System.out.println("in match");
System.out.println("Deleting: " + node.getTextContent());
node = null;
}
As Jon Skeet pointed out, first of all, you should repair your String comparison.
String valuePattern = attrs.getNamedItem("valuePattern").getTextContent();
if (("").equals(newNodeName) {
System.out.println(valuePattern);
if (("").equals(valuePattern)
|| (!("").equals(valuePattern) && node.getTextContent().matches(valuePattern))) {
System.out.println("in match");
System.out.println("Deleting: " + node.getTextContent());
node = null;
}
}
I had to create an output depending on an boolean state like
String smily = null;
StringBuffer buff = new StringBuffer();
buff.append(", " + smily == null ? ":)" : ":("); //$NON-NLS-1$
System.out.println(buff.toString());
The problem is the String creation statement
", " + smily == null ? ":)" : ":("
I tested it in 2 different eclipse environments (and may be also 2 diofferent java version, this i did not checked) and the result was different.
Result 1:
:(
Result 2:
false:(
Of course, if i added brackets it is working
buff.append(", " + (smily == null ? ":)" : ":(")); //$NON-NLS-1$
Expected Result:
, :)
Can please somebody explain to me, why java interprets the statement that way?
Thanks
If you check the operator precedence (see this tutorial), then you will notice that addition (+) comes before equality (==). In other words, Java will first evaluate ", " + smily => ", null" before evaluating equality, therefor ", " + smily == null evaluates to false, and so the ternary operator evaluates to ":(".
BTW: You could have avoided this by not concatenating strings before adding them to the StringBuffer (the whole point of a StringBuffer is to make concatenation cheaper):
String smily = null;
StringBuffer buff = new StringBuffer();
buff.append(", ");
buff.append(smily == null ? ":)" : ":(");
the expression ", " + smily == null ? ":)" : ":(" is evaluated as (", " + smily) == null ? ":)" : ":("
This explains your result 1. To be honest, I don't know why result 2 was possible.
StringBuffer.append() takes a String parameter. So when you put this without brackets
buff.append(", " + smily == null ? ":)" : ":(")
at the time of evaluation will be ", " + null. So when the evaluation happens it is always false.
As for why the same code returned two results I can only assume that two different Java versions were used and they handled this situation differently.
String smily = null;
StringBuffer buff = new StringBuffer();
if(smily == null){
buff.append(", " + ":)") ; //$NON-NLS-1$
}else{
buff.append(", " + ":(") ; //$NON-NLS-1$
}
Try this.....................
buff.append(", " + smily == null ? ":)" : ":(");
- In the above statement you are Not mentioning the smily == null ? ":)" : ":(" to be evaluated in the proper way it has to be.
- To solve this you have to use BODMAS rule, the below are always evaluated in the way it has been listed from Left to Right.
Bracket
Power
Division and Multiplication
Addition and Substraction
- Use Bracket to enclose the smily == null ? ":)" : ":("
Eg:
public class Test {
public static void main(String[] args){
String smily = null;
StringBuffer buff = new StringBuffer();
buff.append(", " + (smily == null ? ":)" : ":(")); //$NON-NLS-1$
System.out.println(buff.toString());
}
}
Output: , :)
I have strange problem with token
< NULL: "null" >
in my JavaCC parser.
In expression like
String IsNullClause():
{
String res = "";
}
{
<IS> {res += " IS ";}
[<NOT> {res += " NOT ";} ]
<NULL> {res += " NULL ";}
{
return res;
}
}
parser doesn't see NULL token and throws exception that "null" expected. If I change token definition to < NULL: "null_val" > or something else it works fine.
Is this my mistake or JavaCC doesn't accept 'null' as a token value?
There are sample Java language grammars in JavaCC package, with the following token difinition:
< NULL: "null" >
so I'm pretty sure JavaCC can handle null token.
Are you sure no token declared before NULL matches "null"? Tokens are matched in the order of declaration. You may try to declare NULL at the very beginning.