Can we have try without catch block in java

  • 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.
  • We can place logic like connections closing or cleaning data  in finally.


Java Program to write try without catch block | try with finally block
  1. package exceptionsInterviewQuestions;
  2. public class TryWithoutCatch {
  3.  
  4.     
  5. public static void main(String[] args) {
  6.         
  7.         
  8. try {
  9.             
  10.   System.out.println("inside try block");
  11.             
  12. } finally{
  13.             
  14.             System.out.println("inside finally block");
  15. }
  16.  
  17. }
  18.  
  19. }



Output:


  1. inside try block
  2. inside finally block

  •  Finally block executes Even though the method have return type and try block returns something

Java Program to write try with finally block and try block returns some value

  1. package exceptionsInterviewQuestions;
  2.  
  3. public class TryWithFinally {
  4.  
  5. public static int method(){  
  6.   
  7.        
  8. try {
  9.             
  10.   System.out.println("inside try block");
  11.  
  12.  return 10;        
  13. } finally{
  14.             
  15.             System.out.println("inside finally block");
  16. }
  17.  
  18. }
  19.  
  20. public static void main(String[] args) {
  21.         
  22. System.out.println(method());
  23.  
  24. }
  25.  
  26. }

Output:


  1. inside try block
  2. inside finally block
  3. 10


What happens if exception raised in try block?

  • Even though exception raised in try block finally block executes.

try with finally block in java

Remove duplicates from arraylist without using collections

1.Write a Java program to remove duplicate elements from an arraylist without using collections (without using set)




  1. package arrayListRemoveduplicateElements;
  2. import java.util.ArrayList;
  3.  
  4. public class RemoveDuplicates {
  5. public static void main(String[] args){
  6.     
  7.     ArrayList<Object> al = new ArrayList<Object>();
  8.     
  9.     al.add("java");
  10.     al.add('a');
  11.     al.add('b');
  12.     al.add('a');
  13.     al.add("java");
  14.     al.add(10.3);
  15.     al.add('c');
  16.     al.add(14);
  17.     al.add("java");
  18.     al.add(12);
  19.     
  20. System.out.println("Before Remove Duplicate elements:"+al);
  21.  
  22. for(int i=0;i<al.size();i++){
  23.  
  24.  for(int j=i+1;j<al.size();j++){
  25.             if(al.get(i).equals(al.get(j))){
  26.                 al.remove(j);
  27.                 j--;
  28.             }
  29.     }
  30.  
  31.  }
  32.  
  33.     System.out.println("After Removing duplicate elements:"+al);
  34.  
  35. }
  36.  
  37. }



Output:

  1. Before Remove Duplicate elements:[java, a, b, a, java, 10.3, c, 14, java, 12]
  2. After Removing duplicate elements:[java, a, b, 10.3, c, 14, 12]

2. Write a Java program to remove duplicate elements from an array using Collections (Linkedhashset)

  1. package arrayListRemoveduplicateElements;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.HashSet;
  5. import java.util.List;
  6.  
  7. public class RemoveDuplicates {
  8.  
  9. public static void main(String[] args){
  10.     
  11.     List<String>  arraylist = new ArrayList<String>();
  12.     
  13.     arraylist.add("instanceofjava");
  14.     arraylist.add("Interview Questions");
  15.     arraylist.add("Interview Programs");
  16.     arraylist.add("java");
  17.     arraylist.add("Collections Interview Questions");
  18.     arraylist.add("instanceofjava");
  19.     arraylist.add("Java Experience Interview Questions");
  20.     
  21.     
  22.     System.out.println("Before Removing duplicate elements:"+arraylist);
  23.     
  24.     HashSet<String> hashset = new HashSet<String>();
  25.     
  26.     /* Adding ArrayList elements to the HashSet
  27.      * in order to remove the duplicate elements and 
  28.      * to preserve the insertion order.
  29.      */
  30.     hashset.addAll(arraylist);
  31.  
  32.     // Removing ArrayList elements
  33.     arraylist.clear();
  34.  
  35.     // Adding LinkedHashSet elements to the ArrayList
  36.     arraylist.addAll(hashset );
  37.  
  38.     System.out.println("After Removing duplicate elements:"+arraylist);
  39.  
  40. }
  41.  
  42. }



Output:
 


  1. Before Removing duplicate elements:[instanceofjava, Interview Questions, Interview
  2. Programs, java, Collections Interview Questions, instanceofjava, Java Experience Interview
  3. Questions]
  4. After Removing duplicate elements:[java, Collections Interview Questions, Java Experience
  5. Interview Questions, Interview Questions, instanceofjava, Interview Programs]


arraylist remove duplicates


Enum in java part 2

3. Enum Iteration in for-each loop:




  • You can obtain an array of all the possible values of a Java enum type by calling its static values() method. 
  • All enum types get a static values() method automatically by the Java compiler. Here is an example of iterating all values of an enum:
 
  1. for (Day day : Day.values()) {
  2.     System.out.println(day);
  3. }

  • If you run this code, then you will get the following output:


  1. SUNDAY
  2. MONDAY
  3. TUESDAY
  4. WEDNESDAY
  5. THURSDAY
  6. FRIDAY
  7. SATURDAY




