+84 1649 660 740

Wednesday, 27 August 2014

The boolean Type In Java

The boolean type has two values, false and true. It is used for evaluating logical conditions. You cannot convert between integers and boolean values.

* Note: In C++, numbers and even pointers can be used in place of boolean values. The value 0 is equivalent to the bool value false, and a non-zero value is equivalent true. This is not the case in Java. Thus, Java programmers are shielded from accidents such as

 if (x = 0) // oops... meant x == 0
In C++, this test compiles and runs, always evaluating to false. In Java, the test does not compile because the integer expression x = 0 cannot be converted to a boolean value.

* Example:
=> File: booleanType.java

 package com.webmobileaz;

import java.util.Scanner;

public class booleanType {
 public static void main (String []args) {
  
  Scanner scran = new Scanner(System.in);
  boolean b = scran.nextBoolean();
  if(b == true) {
   System.out.println("Hello!");
  } else {
   System.out.println("Hehe Hihi!");
  }
 }
}

=> Result:
(1). If you input: true
 Hello!

(2). If you input: false
 Hehe Hihi!

(3). Other -> Exception
Exception in thread "main" java.util.InputMismatchException
 at java.util.Scanner.throwFor(Scanner.java:864)
 at java.util.Scanner.next(Scanner.java:1485)
 at java.util.Scanner.nextBoolean(Scanner.java:1782)
 at com.webmobileaz.booleanType.main(booleanType.java:9)


View Project

Download Project

0 comments:

Post a Comment