Java && operators - java

I'm trying to make simple if statement , I need to see if my two String's values are not empty (does not equal "").
I use && operator , but sadly , it only checks one string properly if it's not empty , and if the second string is empty, he passes . Making && kinda useless for me.
if ( StringUtils.isNullOrEmpty(name) && StringUtils.isNullOrEmpty(sname)
) {do something}
I need them both to be checked properly . If at least one string is empty return false .
If both are not empty return true.

Currently your condition is true if both Strings are null or empty.
If you want both not to be null or empty you need :
if ( !StringUtils.isNullOrEmpty(name) && !StringUtils.isNullOrEmpty(sname)
) {do something}

&& is smart and if first condition is false it doesn't try the second.
use & could achieve what you want.

The problem is that your check is wrong. You want it to only pass if both ARE empty.
So you should go for
if ( !StringUtils.isNullOrEmpty(name) && !StringUtils.isNullOrEmpty(sname)
) {do something}
or if u want to catch it in the if statement if one of them IS empty, you should use or:
if ( StringUtils.isNullOrEmpty(name)|| StringUtils.isNullOrEmpty(sname)
) {do something}

isNullOrEmpty will return true if name is empty, but you want it NOT empty, so negate the conditions using !.
if ( !StringUtils.isNullOrEmpty(name) && !StringUtils.isNullOrEmpty(sname)
) {do something}
Another alternative is:
if (!(StringUtils.isNullOrEmpty(name) || StringUtils.isNullOrEmpty(sname)
)) {do something}
However, the above is not a recommended coding style, as it is difficult to catch the ! hidden just before the line, and code readers may get confused.
About || and && operators optimized checking:
|| checks for the first true condition from left to right and skips any further checking if it finds one true condition.
&& checks for the first false condition from left to right and skips any further checking if it finds one false condition.

At first it didn't looked any sense to me , and it didn't worked . Only then I realized that I need to to flip the return statements.
if (!StringUtils.isNullOrEmpty(name) && !StringUtils.isNullOrEmpty(sname)) {
System.out.println("ok");
return true;}
else {
System.out.println("empty names");
return false;
}
Now it seems to work just fine.

Using '&' as logical operator you can do the following thing. Here we have not use StringUtils -
if( ( null!=name && !name.isEmpty() ) &
( null!=sname && !sname.isEmpty() ) ){do something}

Related

What is the difference of null position placedin front and at back

In java, what is the difference between this 2 lines of code, or the second line of code don't even exist
if (name != null){}
if (null != name){}
the real code is something like this
if ( null != name&& !StringUtils.isEmpty(name) )
by the way, I have tested this code and it works
There is no difference between your two top lines of code as both do a valid null check. The main issue is if you did something like this:
if (myString.isEmpty() && (myString != null)) {...}
This would throw a NullPointerException if myString is null since you're dereferencing the variable before doing the null check. Better to do instead:
if ((myString != null) && myString.isEmpty()) {...}
The && operator does a boolean AND test, and will short circuit, will end and not do the right sided test if the test on the left is false.
There is no difference, != is a Logical Operator, and is checking to make sure they are not equivalent, so it doesn't matter which side things are on. For example:
String a = "a";
if(a != null)
{
System.out.println("they are not equal");
}
if(null != a)
{
System.out.println("they are not equal");
}
returns
they are not equal
they are not equal
Difference is in that you cannot assign to NULL anything.
If you would make typo and miss a ! sign within
if (name != null) {}
You could possibly make
if (name = null) {}
And by that assign null value to name
Read this
https://knowthecode.io/yoda-conditions-yoda-not-yoda

Confused on how to use || and && in the same if statement. Can anyone spot the problem?

