Wednesday 29 June 2016

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

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.

Monday 27 June 2016

Underscores in Numeric Literals

In Java SE 7, any number of underscore characters (_) can appear anywhere between digits in a numerical literal.

This feature is used to separate groups of digits in numeric literals, which can improve the readability of your code.

Example:
long creditCardNumber = 1234_5678_9012_3456L;
long socialSecurityNumber = 999_99_9999L;
float pi =      3.14_15F;
long hexBytes = 0xFF_EC_DE_5E;
long hexWords = 0xCAFE_BABE;
long maxLong = 0x7fff_ffff_ffff_ffffL;
byte nybbles = 0b0010_0101;
long bytes = 0b11010010_01101001_10010100_10010010;

Important points:
We cannot place underscores in the following places:
1. At the beginning or end of a number
2. Adjacent to a decimal point in a floating point literal
3. Prior to an F or L suffix
4. In positions where a string of digits is expected.

Invalid Examples:
float pi1 = 3_.1415F;
float pi2 = 3._1415F;
long id = 999_99_9999_L;
int num = _42;
int num = 0_x54;
int num = 0x_52;
int num = 0x52_;
int num = 052_;

Valid Examples:
int num = 5_2;
int num = 5_______2;
int num = 0x5_2;
int num = 0_52; (octal literal) 

Example:
public class UnderscoresNumbers {
     public static void main(String[] args) {
           int a = 10_597;
           int b = 1_11_597;
          
           int sum = a+b;
          
           System.out.println("Sum is: "+ sum);
     }
}

Output:
     Sum is: 122194


Related Posts Plugin for WordPress, Blogger...