Java 17 Recipes


CHAPTER 2 Enhancements from Java 9


Download 3.2 Mb.
Pdf ko'rish
bet32/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   28   29   30   31   32   33   34   35   ...   245
Bog'liq
Java 17 Recipes

CHAPTER 2
Enhancements from Java 9
Through Java 17
Since Java 9, newer versions of Java follow every six months, but this is a long-term 
support (LTS). It receives support for at least eight years and surely until the next LTS 
version in 2023. Each release of the JDK brings new enhancements and capabilities 
to the Java platform. Since the last version of this book, many enhancements have 
occurred. This book includes several recipes covering the new features from Java 9 to 
Java 17. Each release also carries backward compatibility with previous releases. This 
chapter showcases a few of the top enhancements to whet your appetite. By no means is 
this chapter a complete listing of all Java enhancements. Rather, it is a jump start to get 
you going on some of the hot new features of Java up to the last version.
2-1. Introduction to the var Keyword
 Problem
You want to use a keyword detecting the data type of a variable based on the surrounding 
context.
 Solution
Use the local variable type inference introduced in Java 10. Listing 
2-1
is an example.
Listing 2-1. Declarations Local Variable Type Inference Package
org.java17recipes.chapter01.recipe02_01;
public class KeywordVar {
public static void main (String[] args) {


50
var num = 1;
var city = "Taranto";
System.out.println(num);
System.out.println(city);
}
}
Now you should see the following output.
1
Taranto
 How It Works
Prior to Java 10, you declared in the following way.
String city = "Taranto";
Next, you can declare the following.
var city = "Taranto"
It allows programmers to declare the type of the local variable instead of the actual 
type and increases code readability. The compiler decides the type based on the value 
assigned to the variable. In Java 11, the usage of var uniform was extended to lambda 
parameters, as explained in Chapter 
6
.
The local variable type inference cannot be used as a global variable. In fact, if you 
use the following, the IDE raises a compilation error.
// instance variable
var x = 50;
public static void main(String[] args)
{
System.out.println(x);
}
The output is an error.
'var' is not allowed here
Chapter 2 enhanCements from Java 9 through Java 17 


51
For more information on the var keyword, see the documentation at
http://openjdk.java.net/jeps/286
.
Note the Jep–JDK enhancement proposal collects proposals for enhancements 
to the JDK and allows openJDK to develop more informally changes. It does not 
replace JCp, however, which is required to approve changes in Java apI.

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   28   29   30   31   32   33   34   35   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling