Unreachable Blocks in java

Unreachable Catch Blocks:

  • 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.
  • Thus catch block mentioned with the reference of  "Exception" class should and must be always last catch block. Because Exception is super class of all exceptions.



Program:


  1. package com.instanceofjava;
  2. public class ExcpetionDemo {
  3. public static void main(String agrs[])
  4. {
  5.  
  6. try
  7. {
  8. //statements
  9. }
  10. catch(Exception e)
  11. {
  12. System.out.println(e);
  13. }
  14. catch(ArithmeticException e)//unreachable block.. not supported by java. leads to error
  15. System.out.println(e);
  16. }
  17. }

\Java Example program on unreachable catch block


Unreachable blocks in jaba






  1. package com.instanceofjava;
  2. public class ExcpetionDemo {
  3. public static void main(String agrs[])
  4. {
  5.  
  6. try {
  7.            
  8.  System.out.println("Excpetion handling interview questions Java unreachable block");
  9.             
  10. } catch (IllegalThreadStateException e) {
  11.           e.printStackTrace();
  12. }catch (IllegalArgumentException e) {
  13.             e.printStackTrace();
  14. }catch (Exception e) {
  15.         e.printStackTrace();
  16.  }
  17.    
  18. }
  19. }

Output:

  1. Excpetion handling interview questions Java unreachable block

  1. package com.instanceofjava;
  2. public class ExcpetionDemo {
  3. public static void main(String agrs[])
  4. {
  5.  
  6. try {
  7.            
  8.  System.out.println("Excpetion handling interview questions Java unreachable block");
  9.             
  10. }
  11. catch (Exception e) { 
  12.         e.printStackTrace();
  13.  }catch (IllegalThreadStateException e) {//Error: Unreachable catch block for
  14.  //IllegalThreadStateException. It is already handled by the catch block for Exception
  15.           e.printStackTrace();
  16. }catch (IllegalArgumentException e) {
  17.             e.printStackTrace();
  18. }
  19.    
  20. }
  21. }

Iterator and Custom Iterator in java with example programs

Java Iterator 


  • Iterator is an interface which is made for Collection objects like List, Set. It comes inside java.util package and it was introduced in java 1.2 as public interface Iterator. To generate successive elements from a Collection, we can use java iterator. It contains three methods: those are, 

  1. boolean hasNext(): this method returns true if this Iterator has more element to iterate. 
  2. remove(): method remove the last element return by the iterator this method only calls once per call to next().     
  3. Object next() : Returns the next element in the iteration.
  • Every collection classes provides an iterator() method that returns an iterator to the beginning of the collection. By using this iterator object, we can access each element in the collection, one element at a time. In general, to use an iterator to traverse through the contents of a collection follow these steps:
  • Obtain Iterator object by calling Collections’s iterator() method
  • Make a loop to decide the next element availability by calling hasNext() method.
  •  Get each element from the collection by using next() method.
Java Program which explains how to use iterator in java

  • Here is an example demonstrating Iterator. It uses an ArrayList object, You can apply to any type of collection.

  1. import java.util.ArrayList;
  2. import java.util.Iterator;
  3.  
  4. public class IteratorExample {
  5.  
  6. public static void main(String args[]) {
  7.  
  8.  // create an array list. But, you can use any collection
  9.  ArrayList<String> arraylist = new ArrayList<String>();
  10.   
  11. // add elements to the array list
  12.  arraylist .add("Raja");
  13.  arraylist .add("Rani");
  14.  arraylist .add("Shankar");
  15.  arraylist .add("Uday");
  16.  arraylist .add("Philips");
  17.  arraylist .add("Sachin");
  18.  
  19. // use iterator to display contents of arraylist
  20.  System.out.println("Original contents of arraylist : ");
  21.  
  22. Iterator<String> itr = arraylist .iterator();
  23.  
  24.   while (itr.hasNext()) {
  25.  
  26.     Object obj = itr.next();
  27.      System.out.print(obj + "\n");
  28.  
  29.      }
  30.  
  31.  }
  32. }

 

