Lets understand difference between Dynamically Typed and Statically Typed Language.
|
Dynamically Typed
Language
|
Statically Typed
Language
|
|
Perform variable type
checking at runtime
|
perform variable type
checking at compile time
|
|
Not Mandatory
|
Need to
declare the data types of your variables before you use them
|
|
// Java example
int roleNumber; roleNumber = 5;
|
// Groovy example
roleNumber = 5
|
Dynamically typed language if not used properly it may lead to run to errors or exception due to type mismatch or typo.
Java 7 has introduced diamond operator and Lambda (Java 8) expression can infer variable types, see below example.
//Diamond Operator
List<String> nameList = new ArrayList<>();
//Lambda Expr
Function<String, String> convertLower= (s) -> s.toLowerCase();
Prior to Java 10, we used to declare variable like below
String name = "Knowledge cafe"
int age = 20;
double salary = 100.52;
List <String> nameList = new ArrayList<>();
From Java 10 on wards following declaration is compile time valid, When we initialize a local variable, we can replace the explicitly stated left-hand type with the newly introduced reversed-type name var instead.
PS: "var" is not defined as keyword so it can be used as variable name as well.
var name = "Knowledge cafe"
var age = 20;
var salary = 100.52;
var nameList = new ArrayList<String>();
var var = 200 ; // This is also allowed
(var name, var birthYear) -> name.getAge(birthYear); //Lambda Exp can be implicitly typed
Limitations
//When variable is not initialized like below
var price;
var id = null;
//Compound declaration is not allowed :
var fName = "Amit", lName="Himani" ;
//Array initialization :
var prices = {5,10.3, 11};
//Instance fields :
public var price;
//Method parameters:
public void setPrice (var price)
//Method return type :
public var getPrice()
Limitation with Lambda expression:
//We can't mix implicit and explicit declaration :
(String x, y) -> x.charAt(y)
//We can't mix var and non-var implicit declaration:
(var x, y) -> x.process(y)
//We can't mix var and non-var explicit declaration:
(var x, int y) -> x.process(y)
//We can't omit parenthesis for singly declared lambda:
var x -> x.toString() ; String x -> x.length()
Benefit of this syntax is code become more readable, see below example
//without type inference
List <VeryLongObjectNameWhichIsNotReadable> myList= new ArrayList<VeryLongObjectNameWhichIsNotReadable>();
//With Type Inference
var myList= new ArrayList<VeryLongObjectNameWhichIsNotReadable>();
So, In my Opinion Java is still statically typed language but with little flexibility in syntax for compile time local variable inference, which will help developers to write code faster and code become less verbose and more readable.