Java Programming

Monday, April 1, 2019

Conditional

Java uses boolean variable to check the condition. The value can be only true or false compared or checked with the condition.

if statement in Java

For example:
int a = 1;
int b = 1;

if (a==b) {
    System.out.println("It's true!");
}
if (a==1) { 
    System.out.println("It's true!");
}
if (b==1) { 
    System.out.println("It's true!");

}

if else statement in Java

For example:
int a = 2;

if (a==1) {
    System.out.println("It's true!");
} else { 
    System.out.println("It's false!");
}

else if statement in Java

For example:
int a = 2;

if (a==1) {
    System.out.println("a is 1!");
} else if (a==2) { 
    System.out.println("a is 2!");
}

boolean operators in Java

int a = 3;
int b = 4;
boolean result;
result = a < b; // true
result = a > b; // false
result = a <= 3; // a smaller or equal to 3 - true
result = b >= 5; // b bigger or equal to 5 - false
result = a == b; // a equal to b - false
result = a != b; // a is not equal to b - true
result = a > b || a < b; // Logical or - true
result = 2 < a && a < 5; // Logical and - true
result = !result; // Logical not - false

== and equals

  • == is used to compare with primitive data type
  • equals is used to compare with object data type
For example:
String a = new String("Hello");
String b = new String("Hello");
if (a.equals(b)) {
     System.out.println("It is true!");
}

No comments:

Post a Comment