Prabhu Sunderaraman

Fullstack Engineer, Programmer, Writer, Trainer

prabhu.bits@gmail.com,     GitHub     Youtube     LinkedIn
  • Home
  • Profile
  • Books
  • Reading List
Browsing: / Home
Shortlink

Lockdown Learning – Day #4 – Sealed Interfaces in Java

By Prabhu Sunderaraman on March 29, 2020 in Java, Java 8

Let’s continue with our lessons during this corona lockdown. In the last three posts we discussed textblocks, instanceof and record types in Java 13 and 14.

  • record
  • improved instanceof
  • text blocks

In this post, let’s talk about a proposed feature, sealed interfaces

In languages like C#, sealed types are equivalent to final classes in Java. The problem with final classes in Java is no other class present in any other library can extend it. It’s tightly packed.
Now, Java is about to introduce a new sealed keyword, for creating sealed interfaces. We can create sealed interfaces and specify the types that can implement the interfaces. So sealed interfaces unlike final types, specify restricted implementations.

sealed interface Animal permits Dog, Cat {}
class Dog implements Animal {}
class Cat implements Animal {}
class Ant implement Animal {} //ERROR

In the code above, Animal is a sealed interface and only Dog and Cat classes can implement it. Ant will not be allowed to implement. So naturally even an anonymous/lambda implementation of Animal is also not possible.
Therefore the compiler as well as the JVM enforce the implementation of sealed types.

Share this on: Mixx Delicious Digg Facebook Twitter
Shortlink

Lockdown Learning – Day #3 – Java 14 – record (data class or tuple)

By Prabhu Sunderaraman on March 27, 2020 in Java, Java 8

Let’s continue with our lessons during this corona lockdown. In the last two posts we discussed textblocks and instanceof in Java 13 and 14.

  • improved instanceof
  • text blocks

In this post, we’ll discuss a very cool feature introduced in Java 14, record.

Say, you have a shopping cart that is a collection of ShoppingItem with id, name, price and quantity members. Building this will involve writing so many lines of code as shown below.

class ShoppingItem {
   private int id;	
   private String name;
   private double price;
   private int quantity;
	
   public ShoppingItem(int id, String name, double price, int quantity) {
	this.id = id;
	this.name = name;
	this.price = price;
	this.quantity = quantity;
   }
	
   public int getId() {
	return id;
   }
   public void setId(int id) {
	this.id = id;
   }
   public String getName() {
	return name;
   }
   public void setName(String name) {
	this.name = name;
   }
   public double getPrice() {
	return price;
   }
   public void setPrice(double price) {
	this.price = price;
   }
   public int getQuantity() {
	return quantity;
   }
   public void setQuantity(int quantity) {
	this.quantity = quantity;
   }
	
   public int hashCode() {
	return id;
   }
	
   public boolean equals(Object obj) {
	if(obj instanceof ShoppingItem item) {
		return item.id == this.id;
	}
	return false;
   }
   
   public String toString() {
	return name;
   }
}

public class RecordsExample {
   public static void main(String[] args) {
	ShoppingItem book = new ShoppingItem(21321, "Programming Java", 12.34, 1);
	ShoppingItem mobile = new ShoppingItem(21233, "iPhone 11 pro", 999, 1);
	List<ShoppingItem> cart = Arrays.asList(book, mobile);
	cart.forEach(System.out::println);
   }
}

Phew! That’s lot of code for just storing some data

Code-Monkey-Computing-Readability Image source: https://blog.submain.com/evaluate-code-readability/


Enter record

ShoppingItem class can be replaced with just one line code using a record. If you define a class as record with the members, the hashCode(), equals(), toString(), getters/setters are automatically generated for you by the compiler. So the code using record is as shown below.

public class RecordsExample {
   record ShoppingItem(int id, String name, double price, int quantity) {}
   public static void main(String[] args) {
	ShoppingItem book = new ShoppingItem(21321, "Programming Java", 12.34, 1);
	ShoppingItem mobile = new ShoppingItem(21233, "iPhone 11 pro", 999, 1);
	List<ShoppingItem> cart = Arrays.asList(book, mobile);
	cart.forEach(System.out::println);
  }
}

This one line
record ShoppingItem(int id, String name, double price, int quantity) {}
does the trick

Record in Java, in short is a data class or a tuple that’s a simple data structure.

Please remember to compile using –enable-preview and –release 14 switches

Share this on: Mixx Delicious Digg Facebook Twitter
Shortlink

Lockdown Learning – Day #2 – Java 14 – Improved instanceOf (Pattern matching)

By Prabhu Sunderaraman on March 26, 2020 in Java, Java 8

Last post we saw multiline strings in Java 13.

Let’s continue with a new topic; improved version of instanceOf operator introduced in Java 14.

Let’s look at the use of instanceOf keyword in checking for the type of an object during runtime.

class Vehicle {}
	
class Car extends Vehicle {
  public void drive() {
	System.out.println("Driving car");
  }
}

