Showing posts with label full stack adda. Show all posts
Showing posts with label full stack adda. Show all posts

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.

    1. List of case constants
    2. Switch expression
    3. yield statement
    4. case statement with arrow operator    

List of case constants

  • If we want execute same block of code for some switch case constants , we write like below.


Output:





  • The above example can be re-written using list of constants like below.

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.
    case "JAN" :
    can be written as below.
    case "JAN" ->
  • Arrow operator case statement can be in below three forms.
        case "JAN" -> expression;
        case "JAN" -> { block of statements}
        case "JAN" -> throw exception;
  • Let's look at few examples using arrow operator .


  • 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.

Conclusion:

These enhancements are really good addition to Java programming language. It optimizes the code. Thanks for reading . Happy Coding 😀.




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.

 

  • You can use var keyword as variable name also.








Restrictions :

  • You can't use var to declare a variable without initializing it. You can't use with null variables.
    










  • You can't use var to declare multiple variables in single declaration.
    




  • You can't use var to declare array initializer .
    




  • You can't use var to declare class level instance , static variables.










  • You can't use var keyword to declare method parameters.






  • You can't use var as method return type.










Conclusion:

var keyword is good addition to Java programming language. It shortens the variables declaration. This is all for today. Happy Coding 😀




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 feature is useful to define definite level of inheritance for our classes and interfaces. When our developing rest services , We can use this feature for interface to specify what all classes can implement it. It is mainly useful when we are developing some library or framework.


This is all about sealed classes and interfaces . If you have any questions, please comment below. Happy Coding 😀.


Java Record


You have a Student data in the database . To return student data, you may write modal class as below. 
public class Student {
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.
 import lombok.Data;
@Data
public class Student {
private int rollNumber;
private String name;
private String address;
}

  • 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.  
Syntax
record recordName(variables declaration) {
//optional body
}
  

 

  • We can write the above Student modal class using record as below
public record Student(int rollNumber, String name, String address) {
}

  • 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


  • Here getter methods are not prefixed by get word. They are same as variable name. 
  • To test equals, hashcode methods implementation , let's add Student objects to HashSet collection object. 

  • 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. 

 
 
How to write our own constructor in record:

  • 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.
  1. Canonical constructor
  2. Non Canonical constructor

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. 
Non Canonical constructor

  • 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. 
I hope you have learned something new today. Thanks for reading . Please share it with your friends. Happy Coding 😀. Jai Hind !!




Text Blocks in Java


If you want to write multi line string in java , you must \n escape sequence which inserts new line. 
For example
public class Test {

public static void main(String[] args) {
String addressWithOutTextBlock = "H.No. 1234\n" + "Hitec city\n" + "Madhapur\n" + "Hyderabad - 500081";
System.out.println("Address WithOut TextBlock");
System.out.println(addressWithOutTextBlock);

}
}
Output:
Address WithOut TextBlock
H.No. 1234
Hitec city
Madhapur
Hyderabad - 500081

  • 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.

public class Test {

public static void main(String[] args) {
String addressWithTextBlock = """
H.No. 1234
Hitec city
Madhapur
Hyderabad - 500081
""";
System.out.println("Address With TextBlock");
System.out.println(addressWithTextBlock);
}

}
Output:
Address With TextBlock
H.No. 1234
Hitec city
Madhapur
Hyderabad - 500081

  • 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.
String addressWithTextBlock = """
H.No. 1234
Hitec city
Madhapur
Hyderabad - 500081""";
  • You can also use double quotes within text block. You don't have to use \" escape sequence.
String addressWithTextBlock = """
H.No. 1234
"Hitec city"
Madhapur
Hyderabad - 500081""";
Output:
H.No. 1234
"Hitec city"
Madhapur
Hyderabad - 500081
  • You can use two new escape sequences in text blocks \s, \. 
  • \s adds space , \ indicates line continuation. 
String addressWithTextBlock = """
H.No.\s1234
Hitec city \
Madhapur
Hyderabad - 500081""";
Output:
H.No. 1234
Hitec city Madhapur
Hyderabad - 500081
  • 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.
String addressWithTextBlock = """
 H.No.1234
 Hitec city 
 Madhapur
 Hyderabad - 500081
""";
Output:
H.No.1234
Hitec city
Madhapur
Hyderabad - 500081
  • If there are odd number of white spaces before each line , least of number of white spaces will be removed. 
String addressWithTextBlock = """
   H.No.1234
     Hitec city 
       Madhapur
  Hyderabad - 500081
""";
Output:
 H.No.1234
   Hitec city
     Madhapur
Hyderabad - 500081
  • 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.
String addressWithTextBlock = """
 H.No.1234
 Hitec city 
 Madhapur
 Hyderabad - 500081
""";
Output:
H.No.1234
Hitec city
Madhapur
Hyderabad - 500081
String addressWithTextBlock = """
      H.No.1234
      Hitec city 
      Madhapur
      Hyderabad - 500081
  """;
Output:
    H.No.1234
    Hitec city
    Madhapur
    Hyderabad - 500081

I hope you have learned something new .  Thanks for reading. If you have questions, please leave a comment below. You can watch same content video in my youtube channel Full Stack Adda .  
Happy Coding 😀. Jai Hind.



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 :


let amount = 100000;

After:


let amount = 1_00_000;
let price = 5_678.97