Output:

  1. Original contents of arraylist : 
  2. Raja
  3. Rani
  4. Shankar
  5. Uday
  6. Philips
  7. Sachin


  •  Iterator is the best choice if you have to iterate the objects from a Collection. But, Iterator having some limitations.

  • Those are,
  1. Iterator is not index based 
  2.  If you need to update the collection object being iterated, normally you are not allowed to because of the way the iterator stores its position. And it will throw ConcurrentModificationException.
  3. It does not allow to traverse to bi directions.
custom ierator interface in java


  • To overcome these on other side,  we have For-each loop. It was introduced in Java 1.5
  • Advantages of For each loop :
  1. Index Based  
  2. Internally the for-each loop creates an Iterator to iterate through the collection.
  3. If you want to replace items in your collection objects, use for-each loop
  • Consider the following code snippet, to understand the difference between how to use Iterator and for-each loop. 



  1. Iterator<String> itr = aList.iterator();
  2.  
  3. while (itr.hasNext()) {
  4. Object obj = itr.next();
  5. System.out.print(obj + "\n");
  6. }
  7.  
  8. Is same as,
  9.  
  10. For (String str : aList){
  11. System.out.println(str);
  12. }

  • Same code has been rewritten using enhanced for-loops which looks more readable. But enhanced for-loops can’t be used automatically in Collection objects that we implement. Then what do we do? This is where Iterable interface comes in to picture. Only, if our Collection implemented Iterable interface, we can iterate using enhanced for-loops. The advantage of implementing Iterable interface So, we should implement Java Iterable interface in order to make our code more elegant.
  • Here I am going to write a best Practice to develop a custom iterator. Following is the Syntax.


  1. public class MyCollection<E> implements Iterable<E>{
  2.  
  3. public Iterator<E> iterator() {
  4.         return new MyIterator<E>();
  5.     }
  6.  
  7. public class MyIterator <T> implements Iterator<T> {
  8.  
  9.     public boolean hasNext() {
  10.     
  11.         //implement...
  12.     }
  13.  
  14.     public T next() {
  15.         //implement...;
  16.     }
  17.  
  18.     public void remove() {
  19.         //implement... if supported.
  20.     }
  21.  
  22. public static void main(String[] args) {
  23.     MyCollection<String> stringCollection = new MyCollection<String>();
  24.  
  25.     for(String string : stringCollection){
  26.     }
  27. }
  28. }
  29.  
  30. }


  1. package com.instanceofjava.customIterator;
  2.  
  3. public class Book {
  4.  
  5.     String name;
  6.     String author;
  7.     long isbn;
  8.     float price;
  9.    
  10.  
  11.     public Book(String name, String author, long isbn, float price) {
  12.         this.name = name;
  13.         this.author = author;
  14.         this.isbn = isbn;
  15.         this.price = price;
  16.     }
  17.  
  18.  public String toString() {
  19.         return name + "\t" + author + "\t" + isbn + "\t" + ": Rs" + price;
  20.   }
  21.  
  22. }

  1. package com.instanceofjava.customIterator;
  2. import java.util.ArrayList;
  3. import java.util.Iterator;
  4. import java.util.List;
  5. import com.pamu.test.Book;
  6. import java.lang.Iterable;
  7.  
  8. public class BookShop implements Iterable<Book> {
  9.  
  10.     List<Book> avail_books;
  11.  
  12.     public BookShop() {
  13.         avail_books = new ArrayList<Book>();
  14.     }
  15.  
  16.     public void addBook(Book book) {
  17.         avail_books.add(book);
  18.     }
  19.  
  20.     public Iterator<Book> iterator() {
  21.         return (Iterator<Book>) new BookShopIterator();
  22.     }
  23.  
  24.     class BookShopIterator implements Iterator<Book> {
  25.         int currentIndex = 0;
  26.  
  27.         @Override
  28.         public boolean hasNext() {
  29.             if (currentIndex >= avail_books.size()) {
  30.                 return false;
  31.             } else {
  32.                 return true;
  33.             }
  34.         }
  35.  
  36.         @Override
  37.         public Book next() {
  38.             return avail_books.get(currentIndex++);
  39.         }
  40.  
  41.         @Override
  42.         public void remove() {
  43.             avail_books.remove(--currentIndex);
  44.         }
  45.  
  46.     }
  47.     
  48.     //main method
  49.     
  50.   public static void main(String[] args) {
  51.  
  52.         Book book1 = new Book("Java", "JamesGosling", 123456, 1000.0f);
  53.         Book book2 = new Book("Spring", "RodJohnson", 789123, 1500.0f);
  54.         Book book3 = new Book("Struts", "Apache", 456789, 800.0f);
  55.  
  56.         BookShop avail_books = new BookShop();
  57.         avail_books.addBook(book1);
  58.         avail_books.addBook(book2);
  59.         avail_books.addBook(book3);
  60.  
  61.         System.out.println("Displaying Books:");
  62.         for(Book total_books : avail_books){
  63.             System.out.println(total_books);
  64.         }
  65.  
  66.     }
  67.  
  68. }

  • Here, we created a  BookShop class which contains books. This class able to use for-each loop only if it implements Iterable interface.Here, we have to provide the implementation for iterator method. we define my BookShopIterator as inner class.
  •  Inner classes will provide more security, So that your class is able to access with in the Outer class and this will achieve data encapsulation.
  • The best reusable option is to implement the interface Iterable and override the method iterator().The main advantage of Iterable is, when you implement Iterable then those object gets support for for:each loop syntax.
  • Execute above program and check output. Practice makes perfect.

