Showing posts with label Java 7. Show all posts
Showing posts with label Java 7. Show all posts

Monday, 21 November 2016

Handling Weeks in Java 7

Some applications in their business logic deals with the number of weeks in a year and the current week of the year. There are 52 weeks in a year, but 52 weeks multiplied by 7 days per week equals 364 days per year, not the actual 365 days. A week number is used to refer to the week of the year.

Java 7 has introduced several methods to support determining the week of the year.

Some implementations of the abstract java.util.Calendar class do not support week calculations. To determine if the Calendar implementation supports week calculations, we need to execute the isWeekDateSupported method. It returns true if the support is provided. To return the number of weeks for the current calendar year, use the getWeeksInWeekYear method. To determine the week for the current date, use the get method with the WEEK_OF_YEAR as its argument.

Below is the code to get total number of weeks and current week.
import java.util.Calendar;

public class WeeksInYear {
      public static void main(String[] args) {
            Calendar calendar = Calendar.getInstance();
            if(calendar.isWeekDateSupported()) {
                  System.out.println("Number of weeks in this year: " +
                              calendar.getWeeksInWeekYear());
                  System.out.println("Current week number: " + calendar.
                              get(Calendar.WEEK_OF_YEAR));
            }
      }
}


The above code will give the following out put
Number of weeks in this year: 53
Current week number: 47

Explanation of Code
An instance of the Calendar class is created, which is an instance of the

GregorianCalendar class. An if statement was controlled by the isWeekDateSupported method. It returned true, which resulted in the execution of the getWeeksInWeekYear and get methods. The get method was passed in the field WEEK_OF_YEAR, which returned the current week number.

Wednesday, 16 November 2016

Catching multiple exception types in Java 7

In Java 7 and later, a single catch block can handle more than one type of exception. This feature helps reduce code duplication.
Consider the following example which we use prior to Java 7, which contains duplicate code in each of the catch blocks:
try{
// do some thing
}
catch (IOException ex) {
     ex.printStackTrace();
}
catch (SQLException ex) {
     ex.printStackTrace();
}

The following example, which is valid in Java  7 and later, eliminates the duplicated code:
try{
// do some thing
}
catch (IOException | SQLException ex) {
    ex.printStackTrace();
}


The catch clause specifies the types of exceptions that the block can handle, and each exception type is separated with a vertical bar (|).

Friday, 11 November 2016

Using the try-with-resources block

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.

This approach enables a better programming style as it avoids nested and excessive try-catch blocks. It also ensures accurate resource management, which is referred to as
Automated Resource Management (ARM).

The following example illustrates the use of try-with-resource

    try (BufferedReader br = new BufferedReader(new FileReader(path))) 


In this example, the resource declared in the try-with-resources statement is a BufferedReader. The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java  7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly.


Prior to Java  7, you can use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly.

You may declare one or more resources in a try-with-resources statement. 
The following code snippet illustrates one or more resources in a try-with-resources statement. 
try (
        ZipFile zf = new java.ZipFile(zipFileName);
       BufferedWriter writer = Files.newBufferedWriter(outputFilePath, charset)
    ) {
               // To – Do
               }


In the above example, the try-with-resources statement contains two declarations that are separated by a semicolon

Example :
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Java7TryResource {

public static void main(String[] args) {
 try (BufferedReader br = new BufferedReader(new FileReader(
    "C:\\myfile.txt"))) {
   System.out.println(br.readLine());
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}


Sunday, 6 November 2016

Using underscores in literals

Using underscores in literals to improve code readability

In Java SE 7 and later, any number of underscore characters (_) can appear anywhere between digits in a numerical literal. This feature enables you, to separate groups of digits in numeric literals, which can improve the readability of your code.

This is intended to improve the readability of code by separating digits of a literal into significant groups at almost any arbitrary place that meets the needs of the developer. The underscore can be applied to primitive data types in any supported base (binary, octal, hexadecimal, or decimal), and to
both integer and floating-point literals.

Example to show ways you can use the underscore in numeric literals:

            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;

You can place underscores only between digits; you cannot place underscores in the following places:
·         At the beginning or end of a number
·         Adjacent to a decimal point in a floating point literal
·         Prior to an F or L suffix
·         In positions where a string of digits is expected

The following are the examples of invalid underscore usages:
            long creditCardNumber = _12345_67890_09876_54321L;
            float pi = 3._14_15F;
long licenseNumber = 123_456_789_L;


Friday, 4 November 2016

String literals in switch statements

Prior to Java 7, only integer values were the valid arguments in a switch statement. It is very common to make a decision based on a string value, up till now developers have been using if statements whenever there is a need to make a decision based on String values, use of String in switch statement result in more readable and efficient code.


Code Snippet to display the use of String in Switch Statement

String day;
            day= "";
            switch(day){
            case "Monday" :
                  System.out.println("1st Day");
                  break;
            case "Tuesday" :
                  System.out.println("2nd Day ");
                  break;
                  default:
                        System.out.println("Holiday ");
            }

When using strings, you need to be careful about the following two issues:
ü  Null values for strings : Using a string reference variable that is assigned a null value will result in a java.lang.NullPointerException.
ü  The case of the string : The evaluation of a case expression is case sensitive in a switch statement.

 . . . read more




Related Posts Plugin for WordPress, Blogger...