This question already has answers here:
String concatenation and comparison gives unexpected result in println statement
(5 answers)
Closed 7 years ago.
I've programmed for quite a time, but I never got to this. I deploy on JRE 1.8.0_66.
I wrote an abstract class called Grenade. Then I made these statements in class Profile:
public class Profile {
Grenade varGrenade; // Field
public void check() {
varGrenade = null; // set reference to null
System.out.println("Am i null: " + this.varGrenade == null);
}
}
This statement returns
Am i null: false
If I would want to print the result of varGreanade, it would print null. Where have I gone wrong? (Don't know if it has something with abstract Grenade class) How do I check it for null without throwing NullPointerException?
It's just an issue of parentheses. What you want is
System.out.println("Am i null: " + (this.varGrenade == null));
What you're getting is
System.out.println(("Am i null: " + this.varGrenade) == null);
"Am i null: " + this.varGrenade is not null.
You need parentheses to force it to concatenate to the null-check.
(just like 1 + 2 == 3 doesn't mean 1 + (2 == 3))
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
please note that I'm a complete beginner to programming and have found learning Java quite hard. I have a school task that requires me to write a code for a toString() method and I've blindly followed what my teacher has been writing/teaching in class but for some reason my code doesn't seem to work when I run the test file? I've included my code below.
I do get an error that says the following- "Null pointer access: The variable coef can only be null at this location" but when I change all my coef[] variables, then my code becomes moot because it just equates to null.
Any pointers greatly appreciated!
EDIT 1: Thank you for your responses - I thought I needed to intialise coef[] as a variable inside my toString() method (big oops!!). Also thank you for providing the link to the NullPointer question - it had some really thorough explanations and now I understand that I dereferenced the coeff[] variable.
QUERY a: I've removed my first line but now it seems that my code fails on this line return coef[1]+ "x + " + coef[0];
QUERY b: curious to know why it's a bad sign if the class is plural?
public class Polynomials {
public Double coefficient;
public Integer exponent;
private int[] coef;
public String toString() {
String[] coef = null;
if (exponent <= -1)
return "0";
else if (exponent == 0)
return "" + coef[0];
else if (exponent == 1)
return coef[1]+ "x + " + coef[0];
String s = coef[exponent] + "x^" + exponent;
return s;
}
Your Polynomials class has 3 fields, and one is called coef. In your toString method you then declare a local variable, also called coef.
In java, that means the local variable 'shadows' the field - in other words, for that entire method, coef refers to the String[] coef = null; and not the int[] coef.
And that local field is always null - you create it, initialize it to null, and never change it. Thus, choef[0] will guaranteed throw a NullPointerException at runtime.
The fix seems to be to .... just remove that String[] coef = null; line entirely. I have no idea why you wrote that or what it's trying to accomplish.
NB: Shouldn't the class be named Polynomial? Naming a class a plural is usually a bad sign.
This question already has answers here:
Checking for a null int value from a Java ResultSet
(13 answers)
Closed 6 years ago.
I guess that an integer null value within a sqlite table is not equivalent to 0 in Java. So how can I check whether the int I extract from my table with
if(resultSet.getInt(columnNumber) != 0){
System.out.println("int is not null");
}
is not null? I do not want to use the sqlite constraint "IS NOT NULL".
It all depends what this method is doing: resultSet.getInt(...)
if getInt is returning a primitive integer, then that can not be null, but if that is an object of the class Integer then you need to check the nullabilty by doing a normal check like: resultSet.getInt(...)!= null and then after been sure that is ot null check if is not zero:
resultSet.getInt(...)!=0
Example:
if(resultSet.getInt(columnNumber) != null){
if(resultSet.getInt(columnNumber) != 0){
System.out.println("int is not zero");
} else {
System.out.println("int is zero");
}
}else{
System.out.println("int is null");
}
This question already has answers here:
How to check if my string is equal to null?
(28 answers)
Closed 8 years ago.
Here is my code :
if (ChoixPortCom.equals(null) == true ) JOptionPane.showMessageDialog(null, "Choose Port COM");
and I get the famous java.lang.NullPointerException
My JCombobox is filled like :
1st -> nothin/empty null no String nothing
2nd -> COM1
3nd -> COM2
....
Why is "if" condition not right ?
choixPortCom.equals(null) will never be true. If choixPortCom is not null, then the expression will return false as expected. If choixPortCom is null, then the expression will throw a NullPointerException, since you are attempting to call a method on null; this is what's happening in your case. The appropriate way to check for null is:
if (choixPortCom == null) // I've assumed a more common naming convention
There is also an Objects class in Java 7 that has some useful methods for null-checking. For example, Objects.requireNonNull():
Objects.requireNonNull(choixPortCom, "input can't be null!")
It should be
if (ChoixPortCom == null)
Now if ChoixPortCom is null it will throw a NullPointer because you are trying to invoke a method (equals) on a null reference.
And something I like to think of as a best practice is to always use brackets:
if (ChoixPortCom == null) {
JOptionPane.showMessageDialog(null, "Choose Port COM");
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am working on developing a timer application in eclipse using swing tables to store data.
The main issue I'm running into is that this if statement keeps returning true, even when the values in those variables are identical (as shown by the output). What could be causing this?
Here is my snippet of code:
String currentPID = lblCurrentPID.getText();
for (int i = 0; i < tableActive.getRowCount(); i++) {
String currentValue = (String) tableActive.getValueAt(i, 2);
System.out.println(i + ": Current Value: " + currentValue + " - Current PID: "+ currentPID);
if (currentPID != currentValue) {
System.out.println("The value and PID are not the same for some reason!");
}
else {
tableActive.setValueAt(ts1.getOverallTotalTime(), i, 3);
System.out.println(i + ": Row Was Changed!");
}
}
Here is the Output:
0: Current Value: Test3 - Current PID: Test3
The value and PID are not the same for some reason!
1: Current Value: 12345 - Current PID: Test3
The value and PID are not the same for some reason!
2: Current Value: 54321 - Current PID: Test3
The value and PID are not the same for some reason!
if (currentPID != currentValue){
should be
if (!currentPID.equals(currentValue)){
Use equals() to check string equality. == operator only checks if two ref varibales refer to the same String object.
should be if (!currentPID.equals(currentValue))
In order to compare Strings in java, use equals and not == (or !=) see Java String.equals versus == to get all the good reasons.
When you do String (or) Object comparison, it is better to use equals()
if (!currentPID.equals(currentValue)){
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
I am newbie in java but I think I have done well teaching myself in these few weeks. But now I am stuck at this loop.
Here is a method from one of my class. To help me debug, I have added "myString" string and "syntax" list inside this method to demonstrate what is happening and to keep it simple, at least for now.
public void getIndex(){
String myString = "2 2 + 3 5";
String[] syntax = myString.split(" ");
for (int index = 0; index < syntax.length; index++){
System.out.println("current index is: " + index);
System.out.println("It has: " + syntax[index]);
// these print statements are made to help me debug
if (syntax[index] == "+"){
indexNeeded = index;
break;
}
}
System.out.println("Index Needed: " + indexNeeded);
As you can see inside the loop, I want to break the "for loop" when the element of the list, "syntax" is "+".
(I am showing "+" here but it can be anything in the actual program.)
Here is the output, when run this method:
current index is: 0
It has: 2
current index is: 1
It has: 2
current index is: 2
It has: +
current index is: 3
It has: 3
current index is: 4
It has: 5
Index Needed: 0
The loop should have stopped when it found "+" but it seems that "if statement" is not working at all, and hence "indexNeeded" hasn't changed.
It's a simple method but what am I doing wrong here?
You're trying to compare strings with ==. That doesn't work, you need to use .equals():
change:
syntax[index] == "+"
to
syntax[index].equals("+")
== only returns true when both objects refer to the same instance. equals() will return true when the contents of the string are the same. This is what you want.
Replace
if (syntax[index] == "+"){
with
if (syntax[index].equals("+")){
When you are trying == it comparing the references and syntex[index] is not referring to same location where literal "+" is. So they are not equal.
// If syntax[index] get '+' value from somewhere but not literal
if(syntax[index] == "+" ) // is false
// right way is
if(syntax[index].equals("+")) // is true
// If syntax[index] get '+' value from literal
syntax[index] = "+";
if(syntax[index] == "+" ) // is true
// This approach is faster but has mentioned above has limitations.
When you do equals it actually compares the content.
You should write:
syntax[index].equals("+")
"+" is a reference to a String, and syntax[index] is another. But here you want to compare the objects themselves, not their references.
If you take two objects a and b of whatever class, a == b will test that the references are the same. Testing that they are "the same" is written a.equals(b).
You should read Java's .equals() documentation carefully, it is a fundamental part to understand.
for String, you need to do
syntax[index].equals("+")
If you want to compare the value of a String you need to use .equals() but if you want to compare references you use the operator ==. That a common mistake with newbies.
Take a minute and see the difference between:
syntax[index] == "+"
and
"+".equals(syntax[index])
it that order you don't allow possible null pointer in syntax[index]
Here's a fun, educational way to fix your problem. Add a call to String.intern() to your method and it will work fine. Amaze your friends! :)
public int getIndex()
{
String myString = "2 2 + 3 5";
String[] syntax = myString.split(" ");
int indexNeeded = -1;
for (int index = 0; index < syntax.length; index++)
{
System.out.println("current index is: " + index);
System.out.println("It has: " + syntax[index]);
// these print statements are made to help me debug
if (syntax[index].intern() == "+")
{
indexNeeded = index;
break;
}
}
return indexNeeded;
}
Note that it is better to return a value from a method than it is to use variables with class scope. Class-scoped variables should be reserved for data that can be considered a property of the object. indexNeeded doesn't meet that description, and it's a poor name for an int - it sounds like it should be a boolean.
Equality checks in Java come in two forms.
The equality operator "==" checks to see if two variables refer to the same object. In your case, this test fails because, though their content is the same, you're referring to two different string objects.
The .equals() method is available on every Java object and provides extensible equality checking. In the case of Strings, consider the following:
"+".equals("+") // evaluates to true
going back to the equality operator:
"+" == "+" // evaluates to false
See this page for more detail.
Use return; instead of break;
it works for me