Monday, October 8, 2018

Java - Convert String to Boolean Example

There are two ways to convert a String to boolean in Java, first, by using Boolean.parseBoolean() method and second, by using Boolean.valueOf() method.The parseBoolean() method returns an equivalent boolean value of given String, for example, if you pass "true" it will return the primitive boolean value true. Similarly, if you pass "false" it will return false. The good thing about this method is that it is case insensitive, which means if you pass "true", "TRUE", or "True" you will still get a true boolean value.

 Another good thing about this method is that it doesn't throw an exception if you pass any String value other than true and false. For example, if you pass "YES" it will return false, which is not obvious but that's still better than throwing an exception like NumberFormatException.

The Boolean.valueOf() method work similar, it returns a true boolean value for a non-null String equal to true, ignoring case and returns false for everything else. It also returns a Boolean object instead of a primitive boolean value.

Also, both valueOf() and parseBoolean() methods are null safe, which means they will return false if you pass null i.e. parseBoolean(null) and valueOf(null) will return false instead of throwing NullPointerExcpeiton.

1. Boolean.parseBoolean() Examples


// parseBoolean returns a boolean primitive value
String value = "true";
boolean b = Boolean.parseBoolean(value);
System.out.println(b);

Output
true

2. Boolean.valueOf() Examples


// valueOf returns a Boolean object
String data = "false";
boolean f = Boolean.valueOf(data);
System.out.println(f);
Output
false

Btw, there is another way to convert String to Boolean in Java, by using the constructor of Boolean class e.g. new Boolean(String input) but I won't advise you to use that because everytime you will use this method it will return a new Boolean Object.

Instead, you should always use valueOf() method because Boolean instances are immutable and just two instances are enough to cover all scenarios.

Difference between parseBoolean and valueOf() in Java


Even though both methods can be used to parse a String to a boolean value, there is a slight difference between them. The parseBoolean() method returns a primitive boolean value while the valueOf() returns a Boolean object.

Though in the age of auto-boxing, a Boolean can easily be stored in a boolean variable, this is an important difference which you should remember.

Another benefit of using the valueOf() method is that it caches the boolean value and returns the already created Boolean.TRUE and Boolean.FALSE value instead of creating a new instance every time.

RUE and Boolean.FALSE value instead of creating a new instance every time.

If you don't need a new instance of the Boolean object then you should always use Boolean.valueOf() method to create Boolean objects to get better performance.

This method is also overloaded to create a Boolean object from both Strings as well as primitive boolean value e.g. both valueOf(true) and valueOf("true") will return same Boolean.TRUE object.

In short:

Oracle Java Tutorial and Materials, Oracle Java Learning, Oracle Java Study Materials, Oracle Java Guides

Java Program to Convert String to Boolean


Here is our complete Java program to convert String to Boolean in Java. It's quite similar to the earlier program for converting String to Integer, Long, Double, Float, Short, and Byte in Java. All of them follow same technique to convert String to other data types. 

/**
 * 
 * A simple example to convert String to Boolean in Java
 */
public class Hello {

  public static void main(String args[]) {

    // parseBoolean returns a boolean primitive value
    String value = "true";
    boolean b = Boolean.parseBoolean(value);
    System.out.println(b);

    // valueOf returns a Boolean object
    String data = "false";
    boolean f = Boolean.valueOf(data);
    System.out.println(f);

    value = "NO";
    b = Boolean.parseBoolean(value);
    System.out.println(b);

    // null String will return false
    System.out.println(Boolean.parseBoolean(null));
    System.out.println(Boolean.valueOf(null));

    // any value other than true (Case-insensitive) will
    // return false
    System.out.println(Boolean.parseBoolean("YES"));
    System.out.println(Boolean.valueOf("Y"));
  }
}

Output
true
false
false
false
false
false
false

Important Points


Some important points about parseBoolean and valueOf methods which are worth remembering:

1. Both parseBoolean() and valueOf() are static methods defined in java.lang.Boolean class.

2. The parseBoolean() returns a primitive boolean value while valueOf() returns a Boolean object.

3. Both parseBoolean() and valueOf() are null-safe which means if you pass null String to them they will return false boolean value instead of throwing NullPointerException.

4. Both methods are also case-insensitive, which means "true", "TRUE", and "True" will return same Boolean.TRUE value.