Basic operators in java

Types of Operators in Java:

  1. Arithmetic Operators
  2. Bit-wise Operators
  3. Logical Operators
  4. Relational Operators 
  5. Assignment Operators
  6. Misc Operators



Java operator precedence

java order of operations

Arithmetic Operators
  • Arithmetic operators are used in mathematical expressions.
  • Following are the arithmetic operators in java.
  1. +  :  Addition
  2. -   : Subtraction
  3. *  : Multiplication
  4. /   : Division
  5. % : Modulus

Bit wise Operators:

  • Bit wise operators operates on individual bits of operands.
  • Following are the Bit-wise operators in java. 
  • Bitwise operators in java

  1. ~      : Bit wise unary not
  2. &     : Bit wise And
  3. |       : Bit wise OR
  4. ^      : Bit wise Exclusive OR
  5. >>    : Shift Right
  6. >>>  : Shift right zero fill
  7. <<    :Shift left

Logical Operators:

  1. && : Logical AND
  2. ||      : Logical OR
  3. !      : Logical NOT

Relational Operators in java

  1. ==  : Equal to
  2. !=   : Not Equal to
  3. <    : Less Than
  4. >    : Greater Than
  5. >=  : Greater Than or Equal to
  6. <= : Less Than or Equal to

Assignment Operators:

  1. =    : Simple Assignment
  2. +=  : Add and assign
  3. -=   : Subtract and assign
  4. *=   : Multiply and assign
  5. %=  : Modulus and assign
  6. /=    : Divide and assign
  7. &=   : Bit wise AND assignment
  8. |=     : Bit wise assignment OR
  9. ^=    : Bit wise Exclusive OR assignment
  10. >>= : Shift Right assignment
  11. >>>= : Shift right  zero fill assignment
  12. <<=   : Shift left assignment


Misc Operators:

Increment and Decrement operators:
  1. ++ : increment
  2. --   : decrement


Conditional Operator: (?:)

  • Also known as ternary operator
  • Example: int a= 1>2?1:2;

Ternary operator in java


Instanceof Operator
  • Instance of operator is used to test whether that object is belong to that class type or not.
  • If that object belongs to that class it returns true .otherwise it returns false.
  • Instance of operator is also known as comparison operator.because it compares with the instance of type.
Instanceof operator in java

Top 30 frequently asked java interview programs for freshers

Java Example program convert Decimal to Binary

  • On of the way to convert decimal number to its binary representation using the Integer.toBinaryString() method. This method takes an integer as an argument and returns its binary representation as a string. Here is an example:
public static String decimalToBinary(int decimal) {
    return Integer.toBinaryString(decimal);
}

We can call this method and pass a decimal number as an argument, and it will return the binary representation of that number. For example:

int decimal = 10;
String binary = decimalToBinary(decimal);
System.out.println(binary); // Output: 1010

In the above method will return a string representation of the binary number, if we want to have it as an integer you can use Integer.parseInt(binary, 2) to convert it to an int.

