## Java logical operator short circuit with example

February 06, 2023

## Java logical operator short circuiting

In java we logical operator when we can use short circuit (&& ||)to not evaluate right hand side condition. Short circuiting is using double AND or double OR.
Logical OR and AND :- returns final verdict only after evaluating both expressions. Does not matter if first expression is true or false it will always evaluate the second expression. Short Circuit OR and AND:- if left hand side operand returns true, In case of OR => it will not evaluate second expression if first expression is true. In case of AND => it will not evaluate second expression if first expression is false.
Sample method to test logical and shortcircuit
``````private static boolean appleIsFruit() {
System.out.println("calling apple ");
return true;
}

private static boolean bananaIsFruit() {
System.out.println("calling banana ");
return true;
}

private static boolean cloudIsfruit() {
System.out.println("calling cloud ");
return false;
}
``````
Logical Operator
``````System.out.println("\n\napple | banana");
if (appleIsFruit() | bananaIsFruit()) {
System.out.println("inside apple | banana");
}

System.out.println("\n\ncloud & apple");
if (cloudIsfruit() & appleIsFruit()) {
System.out.println("inside cloud & apple");
}``````
Terminal
Console
```apple | banana
calling apple
calling banana
inside apple | banana

cloud & apple
calling cloud
calling apple ```
Above we can see even though the first method returned false (cloud & apple) the second method was still invoked.
Short circuit logical operation
``````System.out.println("apple || banana");
if (appleIsFruit() || bananaIsFruit()) {
System.out.println("inside apple || banana");
}

System.out.println("\n\ncloud && apple");
if (cloudIsfruit() && appleIsFruit()) {
System.out.println("inside cloud && apple");
}``````
Terminal
Short circuit
```apple || banana
calling apple
inside apple || banana

cloud && apple
calling cloud
```
In the short circuit case the second expression is not evaluated.

### Summary

Short circuiting logical operation can improve performance and efficiency of code. But we have to keep in mind the way short circuiting works.

## How to iterate Map in Java

February 06, 2023

## How to iterate Java Map

Java Map can be iterated various ways to go over all the key:value pairs
Create Map and add some values
``````Map<Integer, String> map = new HashMap<>();
map.put(1,"Argentina");
map.put(2,"France");
map.put(3,"Brazil");
map.put(4,"Germany");``````
Using EntrySet Iterator
``````//EntrySet Iterator
System.out.println("\nEntrySet foreach");
Iterator<Entry<Integer, String>> it = map.entrySet().iterator();
while(it.hasNext()) {
Map.Entry<Integer, String> keyVal = it.next();
System.out.println(keyVal.getKey() + " " + keyVal.getValue());
}``````
Using EntrySet and foreach
``````//EntrySet and foreach
System.out.println("\nEntrySet foreach");
Set<Entry<Integer, String>> entrySet = map.entrySet();
entrySet.forEach((e-> { System.out.println(e.getKey() + " " + e.getValue());}));``````
Using Keyset Iterator
``````//Keyset Iterator
System.out.println("\nKeyset Iterator");
Iterator<Integer> kit = map.keySet().iterator();
while(kit.hasNext()) {
Integer key = kit.next();
System.out.println(key + " " + map.get(key));
}``````
Keyset For loop
``````//Keyset For loop
System.out.println("\nKeyset For loop");
for (Integer key : map.keySet()) {
System.out.println(key + " " + map.get(key));
}``````
Using Java 8 Lambda
``````//map foreach (Java 8 Lambda)
System.out.println("\nUsing Map.foreach (Java 8 Lambda");
map.forEach((key,value)-> {System.out.println(key + " " + value);});``````

### Summary

Here I have covered 5 different ways to iterate over Java Map and access both key and values.

February 06, 2023

## When to use LinkedHashMap.removeEldestEntry method

removeEldestEntry method exists only on subclasses of LinkedHashMap
removeEldestEntry always invoked after an element is inserted. Based on what this method returns following action will happen if method returns true based on some condition, then the oldest entry will be removed. if method always returns true then basically list will be empty. if method return false, then nothing will be deleted and map will behave like any other LinkedHashMap. after every put or putAll insertion, the eldest element will be removed, no matter what. The JavaDoc shows a very sensible example on how to use it:
Lets see an example of removeEldestEntry.
MapRemoveEntry Example
``````import java.util.LinkedHashMap;
import java.util.Map;

