What are the different ways to run Spring boot app ?
Spring Boot Introduction
What is Spring boot ?
What are Spring Boot features ?
What is the difference between Spring and Spring Boot
To know, Please watch below video.
Switch Enhancements in Java
- In this post, we are going to learn about recent enhancements to switch statement in Java.
- There are 4 enhancements to switch statement.
- List of case constants
- Switch expression
- yield statement
- case statement with arrow operator
List of case constants
Switch expression, yield statement:
- Switch expression is simply switch statement which can return a value.
- We can return a value using yield keyword. We can write above using switch expression and yield keyword as below.
- We must add semicolon at the end of switch expression. Because it is treated a statement.
- We no need to write break statement because yield returns value and exit from switch expression. If we write break statement, we get compiler error.
- Normally default is optional for switch. But default is mandatory for switch expression.
Case statement with arrow operator :
- We can use arrow operator after case statement in place of semicolon.
- Arrow operator case statement can be in below three forms.
- We can directly return value from case statement. We don't need to use yield keyword.
- We don't need to use break because we exit from switch after returning value from switch.
- We must write default statement.
- When we use block , we must yield keyword to return value from switch expression.
- We don't need to use break statement. default statement is mandatory.
var keyword in Java
- We declare local variables in a method with its data type.
- From Java 10 or higher version onwards , we can use var keyword to declare local variables in a method. Same variables can be declared with var keyword like below.
- Java compiler takes the variables type from it's initializer. 20 is integer value, so age data type is int.
- You can use var keyword to declare reference variables.
- You can use var to declare variable inside for loop, forEach loop.
Restrictions :
- You can't use var to declare array initializer .
- You can't use var to declare class level instance , static variables.
Conclusion:
Sealed classes and Interfaces in Java
- The above Test class is final . It means no other class can extend it.
- When we write a class in Java, any other class can extend. We can't add a condition to allow only some classes can extend our class.
- We can now leverage the sealed classes feature to define list of classes which can extend our class.
- We can declare sealed class with sealed keyword and We need specify list sub classes using permits keyword.
- Classes in permit clause must extend the sealed class otherwise we get compile time error.
- Classes which are not in permit clause try to extend Test class, we get compile time error.
- Sealed class's subclasses must be final or sealed or non-sealed.
- Test classes defined Test1, Test 2 as its direct sub classes.
- We have declared Test1 as non-sealed . It means any number of classes can extend Test1. We no need to use final, sealed , non-sealed keywords in Test1 subclasses declarations. These are not subclasses for Test class.
- We have declared Test2 as sealed. All sealed class rules are applicable here.
- We can't use non-sealed keyword for a class which doesn't extend any sealed class.
- Sealed classes and its sub classes must be in same module. if the sealed class is in unnamed module, its sub classes also should be in same unnamed module. Sub classes can be in different package.
Sealed Interfaces:
- Sealed interface rules are same like sealed classes.
- We use sealed keyword to declare sealed interface.
- We can specify list of classes which can implement sealed interface and list of interfaces which can extend sealed interface.
- Classes and interfaces which are in permits clause only must implement or extend sealed interface . Other classes and interfaces should not implement or extend the sealed interface.
- Implemented classes must be final or sealed or non-sealed.
- Sub Interfaces must be either sealed or non-sealed.
- A class can extend a sealed class and implement a sealed interface.
Conclusion:
This is all about sealed classes and interfaces . If you have any questions, please comment below. Happy Coding 😀.
Java Record
private int rollNumber;
private String name;
private String address;
public Student(int rollNumber, String name, String address) {
super();
this.rollNumber = rollNumber;
this.name = name;
this.address = address;
}
public int getRollNumber() {
return rollNumber;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
@Override
public int hashCode() {
return Objects.hash(address, name, rollNumber);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Student)) {
return false;
}
Student other = (Student) obj;
return Objects.equals(address, other.address) && Objects.equals(name, other.name)
&& rollNumber == other.rollNumber;
}
}
- Here We have created Student modal with three fields .
- It has a constructor to create Student object.
- It has getter methods to read student data.
- It also has overriden hashcode and equals methods to avoid duplicates.
- If you have multiple tables, You need to all this boiler plate code for all the modal classes.
- To avoid boiler plate code , We can use lombok library.
- We can rewrite the above Student modal class as below using lombok library.
- Instead of using lombok library, We can use Java record.
- Record is special class which is used to store read only data.
- We can create a record using record keyword.
- We can write the above Student modal class using record as below
- We must declare variables within record parenthesis. These are private and final by default.
- Java compiler automatically creates constructor , getter methods, toString, equals , hashCode methods for these variables.
- Java will not generate setter methods. Because record is immutable. Once we have created record object, we can't modify it's data.
- We can use record keyword as variable name also.
- We can create record object using new keyword.
public record Student(int rollNumber, String name, String address) {
}
public class Test {
public static void main(String[] args) {
List<Student> studentList = new ArrayList<>();
var student1 = new Student(1, "Hari", "Nellore");
var student2 = new Student(2, "krishna", "Chennai");
studentList.add(student1);
studentList.add(student2);
studentList.forEach(studentObj->{
System.out.println(studentObj.rollNumber()+" "+studentObj.name()+" "+studentObj.address());
});
} }
Output
1 Hari Nellore
2 krishna Chennai
- We can use generics with record.
- Static variables are allowed within record body. Instance variables are not allowed within record body.
- Both Static and instance methods are allowed to write inside record.
- Abstract method is not allowed.
- Normally Java compiler generated constructor is sufficient.
- We may need to implement our own constructor to write validation conditions. For example if the name is empty or null throw an IllegalArgumentException exception.
- We can implement constructor in two ways.
- Canonical constructor
- Non Canonical constructor
- We can write canonical constructor in two forms . one is full form, other one is compact form.
- Let's write canonical constructor in full form
- Here constructor parameters should match exactly as the variables defined in record definition . Variables type , name and order must be same.
- You can write same constructor using compact form as follows.
- We don't need to declare constructor parameters.
- We don't need to initialize the record variables.
- At end of constructor , constructor parameters are automatically assigned to corresponding record variable.
- This constructor is useful when we want to add default values for some fields while creating record object.
- We must call canonical constructor as first statement inside this constructor.
- Here we are using this keyword to call canonical constructor. Address field data is default Nellore for all record objects.
Text Blocks in Java
- Using text block feature , you don't have to use \n to create new line.
- It was added in java 15 version. To use this feature, you must use jdk 15 or higher version.
- You write a text block using three double quotes characters.
- You can write any number of lines text within pair of three double quotes characters.
- Import point note, you must start writing text in next line of starting three double quote characters.
- If you write in the same line of starting three double quote characters, you get compile time error.
- The ending three double quote characters, adds a new line after our text.
- If you don't want new line, you can write ending three double quote characters at the end of our text like below.
- You can also use double quotes within text block. You don't have to use \" escape sequence.
- You can use two new escape sequences in text blocks \s, \.
- \s adds space , \ indicates line continuation.
- If there are any white spaces before each line, they will be removed as per below rules.
- If every line has same number of white spaces , those all white spaces are removed from each line.
- If there are odd number of white spaces before each line , least of number of white spaces will be removed.
- The ending three double quotes also decides how many white spaces to be removed.
- If the ending three double quotes placed before text, white spaces till that """ characters will be removed.
- If the ending three double quotes placed after text, white spaces till first character of text will be removed.
Javascript ES12 / ES 2021 Features
Separator for numeric literals:
We can use underscore as a separator for numeric literals . It is good to use for amount. It improves readability.
Before :
After:
- You can use underscore with both integers, decimal values.
- You must use underscore only between digits. You get an error if you use it before or after digits.
- Below are valid declarations.
Logical assignment operators:
Logical Nullish assignment(??=):
Nullish coalescing operator returns right side value if left side value is either null or undefined.
Instanceof Enhancement
Before Java 16, To type cast from super class to sub class type, We first need to check with 'instanceof ' operator to know underlying object type to avoid exception.
Object stringObj = "Fullstack Adda";
if (stringObj instanceof String) {
String string = (String) stringObj;
System.out.println(string);
}
Output:
Fullstack Adda
The above code can be written as follows.
Object stringObj = "Fullstack Adda";
if (stringObj instanceof String string) {
System.out.println(string);
}
Output:
Fullstack Adda
This enhancement helps to reduce the code statements.
Happy Coding 😃
Day period support to time
To format 24 hours form time into 12 hours format, We can use letter "a" in the formatter. For time period from "00:00" hours to "11:59", it prints "AM".
LocalTime date1 = LocalTime.parse("00:00");
LocalTime date2 = LocalTime.parse("11:59");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm a");
String date1Str = formatter.format(date1);
String date2Str = formatter.format(date2);
System.out.println(date1Str);
System.out.println(date2Str);
Output :
12:00 AM
11:59 AM
Java 16 features - toList() method
Stream toList() method :
This is a new method added to the Stream interface in Java 16 version.
It converts the Stream into List.
Elements of List will be in the same order of Stream elements.
New List is immutable. If we try to add or remove elements to the List, it throws UnsupportedOperationException.
Before toList() method :
Stream<String> cities = Stream.of("Hyderabad", "Bangalore", "Chennai");
List<String> list = cities.collect(Collectors.toList());
list.forEach(System.out::println);
After toList() method :
Stream<String> cities = Stream.of("Hyderabad", "Bangalore", "Chennai");
List<String> list = cities.toList();
list.forEach(System.out::println);Please check out the full code in my github link.
If you prefer watching video, please watch below my youtube channel video on the same topic.
Happy Coding 😀
-
You have a Student data in the database . To return student data, you may write modal class as below. public class Student { private int ...
-
We declare local variables in a method with its data type. From Java 10 or higher version onwards , we can use var keyword to decl...
-
To format 24 hours form time into 12 hours format, We can use letter "a" in the formatter. For time period from "00:00" ...