Another way to convert a decimal number to its binary representation is by using bit shifting and bitwise operations. You can repeatedly divide the decimal number by 2 and keep track of the remainder. The remainder represents the least significant bit of the binary representation. You can then reverse the order of the remainders to get the binary representation of the decimal number.

In summary, In Java you can use the Integer.toBinaryString() method to convert a decimal number to its binary representation as a string, and you can use Integer.parseInt(binary, 2) to convert it to an int. Also, you can use bit shifting and bitwise operations to convert a decimal number to its binary representation.

Another way to convert a decimal number to its binary representation is by using bit shifting and bitwise operations. 
This method involves repeatedly dividing the decimal number by 2 and keeping track of the remainders. The remainders represent the least significant bits of the binary representation.


public static String decimalToBinaryUsingBitOperation(int decimal) {
    StringBuilder binary = new StringBuilder();
    while (decimal > 0) {
        binary.append(decimal % 2);
        decimal = decimal >> 1;
    }
    return binary.reverse().toString();
}

the function uses a while loop to divide the decimal number by 2 and keep track of the remainders. The remainders are appended to a StringBuilder object. The while loop continues until the decimal number is 0. At the end of the loop, the binary representation of the decimal number is obtained by reversing the order of the remainders using the reverse() method of the StringBuilder. The binary representation is then returned as a string.

This method will also work for negative decimal numbers, but the result will be the two's complement representation of the negative number, it will have a leading 1 in the most significant bit.

It's worth noting that, the above method will return the binary representation as a string, if you want to have it as an integer you can use Integer.parseInt(binary, 2) to convert it to an int.

In summary, there are different ways to convert a decimal number to its binary representation in Java. One way is to use the Integer.toBinaryString() method, another way is by using bit shifting and bitwise operations, this method uses a while loop to repeatedly divide the decimal number by 2 and keep track of the remainders, which represent the binary representation of the decimal number. The result can be returned as a string or as an integer by using the Integer.parseInt(binary, 2)

  • We can convert binary to decimal in three ways
    1.Using Integer.toBinaryString(int num);
    2.Using Stack
    3.Using Custom logic 


1.Write a Java Program to convert decimal to binary in java using Integer.toBinaryString(int num)

  1. import java.util.Scanner;
  2. public class ConvertDecimalToBinary{
  3.  
  4.     /**
  5.      *www.instanceofjava.com
  6.      */
  7.  
  8.  public static void main(String[] args) {
  9.         
  10.  System.out.println("\nBinary representation of 1: ");
  11.  System.out.println(Integer.toBinaryString(1));
  12.  System.out.println("\nBinary representation of 4: ");
  13.  System.out.println(Integer.toBinaryString(4));
  14.  System.out.println("Binary representation of 10: ");
  15.  System.out.println(Integer.toBinaryString(10));
  16.  System.out.println("\nBinary representation of 12: ");
  17.  System.out.println(Integer.toBinaryString(12));
  18.  System.out.println("\nBinary representation of 120: ");
  19.  System.out.println(Integer.toBinaryString(120));
  20.  System.out.println("\nBinary representation of 500: ");
  21.  System.out.println(Integer.toBinaryString(500));

  22. }
  23.  
  24. }





Output:

  1. Binary representation of 1: 
  2. 1
  3. Binary representation of 4: 
  4. 100
  5. Binary representation of 10: 
  6. 1010
  7. Binary representation of 12: 
  8. 1100
  9. Binary representation of 120: 
  10. 1111000
  11. Binary representation of 500: 
  12. 111110100

2.Write a Java Program to convert decimal to binary in java


  1. import java.util.Scanner;
  2. import java.util.Stack;
  3. public class ConvertDecimalToBinary{
  4.  
  5.     /**
  6.      *www.instanceofjava.com
  7.      */
  8.  
  9.  
  10.  public static void main(String[] args) {
  11.         
  12. Scanner in = new Scanner(System.in);
  13.          
  14. // Create Stack object
  15. Stack<Integer> stack = new Stack<Integer>();
  16.      
  17. //Take  User input from keyboard
  18.  System.out.println("Enter decimal number: ");
  19.  int num = in.nextInt();
  20.     
  21. while (num != 0)
  22. {
  23.    int d = num % 2;
  24.    stack.push(d);
  25.    num /= 2;
  26.  
  27.  } 
  28.      
  29.  System.out.print("\nBinary representation is:");
  30.  
  31. while (!(stack.isEmpty() ))
  32.  {
  33.    System.out.print(stack.pop());
  34.  }
  35.         
  36.  
  37. System.out.println();
  38.  
  39. }
  40.  
  41. }
  42.  
  43. }