public class MapRemoveEntry {

public static void main(String argv[]) {

private static final long serialVersionUID = 1L;

protected boolean removeEldestEntry(Map.Entry<Integer,String> eldest) {
return size() > 4;
}
};;

map.put(0, "A");
map.put(1, "B");
map.put(2, "C");
map.put(3, "D");
map.put(4, "E");

map.forEach((k,v) -> { System.out.println("key = " + k + " value = " + v);});
}
}
``````
If we run the above example we will get following output.
Terminal
Console
```key = 1 value = B
key = 2 value = C
key = 3 value = D
key = 4 value = E
```
Reason is, method removeEldestEntry returns true when the map size is >4. That means when the map size is greater than 4 => the oldest entry will be removed. In this case oldest is the very first entry with (key=0, value=A).

### Summary

Using removeEldestEntry we can control when to remove the most oldest entry from the map. This can be used for creating a cache.

## How to create sealed classes in Java

February 03, 2023

## About sealed classes and interfaces

Starting Java 17 we can now allow additional class modifiers like sealed, non-sealed etc. A sealed class or interface can be extended or implemented only by those classes and interfaces permitted to do so.
Earlier we had only two options, allow subclasses to inherit the parent class or interface or not at all. In the later case using Final class modifier. Using sealed we can take a more controlled middle path where the Parent Class or Interface can dictate the Sub classes which can inherit from the Class.
Following are the keywords related to sealed classes. sealed : only permitted classes can extend a sealed class/interface permits: used along with sealed and mentions the names of the child classes. non-sealed: if we want a specific class (inherited from a sealed class) to be inheritable we can open it up by marking it non-sealed.

## Defining sealed class

Let's define a sealed class Tesla with 3 known subclasses that it can have.

### sealed Tesla

Tesla
``````package java17.sealed;

public abstract sealed class Tesla permits Model3, ModelS, TeslaSUV{
public abstract Integer maxRange();
public String basePrice() {
return "25000 USD";
}
}

``````
Now start implementing the subclasses possible. We implement Model3 and mark it final which will make the inheritance chance closed at this level.
Model3
``````//Subclass 1
public final class Model3 extends Tesla {
@Override
public Integer maxRange() {
return 200;
}
}
``````
ModelS
``````
//Subclass 2
public final class ModelS extends Tesla {
@Override
public Integer maxRange() {
return 400;
}
}
``````
In this third case we want the TeslaSUV to be extendable so that it can be extended. That's why we will mark it with non-sealed.
TeslaSUV
``````//Subclass3 (non-sealed)
public non-sealed class TeslaSUV extends Tesla {
@Override
public Integer maxRange() {
// TODO Auto-generated method stub
return null;
}
}
``````

### Style Two: Using member classes

We can also directly implement possible child classes that we want to allow as member classes without using permit. In the following example we are creating a sealed class BMWCars and three member classes.
BMWCars
``````package java17.sealed;

public sealed class BMWCars {

public final class BMW3 extends BMWCars implements ElectricVehicle{

}

public final class BMWI extends BMWCars implements Vehicle {

}

public non-sealed class BMWJV extends BMWCars implements Vehicle {

}

}
``````

### Rules for Defining Sealed Classes or Interfaces

Both Class and Interface can be marked with sealed. Inherited child classes can be marked with either final, sealed and non-sealed. Every permitted subclass must directly extend the sealed class. A permitted subclass may be non-sealed so that it is open for extension by unknown subclasses.

## Summary

With introduction of sealed classes we can define the known subclasses of an abstract class. In other words now we can enforce extension of classes that is known in compile time. It allows us to have greater control of class proliferation and improve security.

## Java record in details with example

February 03, 2023

## Java record in details with example

With Java 14 we have a new way to represent data intensive objects with less boilerplate codes.
Consider the following object representing Address and containing 5 fields. Address:{ street: city: zip: state: country: }
``````package Java14;

public record AddressRecord(String street, String city, Integer zip, String state, String country) {

}
``````
We can instantiate AddressRecord record instance by passing the parameter values. Also system will generate the getter methods. The JVM will generate the getter methods for us. like, street() city() zip() state() country()
``````package Java14;

public static void main (String arg[]) {

}
}
``````
Record can be very useful when we want to write DTO objects which is to carry or represent information. Following are some of the properties/rules that record have.
Rules for record
• record can have Constructor.
• record can have only static fields.
• record cannot have instance field.
• record can implement Interfaces.
• We cannot extends record since implicitly it is final.

## How to check if a Java object is final

February 03, 2023

