Java 7 Features:
----------------
1)Strings in Switch statements:
Before:
public void testStringInSwitch(String param){
final String JAVA5 = "Java 5";
final String JAVA6 = "Java 6";
final String JAVA7 = "Java 7";
if (param.equals(JAVA5)){
System.out.println(JAVA5);
} else if (param.equals(JAVA6)){
System.out.println(JAVA6);
} else if (param.equals(JAVA7)){
System.out.println(JAVA7);
}
}
Java7:
public void testStringInSwitch(String param){
final String JAVA5 = "Java 5";
final String JAVA6 = "Java 6";
final String JAVA7 = "Java 7";
switch (param) {
case JAVA5:
System.out.println(JAVA5);
break;
case JAVA6:
System.out.println(JAVA6);
break;
case JAVA7:
System.out.println(JAVA7);
break;
}
}
2) Binary Literals:
Before:
public void testBinaryIntegralLiterals(){
int binary = 8;
if (binary == 8){
System.out.println(true);
} else{
System.out.println(false);
}
}
Java7:
public void testBinaryIntegralLiterals(){
int binary = 0b1000; //2^3 = 8
if (binary == 8){
System.out.println(true);
} else{
System.out.println(false);
}
}
Underscore Between Literals(Numeric literals with underscores):
public void testUnderscoresNumericLiterals() {
int oneMillion_ = 1_000_000; //new
int oneMillion = 1000000;
if (oneMillion_ == oneMillion){
System.out.println(true);
} else{
System.out.println(false);
}
}
3) Diamond Operator Syntax:
Before:
public void testDiamond(){
List list = new ArrayList();
Map> map = new HashMap>();
}
Java7:
public void testDiamond(){
List list = new ArrayList<>();
Map> map = new HashMap<>();
}
4) Multi-Catch Similar Exceptions(Improved exception handling):
Before:
public void testMultiCatch(){
try {
throw new FileNotFoundException("FileNotFoundException");
} catch (FileNotFoundException fnfo) {
fnfo.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
Java7:
public void testMultiCatch(){
try {
throw new FileNotFoundException("FileNotFoundException");
} catch (FileNotFoundException | IOException fnfo) {
fnfo.printStackTrace();
}
}
5) Try with Resources(Automatic resource management):
Before:
public void testTryWithResourcesStatement() throws FileNotFoundException, IOException{
FileInputStream in = null;
try {
in = new FileInputStream("java7.txt");
System.out.println(in.read());
} finally {
if (in != null) {
in.close();
}
}
}
Java7:
public void testTryWithResourcesStatement() throws FileNotFoundException, IOException{
try (FileInputStream in = new FileInputStream("java7.txt")) {
System.out.println(in.read());
}
}
6) SafeVarargs
Before:
@SuppressWarnings({"unchecked", "varargs"})
public static void printAll(List<String>... lists){
for(List<String> list : lists){
System.out.println(list);
}
}
Java7:
@SafeVarargs
public static void printAll(List<String>... lists){
for(List<String> list : lists){
System.out.println(list);
}
}
7) The java.nio.file package
The java.nio.file package and its related package, java.nio.file.attribute, provide comprehensive support for file I/O and for accessing the file system.
A zip file system provider is also available in JDK 7.
Before:
File file = new File(“hello.txt”); System.out.println(“File exists() == ” + file.exists());
Java7:
Path path = FileSystems.getDefault().getPath(“hello.txt”); System.out.println(“Path exists() == ” + Files.exists(path));
Java 8 Features
auto-boxing, generics, var-args, java annotations, enum, premain method , lambda expressions, functional interface, method references etc.
The important features of JavaSE 8 are lambda expressions, methods references, default methods, functional interface, java 8 date/time, stream classes etc.
Java 8 Date/Time API (Java 8)
Lambda Expressions (Java 8)
Method References (Java 8)
Functional Interfaces (Java 8)
Stream (Java 8)
Base64 Encode Decode (Java 8)
Default Methods (Java 8)
forEach method(Java 8)
Collectors(Java 8)
StringJoiner(Java 8)
Optional class (Java 8)
Nashorn JavaScript (Java 8)
Parallel Array Sorting (Java 8)
Type Inference (Java 8)
Method Parameter Reflection (Java 8)
Type annotations and repeating annotations (Java 8)
Java JDBC Improvements (Java 8)
Java IO Improvement (Java 8)
Java Concurrency Improvement (Java 8)
Lamda Expressions:
Lambda expression is a new and important feature of Java which was included in Java SE 8. It provides a clear and concise way to represent one method interface using an expression. It is very useful in collection library. It helps to iterate, filter and extract data from collection. Before lambda expression, anonymous inner class was the only option to implement the method.
In other words, we can say it is a replacement of java inner anonymous class. Java lambda expression is treated as a function, so compiler does not create .class file.
Why use Lambda Expression :
To provide the implementation of Functional interface.
Less coding.
Method references:
Java Method References
Java provides a new feature called method reference in Java 8. Method reference is used to refer method of functional interface. It is compact and easy form of lambda expression. Each time when you are using lambda expression to just referring a method, you can replace your lambda expression with method reference
Types of Method References
There are four types of method references:
i) Reference to a static method.
Eg:
package com.mycompany.core.MethodReference;
interface Sayable {
void say();
}
public class MethodReference {
public static void saySomething() {
System.out.println("Hello, this is static method.::--> Reference to a Static Method:- Type:-1");
}
public static void main(String[] args) {
Sayable sayble = MethodReference::saySomething;
sayble.say();
}
}
ii) Reference to an instance method of a particular object.
package com.mycompany.core.MethodReference;
interface Testable {
void say();
}
public class InstanceMethodRefernce {
public void saySomething() {
System.out.println("Hello, this is non-static method.");
}
public static void main(String[] args) {
InstanceMethodRefernce iReference = new InstanceMethodRefernce(); // creating
// an
// object
// Referring non-static method using reference
Testable sayble = iReference::saySomething;
// Calling interface method
sayble.say();
// Referring non-static method using anonymous object
Testable sayable2 = new InstanceMethodRefernce()::saySomething; // You use anonymus object also. // can
// Calling interface method
sayable2.say();
}
}
iii) Reference to an instance method of an arbitrary object of a particular type.
iv) Reference to a constructor.
Eg:
package com.mycompany.core.MethodReference;
interface Messageable {
Message getMessage(String msg);
}
class Message {
public Message(String msg) {
System.out.print(msg);
}
}
public class ConstructorReference {
public static void main(String[] args) {
Messageable hello = Message::new;
hello.getMessage("Hello");
}
}
Stream filter:
Java stream provides a method filter() to filter stream elements on the basis of given predicate. Suppose you want to get only even elements of your list then you can do this easily with the help of filter method.
syntax: Stream<T> filter(Predicate<? super T> predicate) .
Eg:
package com.mycompany.core.streamfilter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
class Product {
int productId;
String name;
float price;
public Product(int productId, String name, float price) {
this.productId = productId;
this.name = name;
this.price = price;
}
}
public class JavaStreamfilterEx {
public static void main(String[] args) {
List<Product> productsList = new ArrayList<Product>();
// Adding Products
productsList.add(new Product(1, "HP Laptop", 25000f));
productsList.add(new Product(2, "Dell Laptop", 30000f));
productsList.add(new Product(3, "Lenevo Laptop", 28000f));
productsList.add(new Product(4, "Sony Laptop", 28000f));
productsList.add(new Product(5, "Apple Laptop", 90000f));
/* productsList.stream()
.filter(p ->p.price> 30000) // filtering price
.map(pm ->pm.price) // fetching price
.forEach(System.out::println); // iterating price
*/
List<Float> pricesList = productsList.stream().filter(p -> p.price > 30000).map(pm -> pm.price).collect(Collectors.toList());
System.out.println(pricesList); //
}
}
Java forEach loop:
forEach() Signature in Iterable Interface.
Eg:
package com.mycompany.collections;
import java.util.ArrayList;
import java.util.List;
public class ForEachExample {
public static void main(String[] args) {
List<String> gamesList = new ArrayList<String>();
gamesList.add("Football");
gamesList.add("Cricket");
gamesList.add("Chess");
gamesList.add("Hocky");
System.out.println("------------Iterating by passing lambda expression--------------");
gamesList.forEach(games->System.out.println(games));
System.out.println("------------Iterating by passing method reference---------------");
gamesList.forEach(System.out::println);
}
}
Java Collectors:
Collectors is a final class that extends Object class. It provides reduction operations, such as accumulating elements into collections, summarizing elements according to various criteria, etc.
Eg:
package com.mycompany.collections;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
class Product {
int id;
String name;
float price;
public Product(int id, String name, float price) {
this.id = id;
this.name = name;
this.price = price;
}
}
public class CollectorsExample {
public static void main(String[] args) {
List<Product> productsList = new ArrayList<Product>();
//Adding Products
productsList.add(new Product(1,"HP Laptop",25000f));
productsList.add(new Product(2,"Dell Laptop",30000f));
productsList.add(new Product(3,"Lenevo Laptop",28000f));
productsList.add(new Product(4,"Sony Laptop",28000f));
productsList.add(new Product(5,"Apple Laptop",90000f));
List<Float> productPriceList = productsList.stream()
.map(x->x.price).collect(Collectors.toList());
System.out.println(productPriceList);
}
}
Java StringJoiner :
Java added a new final class StringJoiner in java.util package. It is used to construct a sequence of characters separated by a delimiter. Now, you can create string by passing delimiters like comma(,), hyphen(-) etc. You can also pass prefix and suffix to the char sequence.
Eg:
package com.mycompany.core;
import java.util.StringJoiner;
public class StringJoinerExample {
public static void main(String[] args) {
StringJoiner joinNames = new StringJoiner(",", "[", "]"); // passing comma(,) and square-brackets as delimiter
//StringJoiner joinNames = new StringJoiner(",");
joinNames .add("Rahul");
joinNames .add("Nambiyar");
joinNames .add("Karan");
joinNames .add("Arjun");
joinNames .add("Preethi Jintha");
System.out.println(joinNames);
}
}
Java Optional Class:
Java introduced a new class Optional in jdk8. It is a public final class and used to deal with NullPointerException in Java application. You must import java.util package to use this class. It provides methods which are used to check the presence of value for particular variable.
Example:
package com.mycompany.core;
import java.util.Optional;
public class OptionalClassEx {
public static void main(String[] args) {
String[] str = new String[10];
str[5] = "JAVA OPTIONAL CLASS EXAMPLE";// Setting value for 5th index
Optional<String> checkNull = Optional.ofNullable(str[5]);
if (checkNull.isPresent()) {
String lowercaseString = str[5].toLowerCase();
System.out.print(lowercaseString);
} else {
System.out.println("string value is not present");
}
}
}
Java Parallel Array Sorting:
Java provides a new additional feature in Array class which is used to sort array elements parallel.New methods has added to java.util.Arrays package that use the JSR 166 Fork/Join parallelism common pool to provide sorting of arrays in parallel.The methods are called parallelSort() and are overloaded for all the primitive data types and Comparable objects.
Eg:
package com.mycompany.core;
import java.util.Arrays;
public class ParallelArraySorting {
public static void main(String[] args) {
int []arr = {5,8,1,0,6,9};
for(int i: arr){
System.out.print(i+" ");
}
Arrays.parallelSort(arr);
System.out.println("\nArray elements after sorting");
for(int i: arr){
System.out.print(i+" ");
}
}
}
Java Type Inference:
Type inference is a feature of Java which provides ability to compiler to look at each method invocation and corresponding declaration to determine the type of arguments.
Java provides improved version of type inference in Java 8. the following example explains, how we can use type inference in our code:
Here, we are creating arraylist by mentioning integer type explicitly at both side. The following approach is used earlier versions of Java.
List<Integer> list = new ArrayList<Integer>();
Example:
package com.mycompany.collections;
import java.util.ArrayList;
import java.util.List;
public class TypeInferenceExample {
public static void showList(List<Integer> list) {
if (!list.isEmpty()) {
list.forEach(System.out::println);
} else {
System.out.println("list is empty");
}
}
public static void main(String[] args) {
List<Integer> list1 = new ArrayList<Integer>();
list1.add(11);
showList(list1);
// Java 7
List<Integer> list2 = new ArrayList<>(); // You can left it blank, compiler can infer type
list2.add(12);
showList(list2);
// Compiler infers type of ArrayList, in Java 8
showList(new ArrayList<>());
}
}
Java Type Annotations :
Java 8 has included two new features repeating and type annotations in its prior annotations topic. In early Java versions, you can apply annotations only to declarations. After releasing of Java SE 8 , annotations can be applied to any type use. It means that annotations can be used anywhere you use a type. For example, if you want to avoid NullPointerException in your code, you can declare a string variable like this:
Example:
package com.mycompany.core;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Repeatable(Games.class)
@interface Game {
String name();
String day();
}
// Declaring container for repeatable annotation type
@Retention(RetentionPolicy.RUNTIME)
@interface Games {
Game[] value();
}
// Repeating annotation
@Game(name = "Cricket", day = "Sunday")
@Game(name = "Hockey", day = "Friday")
@Game(name = "Football", day = "Saturday")
public class RepeatingAnnotationsExample {
public static void main(String[] args) {
Game[] game = RepeatingAnnotationsExample.class.getAnnotationsByType(Game.class);
for(Game game2 : game){
System.out.println(game2.name()+" on "+game2.day());
}
}
}
Java 8 JDBC Improvements:
1) The JDBC-ODBC Bridge has been removed.
Oracle does not support the JDBC-ODBC Bridge. Oracle recommends that you use JDBC drivers provided by the vendor of your database instead of the JDBC-ODBC Bridge.
2) Added some new features in JDBC 4.2 :-
Java JDBC 4.2 introduces the following features:
Addition of REF_CURSOR support.
Addition of java.sql.DriverAction Interface
Addition of security check on deregisterDriver Method in DriverManager Class
Addition of the java.sql.SQLType Interface
Addition of the java.sql.JDBCType Enum
Add Support for large update counts
Changes to the existing interfaces
Rowset 1.2: Lists the enhancements for JDBC RowSet.
----------------
1)Strings in Switch statements:
Before:
public void testStringInSwitch(String param){
final String JAVA5 = "Java 5";
final String JAVA6 = "Java 6";
final String JAVA7 = "Java 7";
if (param.equals(JAVA5)){
System.out.println(JAVA5);
} else if (param.equals(JAVA6)){
System.out.println(JAVA6);
} else if (param.equals(JAVA7)){
System.out.println(JAVA7);
}
}
Java7:
public void testStringInSwitch(String param){
final String JAVA5 = "Java 5";
final String JAVA6 = "Java 6";
final String JAVA7 = "Java 7";
switch (param) {
case JAVA5:
System.out.println(JAVA5);
break;
case JAVA6:
System.out.println(JAVA6);
break;
case JAVA7:
System.out.println(JAVA7);
break;
}
}
2) Binary Literals:
Before:
public void testBinaryIntegralLiterals(){
int binary = 8;
if (binary == 8){
System.out.println(true);
} else{
System.out.println(false);
}
}
Java7:
public void testBinaryIntegralLiterals(){
int binary = 0b1000; //2^3 = 8
if (binary == 8){
System.out.println(true);
} else{
System.out.println(false);
}
}
Underscore Between Literals(Numeric literals with underscores):
public void testUnderscoresNumericLiterals() {
int oneMillion_ = 1_000_000; //new
int oneMillion = 1000000;
if (oneMillion_ == oneMillion){
System.out.println(true);
} else{
System.out.println(false);
}
}
3) Diamond Operator Syntax:
Before:
public void testDiamond(){
List list = new ArrayList();
Map> map = new HashMap>();
}
Java7:
public void testDiamond(){
List list = new ArrayList<>();
Map> map = new HashMap<>();
}
4) Multi-Catch Similar Exceptions(Improved exception handling):
Before:
public void testMultiCatch(){
try {
throw new FileNotFoundException("FileNotFoundException");
} catch (FileNotFoundException fnfo) {
fnfo.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
Java7:
public void testMultiCatch(){
try {
throw new FileNotFoundException("FileNotFoundException");
} catch (FileNotFoundException | IOException fnfo) {
fnfo.printStackTrace();
}
}
5) Try with Resources(Automatic resource management):
Before:
public void testTryWithResourcesStatement() throws FileNotFoundException, IOException{
FileInputStream in = null;
try {
in = new FileInputStream("java7.txt");
System.out.println(in.read());
} finally {
if (in != null) {
in.close();
}
}
}
Java7:
public void testTryWithResourcesStatement() throws FileNotFoundException, IOException{
try (FileInputStream in = new FileInputStream("java7.txt")) {
System.out.println(in.read());
}
}
6) SafeVarargs
Before:
@SuppressWarnings({"unchecked", "varargs"})
public static void printAll(List<String>... lists){
for(List<String> list : lists){
System.out.println(list);
}
}
Java7:
@SafeVarargs
public static void printAll(List<String>... lists){
for(List<String> list : lists){
System.out.println(list);
}
}
7) The java.nio.file package
The java.nio.file package and its related package, java.nio.file.attribute, provide comprehensive support for file I/O and for accessing the file system.
A zip file system provider is also available in JDK 7.
Before:
File file = new File(“hello.txt”); System.out.println(“File exists() == ” + file.exists());
Java7:
Path path = FileSystems.getDefault().getPath(“hello.txt”); System.out.println(“Path exists() == ” + Files.exists(path));
Java 8 Features
auto-boxing, generics, var-args, java annotations, enum, premain method , lambda expressions, functional interface, method references etc.
The important features of JavaSE 8 are lambda expressions, methods references, default methods, functional interface, java 8 date/time, stream classes etc.
Java 8 Date/Time API (Java 8)
Lambda Expressions (Java 8)
Method References (Java 8)
Functional Interfaces (Java 8)
Stream (Java 8)
Base64 Encode Decode (Java 8)
Default Methods (Java 8)
forEach method(Java 8)
Collectors(Java 8)
StringJoiner(Java 8)
Optional class (Java 8)
Nashorn JavaScript (Java 8)
Parallel Array Sorting (Java 8)
Type Inference (Java 8)
Method Parameter Reflection (Java 8)
Type annotations and repeating annotations (Java 8)
Java JDBC Improvements (Java 8)
Java IO Improvement (Java 8)
Java Concurrency Improvement (Java 8)
Lamda Expressions:
Lambda expression is a new and important feature of Java which was included in Java SE 8. It provides a clear and concise way to represent one method interface using an expression. It is very useful in collection library. It helps to iterate, filter and extract data from collection. Before lambda expression, anonymous inner class was the only option to implement the method.
In other words, we can say it is a replacement of java inner anonymous class. Java lambda expression is treated as a function, so compiler does not create .class file.
Why use Lambda Expression :
To provide the implementation of Functional interface.
Less coding.
Method references:
Java Method References
Java provides a new feature called method reference in Java 8. Method reference is used to refer method of functional interface. It is compact and easy form of lambda expression. Each time when you are using lambda expression to just referring a method, you can replace your lambda expression with method reference
Types of Method References
There are four types of method references:
i) Reference to a static method.
Eg:
package com.mycompany.core.MethodReference;
interface Sayable {
void say();
}
public class MethodReference {
public static void saySomething() {
System.out.println("Hello, this is static method.::--> Reference to a Static Method:- Type:-1");
}
public static void main(String[] args) {
Sayable sayble = MethodReference::saySomething;
sayble.say();
}
}
package com.mycompany.core.MethodReference;
interface Testable {
void say();
}
public class InstanceMethodRefernce {
public void saySomething() {
System.out.println("Hello, this is non-static method.");
}
public static void main(String[] args) {
InstanceMethodRefernce iReference = new InstanceMethodRefernce(); // creating
// an
// object
// Referring non-static method using reference
Testable sayble = iReference::saySomething;
// Calling interface method
sayble.say();
// Referring non-static method using anonymous object
Testable sayable2 = new InstanceMethodRefernce()::saySomething; // You use anonymus object also. // can
// Calling interface method
sayable2.say();
}
}
iv) Reference to a constructor.
Eg:
package com.mycompany.core.MethodReference;
interface Messageable {
Message getMessage(String msg);
}
class Message {
public Message(String msg) {
System.out.print(msg);
}
}
public class ConstructorReference {
public static void main(String[] args) {
Messageable hello = Message::new;
hello.getMessage("Hello");
}
}
Stream filter:
Java stream provides a method filter() to filter stream elements on the basis of given predicate. Suppose you want to get only even elements of your list then you can do this easily with the help of filter method.
syntax: Stream<T> filter(Predicate<? super T> predicate) .
Eg:
package com.mycompany.core.streamfilter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
class Product {
int productId;
String name;
float price;
public Product(int productId, String name, float price) {
this.productId = productId;
this.name = name;
this.price = price;
}
}
public class JavaStreamfilterEx {
public static void main(String[] args) {
List<Product> productsList = new ArrayList<Product>();
// Adding Products
productsList.add(new Product(1, "HP Laptop", 25000f));
productsList.add(new Product(2, "Dell Laptop", 30000f));
productsList.add(new Product(3, "Lenevo Laptop", 28000f));
productsList.add(new Product(4, "Sony Laptop", 28000f));
productsList.add(new Product(5, "Apple Laptop", 90000f));
/* productsList.stream()
.filter(p ->p.price> 30000) // filtering price
.map(pm ->pm.price) // fetching price
.forEach(System.out::println); // iterating price
*/
List<Float> pricesList = productsList.stream().filter(p -> p.price > 30000).map(pm -> pm.price).collect(Collectors.toList());
System.out.println(pricesList); //
}
}
Java forEach loop:
forEach() Signature in Iterable Interface.
Eg:
package com.mycompany.collections;
import java.util.ArrayList;
import java.util.List;
public class ForEachExample {
public static void main(String[] args) {
List<String> gamesList = new ArrayList<String>();
gamesList.add("Football");
gamesList.add("Cricket");
gamesList.add("Chess");
gamesList.add("Hocky");
System.out.println("------------Iterating by passing lambda expression--------------");
gamesList.forEach(games->System.out.println(games));
System.out.println("------------Iterating by passing method reference---------------");
gamesList.forEach(System.out::println);
}
}
Java Collectors:
Collectors is a final class that extends Object class. It provides reduction operations, such as accumulating elements into collections, summarizing elements according to various criteria, etc.
Eg:
package com.mycompany.collections;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
class Product {
int id;
String name;
float price;
public Product(int id, String name, float price) {
this.id = id;
this.name = name;
this.price = price;
}
}
public class CollectorsExample {
public static void main(String[] args) {
List<Product> productsList = new ArrayList<Product>();
//Adding Products
productsList.add(new Product(1,"HP Laptop",25000f));
productsList.add(new Product(2,"Dell Laptop",30000f));
productsList.add(new Product(3,"Lenevo Laptop",28000f));
productsList.add(new Product(4,"Sony Laptop",28000f));
productsList.add(new Product(5,"Apple Laptop",90000f));
List<Float> productPriceList = productsList.stream()
.map(x->x.price).collect(Collectors.toList());
System.out.println(productPriceList);
}
}
Java StringJoiner :
Java added a new final class StringJoiner in java.util package. It is used to construct a sequence of characters separated by a delimiter. Now, you can create string by passing delimiters like comma(,), hyphen(-) etc. You can also pass prefix and suffix to the char sequence.
Eg:
package com.mycompany.core;
import java.util.StringJoiner;
public class StringJoinerExample {
public static void main(String[] args) {
StringJoiner joinNames = new StringJoiner(",", "[", "]"); // passing comma(,) and square-brackets as delimiter
//StringJoiner joinNames = new StringJoiner(",");
joinNames .add("Rahul");
joinNames .add("Nambiyar");
joinNames .add("Karan");
joinNames .add("Arjun");
joinNames .add("Preethi Jintha");
System.out.println(joinNames);
}
}
Java Optional Class:
Java introduced a new class Optional in jdk8. It is a public final class and used to deal with NullPointerException in Java application. You must import java.util package to use this class. It provides methods which are used to check the presence of value for particular variable.
Example:
package com.mycompany.core;
import java.util.Optional;
public class OptionalClassEx {
public static void main(String[] args) {
String[] str = new String[10];
str[5] = "JAVA OPTIONAL CLASS EXAMPLE";// Setting value for 5th index
Optional<String> checkNull = Optional.ofNullable(str[5]);
if (checkNull.isPresent()) {
String lowercaseString = str[5].toLowerCase();
System.out.print(lowercaseString);
} else {
System.out.println("string value is not present");
}
}
}
Java Parallel Array Sorting:
Java provides a new additional feature in Array class which is used to sort array elements parallel.New methods has added to java.util.Arrays package that use the JSR 166 Fork/Join parallelism common pool to provide sorting of arrays in parallel.The methods are called parallelSort() and are overloaded for all the primitive data types and Comparable objects.
Eg:
package com.mycompany.core;
import java.util.Arrays;
public class ParallelArraySorting {
public static void main(String[] args) {
int []arr = {5,8,1,0,6,9};
for(int i: arr){
System.out.print(i+" ");
}
Arrays.parallelSort(arr);
System.out.println("\nArray elements after sorting");
for(int i: arr){
System.out.print(i+" ");
}
}
}
Java Type Inference:
Type inference is a feature of Java which provides ability to compiler to look at each method invocation and corresponding declaration to determine the type of arguments.
Java provides improved version of type inference in Java 8. the following example explains, how we can use type inference in our code:
Here, we are creating arraylist by mentioning integer type explicitly at both side. The following approach is used earlier versions of Java.
List<Integer> list = new ArrayList<Integer>();
Example:
package com.mycompany.collections;
import java.util.ArrayList;
import java.util.List;
public class TypeInferenceExample {
public static void showList(List<Integer> list) {
if (!list.isEmpty()) {
list.forEach(System.out::println);
} else {
System.out.println("list is empty");
}
}
public static void main(String[] args) {
List<Integer> list1 = new ArrayList<Integer>();
list1.add(11);
showList(list1);
// Java 7
List<Integer> list2 = new ArrayList<>(); // You can left it blank, compiler can infer type
list2.add(12);
showList(list2);
// Compiler infers type of ArrayList, in Java 8
showList(new ArrayList<>());
}
}
Java Type Annotations :
Java 8 has included two new features repeating and type annotations in its prior annotations topic. In early Java versions, you can apply annotations only to declarations. After releasing of Java SE 8 , annotations can be applied to any type use. It means that annotations can be used anywhere you use a type. For example, if you want to avoid NullPointerException in your code, you can declare a string variable like this:
Example:
package com.mycompany.core;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Repeatable(Games.class)
@interface Game {
String name();
String day();
}
// Declaring container for repeatable annotation type
@Retention(RetentionPolicy.RUNTIME)
@interface Games {
Game[] value();
}
// Repeating annotation
@Game(name = "Cricket", day = "Sunday")
@Game(name = "Hockey", day = "Friday")
@Game(name = "Football", day = "Saturday")
public class RepeatingAnnotationsExample {
public static void main(String[] args) {
Game[] game = RepeatingAnnotationsExample.class.getAnnotationsByType(Game.class);
for(Game game2 : game){
System.out.println(game2.name()+" on "+game2.day());
}
}
}
Java 8 JDBC Improvements:
1) The JDBC-ODBC Bridge has been removed.
Oracle does not support the JDBC-ODBC Bridge. Oracle recommends that you use JDBC drivers provided by the vendor of your database instead of the JDBC-ODBC Bridge.
2) Added some new features in JDBC 4.2 :-
Java JDBC 4.2 introduces the following features:
Addition of REF_CURSOR support.
Addition of java.sql.DriverAction Interface
Addition of security check on deregisterDriver Method in DriverManager Class
Addition of the java.sql.SQLType Interface
Addition of the java.sql.JDBCType Enum
Add Support for large update counts
Changes to the existing interfaces
Rowset 1.2: Lists the enhancements for JDBC RowSet.
Thanks for sharing this informative content , Great work
ReplyDeleteLeanpitch provides online training in Agile coach during this lockdown period everyone can use it wisely.
Certified agile coaching Bangalore
Thanks for sharing this informative content , Great work
ReplyDeleteCreative Thinking for creating an impact!
Product Thinking Community introduces PT Labs powered by Leanpitch
Product thinking conference