Output:

  1. Enter decimal number: 
  2. 12
  3.  
  4. Binary representation is:1100

java program convert decimal to binary


3.Write a Java Program to convert decimal to binary in java


  1. import java.util.Scanner;
  2. public class ConvertDecimalToBinary{
  3.  
  4.     /**
  5.      *www.instanceofjava.com
  6.      */
  7.  
  8. public static void convertDeciamlToBinary(int num){
  9.  
  10.   int binary[] = new int[40];
  11.          int index = 0;
  12.  while(num > 0){
  13.            binary[index++] = num%2;
  14.            num = num/2;
  15.  }

  16. for(int i = index-1;i >= 0;i--){
  17.            System.out.print(binary[i]);
  18. }
  19.  
  20. }
  21.  
  22.  public static void main(String[] args) {
  23.         
  24. System.out.println("Binary representation of 1: ");
  25. convertDeciamlToBinary(1);
  26.  
  27. System.out.println("\nBinary representation of 4: ");
  28. convertDeciamlToBinary(4);
  29.  
  30. System.out.println("\nBinary representation of 10: ");
  31. convertDeciamlToBinary(10);
  32.  
  33. System.out.println("\nBinary representation of 12: ");
  34.  convertDeciamlToBinary(12);
  35.  
  36. }
  37.  
  38. }


Output:

  1. Binary representation of 1: 
  2. 1
  3. Binary representation of 4: 
  4. 100
  5. Binary representation of 10: 
  6. 1010
  7. Binary representation of 12: 
  8. 1100

You Might Like:

 


Java programming interview questions

  1. Print prime numbers? 
  2. What happens if we place return statement in try catch blocks 
  3. Write a java program to convert binary to decimal 
  4. Java Program to convert Decimal to Binary
  5. Java program to restrict a class from creating not more than three objects
  6. Java basic interview programs on this keyword 
  7. Interfaces allows constructors? 
  8. Can we create static constructor in java 
  9. Super keyword interview questions java 
  10. Java interview questions on final keyword
  11. Can we create private constructor in java
  12. Java Program Find Second highest number in an integer array 
  13. Java interview programming questions on interfaces 
  14. Top 15 abstract class interview questions  
  15. Java interview Questions on main() method  
  16. Top 20 collection framework interview Questions
  17. Java Interview Program to find smallest and second smallest number in an array 
  18. Java Coding Interview programming Questions : Java Test on HashMap  
  19. Explain java data types with example programs 
  20. Constructor chaining in java with example programs 
  21. Swap two numbers without using third variable in java 
  22. Find sum of digits in java 
  23. How to create immutable class in java 
  24. AtomicInteger in java 
  25. Check Even or Odd without using modulus and division  
  26. String Reverse Without using String API 
  27. Find Biggest substring in between specified character
  28. Check string is palindrome or not?
  29. Reverse a number in java?
  30. Fibonacci series with Recursive?
  31. Fibonacci series without using Recursive?
  32. Sort the String using string API?
  33. Sort the String without using String API?
  34. what is the difference between method overloading and method overriding?
  35. How to find largest element in an array with index and value ?
  36. Sort integer array using bubble sort in java?
  37. Object Cloning in java example?
  38. Method Overriding in java?
  39. Program for create Singleton class?
  40. Print numbers in pyramid shape?
  41. Check armstrong number or not?
  42. Producer Consumer Problem?
  43. Remove duplicate elements from an array
  44. Convert Byte Array to String
  45. Print 1 to 10 without using loops
  46. Add 2 Matrices
  47. Multiply 2 Matrices
  48. How to Add elements to hash map and Display
  49. Sort ArrayList in descending order
  50. Sort Object Using Comparator
  51. Count Number of Occurrences of character in a String
  52. Can we Overload static methods in java
  53. Can we Override static methods in java 
  54. Can we call super class static methods from sub class 
  55. Explain return type in java 
  56. Can we call Sub class methods using super class object? 
  57. Can we Override private methods ? 
  58. Basic Programming Questions to Practice : Test your Skill
  59. Java programming interview questions on collections

