Java Fundamentals  «Prev  Next»
Lesson 9Using Java's Boolean, string, and assignment operators
ObjectiveExamine Boolean, string, and assignment operators in Java.

Java Boolean, String, Assignment Operators

Java also supports a number of Boolean, string, and assignment operators.
Boolean operators are used to perform logical comparisons, and always result in one of two values: true or false. Following are the most commonly used Boolean operators:

AND, OR, Negation, Equal-to, Not Equal-to

1) AND: Compares two values and returns true if they are both true
1) AND: Compares two values and returns true if they are both true

2) OR: Compares two values and returns true if either of the values are true
2) OR: Compares two values and returns true if either of the values are true

3) Negation: Flips the state of a value
3) Negation: Flips the state of a value

4) Equal-to: Compares two values for equality
4) Equal-to: Compares two values for equality

5)Not-equal-to (!=): Compares two values for inequality
5) Not-equal-to (!=): Compares two values for inequality


Given the following Class:
class BooleanTest1 {
 public static void main(String[] args) {
  boolean b1 = false;
  int i1 = 2;
  int i2 = 3;
  if (b1 = i1 == i2) {
   System.out.println("true");
  }
  else {
   System.out.println("false");
  }
 } 
}

Select 1 option
  1. Compile time error.
  2. It will print true
  3. It will print false
  4. Runtime error.
  5. It will print nothing.

Answer: c
Explanation:
All an if statement needs is a boolean. Now i1 == i2 returns false which is a boolean and since b1 = false is an expression and every expression has a return value (which is actually the Left Hand Side of the expression), it returns false which is again a boolean. Therefore, in this case, the else condition will be executed.

  1. AND: Compares two values and returns true if they are both true
  2. OR: Compares two values and returns true if either of the values are true
  3. Negation: Flips the state of a value
  4. Equal-to: Compares two values for equality
  5. Not-equal-to: Compares two values for inequality

Java Boolean Operators

String operators

There is only one string operator, the concatenation operator (+), which appends a string onto another string. Following is an example of using the concatenation operator:
String nickname = "tough guy";
String message = "Hey there, " + nickname + "!";

The nickname string is effectively placed in the middle of a sentence. This code acts somewhat like a form letter in that you provide a sentence and then plug a name into it.

Assignment operators

Assignment operators all perform some type of operation that results in a value being stored in a variable. The following link contains the most commonly used assignment operators:

prime Application - Exercise

In this exercise, You will create a command-line application to determine whether a number is prime.
prime Application - Exercise