I am confused on how to use || and && in the same if statement.
What I am trying to do is have it print something if the string starts with an "D" or an "O", and if one is true check if the string has a character length of two.
Example: if the string is "DE" it will print something. However, if it is "SE" it will not print anything.
else if( (answer.startsWith("D") || answer.startsWith("O"))
&& (answer.length() == 2) ) {
//print something
}
Java is applying a "short circuit" to your logic. It does the first part (starts with "D" or "O") and if that's true it proceeds to the second part (length is 2). However if the first part evaluates to false then it never even bothers to execute the second part.
So your "SE" string will never go into the "print something" bit because it doesn't meet your first criteria of starting with D or O. And based on your description of what the logic should be, that is correct.
If you actually mean that if it starts with "D" or "O" OR is 2 characters long then your logic statement should have been:
else if( answer.startsWith("D") || answer.startsWith("O")
|| (answer.length() == 2 ) {
//print something
}
Edit: Oops, just pasted the original code in the first time...!
I would check first the length and after the two conditions e.g.
else if (answer.lenght()==2) {
if (answer.startsWith("D") || answer.startsWith("O"){
//print something that lenght is 2 and starts with D or O
}
}
}
In that case you have to check length first because && will true if left side and right side both true
else if( (answer.length() == 2)&&(answer.startsWith("D") || answer.startsWith("O"))
{
//your logic
}

JAVA Comparing two Strings isn't working

So here's a snippet of code I'm working on:
String direction = s.readLine();
System.out.println(direction);
if (direction.equals("up") != true && direction.equals("down") != true &&
direction.equals("left") != true && direction.equals("right") &&
direction.equals(null) != true) {
System.out.println("Invalid Solution file");
System.exit(0);
}
What it is supposed to do is read a line from a text file (using a BufferedReader) and then if the line isn't either a valid direction or blank then it should print "Invalid Solution" and exit.
The problem is that no matter what the direction string is the if statement still runs. I put in a println to check whether the direction was being read correctly but it seems absolutely fine. So why isn't the code working as intended?
Part of your problem is readability. Fix that and your problem is 90% solved:
private static List<String> DIRECTIONS = Arrays.asList("up", "down", "left", "right");
then
if (!DIRECTIONS.contains(direction)) {
System.out.println("Invalid Solution file");
System.exit(0);
}
The other 10% was how to check for null, which is direction == null, but if you use this code you don't need to, because contains(null) will conveniently return false.
You code is much more complex than it is needs to.
Consider this instead:
Set<String> validDirections = new HashSet<>(Arrays.asList("up", "down", ...
if (validDirections.contain(direction.toLowerCase()) {
// good ...
} else {
// bad ..
}
You can make validDirections a global constant for example; so it could be used in other places as well.
What I am trying to explain here is: your code is low-level. Low level code is hard to write, read, maintain and extend. Programming is always about creating good abstractions. Or vice versa: if you don't use abstractions, you end up with pretty abstract code, like the one you are showing here!
For example: if you need another direction, you have to put into your already way too complicated if condition. In my solution, you just put it into the statement that builds that Set.
Finally: your error message, is saying nothing. So, that string is bad; but why is it? Wouldn't it be better to at least print the string that caused the error?!
Here && direction.equals("right") I think you have done a mistake since it is on contradiction with the rest :
direction.equals("up") != true &&
direction.equals("down") != true &&
direction.equals("left") != true
You test the negation in the most of conditions but direction.equals("right") tests the affirmation.
Try it , it's the same thing but less verbose and more readable :
if (direction !=null && !direction.equals("up") &&
!direction.equals("down") &&
!direction.equals("left") &&
!direction.equals("right") ){
System.out.println("Invalid Solution file");
System.exit(0);
}
First, you should not use != true with a boolean statement, it is bad form. Rewrite like this:
direction !=null &&
!direction.equals("up") &&
!direction.equals("down") &&
!direction.equals("left") &&
!direction.equals("right")
Your error was that you did not include the != true part on one of your statements within the compound if. Replace with the above code to solve the issue.
I'm confused why you are using !=true when your .equals method already returns a boolean. Try this.
String direction = s.readLine();
System.out.println(direction);
if ( direction!=null && !direction.equals("up") && !direction.equals("down")&& !direction.equals("left")&& direction.equals("right")){
System.out.println("Invalid Solution file");
System.exit(0);
}
Try the following code:
boolean match = false;
if (direction.equals("up"))
{ match = true; }
if (direction.equals("down"))
{ match = true; }
if (direction.equals("left"))
{ match = true; }
if (direction.equals("right"))
{ match = true; }
if (direction.equals(null))
{ match = true; }
if (match == false){
System.out.println("Invalid Solution file");
System.exit(0);
}
You might also want to trim the direction string after reading from file.
The quals method returns a boolean so the result does not need to be compared with the true or false value. Also, I would start with null comparison - boolean expressions in Java are shortened so if this part will be fulfilled rest of the expression is not evaluated. The correct expression might look like this:
 
if (direction == null || (!direction.equals("up") && !direction.equals("down") && !direction.equals("left") && !direction.equals ("right "))) {
}
But this code is not readable. You could use enums or list of Strings like below
List<String> directions = Arrays.asList("up", "down", "left", "right");
String direction = "readValue"
if (!directions.contains(direction)) {
System.out.println("Invalid direction");
System.exit(0)
}

How to compare text input to multiple strings?

I want the following if statement to compare against multiple strings but when i compare against more than one it gives me the error message that I created. Below is the code which does not work.
The variables are test = 'c3400553' and test2 = 'c3400554'
if (!uname.getText().toString().matches("[cC][0-9]{7}") ||
!uname.getText().toString().equals(test) ||
!uname.getText().toString().equals(test2)
) {
uname.setError("Incorrect ID Format");
}
Below is the code which works for one comparison.
String test = "c3400553";
...
if (!uname.getText().toString().matches("[cC][0-9]{7}") ||
!uname.getText().toString().equals(test)
) {
uname.setError("Incorrect ID Format" );
}
I don't understand what the issue is
That's because you either need to remove some !, or you need to replace your || by &&.
It depends on what you are trying to achieve. If you want the id to be declared incorrect if it doesn't match the format AND if it is not equal to test AND ALSO not equal to test2, then the solution is this :
if (!uname.getText().toString().matches("[cC][0-9]{7}") &&
!uname.getText().toString().equals(test) &&
!uname.getText().toString().equals(test2) ) {
uname.setError("Incorrect ID Format" );
}
Otherwise, if what you want to do is to check whether uname matches the format, and is NOT equal to test and test2, then the problem is that you need to remove the ! before comparisons with test and test2 :
if (!uname.getText().toString().matches("[cC][0-9]{7}") ||
uname.getText().toString().equals(test) ||
uname.getText().toString().equals(test2) ) {
uname.setError("Incorrect ID Format" );
}

How to check if there is text within my JButton

I want to check whether there is something in my JButton. What would i insert into the equalsIgnoreCase() area?
if (jButton1.getText().equalsIgnoreCase("") &&
jButton2.getText().equalsIgnoreCase("") &&
jButton3.getText().equalsIgnoreCase("") &&
jButton4.getText().equalsIgnoreCase("") &&
jButton5.getText().equalsIgnoreCase("") &&
jButton6.getText().equalsIgnoreCase("") &&
jButton7.getText().equalsIgnoreCase("") &&
jButton8.getText().equalsIgnoreCase("") &&
jButton9.getText().equalsIgnoreCase(""))
To check that there is a text, you can do:
!jButton1.getText().isEmpty()
or, if you want to exclude a text that only contains spaces:
!jButton1.getText().trim().isEmpty()
You can use
jButton1.getText().isEmpty()
(use ! to negate if you want to know it's not empty...)
or you can check the length of the value
jButton1.getText().length > 0
you can use
bool somethingIn = !jButton1.getText().isEmpty();
Nothing, just what you did. But you should put exclamation symbols before conditions to negate them:
if (!jButton1.getText().equals("") &&
!jButton2.getText().equals("") &&
!jButton3.getText().equals("") &&
!jButton4.getText().equals("") &&
!jButton5.getText().equals("") &&
!jButton6.getText().equals("") &&
!jButton7.getText().equals("") &&
!jButton8.getText().equals("") &&
!jButton9.getText().equals(""))
In this case body of if will be executed if all your JButtons have some text. And ignoreCase is not necessary. Emptiness has no lower or upper case ))

Categories

Resources