Bitwise operators in java with example

  • Bitwise operators in java performs operation on bits 
  • Bitwise operators performs bit by bit operations
  • Bit-wise operators operates on individual bits of operands.



 Bit wise Operators in Java:

  1. ~      : Bit wise unary not
  2. &     : Bit wise And
  3. |       : Bit wise OR
  4. ^      : Bit wise Exclusive OR


 1.Bit wise Unary Not  ~:

  • Bit wise Unary not Inverts the bits.
  • Lets see a java program on bit wise unary not

Java Example program on bit wise unary not operator ~:

  1. package operatorsinjava;
  2. public class BitwiseUnaryNotDemo {
  3.  
  4.     /**
  5.      * @www.instanceofjava.com
  6.      */
  7.     public static void main(String[] args) {
  8.  
  9.   int x=2;
  10.  
  11.   System.out.println(~x);
  12.         
  13.   int y= 3;
  14.  
  15.   System.out.println(~y);
  16.         
  17.   int z= 4;
  18.         
  19.   System.out.println(~z);
  20.  
  21.     }
  22.  
  23. }

Output:


  1. -3
  2. -4
  3. -5

bitwise unary operator in java


2. Bitwise AND operator:

  • Bit wise And returns 1 if both operands position values are 1 otherwise 0.
  • Bitwise operation on two numbers
  • 1 & 2
  • 001
    010
    -----
    000 =0
    -----
  • 2 & 3
  • 010
    011
    -----
    010 =2
    -----
Java Example program on bitwise AND operator &:


  1. package operatorsinjava;
  2. public class BitwiseAndDemo {
  3.  
  4.     /**
  5.      * @www.instanceofjava.com
  6.      */
  7. public static void main(String[] args) {

  8.    int x=1;
  9.    int y=2;
  10.         
  11.   System.out.println(x&y);
  12.         
  13.   int i=2;
  14.   int j=3;
  15.         
  16.  System.out.println(i&j);
  17.         
  18.  System.out.println(4&5);
  19.  
  20. }
  21.  
  22. }

Output:


  1. 0
  2. 2
  3. 4
Bitwise And operator in java Example


3.Bitwise OR operator in Java | :

  • Bit wise OR returns 1 if  any one operands position values are 1 or both 1 s. otherwise 0.
  • 1 |2
  • 001
    010
    -----
    011 =3
    -----
  • 2 | 3
  • 010
    011
    -----
    011 =3
    -----
Java Example program on bitwise OR operator |:

  1. package operatorsinjava;
  2. public class BitwiseORDemo {
  3.  
  4.     /**
  5.      * @www.instanceofjava.com
  6.      */
  7. public static void main(String[] args) {

  8.    int x=1;
  9.    int y=2;
  10.         
  11.   System.out.println(x|y);
  12.         
  13.   int i=2;
  14.   int j=3;
  15.         
  16.  System.out.println(i|j);
  17.         
  18.  System.out.println(4|5);
  19.  
  20. }
  21.  
  22. }

Output:

  1. 3
  2. 3
  3. 5

4.Bit wise Exclusive OR operator in java ^:

  • Bit wise XOR operator returns 1 if any of the operands bits position 1 
  • Java XOR operator returns 0 if both operands position is 1.
  • Lest see java Xor on 1 ^ 2
  • 1 ^ 2
  • 001
    010
    -----
    011 =3
    -----
  • Lest see java xor operation on 2 ^3
  • 2 ^ 3
  • 010
    011
    -----
    001 =1
    -----

Java Example program on bitwise OR operator |:

  1. package operatorsinjava;
  2. public class BitwiseXORDemo {
  3.  
  4.     /**
  5.      * @www.instanceofjava.com
  6.      */
  7. public static void main(String[] args) {

  8.    int x=1;
  9.    int y=2;
  10.         
  11.   System.out.println(x^y);
  12.         
  13.   int i=2;
  14.   int j=3;
  15.         
  16.  System.out.println(i^j);
  17.         
  18.  System.out.println(4^5);
  19.  
  20. }
  21.  
  22. }

Output:

  1. 3
  2. 1
  3. 1


Java XOR bitwise operator

Ternary operator in java

  • Ternary operator also known as conditional operator in java.
  • Ternary operator used to evaluate boolean expression and it consists of three operands.
