Kamis, 28 April 2016

Control statements in java with examples

  • Programs in java will be executed in sequential manner means line by line execution of statements.
  • By using control statements we can control the flow of execution.
  • We have three types of control statements in java.
  1. Decision making Statements.
  2. Iteration statements.
  3. Branching statements. 




1.Decision making statements in java: 

  • In some cases we will have a situation like need to execution set of statements based on a condition
  • In this scenario we need to use decision making statements in java.
  1. if
  2. if-else
  3. if-else-if
  4. switch

Simple if

  • Based on some condition if we want to execute some set of statements then we need to use if condition in java.
  • We need to keep all the required statements inside if block .
  • If the condition is true then control executes the whole block otherwise it skips the if block of statements.

  1. if( condition ){
  2. // code
  3. }

Java example program on if control statement:

  1. package controlstatementsinjava;
  2. import java.util.Scanner;
  3.  
  4. public class ControlStatementsInjava {
  5.  
  6.     /**
  7.      * @website: www.instanceofjava.com
  8.      */
  9. public static void main(String[] args) {
  10.         
  11.   Scanner in= new Scanner(System.in);
  12.  
  13.   System.out.println("Please enter a number");
  14.   int n=in.nextInt();
  15.         
  16. if(n%2==0){
  17.    System.out.println(n+" is even number");
  18.         
  19.  }
  20.   
  21. if(n%2!=0){
  22.      System.out.println(n+" is odd number");
  23. }
  24.  
  25. }
  26. }

Output:

  1. Please enter a number
  2. 5
  3. 5 is odd number

If else condition:

  • If the condition is true then control executes the whole block otherwise it skips the if block of statements
  • if condition is false  if we need to execute another set of statement we can write another if and keep all the statements in that block.
  • instead of checking multiple times we can simply use else block .
  • More about in else statement in java

    1. if( condition ){
    2. // code
    3. }else{
    4. //code
    5. }

     if else control statement with example programs:

    1. package controlstatementsinjava;
    2. import java.util.Scanner;
    3.  
    4. public class ControlStatementsInjava {
    5.  
    6.     /**
    7.      * @website: www.instanceofjava.com
    8.      */
    9. public static void main(String[] args) {
    10.         
    11.   Scanner in= new Scanner(System.in);
    12.  
    13.   System.out.println("Please enter a number");
    14.   int n=in.nextInt();
    15.         
    16. if(n%2==0){
    17.    System.out.println(n+" is even number");
    18.         
    19.  }else{
    20.      System.out.println(n+" is odd number");
    21. }

    22.  
    23. }
    24. }

    Output:

    1. Please enter a number
    2. 5
    3. 5 is odd number


    if else ladder :

    • In some cases we may get requirement with multiple conditions in such cases we need to use if else ladder.(if -else-if-else if -else...)

    1. if( condition ){
    2. // code
    3. }else if{
    4. //code
    5. }else {
    6.  //code
    7. }

     if else if control statement with example programs:


    1. package controlstatementsinjava;
    2. import java.util.Scanner;
    3.  
    4. public class ControlStatementsInjava {
    5.  
    6.     /**
    7.      * @website: www.instanceofjava.com
    8.      */
    9. public static void main(String[] args) {
    10.         
    11.   Scanner in= new Scanner(System.in);
    12.  
    13.   System.out.println("Please enter your age");
    14.   int age=in.nextInt();
    15.         
    16. if(age<=18){
    17.    System.out.println("Your age is between 1-18");
    18.         
    19.  }else if ((age>=18) && (age<=35)){
    20.      System.out.println(" Your age is between 18-35");
    21. }
    22. else if ((age>=35) && (age<=50)){
    23.      System.out.println(" Your age is between 35-50");
    24. }else{
    25.  
    26.   System.out.println(" Your age is above 50");
    27.  
    28. }
    29.  
    30. }
    31. }

    Output:

    1. Please enter your age
    2. 20
    3. Your age is between 18-35

    control statements in java

    Switch statement in java:

    • Instead if writing number of if conditions we can use single switch statement


    1. switch(value)
    2.  case n1: statements;
    3. break;
    4. case n2 : statements;
    5. break;
    6. default: statements;
    7. }

    Java example program on switch statement in java:


    switch statement in java

    Baca selengkapnya

    Rabu, 27 April 2016

    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

    Baca selengkapnya

    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.




    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


      Baca selengkapnya

      Senin, 25 April 2016

      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
      Baca selengkapnya

      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
      Baca selengkapnya

      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
      Baca selengkapnya

      Minggu, 24 April 2016

      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.
        Baca selengkapnya

        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

        Baca selengkapnya

        Kamis, 21 April 2016

        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


        Baca selengkapnya

        Selasa, 19 April 2016

        Enum in java part 2

        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.
        Baca selengkapnya

        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
            Baca selengkapnya