Wednesday, April 21, 2021

How ArrayList Works Internally in Java

ArrayList arguably would be the most used collection along with the HashMap. Many of us programmers whip up code everyday which contains atleast one of these data structures to hold objects. I have already discussed how HashMap works internally in Java, in this post I'll try to explain how ArrayList internally works in Java.

As most of us would already be knowing that ArrayList is a Resizable-array implementation of the List interface i.e. ArrayList grows dynamically as the elements are added to it. So let's try to get clear idea about the following points-

  • How ArrayList is internally implemented in Java.
  • What is the backing data structure for an ArrayList.
  • How it grows dynamically and ensures that there is always room to add elements.
Because of all these side questions it is also a very important Java Collections interview question.

Note - Code of ArrayList used here for reference is from Java 10.


Where does ArrayList internally store elements

Basic data structure used by Java ArrayList to store objects is an array of Object class, which is defined as follows-

transient Object[] elementData;

I am sure many of you would be thinking why transient and how about serializing an ArrayList then?
ArrayList provides its own version of readObject and writeObject methods so no problem in serializing an ArrayList and that is the reason, I think, of making this Object array as transient.

Tuesday, April 20, 2021

EnumSet in Java With Examples

EnumSet in Java is a specialized set implementation for use with enum types. EnumSet was introduced in Java 5 along with the Enum. All of the elements stored in an EnumSet must, explicitly or implicitly, come from a single enum type that is specified while creating the set. All basic operations of the EnumSet execute in constant time. They are likely (though not guaranteed) to be much faster than their HashSet counterparts.

According to Java docs "Enum sets are represented internally as bit vectors. This representation is extremely compact and efficient. The space and time performance of this class should be good enough to allow its use as a high-quality, typesafe alternative to traditional int-based "bit flags." Even bulk operations (such as containsAll and retainAll) should run very quickly if their argument is also an enum set."

How EnumSet works in Java

One of the things to note about EnumSet is that it is an abstract class and uses factory methods to create objects. There are two concrete implementations of EnumSet in Java-

  • RegularEnumSet- Private implementation class for EnumSet, for "regular sized" enum types
  • JumboEnumSet- Private implementation class for EnumSet, for "jumbo" enum types (i.e., those with more than 64 elements).
Both of these classes can't be instantiated directly by the user as these classes have default (package-private) access.

Depending upon the size of the Enum any of these classes is instantiated by the EnumSet class itself. If Enum has 64 or fewer enum constants then RegularEnumSet is used otherwise JumboEnumSet.

Monday, April 19, 2021

Converting String to float in Java

There are several instances when you want to convert a String to float data type so in this post we’ll see what different ways do we have to convert String to float in Java.

In Java, Float class provides two methods for converting string to float-

  • parseFloat(String s)- Returns a new float initialized to the value represented by the specified String. Throws NumberFormatException if the string does not contain a parsable number. See example.
  • valueOf(String s)- Returns a Float object holding the float value represented by the String argument s. Throws NumberFormatException if the String does not contain a parsable number. See example.

Here Few things to note are-

  1. Both of the methods are static so you can use them directly with the class i.e. Float.parseFloat(String s) and Float.valueOf(String s).
  2. If you have noticed parseFloat method returns float (primitive data type) where as valueOf() method returns Float class object.
  3. String passed should have digits only except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value.
  4. You can use “f” or “F” (even d or D which denotes double) with the float value so having string as “56.78f” will not throw NumberFormatException while converting where as “56.78a” will throw exception.

Float class also has a constructor that takes String as argument so that is also one way to convert string to float. Note that this constructor is deprecated Java 9 onward.

  • Float(String s)- Constructs a newly allocated Float object that represents the floating-point value of type float represented by the string.

Sunday, April 18, 2021

Converting String to double in Java

There are several instances when you want to convert a string to double data type so in this post we’ll see what different ways do we have to convert String to double in Java.

Double class in Java provides two methods for converting String to double-

  • parseDouble(String s)- Returns a new double initialized to the value represented by the specified String. Throws NumberFormatException if the string does not contain a parsable double.
  • valueOf(String s)- Returns a Double object holding the double value represented by the argument string s. Throws NumberFormatException if the string does not contain a parsable number. If s is null, then a NullPointerException is thrown.

Here Few things to note are-

  1. Both of the methods are static so you can use them directly with the class i.e. Double.parseDouble(String s) and Double.valueOf(String s).
  2. If you have noticed parseDouble method returns double (primitive data type) where as valueOf() method returns Double class object.
  3. String passed should have digits only except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value.
  4. You can use “d” or “D” (even f or F which denotes float) with the value so having string as “43.67d” will not throw NumberFormatException while converting where as “43.67e” will throw exception.

Note that Double class also has a constructor that takes String as argument so that is also one way to convert string to float.

Double(String s)- Constructs a newly allocated Double object that represents the floating-point value of type double represented by the string.

Wednesday, April 14, 2021

How to Read Properties File in Java

In this tutorial you will see how to read a properties file in Java. If you have any configurable data in your application like DB configuration, user settings its better to keep it in a properties file and read it from there. A properties file stores data in the form of key/value pair.

For reading a properties file in Java there are two ways to load properties file-

  1. Loading properties file from the file system. See example.
  2. Loading properties file from classpath. See example.

Project structure

For this example we’ll have a properties file named app.properties file in a folder called resource. The resource folder is at the same level at the src folder in the Java project.

read properties file in java

Steps for reading a properties file in Java

  1. Create an instance of Properties class.
  2. Create a FileInputStream by opening a connection to the properties file.
  3. Read property list (key and element pairs) from the input stream using load() method of the Properties class.

Content of the properties file

Here the properties file used is named app.properties file with it’s content as-

user=TestUser
url=https://www.netjstech.com

Loading properties file from the file system

One way to read properties file in Java is to load it from the file system.

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PropDemo {
  private Properties properties = new Properties();
  public static void main(String[] args) {
    PropDemo pDemo = new PropDemo();
    pDemo.loadPropertiesFile();
    pDemo.readProperties();
  }
  
  // This method is used to load the properties file
  private void loadPropertiesFile(){
    InputStream iStream = null;
      try {
        // Loading properties file from the path (relative path given here)
        iStream = new FileInputStream("resource/app.properties");   
        properties.load(iStream);
      } catch (IOException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      }finally {
        try {
          if(iStream != null){
            iStream.close();
          }
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }
  
  /**
  * Method to read the properties from a
  * loaded property file
  */
  private void readProperties(){
    System.out.println("User name - " + properties.getProperty("user"));
    System.out.println("URL - " + properties.getProperty("url"));
    // reading property which is not there
    System.out.println("City - " + properties.getProperty("city"));
  }
}

Output

User name - TestUser
URL - https://www.netjstech.com
City - null

Here you can see that in the code there is an attempt to read the property “city” which doesn’t exist in the app.properties file that’s why it is retrieved as null.

Loading properties file from classpath

If you have properties file in the project classpath then you can load it by using the getResourceAsStream method. That is another way to read properties file in Java.

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PropDemo {
 private Properties properties = new Properties();
 public static void main(String[] args) {
   PropDemo pDemo = new PropDemo();
   pDemo.loadProperties();
   pDemo.readProperties();
 }
 
 // This method is used to load the properties file
 private void loadProperties(){
   InputStream iStream = null;
   try {
    // Loading properties file from the classpath
    iStream = this.getClass().getClassLoader()
                             .getResourceAsStream("app.properties");
    if(iStream == null){
     throw new IOException("File not found");
    }
    properties.load(iStream);
   } catch (IOException e) {
    e.printStackTrace();
   }finally {
    try {
     if(iStream != null){
      iStream.close();
     }
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
 }
  
 /**
  * Method to read the properties from a
  * loaded property file
 */
 private void readProperties(){
   System.out.println("User name - " + properties.getProperty("user"));
   System.out.println("URL - " + properties.getProperty("url"));
 }
}

Output

User name - TestUser
URL - https://www.netjstech.com

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 to Read Properties File in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. How to Read File From The Last Line in Java
  2. Unzip File in Java
  3. Reading File in Java Using Files.lines And Files.newBufferedReader
  4. Write to a File in Java
  5. How to Read Properties File in Spring Framework

You may also like-

  1. How to Create PDF From XML Using Apache FOP
  2. Setting And Getting Thread Name And Thread ID in Java
  3. How to Convert Date And Time Between Different Time-Zones in Java
  4. How to Reverse a String in Java
  5. Fail-Fast Vs Fail-Safe Iterator in Java
  6. Java ReentrantReadWriteLock With Examples
  7. BigDecimal in Java With Examples
  8. instanceof Operator in Java With Examples

Tuesday, April 13, 2021

How to Use ngFor and ngIf on Same Element in Angular

In Angular if you want to use two structural directives like *ngFor and *ngIf on the same element that results in an error.

Can't have multiple template bindings on one element. Use only one attribute prefixed with *

How to use ngFor and ngIf on same element

It is very common to show only specific elements while looping i.e. having ngIf to test a condition with in a ngFor loop or to loop elements only when a condition is true i.e. having ngFor within ngIf condition.

For example let’s say you have to iterate through Region objects using ngFor showing only those records where sales is greater than 200, writing it as given below results in error as both *ngFor and *ngIf are with in the same <tr> element.

<div class="container">
  <table class="table table-sm table-bordered m-t-4 table-striped">
    <thead>
      <tr>
        <th>Region</th>
        <th>Manager</th>
        <th>Sales (in millions)</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let region of regions" *ngIf="region.sales > 200">       
        <td>{{region.region}}</td>
        <td>{{region.regionalManager}}</td>               
        <td>{{region.sales}}</td>
      </tr>
    </tbody>
  </table>
</div>

Monday, April 12, 2021

Angular @Output() Decorator With Examples

Angular @Output() decorator in a child component or directive allows data to flow from the child to the parent. A property decorated with @Output in child component is used to raise an event to notify the parent of the change. That property must be of type EventEmitter, which is a class in @angular/core that you use to emit custom events.

Angular @Output() Decorator

@Output, $event and EventEmitter in Angular

In order to know how to use @Output decorator in Angular you should have idea about the following entities-

  • @Output decorator
  • EventEmitter class
  • $event object

1. @Output decorator

A property in a Component that emits a custom event is decorated with @Output decorator. For example in the statement

 @Output() messageEvent = new EventEmitter<string>();

messageEvent property is decorated with @Output() which means this property is going to emit a custom event. That is why this property is of type EventEmitter.