4.    Enum fields:


  • It is possible to add fields to Java Enum. Each constant enum value gets these fields. The field values must be supplied to the constructor of the enum when defining the constants. 
  • Here is an example:

  1. public enum Day {
  2.     SUNDAY(1), MONDAY(2), TUESDAY(3), WEDNESDAY(4), THURSDAY(5),
  3. FRIDAY(6), SATURDAY(7); 
  4.  
  5.     private final int dayCode;
  6.     private Day(int dayCode) {
  7.         this.dayCode = dayCode;
  8.     }
  9.  
  10. }
  • The example above has a constructor which takes an int. The enum constructor sets the int field. When the constant enum values are defined, an int value is passed to the enum constructor.
  • The enum constructor must be either private or package scope (default). You cannot use public or protected constructors for a Java enum.

5. Enum Methods:

  • It is possible to add methods to Java Enum. Here I am showing an example that how to do it.

  1. public enum Day {
  2.  
  3.     SUNDAY(1), MONDAY(2), TUESDAY(3), WEDNESDAY(4), THURSDAY(5),
  4. FRIDAY(6), SATURDAY(7); 
  5.  
  6.     private final int dayCode;
  7.  
  8.     private Day(int dayCode) {
  9.         this.dayCode = dayCode;    
  10.      }
  11.     public int getDayCode() {
  12.         return this.dayCode;
  13.     }
  14.     
  15. }

  • It is possible to call an Enum method through a reference to one of the constant values. The following code will show you how to call Java Enum method.
  • Day day = Day.MONDAY;
  • System.out.println(day.getDayCode()); //which gives 2.Because the dayCode field for the Enum constant MONDAY is 2.
 Some details to know about enum:

  • Java enums extend the java.lang.Enum class implicitly, so your enum types cannot extend another class. Please refer the following code. This code is from Java API.
  1. public abstract class Enum<E extends Enum<E>> implements Comparable<E>,Serializable {
  2. // Enum class code in Java API
  3. }
  • If a Java enum contains fields and methods, the definition of fields and methods must always come after the list of constants in the enum. Additionally, the list of enum constants must be terminated by a semicolon;
  • Java does not support multiple inheritance, and enum also does not support for multiple inheritance.
  • Enums are type-safe. Enum has their own name-space. It means your enum will have a type for example “Day” in below example and you cannot assign any value other than specified in Enum Constants.
  • Enum constants are implicitly static and final and cannot be changed once created.
  • Enum can be safely compare using:
  • Switch-Case Statement
  • == Operator
  • .equals() method
  • You cannot create instance of enums by using new operator in Java because constructor of Enum in Java can only be private and Enums constants can only be created inside Enums itself.
  • Instance of Enum in Java is created when any Enum constants are first called or referenced in code
  •  An enum can be declared outside or inside a class, but NOT in a method.
  • An enum declared outside a class must NOT be marked static, final , abstract, protected , or private
  • Enums can contain constructors, methods, variables, and constant class bodies.
  • Enum constructors can have arguments, and can be overloaded.
  • Enum constructors can have arguments, and can be overloaded.
  • The constructor for an enum type must be package-private or private access. It automatically creates the constants that are defined at the beginning of the enum body. You cannot invoke an enum constructor yourself

  1. package com.enum.exampleprogram;
  2.  
  3.  /**This is an Enum which indicates possible days in a week **/ 
  4.  
  5. public enum Day {
  6.     SUNDAY, MONDAY, TUESDAY, WEDNESDAY,THURSDAY, FRIDAY, SATURDAY;
  7. }


  1. package com.pamu.test;
  2. /** This class is an example of Enum  **/
  3. public class EnumTest {
  4.     Day day;
  5.     public EnumTest(Day day) {
  6.         this.day = day;
  7.     }
  8. //method to get descriptions of the respected days in a switch-statement.
  9.  
  10.  public void getDayDescription() {
  11.  
  12.  switch (day) {
  13.    case MONDAY:
  14.                System.out.println("Monday is First day in a week.");
  15.                 break;      
  16.   case FRIDAY:
  17.                 System.out.println("Friday is a partial working day.");
  18.                 break;        
  19.   case SATURDAY: 
  20.                 System.out.println("Saturday is a Weekend.");
  21.                 break;
  22.  case SUNDAY:
  23.                 System.out.println("Sunday is a Weekend.");
  24.                 break;               
  25.   default:
  26.                 System.out.println("Midweek days are working days.");
  27.                 break;
  28.         }
  29.     }
  30.     public static void main(String[] args) {
  31.  
  32.         EnumTest day1 = new EnumTest(Day.MONDAY);
  33.         day1.getDayDescription();
  34.  
  35.         EnumTest day2 = new EnumTest(Day.TUESDAY);
  36.         day2.getDayDescription();
  37.  
  38.         EnumTest day3 = new EnumTest(Day.WEDNESDAY);
  39.         day3.getDayDescription();
  40.  
  41.         EnumTest day5 = new EnumTest(Day.FRIDAY);
  42.         day5.getDayDescription();
  43.  
  44.         EnumTest day6 = new EnumTest(Day.SATURDAY);
  45.         day6.getDayDescription();
  46.  
  47.         EnumTest day7 = new EnumTest(Day.SUNDAY);
  48.         day7.getDayDescription();
  49.  
  50.     }
  51. }

