New feature of String in java by R4R Team

String deduplication feature (from Java 8 update 20):

a)String deduplication feature was added in Java 8 update 20. It is a part of G1 garbage collector, so it should be turned on with G1 collector: -XX:+UseG1GC -XX:+UseStringDeduplication
b)String deduplication is an optional G1 phase. It depends on the current system load.
c)String deduplication is looking for the strings with the same contents and canonicalizing the underlying char[] with string characters. You don't need to write code to use this feature, but it means you are being left with distinct String objects, each of those occupying 24 bytes. Sometimes it worth to intern strings explicitly using String.intern.
d)String deduplication does not process too young strings. The minimal age of processed strings is managed by -XX:StringDeduplicationAgeThreshold=3 JVM parameter (3 is the default value of this parameter). 

New Java 7 Feature: String in Switch support

With Java 6, or less:

String color = "red";

if (color.equals("red")) {

System.out.println("Color is Red");

} else if (color.equals("green"))  {

System.out.println("Color is Green");

} else {

System.out.println("Color not found"); }


With Java 7:

String color = "red";

switch (color) {

case "red":

System.out.println("Color is Red");

break;

case "green":

System.out.println("Color is Green");

break;

default:

System.out.println("Color not found"); }

The switch statement when used with a String uses the equals() method to compare the given expression to each value in the case statement and is therefore case-sensitive and will throw a NullPointerException if the expression is null. It is a small but useful feature which not only helps us write more readable code but the compiler will likely generate more efficient bytecode as compared to the if-then-else statement.  

Leave a Comment: