Thursday, July 29, 2021

Angular @ViewChild Decorator With Examples

@ViewChild decorator in Angular is used if you want to access any directive, child component or DOM element in the Component class.

Using @ViewChild decorator you can configure a view query, that is done by passing a selector with @ViewChild. For example

@ViewChild('membershipForm') memberForm

Here ‘membershipForm’ is the passed selector.

The change detector looks for the first element or the directive matching the selector in the view DOM and assigns it to the property decorated with @ViewChild.

View queries and ngAfterViewInit callback

View queries are set before the ngAfterViewInit callback is called. That means ngAfterViewInit callback is the best place to manipulate the element or directive by using the reference variable.

ViewChild Metadata Properties

You can pass the following three metadata properties with @ViewChild decorator.

  • selector- The directive type or the name that has to be queried.
  • read- Used to read a different token from the queried elements.
  • static- True to resolve query results before change detection runs, false to resolve after change detection. Defaults to false.

read and static properties are optional.

Friday, July 23, 2021

Angular @HostBinding Decorator With Examples

@HostBinding decorator in Angular is used to mark a DOM property of the host element as a binding property. Angular automatically checks host property bindings during change detection, and if a binding changes it updates the host element of the directive. This decorator is quite useful when creating a custom directive as you can bind a property of the host element to a field in your custom directive. By changing the field in the custom directive you can manipulate the host element of the directive.

There is one option that you can pass with the @ HostBinding decorator-

  • hostPropertyName- The DOM property that is bound to a data property.

Monday, July 19, 2021

Java Exception Handling Tutorial

Exception Handling in Java provides a way to handle a situation when an exception is thrown by showing a meaningful message to the user and continue (or terminate) with the flow of the program.

How Java exception handling works

When an exceptional condition occurs with in a method, the method (where the exception occurred) creates an Exception Object and throws it. The created exception object contains information about the error, its type and the state of the program when the error occurred.

The method where the exception is thrown may handle that exception itself or pass it on. In case it passes it on, run time system goes through the method hierarchy that had been called to get to the current method to search for a method that can handle the exception.

If your program is not able to catch any particular exception, that will ultimately be processed by the default handler. The default handler displays a message describing the exception, prints a stack trace from the point at which the exception occurred, and terminates the program.

Type Casting in Java With Conversion Examples

Type casting in Java is used to cast one type (primitive or object) to another type. Whenever you try to assign data of one type to variable of another type, type conversion happens in Java.

Type conversion in Java may be classified into following scenarios.

Out of these four; widening primitive type conversions and widening reference type conversions happen automatically and type casting is not required. Type casting in Java is required in the case of narrowing primitive type conversions and narrowing reference conversions.

Widening primitive conversions

If destination type (type to which you are converting) is larger than the source type, you are widening the type of your source type. This type conversion will happen with out problem and automatically i.e. type casting is not required in this case.

As example-

int i = 10;
float f = i; // Assigning int to float

i which is an int can safely be assigned to float variable as float is compatible with int and also wider than int.

Widening reference conversions

Same way you can have a widening reference conversion. That is applicable in an inheritance scenario where a parent-child relationship exists.

For example if there is a parent class A and a child class B that extends class A then reference type A can safely hold reference type of class B.

A a;
B b = new B();
a = b; // Widening conversion from sub type to super type

Type casting in Java

Though automatic conversion is convenient and helpful, it may not always be possible. Especially in case of narrowing conversions. Again, narrowing conversion can be of two types-

  • Narrowing primitive conversions
  • Narrowing reference conversions

Narrowing primitive conversions

As the name suggests if you try to fit a value into a source that is narrower than the original type of the value then it is a narrowing conversion.

As example– If we do the exact opposite of what we did in the example of widening conversion and try to assign a float value to an int.

int i;
float f = 19.6f;
i = f; // Compile-time error (Type mismatch: cannot convert from float to int)

As you see, you get a compile-time error if you try to assign a float value to an int as it is a narrowing conversion. In case of narrowing conversion you need to explicitly type cast it to make it work.

General form of type casting in Java

(type) value;

Here type is the type to which the value has to be converted.

So in the above example we have to add an explicit cast to int.

Java type casting example

