java 1.4 feature
Assertions
- Used to check assumptions to guarantee the application always executes complying specifications
- Used as a debugging tool during dev and testing
- Added in 1.4
- Assertions ensure "correctness" of application as per business rules where as Exception Handling ensures "Robustness"
- Also known as "Pre-contracting"
- Syntax
- assert condition;
Eg: assert value == 5;
- assert condition : message;
Eg: assert (value == 5) : "Value should be 5";
To enable asserstions
java -enableassertions AssertionExample
or
java -ea AssertionExample
To disable asserstions
java -da AssertionExample
or
java -disableassertions AssertionExample
Note: Assertions are by default disabled.
Java5 features
Autoboxing
- Converting primitive to its respective wrapper class object is
called autoboxing.
Eg:
int i = 98;
Integer obj = i;//Autoboxing
Integer obj = new Integer(i);//Before java5.
Unboxing
- Converting wrapper class object its respective primitive value
is called unboxing.
Eg:
Integer obj = 98;
int i = obj.intValue();//Before java5
int i = obj;//unboxing.
Note: If the Integer object is NULL and if we apply unboxing
then we will get NPE at runtime.
Static imports
- Static members of a class can be imported into another class
by using static imports
Eg:
import static com.xyz.Utility.m1;
import static com.xyz.Utility.bankName;
Note: Here above import statements will imports static members
"m1" and "bankName".
Note: If we want to import all the static members of a class
at a time then import with *
Eg:
import static com.xyz.Utility.*;
Covariant Return type
- An overridden method in a sub class can have return type of as
same as return type of super class method or sub-class type of
super class method return type. This is is called covariant
return types.
Eg:
class A{
}
class B extends A{
}
class Super{
public A getA(){};
}
class Sub extends Super{
public B getA(){};
}
Note: here overridden method getA() in class "Sub" can have
return type as B because the B is sub type of A.
Formatted output
- There is a method format() is added to PrintStream to produce
formatted output like in 'C'
Eg:
System.out.format("I value = %d and F value = %f",i,f);
Varargs( Variable arguments)
- By using var-args we can pass 0 or more paramters to a method.
- All these parameters are going to bind to a single arugment
of a method
Eg:
public int add(int i, int ...j){
}
1. Here "j" is variable arument in the add method. It will
accept 0 or more integers.
2. var-args should be prefixed with 3 dots i.e. "..."
3. var-args must be the last argument in a method
3. Only one var-arg is allowed for a method.
For each loop/ Enhanced for loop
- By using for each or ehanced for loop we can iterate through the
array of elements or collections of elements with out using
loop counter or iterator.
Eg:
String arr[] = {"abc","xyz","hello","lakven"};
for(String value : arr){
System.out.println("value == "+value);
}
ArrayList<String> al = new ArrayList<String>();
al.add("RAm");
al.add("Amod");
al.add("Yogesh");
al.add("Visu");
for(String value : al){
System.out.println("value == "+value);
}
StringBuilder
- The behavior of this class is same as StringBuffer
- All methods in this class are NOT synchronized where as in
StringBuffer methods are synchronized.
- This class object is not thread-safe.
Scanner
- This class is used read the specific data types for an
input Stream.
Enums
- enums are used to specify list of constants
- In C programming enums are String representation of int constants.
- In java enums are public static final object of enum type
- Java enums are sub classes of java.lang.Enum
- methods, variables, constructors can be added in the enum
- enums can be declared inside or outside of class but not
with in any method
- enums by default final
- if declared inside class they are static
- enum objects can not be created explicitly as new keyword
is not available
ENUM rules
- enum constructor has to be private
- enums can not be private, protected and abstract
- enums are implicitly public, static, final.
- The order of appearance of enum constants is
called their NATURAL ORDERING.
- Advantages of enums
Typesafe
Namespace
Brittleness
Printed values are Informative
Generics
- Generics provides abstraction over Types
- Generics makes type safe code possible
- Generics provides increased readability
Eg:
public class Box<T>{
T value;
public void put(T value){
this.value = value;
}
public T get(){
return value;
}
}
public static void main(String[] args) {
Box<Integer> b = new Box<Integer>();
b.put(56);//IF we add other than interger value
// then the compiler is going to give
// the compilation error.
}
Note: Collection framework classes uses the generics concept
extensively.
Note: Collections are NOT generics.
- Generic Types
- The Diamond Operator(<>)
- Type Parameter Naming Conventions
The most commonly used type parameter names are:
E - Element (used extensively by the
Java Collections Framework)
K - Key
N - Number
T - Type
V - Value
S,U,V etc. - 2nd, 3rd, 4th types
- Generic Methods and Constructors
- Generics and Sub-typing
(ArrayList<Object> ao = new ArrayList<Integer>();//Illegal
- Bounded Type Parameters (x extends Y)
- Wildcards(?)
- Type Erasure
Annotations
- Annotations provide data about a program that is not part of
the program itself.
- They have no direct effect on the operation of the code they annotate.
- Annotations can be applied to a program's declarations of classes, fields, methods, and other program elements.
- The annotation appears first, often (by convention) on its own line, and may include elements with named or unnamed values:
@Author(
name = "Benjamin Franklin",
date = "3/27/2003"
)
class MyClass() { }
or
@SuppressWarnings(value = "unchecked")
void myMethod() { }
If there is just one element named "value," then the name may be omitted, as in:
@SuppressWarnings("unchecked")
void myMethod() { }
Also, if an annotation has no elements, the parentheses may be omitted, as in:
@Override
void mySuperMethod() { }
- Annotations have a number of uses, among them:
Information for the compiler
- Annotations can be used by the compiler to detect errors or suppress
warnings.
Eg: @SuppressWarnings("unchecked"), @Override and @Deprecated
Compiler-time and deployment-time processing
- Software tools can process annotation information to generate java code, XML files, and so forth.
Runtime processing
- Some annotations are available to be examined at runtime
1. Binary Literals
int i = 0B1111;
2. Strings in switch Statements
String str = new String("abc1");
switch (str) {
case "abc":
System.out.println("abc block");
break;
case "xyz":
System.out.println("xyz block");
break;
default:
System.out.println("Deafult block");
break;
}
3.Catching Multiple Exception Types
try{
}catch (NullPointerException | ArithmeticException |
NumberFormatException | ClassCastException |
ClassNotFoundException e) {
}
4. Underscores in Numeric Literals
int i = 1_000_000_000;
5.The try-with autoclosing resources Statement
try(FileInputStream fis = new FileInputStream("abc.txt");
FileInputStream fis2 = new FileInputStream("abc2.txt");) {
} catch (Exception e) {
e.printStackTrace();
}
6. Type Inference for Generic Instance Creation
List<Integer> list = new ArrayList<>();