Java Example Program to convert binary to decimal


  • Famous interview java question on conversions . 
  • We can convert binary to decimal in two ways
    1.Using Integer.parseInt() method
    2.Using custom logic



1.Write a Java Program to convert binary to decimal number in java without using Integer.parseInt() method.

  1. import java.util.Scanner;
  2. public class DecimalFromBinary {
  3.  
  4.     /**
  5.      *www.instanceofjava.com
  6.      */
  7.  
  8.  public static void main(String[] args) {
  9.         
  10.  Scanner in = new Scanner( System.in );
  11.  System.out.println("Enter a binary number: ");
  12.  
  13.   int  binarynum =in.nextInt();
  14.   int binary=binarynum;
  15.         
  16. int decimal = 0;
  17. int power = 0;
  18.  
  19. while(true){
  20.  
  21.  if(binary == 0){
  22.  
  23.         break;
  24.  
  25.  } else {
  26.  
  27.    int tmp = binary%10;
  28.    decimal += tmp*Math.pow(2, power);
  29.    binary = binary/10;
  30.    power++;
  31.  
  32.  }
  33. }
  34.         System.out.println("Binary="+binary+" Decimal="+decimal); ;
  35. }
  36.  
  37. }

Output:


  1. Enter a binary number: 
  2. 101
  3. Binary=101 Decimal=5




2.Write a Java Program to convert binary to decimal number in java using Integer.parseInt() method.



  1. import java.util.Scanner;
  2. public class ConvertBinaryToDecimal{
  3.  
  4.     /**
  5.      *www.instanceofjava.com
  6.      */
  7.  
  8.  public static void main(String[] args) {
  9.         
  10.  Scanner in = new Scanner( System.in );
  11.  
  12.  System.out.println("Enter a binary number: ");
  13.  String binaryString =input.nextLine();
  14.  
  15.  System.out.println("Result: "+Integer.parseInt(binaryString,2));

  16.  
  17. }
  18.  
  19. }


Output:


  1. Enter a binary number:
  2. 001
  3. Result: 1

java program to convert binary to decimal


You Might like:

Get collection values from hashtable example

1.Basic java collection framework example program to get Value collection from hashtable

  •   Collection values()   This method used to get collection of values
  •  Important note is that if any value is removed from set the original hashtable key also removed
  1. package com.setviewHashtable;
  2.  
  3. import java.util.Hashtable;

  4. import java.util.Enumeration;
  5. import java.util.Iterator;
  6. import java.util.Set;
  7.  
  8. public class HashtableExample{
  9.  
  10. public static void main(String[] args) {
  11.   
  12.  //create Hashtable object
  13.        Hashtable<String,String> hashtable = new Hashtable<String,String>();
  14.        
  15. //add key value pairs to Hashtable
  16. hashtable.put("1","Java Interview Questions");
  17. hashtable.put("2","Java Interview Programs");
  18. hashtable.put("3","Concept and example program");
  19. hashtable.put("4","Concept and interview Questions");
  20. hashtable.put("5","Java Quiz");
  21. hashtable.put("6","Real time examples");
  22.  
  23.  
  24.  Collection c = hashtable.values();
  25.  System.out.println("Values of Collection created from Hashtable are :");
  26. //iterate through the Set of keys
  27.  
  28.  Iterator itr = c.iterator();
  29.  while(itr.hasNext())
  30.  System.out.println(itr.next());
  31.            
  32.  c.remove("Java Quiz");
  33.            
  34. System.out.println("Elements in hash table");
  35. Enumeration e=hashtable.elements();
  36.         
  37.  
  38.  while (e.hasMoreElements()) {
  39.         System.out.println(e.nextElement());
  40. }    

  41. }
  42.  
  43. }
     



Output:

  1. Values of Collection created from Hashtable are :
  2. Real time examples
  3. Java Quiz
  4. Concept and interview Questions
  5. Concept and example program
  6. Java Interview Programs
  7. Java Interview Questions
  8. Elements in hash table
  9. Real time examples
  10. Concept and interview Questions
  11. Concept and example program
  12. Java Interview Programs
  13. Java Interview Questions


Select Menu