5. Prefer valueOf() over parseBoolean() if you need Boolean object because it returns cached Boolean objects, defined in the Boolean class itself i.e. Boolean.TRUE for true and Boolean.FALSE for false.

6. The valueOf() provides better performance because of caching.

7. Autoboxing boolean primitive to Boolean object also uses the Boolean.valueOf() method.

That's all about how to convert a String to boolean in Java. You should use the Boolean.parseBoolean() method if you need a primitive boolean value and Boolean.valueOf() if you need a Boolean object. The valueOf() method also provide better performance because it always returns the two pre-created instance i.e. Boolean.TRUE and Boolean.FALSE instead of creating a new object everytime you parse a String to boolean.

Monday, October 1, 2018

How to Subtract two Binary Numbers in Java

Binary subtraction is very similar to binary addition which we have learned in the last article. In this tutorial, you will learn how to subtract two binary numbers. Similar to the last article, we'll see two ways, first by converting binary String to a binary number and then doing subtraction. You can use the Java API Integer.toString(number, radix) for that. On second solution you will learn to develop the logic to perform binary subtraction in Java program by using rules you might have learned in your computer classes. Here is a little summary of how binary subtraction works.

Oracle Java Tutorial and Materials, Oracle Java Guides, Oracle Java Certification

Subtraction works in much the same way:

0 − 0 → 0
0 − 1 → 1, borrow 1
1 − 0 → 1
1 − 1 → 0

Subtracting a "1" digit from a "0" digit produces the digit "1", while 1 will have to be subtracted from the next column. This is known as borrowing. The principle is the same as for carrying. When the result of a subtraction is less than 0, the least possible value of a digit, the procedure is to "borrow" the deficit divided by the radix (that is, 10/10) from the left, subtracting it from the next positional value.

There are also a couple of other ways to perform binary subtraction e.g. binary subtraction using 1's complement and binary subtraction using 2's complement. Let's see how those work by first subtracting two binary number using 1's complement:

How to subtract two binary numbers using 1's complement

In one's complement, you negate the binary number where 1 turned to zero and zero turned to 1. Here are the exact steps to subtract two binary number using 1's complement:

1) Calculate1’s complement of the subtrahend.
2) Add 1's complement with the minuend.
3) If the result of addition has a carryover then it is dropped and a 1 is added in the last bit.
4) If there is no carryover, then 1’s complement of the result of the addition is obtained to get the final result and it is negative.

Example: What is the difference between two binary numbers 110101 – 100101?

Solution: 1’s complement of 10011 is 011010.
Hence

Minuted - 110101
1’s complement of subtrahend - 011010
Carryover - 1 001111
1
010000
The required difference is 10000

Here is another example of subtracting 101011 – 111001. First, let's calculate 1’s complement of 111001, which is 000110.
Hence

Minued - 101011
1’s complement - 000110
difference - 110001

Hence the difference between two binary numbers 101011 and 111001 is 1110

Oracle Java Tutorial and Materials, Oracle Java Guides, Oracle Java Certification

Java Program to subtract two binary numbers


import java.util.Scanner;

/*
 * Java Program to add subtract two binary numbers.
 * You can either write your own method or you 
 * can use Java API for doing binary subtraction.
 * 
 * input: 110101 - 100101
 * output = 1111
 */

public class Main {

  public static void main(String[] args) {

    System.out.println("Welcome to Java program to add two binary numbers");
    Scanner scnr = new Scanner(System.in);

    System.out.println("Please enter first binary number");
    String first = scnr.nextLine();

    System.out.println("Please enter second binary number");
    String second = scnr.nextLine();

    String difference = subtract(first, second);
    System.out.println("difference between two binary number is : "
        + difference);

    scnr.close();

  }

  /**
   * Java method to calculate the difference between two binary numbers this method
   * calculate sum by first converting binary String to binary numbers and then
   * subtracting them using binary arithmetic.
   * 
   * @param first
   * @param second
   * @return sum of two given binary numbers
   */
  public static String subtract(String first, String second) {
    int b1 = Integer.parseInt(first, 2);
    int b2 = Integer.parseInt(second, 2);
    int sum = b1 - b2;
    return Integer.toBinaryString(sum);
  }

}

Output
Welcome to Java program to add two binary numbers
Please enter the first binary number
110101
Please enter the second binary number
100101
difference between two binary number is: 10000