0% found this document useful (0 votes)
4 views

2-Java 10-17 discussion

The document outlines new features introduced in Java 11 and subsequent versions, including type inference with the 'var' keyword, switch expressions, pattern matching for 'instanceof', text blocks, records, and sealed classes. It highlights the benefits of these features, such as reducing verbosity, improving code readability, and enhancing type safety. Additionally, it provides examples and explanations of how to implement these features in Java programming.

Uploaded by

Suresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

2-Java 10-17 discussion

The document outlines new features introduced in Java 11 and subsequent versions, including type inference with the 'var' keyword, switch expressions, pattern matching for 'instanceof', text blocks, records, and sealed classes. It highlights the benefits of these features, such as reducing verbosity, improving code readability, and enhancing type safety. Additionally, it provides examples and explanations of how to implement these features in Java programming.

Uploaded by

Suresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 7

Java 11 new features

-------------------
https://www.studytonight.com/java-11/java-11-string-new-methods

Java 10-17:
-------------
* Time-Based Release Versioning
* Local-Variable Type Inference (var)
* Switch Expressions
* Pattern Matching for instanceof
* Text Blocks , New Methods in String Class for Text Blocks
* Helpful NullPointerExceptions
* Records
* Sealed Classes
* Hidden Classes
* HTTP Client
* Project amber (java 12 onwards)
enum enhancement

Type interence:
--------------
var keyword, some important rules

What is type inference?


-----------------------
The ability to use type inference with local variables ( var )

It reduces the verbosity of the language without compromising Java's dependable


static
binding and type safety.

The compiler infers the type by using the information available in


the code, and adds it to the bytecode that it generates.

Type inference with var


-----------------------

The following lines of code show how local variable

String name = "Java Everywhere";


LocalDateTime dateTime = new LocalDateTime.now

var name = "Java Everywhere";


var dateTime = new LocalDateTime.now();

HashMap<Integer, String> map = new HashMap<Integer, String>();

var map = new HashMap<Integer, String>();


By replacing HashMap<Integer, String> with var , the preceding line of code is much
shorter
important point about var:
------------------------
1. Compulsory non-null initialization
2. var can be used with only local variable
3. Using var with primitive data types

var counter = 9_009_998_992_887; vs var counter = 9_009_998_992_887L;

Eg:
long population = 10L;
float weight = 79.8f;
double distance = 198654.77;
var total1 = cupsOfCoffee + population; // inferred type of total1 is long
var total2 = distance + population; // inferred type of total2 is double
var total3 = weight + population; // inferred type of total3 is float

Switch Expressions
-------------------
Preview in Java 12,13 and std in java 14
Multiple constraints per case
expression vs statement
yeilding a value
exhaustiveness cases

enum WeekDay {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
WeekDay day = WeekDay.TUESDAY;
switch (day) {
case MONDAY:
System.out.println("Let's meet!");
break;
case TUESDAY:
System.out.println("no meeting!");
break;
case WEDNESDAY:
System.out.println("Let's meet!");
break;
case THURSDAY:
System.out.println("no meeting!");
break;
case FRIDAY:
System.out.println("Let's meet!");
break;
case SATURDAY:
System.out.println("no meeting!");
break;
case SUNDAY:
System.out.println("Let's meet (although Sunday should be a free
day, man!)!");
break;
default:
System.out.println("Do I really need this?!");
break;
}

//imporvement 1: we dont need to repeat cases again and again


enum WeekDay {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
//
WeekDay day = WeekDay.MONDAY;
switch (day) {
case MONDAY, WEDNESDAY,FRIDAY:
System.out.println("Let's meet!");
break;
case TUESDAY,THURSDAY,SATURDAY:
System.out.println("no meeting!");
break;
case SUNDAY:
System.out.println("Let's meet (although Sunday should be a free
day, man!)!");
break;
}

//imporvement 2: we need to use -> in order not to write break


// enum WeekDay {
// MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
// }
// WeekDay day = WeekDay.MONDAY;
// switch (day) {
// case MONDAY, WEDNESDAY,FRIDAY ->
// System.out.println("Let's meet!");
// case TUESDAY,THURSDAY,SATURDAY ->
// System.out.println("no meeting!");
// case SUNDAY ->
// System.out.println("Let's meet (although Sunday should be a free
day, man!)!");
//
// }

//improvement 2 form : to ->


// enum WeekDay {
// MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
// }
//
// WeekDay day = WeekDay.MONDAY;
// switch (day) {
// case MONDAY, WEDNESDAY,FRIDAY ->
// System.out.println("Let's meet!");
// case TUESDAY,THURSDAY,SATURDAY ->
// System.out.println("no meeting!");
// case SUNDAY ->
// System.out.println("Let's meet (although Sunday should be a
free day, man!)!");
//
// }