int i;
float f = 19.6f;
i = (int)f;
System.out.println("value " + i); 

Output

value 19

Here you can see that the fractional part is truncated.

Narrowing reference conversions

A super type can hold reference to an object of itself or the sub-types. But doing the opposite, when you want a conversion from super-type to sub-type, you will need type casting.

Since the conversion is from super-type to sub-type it is called narrowing reference conversion.

One important thing to always remember is; an object can only be type cast to its own class or one of its super-type, if you try to cast to any other object you may either get a compile-time error or a class-cast exception (run-time).

Narrowing reference conversion example

If we take the same example as used in widening reference conversion where there is a class A and a child class B that extends class A then reference type A can safely hold reference type of class B. But now we’ll try the opposite too.

A a;
B b = new B()
a = b; // OK widening conversion
b = a; // Compile-time error as it is a narrowing conversion

What you need to do to avoid compile-time error is-

b = (B) a;

Why type casting in Java required

You may have a scenario where child class has methods of its own apart from inheriting methods from the super class or overriding methods of the super class.

Being a good programmer and always trying to achieve polymorphism you will make sure that the reference of the sub-class is held by the super-class object. But one problem is, then you can’t call those methods which are exclusive to sub-class.

In order to call those methods you need casting to the type. Let’s try to understand it with an example.

Type casting Java example code

Here I have a class hierarchy where Payment is an interface and there are two classes CashPayment and CardPayment implementing the Payment interface.

Payment interface

public interface Payment {
 public boolean proceessPayment(double amount);
}

CashPayment class

import org.netjs.examples.interfaces.Payment;

public class CashPayment implements Payment {
 @Override
 public boolean proceessPayment(double amount) {
  System.out.println("Cash payment done for Rs. " + amount);
  return true;
 }
}

CardPayment class

import org.netjs.examples.interfaces.Payment;

public class CardPayment implements Payment {

 @Override
 public boolean proceessPayment(double amount) {
  System.out.println("Card Payment done for Rs. " + amount);
  return true;
 }
 
 public void printSlip(){
  System.out.println("Printing slip for payment" );
 }
}

In CardPayment class, note that, there is an extra method printSlip() which is exclusive to this class. Now when you do some payments using the class as given below-

import org.netjs.examples.interfaces.Payment;

public class PaymentDemo {
 public static void main(String[] args) {
  PaymentDemo pd = new PaymentDemo();
  Payment payment = new CashPayment();
  pd.doPayment(payment, 100);
  payment = new CardPayment();
  pd.doPayment(payment, 300);
  //int i = 10;
  //float f = i;
  
  int i;
  float f = 19.6f;
  i = (int)f;
  System.out.println("value " + i);
 }
 
 public void doPayment(Payment pd, int amt){
  pd.proceessPayment(amt);
  pd.printSlip();
 }
}

This method call pd.printSlip(); gives following compile-time error as the Payment object has no idea of the printSlip() method, thus the error-

The method printSlip() is undefined for the type Payment

If you want to call printSlip() method you need a cast back to CardPayment class type. Beware that there are two child classes and you don’t need that casting for CashPayment class object. Which means you need to use instanceof operator in conjunction with the casting.

With these corrections the code will now look like-

import org.netjs.examples.interfaces.Payment;

public class PaymentDemo {

 public static void main(String[] args) {
  PaymentDemo pd = new PaymentDemo();
  Payment payment = new CashPayment();
  pd.doPayment(payment, 100);
  payment = new CardPayment();
  pd.doPayment(payment, 300);
  //int i = 10;
  //float f = i;
  
  int i;
  float f = 19.6f;
  i = (int)f;
  System.out.println("value " + i);
 }
 
 public void doPayment(Payment pd, int amt){
  pd.proceessPayment(amt);
  
  if (pd instanceof CardPayment){
   CardPayment cardPay = (CardPayment)pd;
   cardPay.printSlip();
  }
 }
}

Output

Cash payment done for Rs. 100.0
Card Payment done for Rs. 300.0
Printing slip for payment
value 19

Here you can see how instanceof operator is used to make sure that the object is indeed of type CardPayment and then casting is done to the CardPayment type, which makes it possible to call the printSlip() method.