## How to check if a Java object is final

final modifier can be applied at class level. If a Class is marked final it cannot be extended.
Sample final Class
``````
final class MyCustomClass {

}``````

### Using java.lang.reflect.Modifier

Using java.lang.reflect.Modifier,, We can check if a class is final though java.lang.reflect.Modifier.isFinal() method. MyCustomClass.class.getModifiers() will provide an integer number representing the class modifier. For example for the above class it prints 16. Now the value returned from the getModifiers() can be decoded with method Modifier.isFinal();
JavaReflectionModifiers
``````import java.lang.reflect.Modifier;

public class JavaReflectionModifiers {

public static void main(String[] args) {

//prints 16
System.out.println(MyCustomClass.class.getModifiers());

//returns true
Modifier.isFinal(MyCustomClass.class.getModifiers());

}

}

final class MyCustomClass {

}``````

### More Examples

Examples
``````package Java14;

import java.lang.reflect.Modifier;

public class JavaReflectionModifiers {

public static void main(String[] args) {

System.out.println(MyCustomClass.class.getModifiers());

//prints true
System.out.println(Modifier.isFinal(MyCustomClass.class.getModifiers()));

//prints true
System.out.println(Modifier.isFinal(String.class.getModifiers()));

//prints false
System.out.println(Modifier.isFinal(Number.class.getModifiers()));

}

}

final class MyCustomClass {

}``````

## Can we extend Java record

February 03, 2023

## Can Java record be extended?

Java record introduced in java 14. It provides a way to reduce boiler plate code while defining data classes. record is final implicitly and cannot be extended.
For example in the following record MobilePhone, we cannot extend it.
record MobilePhone
``````record MobilePhone(String brand, String modelName, Number osVersion, boolean canFlip) {

}``````
Java records are implicitly final it can be confirmed by the following code. Which checks if the java.lang.Class for the object have final modifier or not.
RecordFinalTest
``````package Java14;

import java.lang.reflect.Modifier;

public class RecordFinalTest {

public static void main(String[] args) {

MobilePhone phone1 = new MobilePhone("Samsung", "Galaxy1", 1, false);

//false
System.out.println(Modifier.isFinal(phone1.getClass().getModifiers()));

//false
System.out.println(Modifier.isFinal(MobilePhone.class.getModifiers()));

}

}
``````
For more details about record in Java please check the following references.

January 30, 2023

## How to create double linked list in Java

In Double Linked List we have each node pointing to the previous and next node. Here we will see how to create a custom Double Linked List in java.
Some properties of linked list is that, it has a node that can contain some value and then each node is linked to next node and also previous node. That's why we can traverse the linked list sequentially given we know the starting (head) node or last (tail) node.
``````class MyLinkedList<E> {

/* first points to head of the list */
public Node<E> first = null;

/* last points to tail of the list */
public Node<E> last = null;

/**
* Add item to tail (end) of the List
*
* @param item
* @return
*/
Node<E> newNode = new Node<E>(last, item, null);

if (last == null) {
// last points to the new node created
first = newNode;
} else {
last.next = newNode;
}
// update last so that it points to the new node
last = newNode;
return true;
}

static class Node<E> {
public E value;
public Node<E> next;
public Node<E> prev;

Node(Node<E> prev, E element, Node<E> next) {
this.value = element;
this.next = next;
this.prev = prev;
}
}

}``````
In the above implementation we have defined the main class MyLinkedList and inside it we defined a generic static class Node. Each Node object can hold a value and has links to previous (prev) and next nodes.
``````//create instance

Print the content of the node
``````//Get the first node (head node) and then print it by traversing all nodes
while (node != null) {
System.out.println("Content of Node: " + node.value);
node = node.next;
}``````
Terminal
Output
```Content of Node: 1
Content of Node: 2
Content of Node: 3
Content of Node: 4
Content of Node: 5```

January 29, 2023

## Syntax Highlighting on Webpage including Blogger.com

Syntax Highlighting on Webpage including Blogger.com
Prism is a lightweight syntax highlighter, very easy to use and works very well.

## Prism Source

Like most Java scripts prism can be downloaded and used in any web application or it can also be served from CDN Networks. Some of the CDN Networks are as follows as of writing. https://www.jsdelivr.com/package/npm/prismjs https://cdnjs.com/libraries/prism https://unpkg.com/browse/prismjs@1.29.0/

Include JS and CSS for Prism in the Head section of page
``````<head>
<script src="https://cdn.jsdelivr.net/npm/prismjs@1.29.0/prism.min.js"></script>
``````