//statement vs expression

// switch (){
//
// }
// String value=switch (){
//
// };

// enum WeekDay {
// MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
// }
//
// WeekDay day = WeekDay.SATURDAY;
// String message= switch (day) {
// case MONDAY, WEDNESDAY,FRIDAY ->{
// LocalDate localDate=LocalDate.now();
// yield "let meet "+localDate;
// }
//
// case TUESDAY,THURSDAY,SATURDAY ->{
// LocalDate localDate=LocalDate.of(2011, Month.JANUARY, 11);
// yield "no meeting! "+ localDate;
// }
// case SUNDAY -> "Let's meet (although Sunday should be a free day,
man!)!";
// };
// System.out.println(message);

//Note:
// int day=1;
// String message= switch (day){
// case 1,3,5 -> "lets meet";
// case 2,4,6 -> "no meeting";
// case 7->{
// yield "i told you no meeting! sleep";
// }
// default -> throw new IllegalArgumentException("day must be bw 1-7");
// };
//
// System.out.println(message);

Pattern Matching for instanceof


------------------------------
* gettting rid of typecasting
* preview in java 14
* variable scoping
* Exmaples

// Object data="i love java ...";


// if(data instanceof String){
// String dataString=(String) data;
// }

// Object data="i love java ...";


// if(data instanceof String dataString){
// System.out.println(dataString);
// }

// Object data="i love java ...";


// if(data instanceof String dataString && dataString.length()>10){
// System.out.println(dataString);
// }else {
// System.out.println("something else");
// }

//with not work for or operatoin


// Object data="i love java ...";
// if(data instanceof String dataString || dataString.length()>10){
// System.out.println(dataString);
// }else {
// System.out.println("something else");
// }
// Object book=new Book();
// if (book instanceof Book){
// Book b=(Book)book;
// }

Text Blocks , New Methods in String Class for Text Blocks


---------------------------------------------------------
* Preview in Java 13 and 14
* motivation better way to create long string
* text bblock syntex is very similer to template literal es 6

// ES6 `` ==> """" """"


String sql = """
SELECT id, firstName, lastName
FROM Employee
WHERE departmentId = "IT"
ORDER BY lastName, firstName""";

String html = """


<html>
<body>
<p>Hello World!</p>
</body>
</html>""";

System.out.println(sql);
System.out.println(html);

String sql2 = """


SELECT id, firstName, lastName
FROM Employee
WHERE departmentId = "IT"
ORDER BY lastName, firstName\
""";
System.out.println(sql2);
System.out.println("hello");

Records
---------
What are Java Records and How to Use them Alongside Constructors and Methods?
-------------------------------------------------------------------------------
Adv: less code more stuff

private String name;


private String email;
private double salary;

record is a special type of class declaration aimed at reducing the boilerplate


code.

can use as DTO, VO object

interface Employable{
public double getNetSalary();
}

record Person(String name,String email, double salary) implements Employable{


//compack ctr
public Person{
if (name==null || email==null){
throw new IllegalStateException();
}
}
public Person(String name,String email){
this(name, email, 0.0);
}

@Override
public double getNetSalary() {
return salary*0.7;
}
}

https://www.geeksforgeeks.org/what-are-java-records-and-how-to-use-them-alongside-
constructors-and-methods/

Sealed Classes
---------------

abstract class ------ sealed class ---------- final class

https://rollbar.com/blog/what-are-sealed-classes-in-java/#:~:text=A%20sealed
%20class%20is%20a,less%20prone%20to%20unintended%20extensions.

You might also like