Reference: https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html

That's all for this topic Type Casting in Java With Conversion Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Switch Case Statement in Java With Examples
  2. Access modifiers in Java
  3. Java pass by value or pass by reference
  4. Array in Java With Examples
  5. Java Exception Handling Tutorial

You may also like-

  1. Abstraction in Java
  2. Object Creation Using new Operator in Java
  3. static Import in Java With Examples
  4. Java Collections Interview Questions And Answers
  5. Java Multithreading Interview Questions And Answers
  6. Java Concurrency Interview Questions And Answers
  7. How HashMap Works Internally in Java
  8. Race Condition in Java Multi-Threading

Sunday, July 18, 2021

Difference Between sleep And wait in Java Multi-Threading

Difference between sleep() and wait() methods in Java is a popular Java multi-threading interview question. It is another confusing question just like Difference between yield and sleep because functionality wise both sleep() and wait() look quite similar.

When sleep method is called with a specified time, currently executing thread goes in a TIMED_WAITING state.

Same way when wait method is called on an object the thread currently holding the lock on that object goes in a waiting state (or TIMED_WAITING state depending upon which of the three wait methods is being called).

Since both sleep() and wait() methods when called put the currently executing thread in a waiting state then what exactly is the difference between sleep() and wait() methods in Java, that's what we'll try to find here.

sleep() Vs wait() methods in Java multi-threading

  1. The very first difference is that sleep() is defined as a static method in Thread class and operates on the currently executing thread.
    Whereas wait() method is in Object class and operates on the thread which is currently holding the lock on the object on which the wait method is called.
  2. Since wait method is supposed to release the lock on an object so it has to be called from a synchronized context (with in a synchronized method or synchronized block). Not calling wait() method from a synchronized context will result in a IllegalMonitorStateException being thrown.
    With sleep method there is no such mandatory condition. It doesn't need to be called from a synchronized context.
  3. wait() method releases the lock it holds on an object before going to waiting state which gives another thread a chance to enter the synchronized block.
    sleep() method, if called from a synchronized block or method, will not release the lock so another thread won't get a chance to enter the synchronized block.
  4. When wait() method is called upon an object the thread which is currently holding the lock on that object goes to waiting state and it changes state to runnable only when the notify() or notifyAll() method is called by some thread on the same object.

    There are overloaded wait() methods too

       public final void wait(long timeout) throws InterruptedException
       
    And
      public final void wait(long timeout, int nanos) throws InterruptedException
    

    which causes the current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.

    In case of sleep() method thread changes state to runnable after the specified time is elapsed. As example Thread.sleep(4000); will make the currently executing thread to sleep for 4 seconds and thread is ready to run again when the specified time has elapsed . This sleep period can be terminated by interrupts.

Example of thread interrupt method

public class InterruptDemo extends Thread {
	@Override
	public void run(){  
		try {
			Thread.sleep(4000);
		} catch (InterruptedException Iexp) {
			System.out.println("Thread Interrupted exception "+ Iexp); 
		}
		 
		System.out.println("thread after interruption...");  
	}  
	public static void main(String[] args) {        
		InterruptDemo thread1 = new InterruptDemo();
		thread1.start();
		thread1.interrupt();
	}
}

Output

Thread Interrupted exception java.lang.InterruptedException: sleep interrupted
thread after interruption...

That's all for this topic Difference Between sleep And wait in Java Multi-Threading. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. isAlive() & join() Methods in Java Multi-Threading
  2. Why wait(), notify() And notifyAll() Methods Are in Object Class And Not in Thread Class
  3. What if run() Method Called Directly Instead of start() Method - Java Multi-Threading
  4. Deadlock in Java Multi-Threading
  5. Java Multithreading Interview Questions And Answers

You may also like-

  1. Polymorphism in Java
  2. How HashMap Internally Works in Java
  3. Lock Striping in Java Concurrency
  4. Difference Between CountDownLatch And CyclicBarrier in Java
  5. How to Convert Date And Time Between Different Time-Zones in Java
  6. How to Create Immutable Class in Java
  7. Difference Between throw And throws in Java
  8. How to Inject Prototype Scoped Bean in Singleton Bean