  • 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.


let amount1 = 10_000;
let amount2 = 5_876.98;

Below are invalid declarations 


let amount1 = _1000;
let amount2 = 1000_;
let amount3 = 1000_.56;


You get below error . 






Logical assignment operators: 

Logical Nullish assignment(??=):

Nullish coalescing operator returns right side value if left side value is either null or undefined.


let fullName;
let fName = fullName??='Narayana Bojja';
console.log(fName);


Output:
Narayana Bojja

Here fullName variable doesn't have any data . It's value is undefined . So, It assigns right side value to fName variable.

let fullName='Bojja Narayana';
let fName = fullName??='Narayana Bojja';
console.log(fName);

Output:
Bojja Narayana

Here fullName variable has data . It assigns same data to fName variable. This operator useful if you want to make sure variable has some data.

Logical And Assignment (&&=):

It evaluates from left to right . It assigns value only if left side expression is true.

let x = 10;
let y = 20;
x &&= y;
console.log(x);

Output: 20
Here x has value . It will be evaluated as true. It assigns y value to x.

let x ;
let y = 20;
x &&= y;
console.log(x);

Output: undefined

Here x doesn't have value . It will be evaluated as false. It doesn't assign y value to x. This operator useful if you want to re assign variable with some data.

Logical OR Assignment (||=):

It works opposite to Logical And operator. If left side expression is false, it assigns right side value. 

let x ;
let y = 20;
x ||= y;
console.log(x);

Output : 20

Here x doesn't have value . It will be evaluated as false. It  assigns y value to x.


let x = 10;
let y = 20;
x ||= y;
console.log(x);

Output: 10
Here x has value . It will be evaluated as true. It doesn't assigns y value to x. This operator useful if you want to assign variable with some data in order to avoid any error.

String replaceAll method:

At present , there is replace method which replaces only first occurrence of  a string with another string.

let fullName = "narayana narayana narayana"
fullName = fullName.replace('narayana', 'kavitha');
console.log(fullName);

Output:
kavitha narayana narayana

To replace all occurrences , we need to use regular expression.

let fullName = "narayana narayana narayana"
fullName = fullName.replace(/narayana/g, 'kavitha');
console.log(fullName);

Output:
kavitha kavitha kavitha

We can now use replaceAll method to replace all occurrences of a string with another string.

let fullName = "narayana narayana narayana"
fullName = fullName.replaceAll('narayana', 'kavitha');
console.log(fullName);

Output:
 kavitha kavitha kavitha

I hope you have learned something new today. Please feel free to leave a comment below. Happy Coding 😃
If you would like to watch the same content, please watch below video of my YouTube channel Full Stack Adda






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

In Java 16 , a new literal "B" (or BBBB or BBBBB) is added. It describes the time in human readable way.  It prints as follows.
00:00 - midnight
00:01 to 05:59 - at night
06:00 to 11:59 - in the morning
12:00 to 17:59 - in the afternoon
18:00 to  20:59 - in the evening
21:00 to 23:59 - at night

 LocalTime date1 = LocalTime.parse("00:00");
 LocalTime date2 = LocalTime.parse("05:10");
 LocalTime date3 = LocalTime.parse("08:10");
 LocalTime date4 = LocalTime.parse("13:59");
 LocalTime date5 = LocalTime.parse("18:10");
 LocalTime date6 = LocalTime.parse("22:59");
 DateTimeFormatter formatter =                                                       DateTimeFormatter.ofPattern("hh:mm B");
 String date1Str = formatter.format(date1);
 String date2Str = formatter.format(date2);
 String date3Str = formatter.format(date3);
 String date4Str = formatter.format(date4);
 String date5Str = formatter.format(date5);
 String date6Str = formatter.format(date6);
 System.out.println(date1Str);
 System.out.println(date2Str);
 System.out.println(date3Str);
 System.out.println(date4Str);
 System.out.println(date5Str);
 System.out.println(date6Str);

Output:
12:00 midnight
05:10 at night
08:10 in the morning
01:59 in the afternoon
06:10 in the evening
10:59 at night

Please let me know your opinion in the comments below. 
Happy Coding 😀

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 😀


Different ways to run Spring boot App

 What are the different ways to run Spring boot app ?