Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logic of Java Operators && and ||

Hello dear Programmers,

I have a String String input = "30.09.1993"; Then i want to save all numbers in this string in an array(Only numbers!). The "." are at index 2 and 5 so i want to skip these parts of my string in my loop with an if-statement.

I fixed my problem and everything works fine but I'm confused with the logic of the && and || operators.

This is my working code:

String input = "30.09.1993";
int[] eachNumbers = new int[8];

int x = 0;
for(int i = 0; i <= 9; i++){
    if(i != 2 && i != 5){
       eachNumbers[x] = Integer.parseInt(input.substring(i, i+1));
       x++;
    }
}

And this is the code which doesnt work:

String input = "30.09.1993";
int[] eachNumbers = new int[8];

int x = 0;
for(int i = 0; i <= 9; i++){
    if(i != 2 || i != 5){
       eachNumbers[x] = Integer.parseInt(input.substring(i, i+1));
       x++;
    }
}

The only difference between these two code snippets are the operators in the if-clause.

I thought that the results for these operators are:

&& operator:

false + false = false
true  + false = false
false + true  = false
true  + true  = true

|| operator:

false + false = false
true  + false = true
false + true  = true
true  + true  = true

So in my opinion the second code snippet should work and the first should throw a NumberFormatException. But thats not the case.

I'm sure there are some better solutions for what im doing but my question is only about the logic in my if-statement. Can someone explain me the logic behind this? I'm totally confused and thankful for every helping answer.

Greetings Lukas Warsitz

like image 563
Lukas Warsitz Avatar asked Dec 13 '13 11:12

Lukas Warsitz


2 Answers

In the second snippet, the if-clause will always be true, because i will always be not 2 or not 5 (because it cannot be 2 and 5 at the same time)

For what you want to do your first snippet is fine, it does exactly what you want: If your are not at the third element and neither at the 6th element, you want to parse, else you are at one of the points in the date.

like image 80
LionC Avatar answered Sep 18 '22 12:09

LionC


Key point is here : In && if first case is false, second case won't check.

true && false // Evaluates false because the second is false 
false && true // Evaluates false because the first is false 
true && true // Evaluates true because both are true 
false && false // Evaluates false because the first is false

and

In || if first case is true , second case won't check.

true || false // Evaluates true because the first is true 
false || true // Evaluates true because the second is true 
true || true // Evaluates true because the first is true
false || false // Evaluates false because both are false
like image 33
Jatin Malwal Avatar answered Sep 20 '22 12:09

Jatin Malwal