In Java, the ternary operator is a shorthand way to write an if-else statement. The operator has the following general form:
    (condition) ? expression1 : expression2
      The condition is a Boolean expression that is evaluated to either true or false. If the condition is true, the operator returns the value of expression1, and if the condition is false, it returns the value of expression2.

      Here's an example of how you might use the ternary operator in a Java program:

      int x = 5;
      int y = 10;

      int min = (x < y) ? x : y;
      System.out.println(min);  // Output: 5

      In the above example, the ternary operator compares the values of x and y, and assigns the value of x to the variable min if x is less than y, and assigns the value of y to min otherwise. This can be interpreted as (x<y) ? min=x : min=y .

      It's also possible to use ternary operator for more complex use cases like below:

      String result = condition ? "value if true" : anotherVar == null ? "null value" : anotherVar;

      It's worth noting that, although ternary operator is a shorthand way to write an if-else statement, it can make code harder to read when the expressions are too long or the conditions are too complex. In such cases, it's often better to use an if-else statement instead.





      Ternary operator in java syntax:

      1. variable x = (expression) ? value if true : value if false

      • Value of x will be decided based on the condition. if condition is true then it assigns first value to the variable
      • If Expression is false then it assigns second value to the variable.

      Java simple example program on ternary operator / conditional operator in java


      1. package operatorsinjava;
      2. public class TernaryOperator {
      3.  
      4.     /**
      5.      * @ www.instanceofjava.com
      6.      * 
      7.      */
      8.  public static void main(String[] args) {
      9.         
      10.  // checking condition 2>3 and if true assign 3 else 3
      11.   int x= (2>3)?3:2;
      12.         
      13.   System.out.println(x);
      14.         
      15.  // checking condition 5<4 if true assign 4 else 3
      16.  int y= (5<4)?4:3;
      17.         
      18.  System.out.println(y);
      19.  
      20. }
      21.  
      22. }
      Output:

      1. 2
      2. 3

      Ternary operator in java for boolean:

      Java simple example program on ternary operator / conditional operator for boolean

      1. package operatorsinjava;
      2. public class TernaryOperator {
      3.  
      4.     /**
      5.      * @ www.instanceofjava.com
      6.      * 
      7.      */
      8.  public static void main(String[] args) {
      9.         
      10.  
      11.  boolean x= true ? true: false;
      12.         
      13.  System.out.println(x);
      14.         
      15.  boolean y= false ? true : false;
      16.             
      17.  System.out.println(y);
      18.         
      19.  boolean z= false ? false : true;
      20.         
      21.  System.out.println(z);
      22.  
      23. }
      24.  
      25. }
      Output:

      1. true
      2. false
      3. true

      Ternary operator in java for Strings:

      Java simple example program on ternary operator / conditional operator for String

      1. package operatorsinjava;
      2. public class TernaryOperatorForStrings{
      3.  
      4.     /**
      5.      * @ www.instanceofjava.com
      6.      * 
      7.      */
      8. public static void main(String[] args) {
      9.         
      10.  String str= "java".equals("java") ? "Java Questions" : "Java Programs";
      11.         
      12.  System.out.println(str);
      13.         
      14.  String str1= (1==3)? "its true" : "its false";
      15.         
      16.  System.out.println(str1);
      17.        
      18. }
      19.  
      20. }
      Output:

      1. Java Questions
      2. its false

      Ternary operator in java for null;

      Java simple example program on ternary operator / conditional operator for null check

      1. package operatorsinjava;
      2. public class TernaryOperatorForStrings{
      3.  
      4.     /**
      5.      * @ www.instanceofjava.com
      6.      * 
      7.      */
      8. public static void main(String[] args) {
      9.         
      10. String str= null;
      11.  
      12. String str1= (str==null) ? "its true" : "its false";
      13.  
      14. System.out.println(str1);
      15.         
      16. String str2= (str1!=null) ? "its true" : "its false";
      17.  
      18. System.out.println(str2);

      19. }
      20.  
      21. }
      Output:

      1. its true
      2. its true

      ternary operator in java


      Top 20 Java Exception handling interview questions and answers

      1.What is an exception?


      • Exceptions are the objects representing the logical errors that occur at run time and makes JVM enters into the state of  "ambiguity".
      • The objects which are automatically created by the JVM for representing these run time errors are known as Exceptions



      2.What are the differences between exception and error.

      • An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.
      • Difference between exception and error

      3.How the exceptions are handled in java

      • Exceptions can  be handled using try catch blocks.
      • The statements which are proven to generate exceptions need to keep in try block so that whenever is there any exception identified in try block that will be assigned to corresponding exception class object in catch block
      • More information about try catch finally

      4.What is the super class for Exception and Error

      • Throwable.


      1. public class Exception extends Throwable implements Serializable


      1. public class Error extends Throwable implements Serializable

      5.Exceptions are defined in which java package

      • java.lang.Exception

      6.What is throw keyword in java?

      • Throw keyword is used to throw exception manually.
      • Whenever it is required to suspend the execution of the functionality based on the user defined logical error condition we will use this throw keyword to throw exception.
      • Throw keyword in java

      7.Can we have try block without catch block

      • It is possible to have try block without catch block by using finally block
      • Java supports try with finally block
      • As we know finally block will always executes even there is an exception occurred in try block, Except System.exit() it will executes always.
      • Is it possible to write try block without catch block

      8.Can we write multiple catch blocks under single try block?


      exception handling interview questions and answers


      9. What are unreachable blocks in java

      • The block of statements to which the control would never reach under any case can be called as unreachable blocks.
      • Unreachable blocks are not supported by java.
      • Unreachable blocks in java


      unreachable block exception handling interview question



      10.How to write user defined exception or custom exception in java



      1. class CustomException extends Exception { } // this will create Checked Exception
      2. class CustomException extends IOExcpetion { } // this will create Checked exception
      3. class CustomException extends NullPonterExcpetion { } // this will create UnChecked
      4. exception

      11.What are the different ways to print exception message on console.

      • In Java there are three ways to find the details of the exception .
      • They are 
      1. Using an object of java.lang.Exception
      2. Using public void printStackTrace() method
      3. Using public String getMessage() method.
      print exception message in java



      12.What are the differences between final finally and finalize in java




      13.Can we write return statement in try and catch blocks


      return statement in try catch block exception handling



      14. Can we write return statement in finally block



      return statement in finally exception handling interview


      15. What are the differences between throw and throws


      •  throw keyword used to throw user defined exceptions.(we can throw predefined exception too)
      • Using throws keyword we can explicitly provide the information about unhand-led exceptions of the method to the end user, Java compiler, JVM.
      • Throw vs throws

      throw vs throws

       16.Can we change an exception of a method with throws clause from unchecked to checked while overriding it? 


      •  No. As mentioned above already
      • If super class method throws exceptions in sub class if you want to mention throws  then use  same class  or its  sub class exception.
      • So we can not change from unchecked to checked 

       17.What are the rules we need to follow in overriding if super class method throws exception ?


      •  If sub class throws checked exception super class should throw same or super class exception of this.
      • If super class method  throws checked or unchecked exceptions its not mandatory to put throws in sub class overridden method.
      • If super class method throws exceptions in sub class if you want to mention throws  then use  same class  or its  sub class exception.

       

      18.What happens if we not follow above rules if super class method throws some exception.

      •  Compile time error will come.

      1. package MethodOverridingExamplePrograms;
      2. public class Super{
      3.  
      4. public void add(){
      5.  System.out.println("Super class add method");
      6. }

      7. }

      1. package MethodOverridingInterviewPrograms;
      2. public class Sub extends Super{
      3.   
      4. void add() throws Exception{ //Compiler Error: Exception Exception is not compatible with
      5. throws clause in Super.add()
      6. System.out.println("Sub class add method");

      7. }

      8. }

      1. package ExceptionHandlingInterviewPrograms;
      2. public class Super{
      3.  
      4. public void add(){
      5.  System.out.println("Super class add method");
      6. }

      7. }

      1. package ExceptionHandlingInterviewPrograms;
      2. public class Sub extends Super{
      3.   
      4. void add() throws NullPointerException{ // this method throws unchecked exception so no
      5. isuues
      6. System.out.println("Sub class add method");

      7. }

      8. }

       19. Is it possible to write multiple exceptions in single catch block


      • It is not possible prior to java 7.
      • new feature added in java 7.


      1. package exceptionsFreshersandExperienced;
      2. public class ExceptionhandlingInterviewQuestions{
      3.  
      4. /**
      5.  * @www.instanceofjava.com
      6.  **/
      7.  public static void main(String[] args) {

      8.  
      9. try {
      10.  
      11. // your code here
      12.             
      13. } catch (IOException | SQLException ex) {
      14.             System.out.println(e);
      15. }
      16.  
      17. }
      18.  
      19. }



      20. What is try with resource block

      • One more interesting feature of Java 7 is try with resource 
      • In Java, if you use a resource like input or output streams or any database connection logic you always need to close it after using. 
      • It also can throw exceptions so it has to be in a try block and catch block. The closing logic  should be in finally block. This is a least the way until Java 7. This has several disadvantages:

        1.     You'd have to check if your ressource is null before closing it
        2.     The closing itself can throw exceptions so your finally had to contain another try -catch
        3.     Programmers tend to forget to close their resources

      • The solution given by using try with resource statement.

      1. try(resource-specification) 
      2. {
      3.  
      4. //use the resource
      5.  
      6. }catch(Exception e)
      7. {
      8.  
      9. //code

      10. }

      • Top 20 Java Exception handling interview questions and answers for freshers and experienced

      3 different ways to print exception message in java

      • In Java there are three ways to find the details of the exception .
      • They are 
      1. Using an object of java.lang.Exception
      2. Using public void printStackTrace() method
      3. Using public String getMessage() method.

      1.Using an object of java.lang.Exception

      •  An object of Exception class prints the name of the exception and nature of the exception.



      Write a Java program get detailed message details using exception class object



      1. package exceptions;
      2. public class ExceptionDetails {
      3.  
      4. /**
      5.  * @www.instanceofjava.com
      6.  **/
      7.  public static void main(String[] args) {
      8.  
      9. try {
      10.  
      11. int x=1/0;
      12.             
      13. } catch (Exception e) {
      14.             System.out.println(e);
      15. }
      16.  
      17. }
      18.  
      19. }

       Output:


      1. java.lang.ArithmeticException: / by zero


       2.Using  public void printStackTrace() method


      • This is the method which is defined in java.lang.Throwable class and it is inherited into java.lang.Error class and java.lang.Exception class
      • This method will display the name of the exception and nature of the message and line number where exception has occurred.

      Write a simple java example program to print exception message to console using printStacktrace() method



      1. package exceptions;
      2. public class ExceptionDetails {
      3.  
      4.     /**
      5.      * @www.instanceofjava.com
      6.      */
      7. public static void main(String[] args) {

      8.  
      9.  try {
      10.           int a[]= new int[1];
      11.             a[1]=12
      12.             
      13. } catch (Exception e) {
      14.    e.printStackTrace();
      15.            
      16.  }
      17. }
      18.  
      19. }

       Output:


      1. java.lang.ArrayIndexOutOfBoundsException: 1
            at exceptions.ExceptionDetails.main(ExceptionDetails.java:13)

        3.Using public String getMessage() method

      •  This is also a method which is defined in java.lang.Throwable class and it is inherited in to both java.lanf.Error and java.lang.Exception classes.
      • This method will display the only exception message


      Write a Java program print exception message using getMessage() method.


      1. package exceptions;
      2. public class ExceptionDetails {
      3.  
      4.     /**
      5.      * @www.instanceofjava.com
      6.      */
      7.     public static void main(String[] args) {

      8.  
      9.         try {
      10.             int x=1/0;
      11.             
      12.         } catch (Exception e) {
      13.             System.out.println(e.getMessage());
      14.         }
      15.     }
      16.  
      17. }

       Output:


      1.  / by zero

      print exception message

      throw keyword in java with example

      Throw keyword in java

      • Throw keyword is used to throw exception manually.
      • Whenever it is required to suspend the execution of the functionality based on the user defined logical error condition we will use this throw keyword to throw exception.
      • So we need to handle these exceptions also using try catch blocks.



       Java simple example Program to explain use of throw keyword in java


      1. package exceptions;
      2.  
      3. public class ThrowKeyword {
      4.  
      5.     
      6. public static void main(String[] args) {
      7.  
      8. try {
      9.             
      10.    throw new ArithmeticException();
      11.             
      12.             
      13. } catch (Exception e) {
      14.  
      15.    System.out.println(e);
      16.    e.printStackTrace();
      17. }
      18.  
      19. }
      20.  
      21. }

      Output:



      1. java.lang.ArithmeticException
      2. java.lang.ArithmeticException
      3.     at exceptions.ThrowKeyword.main(ThrowKeyword.java:11)

      Rules to use "throw" keyword in java
      • throw keyword must follow Throwable type of object.
      • It must be used only in method logic.
      • Since it is a transfer statement , we can not place statements after throw statement. It leads to compile time error Unreachable code



      throw keyword in java


      •  We can throw user defined exception using throw keyword.

      1. //Custom exception
      2. package com.instanceofjavaforus;
      3. public class InvalidAgeException extends Exception {
      4.  InvaidAgeException(String msg){
      5.  super(msg);
      6.  }
      7. }
         

      1. package com.exceptions;
      2. public class ThrowDemo {

      3. public boolean isValidForVote(int age){
      4.  
      5.  try{
      6.    if(age<18){
      7.   throw new InvalidAgeException ("Invalid age for voting");
      8. }
      9.  }catch(Exception e){
      10.  System.out.println(e);
      11.  }
      12.   return false;
      13.  }
      14.  
      15. public static void main(String agrs[]){
      16.  
      17.  ThrowDemo obj= new ThrowDemo();
      18.    obj.isValidForVote(17);
      19.  
      20.   }
      21. }


       Output:


      1.  exceptions.InvalidAgeException: Invalid age for voting
      • We can throw predefined exceptions using throw keyword


      1. package com.instanceofjava;
      2.  
      3. public class ThrowKeyword{
      4. public void method(){
      5.  
      6.  try{
      7.   
      8.   throw new NullPointerException("Invalid age for voting");
      9. }
      10.  }catch(Exception e){
      11.  System.out.println(e);
      12.  }
      13.  }
      14.  
      15.   public static void main(String agrs[]){
      16.  
      17.  ThrowKeyword obj= new ThrowKeyword();
      18.  
      19.    obj.method();
      20.  
      21.   }
      22. }

       Output:


      1.  java.lang.NullPointerException: Invalid age for voting

      Multiple catch blocks in java example

      Is there any chance of getting multiple exception?

      • Lets see a java example programs which can raise multiple exceptions.


      1. package exceptions;
      2. public class MultipleCatchBlocks {
      3.  
      4.     /**
      5.      * @www.instanceofjava.com
      6.      */
      7.  
      8. public static void main(String[] args) {
      9.         
      10.         
      11.  int x=10;
      12.  int y=0;
      13.  
      14. try{
      15.             
      16.    int i=x/y;
      17.    int a[]=new int[2];
      18.    a[3]=12;
      19.             
      20. } catch(ArithmeticException e){
      21.             e.printStackTrace();
      22. }
      23.  
      24. }
      25.  
      26. }

      Output:


      1. java.lang.ArithmeticException: / by zero
            at exceptions.MultipleCatchBlocks.main(MultipleCatchBlocks.java:15)

      •  Lets see second case:


      multiple catch blocks in java




      try with multiple catch blocks

      • In the 1st program there is a chance of getting two types of exceptions and we kept only one catch block with  ArithmeticException e . 
      • But there will be chance of getting ArrayIndexOutOfBoundsException too. 
      • So we need to keep multiple catch blocks in order to handle all those exceptions
      • Or else we can keep single catch block with super class Exception class object.

       




      Multiple catch blocks for single try block:

       

      • One try can have multiple catch blocks 
      • Every try should and must be associated with at least one catch block.( try without catch)
      • Whenever an exception object is identified in try block and if there are multiple catch blocks then the priority for the catch block would be given based on order in which catch blocks are have been defined.
      • Highest priority would be always given to first catch block . If the first catch block can not handle the identified exception object then it considers the immediate next catch block.

      Disadvantages of multiple catch blocks:
       
      •  We have to know the names of every corresponding exception class names.
      • We have to understand which statement is generating which exception class object.



      Solution: 

      •  Define a single catch block so that it should be able to handle any kind of exceptions identified in the try block.
      • Exception class is the super class for all the exception classes.
      • To the reference of super class object we can assign any sub class object.
      Select Menu