### Use respective language css class in page

Example for language java.
``````<pre>
<code class="language-java">
Java Code here
</code>
</pre>``````

### Example with Java Script

Example for language javascript.
``````<pre>
<code class="language-javascript">
Javascript Code here
</code>
</pre>``````
Basically for the supported language we need to use respective css class (language-LANGUAGE}, for instance in above case we used language-java and language-javascript as css class. Prism support a lot of different languages, the full list can be found in the official prism site.

January 29, 2023

## About sealed classes and interfaces

Starting Java 17 we can now allow additional class modifiers like sealed, non-sealed etc. A sealed class or interface can be extended or implemented only by those classes and interfaces permitted to do so. Following are the keywords related to sealed classes.
New Keywords
Earlier we had only two options, allow subclasses to inherit the parent class or interface or not at all. In the later case using Final class modifier. Using sealed we can take a more controlled middle path where the Parent Class or Interface can dictate the Sub classes which can inherit from the Class.

## Defining sealed class (Two Styles)

### Style One: Using permit keyword

using the class modifiers sealed and permits we can create sealed classes. In the example bellow we are Defining abstract sealed class Tesla which permits three known subclasses Model3, ModelS and TeslaSUV.
Tesla
``````package java17.sealed;

public abstract sealed class Tesla permits Model3, ModelS, TeslaSUV{
public abstract Integer maxRange();
public String basePrice() {
return "25000 USD";
}
}

//Subclass 1
public final class Model3 extends Tesla {
@Override
public Integer maxRange() {
return 200;
}
}

//Subclass 2
public final class ModelS extends Tesla {
@Override
public Integer maxRange() {
return 400;
}
}

//Subclass3 (non-sealed)
public non-sealed class TeslaSUV extends Tesla {
@Override
public Integer maxRange() {
// TODO Auto-generated method stub
return null;
}
}

``````

### Style Two: Using member classes

In the following example we are creating a sealed class BMWCars and three member classes.
BMWCars
``````package java17.sealed;

public sealed class BMWCars {

public final class BMW3 extends BMWCars implements ElectricVehicle{

}

public final class BMWI extends BMWCars implements Vehicle {

}

public non-sealed class BMWJV extends BMWCars implements Vehicle {

}

}
``````

### Rules for Defining Sealed Classes or Interfaces

Both Class and Interface can be marked with sealed. Inherited child classes can be marked with either final, sealed and non-sealed. Every permitted subclass must directly extend the sealed class. A permitted subclass may be non-sealed so that it is open for extension by unknown subclasses.

## Summary

With introduction of sealed classes we can define the known subclasses of an abstract class. In other words now we can enforce extension of classes that is known in compile time. It allows us to have greater control of class proliferation and improve security.

## How to install Maven Manually on macOS Monterey

January 21, 2023

This article shows how to install Maven (3.6.3) on macOS Monterey(version 12.2.1) with M1 processor.

### Install Maven

Terminal
tar -xvzf apache-maven-4.0.0-alpha-3-bin.tar.gz
```x apache-maven-4.0.0-alpha-3/bin/mvn.cmd
x apache-maven-4.0.0-alpha-3/bin/mvn
x apache-maven-4.0.0-alpha-3/NOTICE
x apache-maven-4.0.0-alpha-3/lib/
```
It will create a folder apache-maven-4.0.0-alpha-3 which will contain unzipped contains from the downloaded file. Now Move the folder apache-maven-4.0.0-alpha-3 to final destination. In my case i moved to a folder DevRuntime which contains other runtimes for my development.
~/.zshenv
export MAVEN_HOME=~/DevRuntime/apache-maven-4.0.0-alpha-3 export PATH=\$PATH:\$MAVEN_HOME/bin
Now source the zshenv file
Terminal
source ~/.zshenv

### Install Maven

Now Check that Maven is working

Terminal
mvn --verison
```Apache Maven 4.0.0-alpha-3 (2ccf57baa5191468f9911fe85fd99672ac3bacb9)
Maven home: /Users/SiddB/DevRuntime/apache-maven-4.0.0-alpha-3
Java version: 18.0.1.1, vendor: Oracle Corporation, runtime: /Library/Java/JavaVirtualMachines/jdk-18.0.1.1.jdk/Contents/Home
Default locale: en_US, platform encoding: UTF-8
OS name: "mac os x", version: "12.2.1", arch: "aarch64", family: "mac"
```