Saturday, July 17, 2021

static Method Overloading or Overriding in Java

Can we overload static Method in Java and can we override static method in Java are important Java interview questions, in this tutorial we'll try to understand whether that is possible or not. To set the context for understanding static method overloading and static method overriding in Java, first let's have a little introduction of what is overloading and what is overriding.

  • Method Overloading- When two or more methods with in the same class or with in the parent-child relationship classes have the same name, but the parameters are different in types or number the methods are said to be overloaded.
    Refer Method overloading in Java for better understanding.
  • Method Overriding- In a parent-child relation between classes, if a method in subclass has the same signature as the parent class method then the method is said to be overridden by the subclass and this process is called method overriding.
    Refer Method overriding in Java for better understanding.

Static method overloading in Java

Static methods in Java can be overloaded just as 'instance methods'. So it is possible to have two or more static methods having the same name, but the parameters are different in types or number.

Friday, July 16, 2021

Angular ngStyle Directive With Examples

Using Angular ngStyle directive you can set the CSS properties for the containing HTML element. Style properties are specified as colon-separated key-value pairs. The key is a style name, with an optional .<unit> suffix (such as 'top.px', 'font-style.em'). The value is an expression to be evaluated.

For example-

Here font-style, color and background-color CSS properties are set for the containing div element using ngStyle.

<div class="container">
  <div [ngStyle]="{'font-style':'italic', color:'white', 'background-color':'blue'}">
    Text styled using ngStyle
  </div>
</div>

Using ngStyle directive dynamically

The real benefit of using ngStyle is when the value is dynamic. The values that you assign to ngStyle can be an expression and the result of that expression is assigned as the value of the CSS property. Here is an example to show that.

In the example there is a Model class Student with 3 marks fields and the color of the mark is changed as per the conditions which are defined with in a function in TypeScript file.

Angular @HostListener Decorator With Examples

@HostListener decorator in Angular is used to declare a DOM event (like click, mouseenter) to listen for and define a handler method to execute when that event occurs. This decorator is quite useful to listen to events emitted by hostelement when creating a custom directive.

There are two options that you can pass with the @HostListener decorator-

  • eventName- The DOM event to listen for. It is of type string.
  • args- A set of arguments to pass to the handler method when the event occurs. It is of type string[].

For example

@HostListener('click', ['$event.target'])

Here 'click' is the event name.

['$event.target'] is the args parameter which will be passed to the handler method.

Thursday, July 15, 2021

Java Multithreading Interview Questions And Answers