class Bicycle extends Vehicle {
  public void ride() {}
}

public class InstanceOfKeyword {
  public static void main(String[] args) {
	Vehicle vObj = new Car();
	if(vObj instanceof Car) {
	   Car car = (Car) vObj;
	   car.drive();
	}
       else if(vObj instanceOf Bicycle) {
          Bicycle bike = (Bicycle)vObj;
          bike.ride();
       }
  }
}

What’s frustrating with the above code is the type-cast of the vehicle object to Car or Bicycle after identifying it’s type using instanceof!

Java 14 changes that, by imparting some pattern matching power to instanceOf like this

       Vehicle vObj = new Car();
       if(vObj instanceof Car car) {
	  car.drive();
       }
       else if(vObj instanceOf Bicycle bike) {
          bike.ride();
       }

In the new version, instanceOf tests for the type and binds to a variable of the type. In our case car and bike variables are automatically bound to the corresponding Car and Bicycle objects respectively, eliminating the need to type-cast. Cool. Isn’t it?
The scope of the variables are limited to the if-else blocks

Share this on: Mixx Delicious Digg Facebook Twitter
Shortlink

Lockdown Learning – Day #1 – Java 13 – Text blocks (Multiline String)

By Prabhu Sunderaraman on March 25, 2020 in Java

Multi-line strings in Java are finally here in the form of Text blocks. It’s available as a preview feature. So you need to use the switches ––enable-preview and ––release 13 or –release 14 while compiling and executing this code.

public class TextBlocks  {
     public static void main(String[] args) {
	String message = """
	     Corona Alert!!!
				
	     Lockdown for 21 days!
	     Stay calm!	
	""";	
	
        System.out.println(message);
    }
}

Compile it using

javac ––enable-preview ––release 13 TextBlocks.java

And when you run it java –enable-preview TextBlocks, you get the following output with the formatting preserved. The compiler also works towards removing trailing whitespaces and meaningless indentations.

Screen Shot 2020-03-25 at 11.07.45 PM

Share this on: Mixx Delicious Digg Facebook Twitter
Shortlink

switch-case is more expressive in Java 12 & above

By Prabhu Sunderaraman on September 25, 2019 in Java, Java 8

One of the features that I am really excited about is pattern matching in Java. Pattern matching is a powerful feature in languages like Scala and Kotlin. You have an input token that’s matched against patterns.
switch-case statement comes close, yet very far, to pattern matching in Java. But starting Java 12 you’ve switch-case available as expressions and not statements, that enables us harness the power of pattern matching.

Here’s an example of using switch-case statement before Java 12.

Before

public class PatternMatching  {
	public static void main(String[] args) {
		int number = 12;
		int mod = number % 2;
		String result = null;
		switch(mod) {
			case 1:
				result = "Odd";
				break;
			case 0:
				result = "Even";
				break;
			default:
				result = "Huh";
		};
		System.out.println(result);
	}
}

And an example that uses switch-case expressions in Java 12.

After

public class PatternMatching  {
	public static void main(String[] args) {
		int number = 12;
		int mod = number % 2;
		
		String result = switch(mod) {
			case 0 -> "Even";
			case 1 -> "Odd";
			default -> "Huh";
		};
		System.out.println(result);
	}
}

You can compile& run PatternMatching.java by enabling preview mode like this.
javac --enable-preview --release 12 PatternMatching.java
java --enable-preview PatternMatching

You can watch the video here.




Share this on: Mixx Delicious Digg Facebook Twitter
« Previous 1 … 9 10 11 … 64 Next »

Youtube Channel




Categories

  • JavaScript (48)
    • RequireJS (5)
  • Go (44)
  • Golang (44)
  • Ext JS (23)
  • Spring (22)
  • Mobile (21)
  • Scala (20)
    • Play (3)
  • Uncategorized (19)
  • Video Sessions (18)
  • GoG (17)
  • Sencha Touch (16)
  • jQuery (14)
  • Languages (13)
  • Java 8 (12)
  • React JS (11)
  • Kotlin (11)
  • HealthyCodeMagazine (9)
  • Video (9)
  • Objective-C (8)
  • NoSQL (8)
  • Android (7)
  • MongoDB (7)
  • GWT (6)
  • Tools (6)
  • HTML 5 (5)
  • Cloud (5)
  • General (5)
  • Micro services (5)
  • Java (5)
  • Books (4)
  • AWS (4)
  • Software Architecture (4)
  • .NET (3)
  • Elixir (3)
  • Docker (3)
  • Reactive (3)
  • NodeJS (2)
  • RoR (2)
  • Backbone (1)
  • AngularJS (1)

Archives

  • 2020 (49)
  • 2019 (7)
  • 2018 (34)
  • 2017 (15)
  • 2016 (7)
  • 2015 (18)
  • 2014 (31)
  • 2013 (55)
  • 2012 (100)

Search

Subscribe




Copyright © 2025 Prabhu Sunderaraman.

Powered by WordPress and News.