Java 17 Recipes


Line 6: System.out.println(professor.length())


Download 3.2 Mb.
Pdf ko'rish
bet35/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   31   32   33   34   35   36   37   38   ...   245
Bog'liq
Java 17 Recipes

Line 6: System.out.println(professor.length());
Line 7: }
Line 8:}
The following is the output.
Exception in thread "main" java.lang.NullPointerException:
Cannot invoke "String.length()" because "professor" is null
at org.java17recipes.chapter02.recipe02_04.NullPointExample.
main(NullPointerExample.java:6)
 How It Works
In Java 14, the Java Virtual Machine describes exactly which variable is null. The 
exception message is on the line of the exception type: in a previous version, there is 
the lack of the sentence: “Cannot invoke “String.length()” because “professor” is null.” 
On the other hand, this enhancement can naturally create overhead to producing a 
stack trace. For more information on NullPointerException, see the documentation at 
https://openjdk.java.net/jeps/358
.
2-5. Pattern Matching for instanceof
 Problem
You want to simplify the conditional extraction of components from objects.
 Solution
Java 14 improves the function, making the cast simpler.
In the following example, the first lines represent the old version of the functionality.
public class InstanceOfExample {
public static void main (String[] args) {
Object selectedObject="I love Taranto";
Chapter 2 enhanCements from Java 9 through Java 17 


56
if (selectedObject instanceof String) {
String selectedString = (String) selectedObject;
System.out.println(selectedString.length());
}
if (selectedObject instanceof String selectedString) {
System.out.println(selectedString.length());
}
}
}
 How It Works
This enhancement was proposed in Java 14 and in production in Java 16 (JEP 394). It is a 
readable and concise form that improves pattern matching for the instanceof operator.
The new version improves the readability of the code, and it avoids repeating the 
type name more times and the probability of generating errors
For more information on pattern matching for the instanceof operator, see the 
documentation at 
https://openjdk.java.net/jeps/394
.

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   31   32   33   34   35   36   37   38   ...   245




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