JCombobox and String.equals(null) [duplicate] - java

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");
}

Related

Why am I getting a NullPointerException for this loop? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I'm writing a for loop to iterate through the array and find the index of the employee with the social security number of 123456789. Why do I keep getting a NullPointerException?
.getSocSecNum() returns a String
empnew[21] = Empthe1;
String temp = "123456789"
for(int i = 0; i < empnew.length - 1; i++){
if(empnew[i].getSocSecNum().compareTo(temp) == 0){
System.out.println("the location of the employee is " + i);
}
}
I want it to output "the location of the employee is 21" but all I get is a NullPointerException
The problem is most likely that empnew has at least one null in it.
So in the loop, you try to get empnew[i].getSocSecNum(), which expands to null.getSocSecNum(), which gives you a null pointer exception, because you can't access class members on null, because it isn't a real object.
The easiest solution might be to just check that empnew[i] != null before accessing the value:
if (empnew[i] != null && empnew[i].getSocSecNum...) {
...
}

Sqlite Integer null == java int 0 [duplicate]

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");
}

Why abstract variable null does not equal to null [duplicate]

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))

if statement with integers [duplicate]

This question already has answers here:
Why does my if condition not accept an integer in java?
(7 answers)
Closed 3 years ago.
I'm new at Java. I'm looking for some help with homework. I wont post the full code I was doing that originally but I dont think it will help me learn it.
I have a program working with classes. I have a class that will validate a selection and a class that has my setters and getters and a class that the professor coded with the IO for the program (it's an addres book)
I have a statement in my main like this that says
//create new scanner
Scanner ip = new Scanner(System.in);
System.out.println();
int menuNumber = Validator.getInt(ip, "Enter menu number: ", 1, 3);
if (menuNumber = 1)
{
//print address book
}
else if (menuNumber = 2)
{
// get input from user
}
else
{
Exit
}
If you look at my if statement if (menuNumber = 1) I get a red line that tells me I cannot convert an int to boolean. I thought the answer was if (menuNumber.equals(1)) but that also gave me a similar error.
I'm not 100% on what I can do to fix it so I wanted to ask for help. Do I need to convert my entry to a string? Right now my validator looks something like:
if (int < 1)
print "Error entry must be 1, 2 or 3)
else if (int > 3)
print "error entry must 1, 2, or 3)
else
print "invalid entry"
If I convert my main to a string instead of an int wont I have to change this all up as well?
Thanks again for helping me I haven't been diong that great and I want to get a good chunk of the assignment knocked out.
if (menuNumber = 1)
should be
if (menuNumber == 1)
The former assigns the value 1 to menuNumber, the latter tests if menuNumber is equal to 1.
The reason you get cannot convert an int to boolean is that Java expects a boolean in the if(...) construct - but menuNumber is an int. The expression menuNumber == 1 returns a boolean, which is what is needed.
It's a common mix-up in various languages. I think you can set the Java compiler to warn you of other likely cases of this error.
A trick used in some languages is to do the comparison the other way round: (1 == menuNumber) so that if you accidentally type = you will get a compiler error rather than a silent bug.
This is known as a Yoda Condition.
In Java, a similar trick can be used if you are comparing objects using the .equals() method (not ==), and one of them could be null:
if(myString.equals("abc"))
may produce a NullPointerException if myString is null. But:
if("abc".equals(myString))
will cope, and will just return false if myString is null.
I get a red line that tells me I cannot convert an int to boolean.
Thats because = is an assignment operator. What you need to use is == operator.
A single equal sign is assignment: you assign value to a variable this way. use two equal signs (==) for comparison:
if ($menuNumber = 1) {
Update: forgot dollar sign: $menuNumber

Another way of writing If statement in java [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What is the Java ?: operator called and what does it do?
Maybe this is a duplicated question to some other questions here but I could not find it.
Yesterday I saw a guy using a new way of writing the if statement by using ? and : and I'm not sure what do they all mean.
If someone could point me out to a tutorial or an already answered question I would so much appreciated.
The conditional operator, it's a type of ternary operator
wikipedia - ?:
wikipedia - ternary operation
(condition) ? (what happens if true) : (what happens if false);
Example use:
int a = 1;
int b = (a == 1) ? 2 : (a + 1);
It's a ternary operator. General form:
expr1 ? expr2 : expr3
If expr1 evaluates to true, the returned result is expr2, otherwise it's expr3. Example:
Object obj = (obj != null) ? obj : new Object();
Easy way to initialize an object if it's null.
(statement) ? TRUE : FALSE
Example in pseudocode: a = (5 > 3) ? 1 : 0
If the statement is true, a will be one (which it is), otherwise it will be 0.
That's called a ternary operator, and it's a cute, if sometimes hard to read, way of writing an IF statement.
if ( x == 3) {
do-magic
}
else {
do-other-magic
}
would be expressed like so:
x == 3 ? do-magic : do-other-magic

Categories

Resources