Video tutorial to demonstrate Java 7 new feature - using String literals in switch statements.
Free Data Structures and Algorithms Course
Showing posts with label Java 7. Show all posts
Showing posts with label Java 7. Show all posts
Java 7 new feature - Using String literals in switch statements (Video Tutorial)
Video tutorial to demonstrate Java 7 new feature - using String literals in switch statements.
Java 7 new feature - Using the try-with-resources block to improve exception handling code (Video Tutorial)
Video tutorial to demonstrate Java 7 new feature - using the try-with-resources block to improve exception handling code.
Java 7 new feature - Catching multiple exception types to improve type checking (Video Tutorial)
A Java program to demonstrate how catching multiple exception types to improve type checking.
Java 7 New Features
- Using String literals in switch statements.
- Using Underscores in literals to improve code readability
- Using the try-with-resources block to improve exception handling code.
- Catching multiple exception types in a single catch block.
- Rethrowing exceptions
- Using the diamond operator for type inference.
- Using the @SafeVarargs annotation.
- How to search / find files in a directory using DirectoryStream in Java 7.?
- How to create and delete a file in Java 7 using java.nio ?
- How to Copy and Move a file in Java 7 using java.nio ?.
- How to read and write a file in Java 7 using java.nio API ?
- Determining the file content type.
- Creating files and directories.
- Binary Literals in Java 7.
Java 7 new feature - Binary Literals
Program to demonstrate Java 7 new feature - Binary Literals.
Output of the program :
public class BinaryLiterals {
public static void main(String[] args) {
// Before Java 7
// In order to use Binary Numbers as Integral types
// Integer class static method parseInt was used.
// This method Parses the string argument as a signed
// integer in the radix specified by the second argument.
int number = Integer.parseInt("1011", 2);
System.out.println("The value of number is : " + number);
// After Java 7
// Binary Literals were introduced which were represented by
// prefix such as 0b and 0B. The prefix denoted that number
// coming after that is binary number
int number2 = 0b1011; // 0b or 0B
System.out.println("The value of number2 is : " + number2);
}
}
Output of the program :
Java 7 new feature : Creating files and directories
Program to demonstrate Java 7 new feature : Creating files and directories.
Output of the program :
package com.hubberspot.nio;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
public class FileCreation {
public static void main(String[] args) {
Path pathToDirectory = FileSystems.getDefault().getPath("C:/Ablage/dev/workspace");
try {
Files.createDirectories(pathToDirectory);
System.out.println("Directory created at path : " + pathToDirectory);
} catch (IOException e) {
e.printStackTrace();
}
Path pathToFile = FileSystems.getDefault().getPath("C:/Ablage/dev/workspace/hello.pdf");
try {
Files.createFile(pathToFile);
System.out.println("File created at path : " + pathToFile);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output of the program :
Java 7 new feature : Determining the file content type
Program to demonstrate Java 7 new feature : Determining the file content type.
Output of the program :
package com.hubberspot.nio;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FileContentType {
public static void main(String[] args) {
printContentType("D:/Downloads/java.txt");
printContentType("D:/Downloads/java.ppt");
printContentType("D:/Downloads/java.doc");
printContentType("D:/Downloads/java.jar");
}
private static void printContentType(String pathToFile) {
Path path = Paths.get(pathToFile);
String contentType = null;
try {
contentType = Files.probeContentType(path);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("File content type is : " + contentType);
}
}
Output of the program :
How to read and write a file in Java 7 using java.nio API ?
Program to demonstrate how to read and write a file in Java 7 using java.nio API.
package com.hubberspot.java7;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class ReadAndWriteFiles {
public static void main(String[] args) {
// Create a path to the file which is
// to be written and read later
// here "D:\\books\\java\\" is the address
// to reach the file created by name "hubberspot.txt"
Path filePath = Paths.get("D:\\books\\java\\hubberspot.txt");
try {
// First we check whether file already exists
// at the filePath by using Files class static
// method by name exists()
if (!Files.exists(filePath)) {
try {
// Second we create a file at
// the specified filePath by using
// Files class createFile() method.
Files.createFile(filePath);
} catch (IOException e) {
e.printStackTrace();
}
}
// Create a BufferedWriter instance by calling
// Files class newBufferedWriter() method which
// returns back BufferedWriter object
// This method takes in three parameters such as:
// 1. Path to the file created above
// 2. Charsets for the format of the file
// 3. Open options which defines the standard open options
BufferedWriter writer = Files.newBufferedWriter(filePath,
StandardCharsets.UTF_16, StandardOpenOption.WRITE);
// Here we use write() method to write some content
// to the file at the path specified above
writer.write("Hello World !!! \n");
writer.write("Welcome to Hubberspot.com.\n");
writer.write("Learn Java By Examples !!!!... \n");
// close the writer
writer.close();
} catch(Exception e) {
e.printStackTrace();
}
try {
// Create a BufferedReader instance by calling
// Files class newBufferedReader() method which
// returns back BufferedReader object
// This method takes in two parameters such as:
// 1. Path to the file created above
// 2. Charsets for the format of the file
BufferedReader reader = Files.newBufferedReader(filePath,
StandardCharsets.UTF_16);
String line;
// To read contents of file line by line
// we use BufferedReader readLine()
// method and prints contents to console
while((line = reader.readLine()) != null) {
System.out.println(line);
}
}
catch(Exception e) {
e.printStackTrace();
}
}
}
Output of the program :
How to Copy and Move a file in Java 7 using java.nio ?.
Program to implement how to Copy and Move a file in Java 7 using java.nio
package com.hubberspot.java7;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import static java.nio.file.StandardCopyOption.*;
public class CopyMoveFile {
public static void main(String[] args) {
// Let say we have a file placed at the directory
// D:\books\java by the name CopyAndMove.txt and
// we want to copy or move it to a different directory
// by name D:\books\CopyAndMove.
// In order to do that we create two Path instances
// in which one path represent the source and other
// represents the target
Path source = Paths.get("D:\\books\\java\\CopyAndMove.txt");
Path target = Paths.get("D:\\books\\CopyAndMove\\CopyAndMove.txt");
// In order to take a backup we usually use copy()
// method of Files class by passing three parameters
// such as source from where it picks the file
// the target where it tranfers the file and
// lastly the CopyOption which tells that
// whether to replace existing file if it exists
// by the name provided already.
try {
Files.copy(source, target, REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
// In order to move a file completely we usually
// use move() method of Files class by passing
// three parameters such as source from
// where it picks the file the target where
// it tranfers the file and lastly the
// CopyOption which tells that whether
// to replace existing file if it exists
// by the name provided already.
try {
Files.move(source, target, REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
}
}
How to create and delete a file in Java 7 using java.nio ?
Program to implement how to create and delete a file in Java 7 using java.nio ?.
package com.hubberspot.java7;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class CreateAndDeleteFile {
public static void main(String[] args) {
// Create a path to the file which is
// to be created and deleted later
// here "D:\\books\\java\\" is the address
// to reach the file created by name "hubberspot.java"
Path filePath = Paths.get("D:\\books\\java\\hubberspot.java");
// First we check whether file already exists
// at the filePath by using Files class static
// method by name exists()
if (!Files.exists(filePath)) {
try {
// Second we create a file at
// the specified filePath by using
// Files class createFile() method.
Files.createFile(filePath);
} catch (IOException e) {
e.printStackTrace();
}
}
// In order to delete there must be a file,
// here we check whether file already exists
// at the filePath by using Files class static
// method by name exists()
if (Files.exists(filePath)) {
try {
// here we delete a file at
// the specified filePath by using
// Files class delete() method.
Files.delete(filePath);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
How to search / find files in a directory using DirectoryStream in Java 7.?
Given directory "D:\books\java" having 5 pdf files as shown below :
Program to demonstrate how to search / find files in a directory using DirectoryStream in Java 7.
Output of the program :
Program to demonstrate how to search / find files in a directory using DirectoryStream in Java 7.
package com.hubberspot.java7;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class SearchFilesInDirectory {
public static void main(String[] args) {
// 1. Create a path to the directory
// where search for the files is to be done.
Path dirPath = Paths.get("D:\\books\\java");
DirectoryStream < Path > dirStream = null;
try {
// 2. Create a DirectoryStream instance using
// Files.newDirectoryStream(). The instance
// is created by passing the Path of the directory
// to be searched and the type of files as a filter
// here we are using filter to search all pdf files
// in the directory
dirStream = Files.newDirectoryStream(dirPath, "*.pdf");
// 3. Looping each file and printing the name
// on the console
for (Path entry : dirStream) {
System.out.println(entry.getFileName());
}
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
// 4. Closing the DirectoryStream
try {
dirStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Output of the program :
Java 7 new feature : Using the @SafeVarargs annotation
Program to demonstrate Java 7 new feature : Using the @SafeVarargs annotation.
Output of the program :
package com.hubberspot.java7;
import java.util.ArrayList;
import java.util.List;
public class SafeVarargsAnnotation {
public static void main(String[] args) {
// Scenario 1 -
// Prior to Java 7, usage of code without @SafeVarargs
withoutSafeVarargsAnnotation();
// Scenario 2 -
// After Java 7, usage of code with @SafeVarargs
withSafeVarargsAnnotation();
}
private static void withoutSafeVarargsAnnotation() {
List< Integer > listOfIntegers = new ArrayList< >();
listOfIntegers.add(1);
listOfIntegers.add(2);
listOfIntegers.add(3);
listOfIntegers.add(4);
List< Float > listOfFloats = new ArrayList< >();
listOfFloats.add(3.0f);
listOfFloats.add(1.0f);
listOfFloats.add(2.0f);
listOfFloats.add(3.2f);
// Calling of a method that takes in a generic type of
// variable arguments without usage of @SafeVarargs
// It generates a warning for the developer for the type safety as
// Type safety: A generic array of List< ? extends Number&Comparable< ? > >
// is created for a varargs parameter
displaywithoutSafeVarargs(listOfIntegers , listOfFloats);
}
// Also throws a warning for
// Type safety: Potential heap pollution via varargs parameter lists
private static < T > void displaywithoutSafeVarargs(T... lists) {
for(T element : lists) {
System.out.println("Display of elements without @SafeVarargs Annotation");
System.out.println(element.getClass().getName() + ": " + element);
}
}
private static void withSafeVarargsAnnotation() {
List< Integer > listOfIntegers = new ArrayList< >();
listOfIntegers.add(1);
listOfIntegers.add(2);
listOfIntegers.add(3);
listOfIntegers.add(4);
List< Float > listOfFloats = new ArrayList< >();
listOfFloats.add(3.0f);
listOfFloats.add(1.0f);
listOfFloats.add(2.0f);
listOfFloats.add(3.2f);
displaywithSafeVarargs(listOfIntegers , listOfFloats);
}
// With usage of @SafeVarargs the Type Safety warning has been
// supressed
@SafeVarargs
private static < T > void displaywithSafeVarargs(T... lists) {
System.out.println();
for(T element : lists) {
System.out.println("Display of elements with @SafeVarargs Annotation");
System.out.println(element.getClass().getName() + ": " + element);
}
}
}
Output of the program :
Java 7 new feature : Using the diamond operator for type inference
Program to demonstrate Java 7 new feature : Using the diamond operator for type inference
package com.hubberspot.java7;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class DiamondOperatorTypeInference {
public static void main(String[] args) {
// Scenario 1 -
// Code prior Java 7
List< String > list1 = new ArrayList< String >();
// Code after coming of Java 7
// we can now provide only the diamond operator
// the compiler comes to know that list2 type
// is a String
List< String > list2 = new ArrayList< >();
// Scenario 2 -
// Code prior Java 7
// the list3 below code is a raw type code for Java 6 and
// earlier versions.
// The compiler generates warning as : ArrayList is a raw type.
// References to generic type ArrayList< E > should be parameterized
List< String > list3 = new ArrayList();
// Code after coming of Java 7
// No warnings generated by the compiler.
List< String > list4 = new ArrayList< >();
// Scenario 3 -
// Code prior Java 7
// the list5 below code is a raw type code for Java 6 and
// earlier versions.
// The compiler generates warning as : ArrayList is a raw type.
// References to generic type ArrayList< E > should be parameterized
// to remove this warning we use @SuppressedWarning annotation
// as :
@SuppressWarnings(value={ "rawtypes", "unchecked" })
List< String > list5 = new ArrayList();
// Code after coming of Java 7
// No warnings generated by the compiler.
// No need of placing @SuppressWarnings({"rawtypes","unchecked"})
List< String > list6 = new ArrayList< >();
// Scenario 4 -
// Code prior Java 7
// the list7 below code is a complex type code
List< Map< String, String > > list7 = new ArrayList();
// Code after coming of Java 7
// No warnings generated by the compiler.
List< Map< String, String > > list8 = new ArrayList< >();
}
}
Java 7 new feature : Rethrowing exceptions
Program to demonstrate Java 7 new feature : Rethrowing exceptions
package com.hubberspot.java7;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.MalformedURLException;
public class RethrowingException {
public static void main(String[] args) {
try {
rethrow();
} catch(IOException e) {
System.out.println(e.getMessage());
}
}
// here mentioning precise rethrow instead of catch type throw
private static void rethrow()
throws FileNotFoundException , MalformedURLException {
try {
// FileReader Constructor throws FileNotFoundException
FileReader fileReader = new FileReader("C://file.txt");
// toURL method of File class throws MalformedURLException
File file = new File("C://file.txt");
file.toURL();
// Instead of catching it as IOException and throwing
// the same IOException in the throws clause above
// we can now catch any sub-class type and throw super-class
// type exception, mentioning what possibilities try block can
// throw in the throws clause mentioned above.
// Here the method try block throw two exceptions as
// FileNotFoundException and MalformedURLException
// we caught it in catch statement and rethrow it as
// IOException. Here compiler knows what exactly its been thrown
} catch (IOException e) {
throw e;
}
}
}
Java 7 new feature : Catching multiple exception types in a single catch block.
Program to demonstrate Java 7 new feature : Catching multiple exception types in a single catch block
Scenario 1 :
Scenario 2 :
package com.hubberspot.java7;
import java.util.InputMismatchException;
public class MultipleExceptionsCatching {
public static void main(String[] args) {
try {
// Scenario 1 : we will pass int parameter
// as -1, which will throw InputMismatchException
int i = Integer.parseInt("String 1");
// Scenario 2 : we will pass String as a int to
// parse. It will throw NumberFormatException
// int i = Integer.parseInt("String 1");
if(i <= 0) {
throw new InputMismatchException();
}
// Initially prior to Java 7, we would have coded multiple exceptions
// into various catch blocks as :
//
// try {
// throw new NumberFormatException() or throw new InputMismatchException()
// }
// catch(NumberFormatException nfe) {
// nfe.printStackTrace();
// }
// catch(InputMismatchException ime) {
// ime.printStackTrace();
// }
// But with introduction of Java 7 we can handle multiple
// exceptions in a single catch block itself
// see the code below :
} catch(NumberFormatException | InputMismatchException e) {
e.printStackTrace();
}
}
}
Output of the program : Scenario 1 :
Scenario 2 :
Java 7 new feature : Using the try-with-resources block to improve exception handling code.
Program to demonstrate Java 7 new feature : Using the try-with-resources block to improve exception handling code.
A complete video tutorial on : Java 7 new feature : Using the try-with-resources block to improve exception handling code.
Output of the program :
1. try.txt file as input:
2. copy.txt file as output :
package com.hubberspot.java7;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class TryWithResourceBlock {
public static void main(String[] args) {
// try-with-resources block was added into
// Java 7 which ensures all of its resources
// being automatically closed when the try block exits.
// The resources which we need to close and forget
// while coding is automatically being closed by
// try-with-resources block. The resources which
// could be closed by this block should implement
// interface java.lang.AutoCloseable
try(BufferedReader br = new BufferedReader(new FileReader("c://try.txt"))
; BufferedWriter bw = new BufferedWriter(new FileWriter("c://copy.txt"))) {
String inputLine = "";
while((inputLine = br.readLine()) != null) {
bw.write(inputLine);
bw.newLine();
}
System.out.println("Reader and Writer are automatically closed ... ");
} catch(IOException e) {
e.printStackTrace();
}
}
}
A complete video tutorial on : Java 7 new feature : Using the try-with-resources block to improve exception handling code.
Output of the program :
1. try.txt file as input:
2. copy.txt file as output :
Java 7 new feature : Using Underscores in literals to improve code readability
Program to demonstrate Java 7 new feature : Using Underscores in literals to improve code readability
Output of the program :
package com.hubberspot.java7;
public class UnderscoresInLiterals {
public static void main(String[] args) {
// Credit Card and Debit Card numbers
// not very clear to read.
// Poor code readability
long debitCard = 4657847382084234L;
long creditCard = 7657382844234084L;
System.out.println("Lets print out credit card and debit card numbers : ");
System.out.println("Debit Card as String: " + Long.toString(debitCard));
System.out.println("Credit Card as String: " + Long.toString(creditCard));
System.out.println();
// Credit Card and Debit Card numbers
// very clear to read.
// Better code readability
debitCard = 4657_8473_8208_4234L;
creditCard = 7657_3828_4423_4084L;
// Result is same as above.
System.out.println("Lets print out credit card and debit card numbers : ");
System.out.println("Debit Card as String: " + Long.toString(debitCard));
System.out.println("Credit Card as String: " + Long.toString(creditCard));
}
}
Output of the program :
Java 7 new feature : Using String literals in switch statements.
Program to demonstrate Java 7 new feature : Using String literals in switch statements
package com.hubberspot.java7;
import java.util.Scanner;
public class StringInSwitch {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
for(int i = 0; i < 3; i++) {
String companyName = scanner.nextLine();
// Instead of using integers in switch statements
// for earlier versions, Java 7 allows us to use
// Strings in switch statements
switch(companyName) {
case "TCS":
System.out.println("You have selected TCS");
break;
case "Wipro":
System.out.println("You have selected Wipro");
break;
case "Accenture":
System.out.println("You have selected Accenture");
break;
case "Apple":
System.out.println("You have selected Apple");
break;
case "Amdocs":
System.out.println("You have selected Amdocs");
break;
default:
System.out.println("Boom Boom ... Wrong selection");
}
}
}
}
Output of the program :
Subscribe to:
Posts (Atom)