In this post Java multithreading interview questions and answers are listed. This compilation will help the Java developers in preparing for their interviews.

  1. What is thread in Java?

    According to JavaDoc A thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.


  2. How do we create thread in Java?

    In Java there are two ways to create thread.

    • By implementing the Runnable interface.
    • By extending the Thread class.

    Example code snippet using Runnable interface

    class MyThread implements Runnable{
      MyThread(){
        Thread t = new Thread(this, "My Thread");
        t.start();
      }
      ..
      ..
    }
    

    Example code snippet using Thread class

    class TestThread extends Thread{
    
    and then
    TestThread t = new TestThread();
    // starting the thread
    t.start();
    
    After the new thread is created, it will not start running until you call the start( ) method.

    Read more about How to create thread in Java here.

Wednesday, July 14, 2021

NgNonBindable Directive in Angular

In this article we'll see how to use the NgNonBindable directive.

Generally if you use any binding or directive with any element it is evaluated to the expression and render that evaluated expression. For example if you have a component to show user name-

non-bindable.component.ts

import { Component } from "@angular/core";

@Component({
    selector: 'non-bindable',
    templateUrl: './non-bindable.component.html',
})
export class NonBindableComponent{
    userName:String = 'TestUser'
}

non-bindable.component.html

<p>Hello {{ userName }}</p>

After compiling this code and running it you would see that the String interpolation {{ userName }} is evaluated to the assigned value and that’s what is rendered.

Java Collections Interview Questions And Answers

In this post Java Collections interview questions and answers are listed. This compilation will help the Java developers in preparing for their interviews.

  1. What is Java Collections Framework? What are the benefits of using Collections framework?

    Java Collections Framework provides a standard way to handle a group of objects. Benefits of the Collections Framework are-

    • High performance, implementation of the Collection classes (ArrayList, LinkedList, HashSet etc.) are very efficient and used as-is in most of the cases.
    • Reduced effort as framework already provides several implementations for most of the scenarios that can be used as-is.
    • Provides interoperability, as exp. if you are using List interface any implementation that implements List interface can be swapped with the existing one.
    • If you want to extend any collection that can be easily done using the standard interfaces provided with in the Collections frameworks.

  2. Describe the Collection framework hierarchy.

    At the root of the Collections framework is Collection interface, it must be implemented by any class that defines a collection. This interface declares the core methods that every collection will have, if any class doesn't implement any of the method then it can throw UnsupportedOperationException.
    Then there are List and Set interfaces that extend Collection interface and provided some of its own behaviour that will be further implemented by the classes that implement List and Set interfaces respectively.
    There is also a Queue interface that extends collection to provide behaviour of a queue. On the other hand there is Map interface which provides core methods for the Map implementations.

Tuesday, July 13, 2021

Producer-Consumer Java Program Using wait notify

This Java program solves the Producer-Consumer problem using threads and wait notify. Where one (Producer) thread produces data and another (consumer) thread retrieves it. This program makes use of inter-thread communication using wait, notify, notifyAll.

Producer-Consumer problem

Producer Consumer problem is one of the classic concurrency problem where two processes Producer and Consumer share a common buffer for inserting or retrieving data.

Task of the Producer is to generate data and insert it into the shared buffer.

Task of the Consumer is to consume data from the shared buffer.

Since both of these processes work in tandem and share a buffer so it becomes important to synchronize their access to shared buffer in such a way that the Producer doesn't try to insert data into the buffer when it is full and Consumer doesn't try to consume data from the buffer when it is empty.

Monday, July 12, 2021

Deadlock in Java Multi-Threading

In Java which supports multi-threading you may have a scenario where a deadlock happens. In this tutorial you'll learn about the scenarios which may lead to a deadlock and some tips about how to avoid deadlock in Java.

What is deadlock

Deadlock in multi-threading describes a situation where two or more threads are blocked forever, waiting for each other.

To describe it in a simple manner let's assume there are two threads Thread-1 and Thread-2 and two objects obj1 and obj2. Thread-1 already holds a lock on obj1 and for further processing it needs a lock on obj2. At the same time Thread-2 holds a lock on obj2 and wants a lock on obj1. In that kind of scenario both threads will be waiting for each other forever to release lock they are already holding thus creating a deadlock.

Saturday, July 10, 2021

Reading File in Java Using BufferedReader

Java NIO and Java 8 provide many new ways to read a file in Java, like using Scanner to read file in Java or Reading File in Java 8 but reading a file in Java using BufferedReader still remains one of the most used way.

The advantage of using buffered I/O streams for reading/writing file in Java is that each request doesn't trigger disk access or network activity.

When buffered input stream is used to read a file in Java data is read from a memory area known as a buffer; the native input API is called only when the buffer is empty.

In case of buffered output stream data is written to a buffer, and the native output API is called only when the buffer is full.

Java Program to read a file using BufferedReader

In the program readLine() method of the BufferedReader class is used to read the file. This method reads data from file one line at a time. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

static Import in Java With Examples

In order to access any static member (static field or method) of the class, it is necessary to qualify references with the class they came from.

ClassName.static_method()

With static import feature of Java 5, members defined in a class as public static can be used without qualifying it with the class name, in any Java class which does a static import. So, static import in Java allows unqualified access to the static member. This shortens the syntax required to use a static member.

Syntax of static import in Java

Any Java program can import the members individually or en masse-

// accessing specific static variable of a class
import static package_name.class_name.static_variable;

// accessing specific static method of a class
import static package_name.class_name.static_method;

// accessing all the static members of a class en masse
import static package_name.class_name.*;

Friday, July 9, 2021

Initializer Block in Java

If you want to initialize an instance variable you will put that code in a constructor. In this post we'll see one alternative to using a constructor that can be used to initialize instance variables which is called initializer block in Java.

Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword.

General form of Initializer block in Java

{
  // whatever code is needed for initialization 
  // goes here
}

Usage of Initializer block in Java

The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors. If you have some common code that you want to be executed regardless of which constructor is used, that code can be put in an initializer block in Java.

Thursday, July 8, 2021

Java StampedLock With Examples

In Java 8 a new kind of lock StampedLock is added which apart from providing separate read and write locks also has a feature for optimistic locking for read operations. StampedLock in Java also provides method to upgrade read lock to write lock which is not there in ReentrantReadWriteLock in Java.

The locking methods of StampedLock in Java return a stamp represented by a long value. You can use these stamps to either release a lock, to check if the lock is still valid, to convert a lock.

So, if you want to use a StampedLock for acquiring a write lock it can be done as-

StampedLock sl = new StampedLock();
//acquiring writelock
long stamp =  sl.writeLock();
try{
 ...
 ...
}finally {
 //releasing lock
 sl.unlockWrite(stamp);
}

Static Synchronization in Java Multi-Threading

With instance method synchronization, threads are executed one thread per instance. That may create problems when we have more than one instance of the same class. In that scenario you may have to synchronize at the class level if you want to have a single lock for all the instances of the class rather than synchronizing at object level. That is what static synchronization in Java does.

There are two ways you can have static synchronization in Java.
  • static synchronized method
  • An enclosed synchronized code block with in a static method.

Synchronized static method in Java

Synchronized instance method is synchronized on the instance(object) of the class. If a class has two objects, then two threads can acquire lock on these two objects and enter the synchronized method or block at the same time.

Wednesday, July 7, 2021

How to Create a Custom Structural Directive in Angular

In this article we’ll see how to create a custom structural directive in Angular. Structural directive is used to modify DOM structure by adding or removing DOM elements.

In order to create a structural directive in Angular you should be clear about how the structural directives internally work so here is a small section on that.

The asterisk, *, syntax on a structural directive, such as *ngIf, is shorthand that Angular interprets into a longer form. Angular transforms the asterisk in front of a structural directive into an <ng-template> that surrounds the host element. For example

<div *ngIf="user" class="name">{{user.name}}</div>

is translated into a <ng-template> element, wrapped around the host element, like this.

<ng-template [ngIf]="user">
  <div class="name">{{user.name}}</div>
</ng-template>

Same way for *ngFor

<div *ngFor="let item of items">
    {{item .name}}
</div>

Above statement is internally expanded into a long form that uses the ngForOf selector on an <ng-template> element. Repeat the <ng-template> for each item in the list

<ng-template ngFor let-item [ngForOf]="items">
  <div>{{item.name}}</div>
</ng-template>

Tuesday, July 6, 2021

Difference Between Runnable And Callable in Java

Differences between Callable and Runnable in Java is a frequently asked Java concurrency interview question and that is the topic of this post.

Runnable and Callable interfaces in Java

Runnable interface is around from JDK 1.0 where as Callable was added much later in Java 5 along with many other concurrent features like ConcurrentHashMap, BlockingQueue, ExecutorService.

If you see basic functionality, both Callable and Runnable interfaces in Java are implemented by any class whose instances are to be executed by another thread. Since Callable is added later so it is obvious that it would have some extra features which were not there in Runnable. Some of the added features in Callable are-

  • It can return value.
  • It can throw checked exception.

Which are not there in Runnable interface in Java. These features make Callable an excellent choice if you have to run a task that involves extensive computation of a value that can be returned later.

Monday, July 5, 2021

How to Create a Custom Attribute Directive in Angular

In this article we’ll see how to create a custom attribute directive in Angular. Attribute directive is used to modify the appearance or behavior of DOM element.

Angular provides a class named ElementRef which is a wrapper class around a native element inside of a View so it can access DOM. Permitting direct access to the DOM can make your application more vulnerable to XSS (Cross-Site Scripting) attacks. It is recommended to create a custom directive and use ElementRef class inside it to change the appearance or behavior of DOM element.

In Angular there is also a Renderer2 class that helps in implementing custom rendering. So in our custom attribute directive we'll make use of the Renderer2 and ElementRef classes to manipulate elements.


Sunday, July 4, 2021

Callable and Future in Java With Examples

In this post we'll see what are Callable and Future in Java and how you can use them to return a result from an asynchronous computation.


Callable in Java

Callable, an interface, was added in Java 5. It allows you to define a task to be completed by a thread asynchronously.

You must be wondering, there is already a Runnable interface, with its run() method to do the same thing then why Callable interface in Java is required? Problem with Runnable is that it can't return a value. It offers a single method run() that accepts no arguments and returns no values, nor can it throw any checked exceptions.

If you have to use Runnable in scenario where you want to return some value, you'll have to write a method outside the interface to get a value back from the completed task, Also you need some kind of notification to know that the task is completed and now value can be retrieved.

Callable in Java provides the functionality out of the box to implement the scenario as stated above. A callable task can return a result and may throw an exception.

Saturday, July 3, 2021

Java BlockingDeque With Examples

BlockingDeque interface in Java (added in Java 6) is a Deque that provides additional support for blocking operations. Here blocking the operations means that the operation will wait for the deque to become non-empty (means deque has at least one element) when retrieving an element, and wait for space to become available in the deque when storing an element.

Deque in Java

Deque is also an interface which was added in Java 6. Deque is short for "double ended queue". As the name suggests Deque supports element insertion and removal at both ends.

Java BlockingDeque

Like any BlockingQueue, BlockingDeque in Java is thread safe, does not permit null elements, and may (or may not) be capacity-constrained.

LinkedBlockingDeque class in Java is the implementation of the BlockingDeque interface.

BlockingDeque methods in Java

As already mentioned BlockingDeque in Java provides support for the blocking operations, but blocking methods come in four forms, categorized in the way these methods will handle operations that cannot be satisfied immediately, but may be satisfied at some point in the future:

  • Throw exception- Methods falling in this category will throw exception if blocked.
  • Return special value- This type of methods will return some value if need to wait, like false.
  • Blocks- This type of methods will wait if necessary for space to become available.
  • Times out- This type of methods will block for only a given maximum time limit before giving up.

These methods are summarized in the following table:

Friday, July 2, 2021

How HashSet Works Internally in Java

In this post we'll see how HashSet internally works in Java, which is also a favourite Java Collections interview question but before going into internal implementation of HashSet in Java it is important to know two points about HashSet.

  1. HashSet in Java only stores unique values i.e. no duplicates are allowed.
  2. HashSet works on the concept of hashing just like HashMap in Java but its working differs from the HashMap in the following way-
    • In HashMap a (Key, Value) pair is added and the hash function is calculated using key.
    • Where as in the HashSet hash function is calculated using the value itself. Note that in HashSet we have add(E e) method which takes just the element to be added as parameter.
    Also you may have guessed by now, since hash function is calculated using value that is why only unique values are stored in the HashSet. If you try to store the same element again, the calculated hash function would be same, thus the element will be overwritten.

HashSet internally uses HashMap

Now coming back to internal implementation of HashSet in Java the most important point is HashSet class implementation internally uses HashMap to store it's elements.

Within the HashSet there are many constructors one without any parameter and several more with initial capacity or load factor but each one of these constructor creates a HashMap. Since HashSet internally uses HashMap so knowing how HashMap works internally in Java will help you to understand how HashSet works internally in Java.

HashSet Constructor snippets

In the HashSet class in Java you can see that constructors of the class do create a HashMap.

/**
* Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
* default initial capacity (16) and load factor (0.75).
*/
public HashSet() {
  map = new HashMap<>();
}
public HashSet(int initialCapacity, float loadFactor) {
  map = new HashMap<>(initialCapacity, loadFactor);
}

And the map, which is used for storing values, is defined as

private transient HashMap<E,Object> map;

In the constructor, if you have noticed, there are parameters named initial capacity and load factor. For HashSet, default initial capacity is 16, that is an array (or bucket) of length 16 would be created and default load factor is 0.75. Where load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased.

How elements are added - HashSet internal implementation

I stated in the point 2 above that HashSet calculates the hash function using value itself and there is no (Key, Value) pair in HashSet and then came the statement that HashSet internally uses HashMap to store objects. These two statements may sound contradictory as HashMap stores (key, value) pair so let's see how these these two contradictory statements hold true.

Actually from add method of HashSet class put() method of HashMap is called where the value, which has to be added in the Set, becomes Key and a constant object "PRESENT" is used as value.

That's how PRESENT is defined in HashSet implementation-

// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();

And that's how add method is implemented in HashSet class -

public boolean add(E e) {
  return map.put(e, PRESENT)==null;
} 

So you can see with in the internal implementation of the HashSet it's a (key, value) pair which is actually getting added. It's just that the actual value (which is added to the HashSet) becomes the key and a dummy value "PRESENT" is added as value when storing it in the backing HashMap.

For example a statement for adding an element to HashSet- set.add("Mumbai"); internally translates into map.put("Mumbai", PRESENT); and then added to the backing HashMap instance.

One thing to note here is, in HashMap value may be duplicate but Key should be unique. That's how HashSet makes sure that only unique values are stored in it, since the value which is to be stored in the HashSet becomes the key while storing it in HashMap.

How element is removed - HashSet internal implementation

When we need to remove an element from the HashSet, internally again remove method of HashSet calls remove(Object key) method of the HashMap.

That is how it is implemented in HashSet class.

public boolean remove(Object o) {
  return map.remove(o)==PRESENT;
}

Here note that remove(Object key) method of the HashMap returns the Value associated with the key. Whereas the remove(Object o) method of the HashSet returns Boolean value. Also we know that for every value added in HashSet, internally when it is added to the associated HashMap, value becomes Key and the value is always an object called PRESENT. Therefore the value that is returned from the remove(Object key) method of the HashMap is always PRESENT thus the condition map.remove(o)==PRESENT.

How elements are retrieved from HashSet in Java

In HashSet there is no get method as provided in Map or List. In HashSet iterator is there which will iterate through the values of the Set. Internally it will call the keyset of the HashMap, as values are stored as keys in the HashMap so what we'll get is the values stored in the HashSet.

That's how iterator is internally implemented in the HashSet in Java.

/**
* Returns an iterator over the elements in this set. The elements
* are returned in no particular order.
*
* @return an Iterator over the elements in this set
* @see ConcurrentModificationException
*/
public Iterator<E> iterator() {
  return map.keySet().iterator();
}

Points to note

  1. Unlike HashMap where hash function is calculated using key HashSet uses the value itself to calculate the hash function.
  2. Since hash function is calculated using value that is why only unique values are stored in the HashSet.
  3. HashSet internally uses HashMap to store its elements.
  4. When element is added to HashSet using add(E e) method internally HashSet calls put() method of the HashMap where the value passed in the add method becomes key in the put() method. A dummy value “PRESENT” is passed as value in the put() method.

Recommendations for learning (Udemy Courses)

  1. Java Programming Masterclass Course
  2. Java In-Depth: Become a Complete Java Engineer!
  3. Spring Framework Master Class Course
  4. Complete Python Bootcamp Course
  5. Python for Data Science and Machine Learning

That's all for this topic How HashSet Works Internally in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How ArrayList Works Internally in Java
  2. How HashMap Works Internally in Java
  3. How LinkedList Class Works Internally in Java
  4. LinkedHashSet in Java With Examples
  5. TreeSet in Java With Examples

You may also like-

  1. EnumSet in Java With Examples
  2. Java Collections Interview Questions And Answers
  3. Varargs (Variable-length Arguments) in Java
  4. finalize method in Java
  5. Interface Static Methods in Java
  6. Method Reference in Java
  7. String Vs StringBuffer Vs StringBuilder in Java
  8. Why wait(), notify() And notifyAll() Must be Called Inside a Synchronized Method or Block

Thursday, July 1, 2021

Directives in Angular

Angular directives are classes that add additional behavior to elements in your Angular applications. Using directives you can change the appearance or behavior of an element, change the DOM layout by adding and removing DOM elements.

Types of directives in Angular

There are three different types of Angular directives-

1. Components— Yes even components are directives only difference with other directives is that components are a directive with a template.

2. Attribute directives— Attribute directives are used to change the appearance or behavior of an element, component, or another directive.

3. Structural directives— Structural directives are used to change the DOM layout. These directives can add and remove DOM elements from the DOM structure.

types of angular directives