Wednesday, 29 June 2016

Oracle queries for the rownum, rank to find the nth highest salary

Find the 2nd highest data in SQL:
SELECT MAX(balance) FROM mtx_wallet_balances WHERE balance NOT IN (SELECT MAX(balance) FROM mtx_wallet_balances )

SELECT MAX(balance) FROM mtx_wallet_balances WHERE balance <> (SELECT MAX(balance) FROM mtx_wallet_balances)


Find the nth highest data in Oracle using rownum:
select * from ( select mwb.*, row_number() over (order by balance DESC) rownumb from mtx_wallet_balances mwb ) where rownumb = 105;

Find the nth highest data in Oracle using RANK:
SELECT * FROM (SELECT balance, RANK () OVER (ORDER BY balance DESC) ranking FROM mtx_wallet_balances) WHERE ranking = 105;



What are the states of object in hibernate?

States of object in hibernate



States of object (instance) in hibernate

Transient: The object is in transient state if it is just created but has no primary key (identifier) and not associated with session i.e. doesn’t represent any row of the database.

Persistent: It represent one row of the database and always associated with some unique hibernate session.

The object is in persistent state if session is open, and you just saved the instance in the database or retrieved the instance from the database.

Changes to persistent objects are tracked by hibernate and are saved into database when commit call happen.

Detached: Detached objects are those who were once persistent in past (object is in detached state if session is closed) and now they are no longer persistent.

After detached state, object comes to persistent state if we call lock() or update() or saveOrUpdate() method (reattach object to hibernate session).


If we want to move an object from persistent to detached state, we need to do either closing that session or need to clear the cache of the session.

If we want to move an object from persistent state into transient state then we need to delete that object permanently from the database.


Strings in switch Statements

 Since: Jdk 1.7
public class SwitchStringExample {

      public static void main(String[] args) {
           
            String day = callSwich("Monday");
            System.out.println(day);
     
            /** NullPointerException */
            day = callSwich(null);
            System.out.println(day);
      }


      private static String callSwich(String day) {
           String typeOfDay;
           switch (day) {
               case "Monday":
                   typeOfDay = "Start of work week";
                   break;
               case "Tuesday":
               case "Wednesday":
               case "Thursday":
                   typeOfDay = "Midweek";
                   break;
               case "Friday":
                   typeOfDay = "End of work week";
                   break;
               case "Saturday":
               case "Sunday":
                   typeOfDay = "Weekend";
                   break;
               default:
                   throw new IllegalArgumentException("Invalid day" + day);
           }
           return typeOfDay;
      }
}

The switch statement compares the String object in its expression with the expressions associated with each case label as if it were using the String.equals method; consequently, the comparison of String objects in switch statements is case sensitive. The Java compiler generates generally more efficient bytecode from switch statements that use String objects than from chained if-then-else statements.

Note:
Make sure to add a NULL check to avoid NullPointerException.

Tuesday, 28 June 2016

Why wait, notify and notifyAll called from synchronized block or method in Java?

If we don't call wait() or notify() method from synchronized method/block, it will throw the "java.lang.IllegalMonitorStateException: current thread not owner".

Why?
For example, one thread read data from a buffer and one thread write data into buffer. The reading data thread needs to wait until the writing data thread completely writes a block data into the buffer. The writing data thread needs to wait until the reading data thread completely read the data from the buffer.


If wait(), notify(), and notifyAll() methods can be called by ordinary method, the reading thread calls wait() and the thread is being added to waiting queue. At the same moment, the writing thread calls notify() to signal the condition changes. The reading thread misses the change and waits forever. Hence, they must be called inside a synchronized method or block which is mutually exclusive.

How to Delete a Directory/Folder in Java using Recursion


package com.java.io;

import java.io.File;

/** To delete folders recursively. */
public class DeleteDirectory {

     public static void main(String[] args) {
           String folder = "C:/temp/Dir";

           /** delete directory recursively */
           recurDelete(new File(folder));
     }

     public static void recurDelete(File file) {
           /** recursive loop termination. */
           if (!file.exists()) {
                return;
           }

           /** if directory, go inside and call recursively */
           if (file.isDirectory()) {
                for (File tFile : file.listFiles()) {
                     /** recursive call */
                     recurDelete(tFile);
                }
           }
          
           /** To delete files and empty directory */
           boolean isFileDeleted = file.delete();

           if(isFileDeleted) {
                System.out.println("File deleted: "+file.getAbsolutePath());
           }
     }
}

AutoCloseable and Closeable interface in Java : Since: JDK 1.7

java.lang interface AutoCloseable

Closeable extends AutoCloseable, and is specifically dedicated to IO streams.

Implementing AutoCloseable (or Closeable) allows a class to be used as a resource of the try-with-resources construct introduced in Java 7, which allows closing such resources automatically at the end of a block, without having to add a finally block which closes the resource explicitly.

try(open file or resource here) {
      //...
}
//after try block, file will close automatically.

void close() throws Exception

This method is invoked automatically on objects managed by the try-with-resources statement.

While this interface method is declared to throw Exception, implementer are strongly encouraged to declare concrete implementations of the close method to throw more specific exceptions, or to throw no exception at all if the close operation cannot fail.
Throws: Exception - if this resource cannot be closed.

Example of AutoCloseable

class Resource implements AutoCloseable {
     
      private String value;
     
      public Resource(String value) {
            this.value = value;
      }
     
      @Override
      public void close() throws Exception {
            /* De-reference the unused resource */
            this.value = null;
            System.out.println("Resource closed !!");
      }
     
      public String getValue() {
            return value;
      }
}

public class Demo {
      public static void main(String[] args) {

            try(Resource res =new Resource("Resource opened !!")) {
                  String str = res.getValue();
                  System.out.println(str+"\n");
            } catch (Exception e) {
            }
      }
}
Output:
Resource opened !!
Resource closed !!

try with resource Statement in Java

In Java 6, we open a file in a try block, and close the file in the finally block
try {
      //open file or resources
} catch(IOException) {
      //handle exception
} finally {
      //close file or resources
}

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

In JDK 7, a new “try-with-resources” approach is introduced.
When a try block is end, it will close or release your opened file automatically.

try(open file or resource here) {
      //...
}
//after try block, file will close automatically.

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it.

The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

Example:

import java.util.Scanner;

class Demo {
     public static void main(String[] args) {

           try(Scanner scan=new Scanner(System.in)) {
                String str = scan.next();
                System.out.println(str);
           }
     }
}

Benefits of using try with resources
1. Automatic resource management.
2. More readable code and number of lines of code is reduced.
3. No need to have finally block just to close the resources.
4. We can open multiple resources in try-with-resources statement separated by a semicolon.

try (BufferedReader br = new BufferedReader(new FileReader("file.txt"));Scanner scan=new Scanner(System.in))) {
      System.out.println(br.readLine());
} catch (IOException e) {
      e.printStackTrace();
}

5. When multiple resources are opened in try-with-resources, it closes them in the reverse order to avoid any dependency issue.

Note@5: We can extend the resource program to prove that.
Related Posts Plugin for WordPress, Blogger...