var in java8

 We all know that java is a strongly typed language. From the past releases it has introduced many features to avoid boilerplate code and simplify the data types of the language.


So Guess what is it?

Let's learn about the Collections operations and var keyword introduced in java 10.

Collections operations

 Set<String> GFG = new HashSet<String>() {{
            add("griet");
            add("jntuh");
            add("osmania");
            add("cbit”);
      
        } };


Instead of using instance of collection to perform operations we can use double brace initialisation concept which reduces the boiler-plate code.

Var keyword:

var a=9;
var b=“hello world”;
var c=34.5;
var d=‘r’;






Rules:

1)The modifier datatypes can be default or final but not any other.
2)The initial value should be declared ignorer to know the datatype for the compiler.
3)It cannot be used as return value, method parameters and fields.
4)It cannot be null because the only null type is null itself and so it won’t be 
much useful.
============================


A new method called parallelSort() was added to Arrays class in Java 8.

Generally, we use Arrays.sort() to sort an array of objects. So, Let's understand the differences between sort() and parallelSort().

ParallelSort() utilises the multithreading approach to perform the operations and uses the parallel sort-merge sorting algorithm where as the sort() uses a quick sort algorithm.




OUTPUT


The Array was divided into sub arrays and the sub arrays were divided into their subarrays and so on. These sub arrays are sorted individually by multiple threads. It uses the ForkJoin pool to execute the parallel tasks and the sorted sub arrays are merged.

Even though we call parallel sort, parallelism will be only used when certain requirements like processor having more than one core are met, otherwise it uses the sequential Quicksort algorithm. 

Why ParallelSort() ? 

It offers considerably better performance for the very large data sets than the normal sort() method.


Fun Fact:
Do you know that comments are executable in Java?

We all know that comments tell what the code is supposed to accomplish. But we can also execute comments in java using a trick.



Guess the output?

A good guess would be 12, but if we run the above code, 9 will be printed. This is due to the presence of unicode character \u000d. Run the code and see the magic for yourself.



==============

oday, let's learn about a new class in java 8 that we may or may not have overlooked.

So which class that might be? Any guesses?


Java added a new final class in java.util package called StringJoiner. It is used to construct a sequence of characters separated by a delimiter. Although this can be done using StringBuilder but StringJoiner provides easy way to do that.

So first let’s have a look at a simple code which uses StringBuilder. 










Now let’s see how we can get the same output using StringJoiner.


The output:- 

So in this way we can use StringJoiner to produce same output as StringBuilder but by using less code.


==============================================================================


The Annotation mechanism enhanced in two ways in java 8.

1. You can repeat the annotations.
        2. You can annotate on Types.

1. Repeated Annotations ;

-> Older versions of java refuse to place same annotation type on the same declaration. 


Before Java 8 :

-> We can’t use same annotation on any element more than once, we have to wrap repeatable annotation in container annotation.  




Why do we need to use them ?
-> Prevents bugs at compile time.
        -> Improves your code readablity.
 
How do we make user-defined repeatable annotation ??

->There are two steps :

1. Define container annotation .


2. Mark your user defined annotation with @Repeatable annotation.


As a result , Any class can be annotated with multiple @Author annotation.



At compile time , @Author annotations still wrapped in a container annotation @Authors to ensure behavioral compatibility with legacy reflection methods.



2. Type Annotations :


-> Java 8 allows annotations to be used on types including new operator , generic type arguments, type casts, instanceof checks, implements and throws.

         Belo line of code marked with @NonNull annotation indicates that the variable name of type String can’t be null .


-> With new operator


    -> With generic type arguments






Did you know that Integer class in Java uses caching?

In Java , Integer class uses caching for a range of numbers .This feature was introduced in Java 1.5 version to improve the memory management.

Let us first have a look at a sample code which uses Integers . Can you guess the output of the following Java program?  


What we generally expect is to have both statements to print false. Now let's look at the above code snippet’s output




The answer is INTEGER CACHING!


What is Integer Caching ?

The Integer class keeps a cache of Integer instances in the range of -128 to +127. Whenever an Integer within this range is used , Integer class will return the same instance from its cache every time.


So in the code snippet, the primitive values are automatically converted into Integer class through auto-boxing. It is performed by Integer.valueOf( ) method in Integer class. The valueOf method will not create a new object if the integer falls under the caching range . 

In our code , when we are comparing integer1 and integer2, both the variables will be pointing to same memory location in cache and thus gives the output as true. In case of integer3 and integer4 comparison , the memory locations will be different because they are out of the caching range and thus it gives the output as false.



How to fix these bugs?

Integer caching might be useful in memory management but it can lead to serious bugs in application. When performing database validations or other validations , comparing the integer related data in this way will generate unexpected results. So when comparing the integer objects always use intValue( ) method on Integer objects. 

<Screenshot 2021-06-16 at 3.59.39 PM.png>


Now we got the correct output.  

<PastedGraphic-10.png>






Does Java supports Lazy evaluation?

<pastedGraphic.png>

Some Languages are born Lazy while others have to work hard to be Lazy. Java by birth is not Lazy. Let's understand this in details.

Let's understand the default nature of Java by an example. 

<Screenshot 2021-06-14 at 4.53.44 PM.png>

So it is observed from the output that the method expensive() is called even if it is not required.

Now the obvious question that will come in our mind, Can we make Java change its default nature and make it Lazy? 

Let’s check it.

There was a famous British scientist named David Wheeler, who used to say

“In Computer Science, we can solve any problem by introducing another level of indirection”

What is Indirection?

Indirection does not solve a problem directly, this in turn researches and solves a problem. It fundamentally changes our design and our way of thinking.

Implementation of Indirection in Java

In Java, Functional programming introduced a concept called Lambdas which transformed our way of writing conventional code. Lambdas are a level of indirection. It helps not to execute the operation now but defers it to a later time when required. Lambdas helps to make Java Lazy.

Now let’s practically understand how Lambdas make Java Lazy 

<Screenshot 2021-06-14 at 4.55.08 PM.png>



Comments