KEMBAR78
Session 38 - Core Java (New Features) - Part 1 | PPTX
Java & JEE Training
Session 38 – Core Java (New Features) with Examples
Page 1Classification: Restricted
Agenda
• Core Java features with Examples
• Assertions
• Varargs
• Static import
• Autoboxing and Unboxing
• Enum
• Covariant
• Annotations
• Generics
• Instrumentation
• Catch Multiple Exceptions
Page 2Classification: Restricted
What were the new features added to Core Java library?
• Very important from interview perspective.
• Most of the Core Java questions asked in interviews are relevant to the new
features introduced in later versions of Java i.e. 4 and above.
Page 3Classification: Restricted
Java versions…
Code name culture dropped after Oracle took over 
Page 4Classification: Restricted
New features…
J2SE 4 (JDK 1.4)
• Assertions
Java 6
• Instrumentation
Java 7
• String in switch statement
• Binary Literals
• The try-with-resources
• Catching Multiple Exceptions by
single catch
• Underscores in Numeric Literals
Java 8
• Java 8 Date/Time API
• Lambda Expressions
• Method References
• Functional Interfaces
• Stream Collectors
• Optional class
• Nashorn JavaScript
• And many more…
JDK 1.5 or Java SE 5
• For-each loop
• Varargs
• Static Import
• Autoboxing and Unboxing
• Enum
• Covariant Return Type
• Annotation
• Generics
Tomorrow’s
session
Page 5Classification: Restricted
Assertions (JDK 1.4)
• Assertion is a statement in java. It can be used to test your assumptions
about the program.
• While executing assertion, it is believed to be true. If it fails, JVM will throw
an error named AssertionError. It is mainly used for testing purpose.
• Examples:
assert age>=18; //without custom assert error message
assert age>=18:”Age not valid”; //with custom assert error message
• AssertionError is a subclass of java.lang.Error.
• Not of any use in production. This is a development tool.
Page 6Classification: Restricted
For-Each Loop (JDK 1.5) – Arrays example
class ForEachExample1{
public static void main(String args[]){
int arr[]={12,13,14,44};
for(int i:arr){
System.out.println(i);
}
}
}
Page 7Classification: Restricted
For-Each Loop (JDK 1.5) – Collections example
import java.util.*;
class ForEachExample2{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();
list.add(“Pawan");
list.add(“Bill");
list.add(“George");
for(String s:list){
System.out.println(s);
}
}
}
Page 8Classification: Restricted
Varargs (Java 5)
• The varargs allows the method to accept zero or muliple arguments.
• Before varargs either we use overloaded method or take an array as the
method parameter but it was not considered good because it leads to the
maintenance problem.
• If we don't know how many argument we will have to pass in the method,
varargs is the better approach.
Page 9Classification: Restricted
Varargs (Java 5) Example
class VarargsExample{
static void display(String... values){
System.out.println("display method invoked ");
for(String s:values){
System.out.println(s);
}
}
public static void main(String args[]){
display();//zero argument
display("my","name","is","varargs");//four arguments
}
}
Page 10Classification: Restricted
Static import (Java 5)
• The static import feature of Java 5 facilitate the java programmer to access
any static member of a class directly.
• There is no need to qualify it by the class name.
• Advantage is less coding required. But do not overuse and it will impact
readability and maintainability of the code.
Page 11Classification: Restricted
Static import (Java 5)
import static java.lang.System.*;
class StaticImportExample{
public static void main(String args[]){
out.println("Hello"); //Now no need of System.out
out.println("Java");
}
}
Page 12Classification: Restricted
Static import (Java 5): How different from regular import?
• Import => Access classes without package qualification.
• Static import => Access static members without class qualification.
Page 13Classification: Restricted
Autoboxing and Unboxing (Java 5)
• No need of conversion between primitives and Wrappers manually so less coding is required.
class BoxingExample1{
public static void main(String args[]){
int a=50;
Integer a2=new Integer(a);//Boxing
Integer a3=5;//Boxing
System.out.println(a2+" "+a3);
}
}
class UnboxingExample1{
public static void main(String args[]){
Integer i=new Integer(50);
int a=i; //Unboxing
System.out.println(a);
}
}
Page 14Classification: Restricted
Enum (Java 5)
• Enum in java is a data type that contains fixed set of constants.
• E.g. (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY and
SATURDAY)
• E.g. (NORTH, SOUTH, EAST and WEST)
Page 15Classification: Restricted
Enum (Java 5) Example
class EnumExample1{
public enum Season { WINTER, SPRING, SUMMER, FALL }
public static void main(String[] args) {
for (Season s : Season.values()){ //.values() returns array
System.out.println(s);
}
}
}
Page 16Classification: Restricted
Enum (Java 5) Example
enum Season { WINTER, SPRING, SUMMER, FALL }
class EnumExample2{
public static void main(String[] args) {
Season s=Season.WINTER;
System.out.println(s);
}}
Page 17Classification: Restricted
Enum (Java 5) Example
class EnumExample5{
enum Day{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY}
public static void main(String args[]){
Day day=Day.MONDAY;
switch(day){
case SUNDAY:
System.out.println("sunday");
break;
case MONDAY:
System.out.println("monday");
break;
default:
System.out.println("other day");
}
}}
Page 18Classification: Restricted
Covariant return type (Java 5)
• Covariant return, means that when one overrides a method, the return type of the overriding
method is allowed to be a subtype of the overridden method's return type.
class A{
A get(){return this;}
}
class B1 extends A{
B1 get(){return this;}
void message(){System.out.println("welcome to covariant return type");}
public static void main(String args[]){
new B1().get().message();
}
}
Page 19Classification: Restricted
Annotations (Java 5)
• Java Annotation is a tag that represents the metadata i.e. attached with class, interface,
methods or fields to indicate some additional information which can be used by java compiler
and JVM.
• Annotations in java are used to provide additional information, so it is an alternative option for
XML and java marker interfaces.
Examples:
• @Override: assures that the subclass method is overriding the parent class method. If it is not
so, compile time error occurs.
• @SuppressWarnings: is used to suppress warnings issued by the compiler.
• @Deprecated: annotation marks that this method is deprecated so compiler prints warning. It
informs user that it may be removed in the future versions. So, it is better not to use such
methods.
Page 20Classification: Restricted
Generics (Java 5)
• Before generics, we can store any type of objects in collection i.e. non-generic.
• Now generics, forces the Java programmer to store specific type of objects.
• Before Generics:
List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0); //typecasting
• After Generics:
List<String> list = new ArrayList<String>();
list.add("hello");
String s = list.get(0);
Page 21Classification: Restricted
Generics (Java 5): Advantages
• Type Casting not required
• Compile time checking.
List<String> list = new ArrayList<String>();
list.add("hello");
list.add(32); //Compile Time Error
Page 22Classification: Restricted
Generic Classes (Java 5): Example
class MyGen<T>{
T obj;
void add(T obj){this.obj=obj;}
T get(){return obj;}
}
class TestGenerics3{
public static void main(String args[]){
MyGen<Integer> m=new MyGen<Integer>();
m.add(2);
//m.add("vivek");//Compile time error
System.out.println(m.get());
}}
Page 23Classification: Restricted
Instrumentation (Java 6)
• We can access a class that is loaded by the Java classloader from the JVM
and modify its bytecode by inserting our custom code, all these done at
runtime.
• Mostly profilers, application monitoring agents, event loggers use Java
instrumentation.
• Not of direct use for writing web apps.
• http://javapapers.com/core-java/java-instrumentation/
Page 24Classification: Restricted
Binary literals (Java 7)
• To specify a binary literal, add the prefix 0b or 0B to the integral value.
• Can be used for byte, short, int or long.
byte b1 = 0b101; // Using b0, this b can be lower or upper case
short s1 = 0B101; // Using B0
System.out.println("----------Binary Literal in Byte----------------");
System.out.println("b1 = "+b1); //prints “5”
System.out.println(“s1 = "+s1); //prints “5”
Page 25Classification: Restricted
Underscores in numeric literals (Java 7): Increase readability
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;
Page 26Classification: Restricted
Underscores in numeric literals (Java 7): Increase readability
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
float pi2 = 3._1415F; // Invalid; cannot put underscores adjacent to a
decimal point
long ssn = 999_99_9999_L;// Invalid; cannot put underscores prior to an L
suffix
Page 27Classification: Restricted
String in switch statement (Java 7)
public class StringInSwitchStatementExample {
public static void main(String[] args) {
String game = "Cricket";
switch(game){
case "Hockey":
System.out.println("Let's play Hockey");
break;
case "Cricket":
System.out.println("Let's play Cricket");
break;
case "Football":
System.out.println("Let's play Football");
}
}
}
Switch also works with byte, short, int, char, Byte, Short, Integer,
Character, Enum and Strings
Page 28Classification: Restricted
String in switch statement
public class StringInSwitchStatementExample {
public static void main(String[] args) {
String game = "Card-Games";
switch(game){
case "Hockey": case"Cricket": case"Football":
System.out.println("This is a outdoor game");
break;
case "Chess": case"Card-Games": case"Puzzles": case"Indoor basketball":
System.out.println("This is a indoor game");
break;
default:
System.out.println("What game it is?");
}
}
}
Page 29Classification: Restricted
Catch Multiple Exceptions (Java 7)
public class MultipleExceptionExample{
public static void main(String args[]){
try{
int array[] = newint[10];
array[10] = 30/0;
}
catch(ArithmeticException | ArrayIndexOutOfBoundsException e){
System.out.println(e.getMessage());
}
}
}
Page 30Classification: Restricted
Catch Multiple Exceptions (Java 7): What is the output?
public class MultipleExceptionExample{
public static void main(String args[]){
try{
int array[] = newint[10];
array[10] = 30/0;
}
catch(Exception | ArithmeticException | ArrayIndexOutOfBoundsExcepti
on e){
System.out.println(e.getMessage());
}
}
}Compile time error: The exception ArithmeticException is
already caught by the alternative Exception
Page 31Classification: Restricted
Try with resources (Java 7)
• try-with-resources statement is a try statement that declares one or more
resources.
• The resource is as an object that must be closed after finishing the
program.
• The try-with-resources statement ensures that each resource is closed at
the end of the statement execution.
Page 32Classification: Restricted
Try with resources (Java 7)
import java.io.FileOutputStream;
public class TryWithResources {
public static void main(String args[]){
// Using try-with-resources
try(FileOutputStream fileOutputStream =newFileOutputStream("/abc.txt")){
String msg = "Welcome to javaTpoint!";
byte byteArray[] = msg.getBytes(); //converting string into byte array
fileOutputStream.write(byteArray);
System.out.println("Message written to file successfuly!");
}catch(Exception exception){
System.out.println(exception);
}
}
}
Page 33Classification: Restricted
Try with resources (Java 7)
• Can also use multiple resources
try( // Using multiple resources
FileOutputStream fileOutputStream =new FileOutputStream(“/xyz.txt");
InputStream input = new FileInputStream(“/abc.txt")) {
….
}catch(Exception exception){
System.out.println(exception);
}
Page 34Classification: Restricted
Topics to be covered in next session
• Hibernate
• Advantages of Hibernate
• Hibernate Architecture – High Level
• Hibernate – Detailed Architecture
• Hibernate Architecture – Important Levels
• Hibernate jar files
• Hibernate tools download
• CRUD Operations
• Create
• Read
• Update
• Delete
• Hibernate with Annotations
• Design Patterns in Java
Page 35Classification: Restricted
Thank you!

Session 38 - Core Java (New Features) - Part 1

  • 1.
    Java & JEETraining Session 38 – Core Java (New Features) with Examples
  • 2.
    Page 1Classification: Restricted Agenda •Core Java features with Examples • Assertions • Varargs • Static import • Autoboxing and Unboxing • Enum • Covariant • Annotations • Generics • Instrumentation • Catch Multiple Exceptions
  • 3.
    Page 2Classification: Restricted Whatwere the new features added to Core Java library? • Very important from interview perspective. • Most of the Core Java questions asked in interviews are relevant to the new features introduced in later versions of Java i.e. 4 and above.
  • 4.
    Page 3Classification: Restricted Javaversions… Code name culture dropped after Oracle took over 
  • 5.
    Page 4Classification: Restricted Newfeatures… J2SE 4 (JDK 1.4) • Assertions Java 6 • Instrumentation Java 7 • String in switch statement • Binary Literals • The try-with-resources • Catching Multiple Exceptions by single catch • Underscores in Numeric Literals Java 8 • Java 8 Date/Time API • Lambda Expressions • Method References • Functional Interfaces • Stream Collectors • Optional class • Nashorn JavaScript • And many more… JDK 1.5 or Java SE 5 • For-each loop • Varargs • Static Import • Autoboxing and Unboxing • Enum • Covariant Return Type • Annotation • Generics Tomorrow’s session
  • 6.
    Page 5Classification: Restricted Assertions(JDK 1.4) • Assertion is a statement in java. It can be used to test your assumptions about the program. • While executing assertion, it is believed to be true. If it fails, JVM will throw an error named AssertionError. It is mainly used for testing purpose. • Examples: assert age>=18; //without custom assert error message assert age>=18:”Age not valid”; //with custom assert error message • AssertionError is a subclass of java.lang.Error. • Not of any use in production. This is a development tool.
  • 7.
    Page 6Classification: Restricted For-EachLoop (JDK 1.5) – Arrays example class ForEachExample1{ public static void main(String args[]){ int arr[]={12,13,14,44}; for(int i:arr){ System.out.println(i); } } }
  • 8.
    Page 7Classification: Restricted For-EachLoop (JDK 1.5) – Collections example import java.util.*; class ForEachExample2{ public static void main(String args[]){ ArrayList<String> list=new ArrayList<String>(); list.add(“Pawan"); list.add(“Bill"); list.add(“George"); for(String s:list){ System.out.println(s); } } }
  • 9.
    Page 8Classification: Restricted Varargs(Java 5) • The varargs allows the method to accept zero or muliple arguments. • Before varargs either we use overloaded method or take an array as the method parameter but it was not considered good because it leads to the maintenance problem. • If we don't know how many argument we will have to pass in the method, varargs is the better approach.
  • 10.
    Page 9Classification: Restricted Varargs(Java 5) Example class VarargsExample{ static void display(String... values){ System.out.println("display method invoked "); for(String s:values){ System.out.println(s); } } public static void main(String args[]){ display();//zero argument display("my","name","is","varargs");//four arguments } }
  • 11.
    Page 10Classification: Restricted Staticimport (Java 5) • The static import feature of Java 5 facilitate the java programmer to access any static member of a class directly. • There is no need to qualify it by the class name. • Advantage is less coding required. But do not overuse and it will impact readability and maintainability of the code.
  • 12.
    Page 11Classification: Restricted Staticimport (Java 5) import static java.lang.System.*; class StaticImportExample{ public static void main(String args[]){ out.println("Hello"); //Now no need of System.out out.println("Java"); } }
  • 13.
    Page 12Classification: Restricted Staticimport (Java 5): How different from regular import? • Import => Access classes without package qualification. • Static import => Access static members without class qualification.
  • 14.
    Page 13Classification: Restricted Autoboxingand Unboxing (Java 5) • No need of conversion between primitives and Wrappers manually so less coding is required. class BoxingExample1{ public static void main(String args[]){ int a=50; Integer a2=new Integer(a);//Boxing Integer a3=5;//Boxing System.out.println(a2+" "+a3); } } class UnboxingExample1{ public static void main(String args[]){ Integer i=new Integer(50); int a=i; //Unboxing System.out.println(a); } }
  • 15.
    Page 14Classification: Restricted Enum(Java 5) • Enum in java is a data type that contains fixed set of constants. • E.g. (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY and SATURDAY) • E.g. (NORTH, SOUTH, EAST and WEST)
  • 16.
    Page 15Classification: Restricted Enum(Java 5) Example class EnumExample1{ public enum Season { WINTER, SPRING, SUMMER, FALL } public static void main(String[] args) { for (Season s : Season.values()){ //.values() returns array System.out.println(s); } } }
  • 17.
    Page 16Classification: Restricted Enum(Java 5) Example enum Season { WINTER, SPRING, SUMMER, FALL } class EnumExample2{ public static void main(String[] args) { Season s=Season.WINTER; System.out.println(s); }}
  • 18.
    Page 17Classification: Restricted Enum(Java 5) Example class EnumExample5{ enum Day{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY} public static void main(String args[]){ Day day=Day.MONDAY; switch(day){ case SUNDAY: System.out.println("sunday"); break; case MONDAY: System.out.println("monday"); break; default: System.out.println("other day"); } }}
  • 19.
    Page 18Classification: Restricted Covariantreturn type (Java 5) • Covariant return, means that when one overrides a method, the return type of the overriding method is allowed to be a subtype of the overridden method's return type. class A{ A get(){return this;} } class B1 extends A{ B1 get(){return this;} void message(){System.out.println("welcome to covariant return type");} public static void main(String args[]){ new B1().get().message(); } }
  • 20.
    Page 19Classification: Restricted Annotations(Java 5) • Java Annotation is a tag that represents the metadata i.e. attached with class, interface, methods or fields to indicate some additional information which can be used by java compiler and JVM. • Annotations in java are used to provide additional information, so it is an alternative option for XML and java marker interfaces. Examples: • @Override: assures that the subclass method is overriding the parent class method. If it is not so, compile time error occurs. • @SuppressWarnings: is used to suppress warnings issued by the compiler. • @Deprecated: annotation marks that this method is deprecated so compiler prints warning. It informs user that it may be removed in the future versions. So, it is better not to use such methods.
  • 21.
    Page 20Classification: Restricted Generics(Java 5) • Before generics, we can store any type of objects in collection i.e. non-generic. • Now generics, forces the Java programmer to store specific type of objects. • Before Generics: List list = new ArrayList(); list.add("hello"); String s = (String) list.get(0); //typecasting • After Generics: List<String> list = new ArrayList<String>(); list.add("hello"); String s = list.get(0);
  • 22.
    Page 21Classification: Restricted Generics(Java 5): Advantages • Type Casting not required • Compile time checking. List<String> list = new ArrayList<String>(); list.add("hello"); list.add(32); //Compile Time Error
  • 23.
    Page 22Classification: Restricted GenericClasses (Java 5): Example class MyGen<T>{ T obj; void add(T obj){this.obj=obj;} T get(){return obj;} } class TestGenerics3{ public static void main(String args[]){ MyGen<Integer> m=new MyGen<Integer>(); m.add(2); //m.add("vivek");//Compile time error System.out.println(m.get()); }}
  • 24.
    Page 23Classification: Restricted Instrumentation(Java 6) • We can access a class that is loaded by the Java classloader from the JVM and modify its bytecode by inserting our custom code, all these done at runtime. • Mostly profilers, application monitoring agents, event loggers use Java instrumentation. • Not of direct use for writing web apps. • http://javapapers.com/core-java/java-instrumentation/
  • 25.
    Page 24Classification: Restricted Binaryliterals (Java 7) • To specify a binary literal, add the prefix 0b or 0B to the integral value. • Can be used for byte, short, int or long. byte b1 = 0b101; // Using b0, this b can be lower or upper case short s1 = 0B101; // Using B0 System.out.println("----------Binary Literal in Byte----------------"); System.out.println("b1 = "+b1); //prints “5” System.out.println(“s1 = "+s1); //prints “5”
  • 26.
    Page 25Classification: Restricted Underscoresin numeric literals (Java 7): Increase readability 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;
  • 27.
    Page 26Classification: Restricted Underscoresin numeric literals (Java 7): Increase readability 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 float pi2 = 3._1415F; // Invalid; cannot put underscores adjacent to a decimal point long ssn = 999_99_9999_L;// Invalid; cannot put underscores prior to an L suffix
  • 28.
    Page 27Classification: Restricted Stringin switch statement (Java 7) public class StringInSwitchStatementExample { public static void main(String[] args) { String game = "Cricket"; switch(game){ case "Hockey": System.out.println("Let's play Hockey"); break; case "Cricket": System.out.println("Let's play Cricket"); break; case "Football": System.out.println("Let's play Football"); } } } Switch also works with byte, short, int, char, Byte, Short, Integer, Character, Enum and Strings
  • 29.
    Page 28Classification: Restricted Stringin switch statement public class StringInSwitchStatementExample { public static void main(String[] args) { String game = "Card-Games"; switch(game){ case "Hockey": case"Cricket": case"Football": System.out.println("This is a outdoor game"); break; case "Chess": case"Card-Games": case"Puzzles": case"Indoor basketball": System.out.println("This is a indoor game"); break; default: System.out.println("What game it is?"); } } }
  • 30.
    Page 29Classification: Restricted CatchMultiple Exceptions (Java 7) public class MultipleExceptionExample{ public static void main(String args[]){ try{ int array[] = newint[10]; array[10] = 30/0; } catch(ArithmeticException | ArrayIndexOutOfBoundsException e){ System.out.println(e.getMessage()); } } }
  • 31.
    Page 30Classification: Restricted CatchMultiple Exceptions (Java 7): What is the output? public class MultipleExceptionExample{ public static void main(String args[]){ try{ int array[] = newint[10]; array[10] = 30/0; } catch(Exception | ArithmeticException | ArrayIndexOutOfBoundsExcepti on e){ System.out.println(e.getMessage()); } } }Compile time error: The exception ArithmeticException is already caught by the alternative Exception
  • 32.
    Page 31Classification: Restricted Trywith resources (Java 7) • try-with-resources statement is a try statement that declares one or more resources. • The resource is as an object that must be closed after finishing the program. • The try-with-resources statement ensures that each resource is closed at the end of the statement execution.
  • 33.
    Page 32Classification: Restricted Trywith resources (Java 7) import java.io.FileOutputStream; public class TryWithResources { public static void main(String args[]){ // Using try-with-resources try(FileOutputStream fileOutputStream =newFileOutputStream("/abc.txt")){ String msg = "Welcome to javaTpoint!"; byte byteArray[] = msg.getBytes(); //converting string into byte array fileOutputStream.write(byteArray); System.out.println("Message written to file successfuly!"); }catch(Exception exception){ System.out.println(exception); } } }
  • 34.
    Page 33Classification: Restricted Trywith resources (Java 7) • Can also use multiple resources try( // Using multiple resources FileOutputStream fileOutputStream =new FileOutputStream(“/xyz.txt"); InputStream input = new FileInputStream(“/abc.txt")) { …. }catch(Exception exception){ System.out.println(exception); }
  • 35.
    Page 34Classification: Restricted Topicsto be covered in next session • Hibernate • Advantages of Hibernate • Hibernate Architecture – High Level • Hibernate – Detailed Architecture • Hibernate Architecture – Important Levels • Hibernate jar files • Hibernate tools download • CRUD Operations • Create • Read • Update • Delete • Hibernate with Annotations • Design Patterns in Java
  • 36.