Output:

  1. Monday is First day in a week.
  2. Midweek days are working days.
  3. Midweek days are working days.
  4. Friday is a partial working day.
  5. Saturday is a Weekend.
  6. Sunday is a Weekend.

Enum in java Example

Java Enum:
  • In this tutorial I will explain what is enum, how to use enum in different areas of a Java program and an example program on it.



  • An Enum type is a special data type which is added in Java 1.5 version. It is an abstract class in Java API which implements Cloneable and Serializable interfaces. It is used to define collection of constants. When you need a predefined list of values which do not represent some kind of numeric or textual data, at this moment, you have to use an enum.
  • Common examples include days of week (values of SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, and SATURDAY), directions, and months in a year. Etc.
  • You can declare simple Java enum type with a syntax that is similar to the Java class declaration syntax. Let’s look at several short Java enum examples to get you started.

Enum declaration Example 1:

  1. public enum Day {
  2.  SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY 
  3. }


Enum declaration Example 2:

  1.  public enum Month{
  2. JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER,
  3. OCTOBER, NOVEMBER, DECEMBER
  4. }

  • Enums are constants; they are by default static and final. That’s why the names of an enum type's fields are in uppercase letters.
  • Make a note that the enum keyword which is used in place of class or interface. The Java enum keyword signals to the Java compiler that this type definition is an enum.
    You can refer to the constants in the enum above like this:
  •  
  1. Day day = Day.MONDAY;



  • Here the ‘day’ variable is of the type ‘Day’ which is the Java enum type defined in the example above. The ‘day’ variable can take one of the ‘Day’ enum constants as value (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY). In this case ‘day’ is set to MONDAY.
  • If you use enum instead of integers or String codes, you increase compile-time checking and avoid errors from passing in invalid constants, and you document which values are legal to use.
  • How to use a Java enum type in various areas in a Java Program:
  • We have seen how to declare simple Java enum types, let’s take a look at how to use them in various areas. We have to use a Java enum type in a variety of situations, including in a Java 5 for loop, in a switch statement, in an if/else statement, and more. For simple, Enum comparison, there are 3 ways to do it. They are, Switch-Case Statement, == Operator, .equals() method. Like that there are other places where you have to use Enum.
  • Let's take a look at how to use our simple enum types with each of these Java constructs.
  1. Enum in IF statement
  2. Enum in Switch statement
  3. Enum Iteration in for-each loop 
  4. Enum Fields 
  5. Enum Methods

1. Enum in IF statements:


  • We know Java Enums are constants. Sometimes, we have a requirement to compare a variable of Enum constant against the possible other constants in the Enum type. At this moment, we have to use IF statement as follows.
  • Day day = ----- //assign some Day constants to it.
     
  1. If(day ==Day.MONDAY){
  2. ….//your code
  3. } else if (day == Day.TUESDAY){
  4. ….//your code
  5. } else if (day == Day.WEDNESDAY){
  6. ….//your code
  7. } else if (day == Day. THURSDAY){
  8. ….//your code
  9. } else if (day == Day.FRIDAY){
  10. ….//your code
  11. } else if (day == Day.SATURDAY){
  12. ….//your code
  13. } else if (day == Day.SUNDAY){
  14. ….//your code
  15. }

  • Here, you can use “.equals()” instead of “==”. But, my preference is to use “==” because, it will never throws NullPointerException, safer at compile-time, runtime and faster.
  • The code snippet compares the ‘day’ variable against each of the possible other Enum constants in the ‘Day’ Enum.

2. Enums in Switch Statements:


  • Just assume that your Enum have lot of constants and you need to check a variable against the other values in Enum. For a small Enum IF Statement will be OK. If you use same IF statement for lot of Enum constants then our program will be increased and it is not a standard way to write a Java program. At this Situation, use Switch Statement instead of IF statement.
  • You can use enums in switch statements as follows:
  • Day day = ...  //assign some Day constant to it

  1. switch (day) { 
  2.     
  3. case SUNDAY   : //your code; break; 
  4. case MONDAY //your code; break;
  5. case TUESDAY    : //your code; break;     
  6. case WEDNESDAY    : //your code; break;
  7. case THURSDAY: //your code; break;
  8. case FRIDAY    : //your code; break;
  9. case SATURDAY    : //your code; break;
  10.  
  11. }

  • Here, give your code in the comments, “//your code”. The code should be a simple Java operation or a method call..etc 

Enum in java

3.Enum Iteration in for-each loop
4.Enum Fields
5.Enum Methods

Please click here  Enum in java part 2

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.
Select Menu