Posts

Showing posts from February, 2019

Java Switch statements : Executing same code for two values without redundant code

This is something I learnt recently. Assume that you want to execute the same code when the switch variable value is one of multiple values. This can be dine without repeating the same code in multiple case statements.

For example consider below code. There two case statements that check value for 3 or 4, executes same code block.  We can do this without duplicating the code.


switch(number){case(1): System.out.println("Number is 1");break;case(2): System.out.println("Number is 2");break;case(3): System.out.println("Number is 3 or 4");break;case(4): System.out.println("Number is 3 or 4");break;default: System.out.println("Number is not 1, 2, 3 or 4");break;}
See below.

switch(number){case(1): System.out.println("Number is 1");break;case(2): System.out.println("Number is 2");break;case(3):case(4): System.out.println("Number is 3 or 4");break;default: System.out.println("Number is not 1,…

Java: Difference between Conditional and Bitwise AND operator - & vs &&

There two AND operators in Java that we can use.

& - Bitwise AND operator
&& - Conditional AND operator.

In Java both above operators can be used in if conditions. However there is a difference how each works. Let's see with an example.

(x != 0) & (x > 1)  - With bitwise AND, it evaluates both (x !=0) and (x > 1) conditions. Then takes the AND of the two results.

(x != 0) && (x > 1)  - With conditional AND, it first valuates (x !=0) and only if it is true, (x > 1) condition will be evaluated. Then takes the AND of the two results. If (x!= 0) was false, it simply returns false.

What is the problem with using & in a condition? There are cases where we can only execute a condition only some other condition is true.
See the example below.

(x != 0) & (3/x  > 1) - This will throw an exception if the x=0. So for such cases we can only use &&.

So in summary, it is always advisable to use conditional AND (&&) in if conditions. &…