Wednesday, 18 October 2017

How to Find Common Elements in Two Arrays - Java Program

This post is about writing a Java program to find common elements in the given arrays. It is a common interview question where it is asked with a condition not to use any inbuilt method or any inbuilt data structure like list or set.

Steps for solution

A simple solution is to loop through an array in the outer loop and then traverse through the other array in an inner loop and compare the element of the outer array with all the elements of the inner array.

If similar element is found print it and break from the inner loop.

Java program with array of numbers

 
public class FindCommonElement {

 public static void main(String[] args) {
  int[] numArray1 = {1, 4, 5};
  int[] numArray2 = {6, 1, 8, 34, 5};
  // Outer loop
  for(int i = 0; i < numArray1.length; i++){
   for(int j = 0; j < numArray2.length; j++){// inner loop
    if(numArray1[i] == numArray2[j]){
     System.out.println(numArray1[i]);
     break;
    }
   }
  }
  
 }

}

Output

1
5

Java program with array of strings

Logic remains same in case of array of Strings. Only thing that changes is how you compare, with Strings you will have to use .equals method.
 
public class FindCommonElement {

 public static void main(String[] args) {
  String[] numArray1 = {"Java", "Scala", "Python"};
  String[] numArray2 = {".Net", "Scala", "Clojure", "Java", 
    "Java Script", "Python"};
  // Outer loop
  for(int i = 0; i < numArray1.length; i++){
   for(int j = 0; j < numArray2.length; j++){// inner loop
    if(numArray1[i].equals(numArray2[j])){
     System.out.println(numArray1[i]);
     break;
    }
   }
  }
  
 }

}

Output

Java
Scala
Python

That's all for this topic How to Find Common Elements in Two Arrays - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to remove duplicate elements from an array - Java Program
  2. How to remove elements from an array - Java Program
  3. Array in Java
  4. Matrix Addition - Java Program
  5. If Given String Sub-Sequence of Another String - Java Program

You may also like -

>>>Go to Java Programs page

Monday, 16 October 2017

Just In Time Compiler (JIT) in Java

When we start studying Java we get to know one of the prominent feature of Java is that Java is platform independent.

How platform independence is achieved

In a short sentence, Java is platform independent because of the fact it is both compiled and interpreted.

To explain it further; first when we compile our JAVA code .class files are generated having the platform independent byte code which is interpreted to machine native code at run time by the JVM.

Where does JIT compiler fit

This two step process, though makes Java platform independent, where you are not worried about the OS or processor while writing your code, but at the same time execution is slow because byte code is interpreted to the native code at the run time.

Because of this interpretation of the byte code to the host CPU's native instruction set there is an overhead of processor and memory usage which results in slow execution of the code.

That’s where JustInTime (JIT) compiler comes into the picture. In simple terms you can say JIT compiler compiles the already compiled code to the native code as per the processor. Since this compilation of the compiled byte code to the native machine code is done at the run time (Just in time) thus the name Just in Time compiler (JIT).

How does JIT compiler work

While the code is executed JVM automatically monitors which methods are being executed frequently and start marking the methods that are “hot”. Note that JIT compiler initially itself doesn’t compile all the code at once, initially methods are interpreted from byte code.

Marked "hot" methods are scheduled for compilation into machine code. This compilation into machine code happens on a separate JVM thread without interrupting the execution of the program. While the hot method is compiled by the JIT compiler, the JVM will keep using the interpreted version of the method and switch over to the compiled method once it is ready.

Initial compilation of the method is quick but the resulting code may not be as efficient as it could be. If a method is used quite frequently the system can get a performance boost if the code for that particular method is regenerated in a more efficient way. That is why same method may get compiled more than once and more optimizations may get applied while the code is compiled.

Once the method is marked for compilation and compiled, its count is set to zero. If method call again reaches the call count threshold the method is recompiled and more optimizations are applied to the method to make it more efficient.

That recompilation and more optimization happens because the optimization techniques are often layered and once the compiler has applied one optimization then only it may be able to see other optimizations that can be applied.

JIT compiler

How does JIT complier optimize code

Some of the optimization techniques used by JIT complier are -

  1. Inlining methods – One of the most common technique for optimizing code is method inlining. In method inlining the method call is substituted by the method body in the places where method is called. By replacing the method body in the method call the call to the method, resultant creation of stack frames is saved.

    Example code

    class A {
      B b;
      public void doProcessing() {
        x = b.getValue();
        ...
        ...
        y = b.getValue();
        ………………………….
    
      }
    }
    
    class B {
       int value;
       final int getValue() {
          return value;
       }
    }
    

    Inlining final method

    Notice in Class A method calls (getValue) are eliminated.

    class A {
      B b;
      public void doProcessing() {
        x = b.value;
        ...
        ...
        y = b.value;
        ………………………….
    
      }
    }
    

    Removing redundant loads

    y = b.value; is replaced with y = x so that local value itself can be used.
    class A {
      B b;
      public void doProcessing() {
        x = b.value;
        ...
        ...
        ...
        y = x;
        ………………………….
    
      }
    }
    
  2. Monomorphic dispatch

    Java being an object-oriented language uses subtyping/polymorphism which means most of the method invocations are virtual method lookup. The JVM checks how many different implementations of the method are there –

    • If there is only one implementation it is a monomorphic dispatch.
    • If there are 2 then it is bimorphic dispatch, in case of more than 2 it is megamorphic dispatch.

    In the monomorphic case, path-dependent types (sub type or super type) does not happen. So, we know the exact method definitions that will be called when methods are called on the passed object, because we don’t need to check which override is actually being used. This means we can eliminate the overhead of doing virtual method lookup.

  3. Removing unwanted synchronization – Overhead of obtaining locks to enter a monitor can be eliminated by removing the synchronization, if synchronized block can only be accessed by a single thread.

    As example

    public void methodA{
     B b = new B()
      Synchronized(b){
       …..
       ……
      }
    }
    

    Here new object is created with in the method so every thread will have its own object thus the synchronized block has no effect here. JVM will notice that and the method will be optimized by JIT compiler.

  4. Merging adjacent synchronized block with same object – If there are adjacent synchronized block on the same object those will be merged as an optimization.
    Public void testMethod{
      synchronized(Test.class){
       ……
       …
      }
      synchronized(Test.class){
       ……
       …
      }
    }
    
    Here these 2 synchronized blocks can be merged to create a single synchronized block.

There are many other optimizations applied like loop optimization, dead code elimination.

Reference -

http://www.oracle.com/technetwork/articles/java/architect-evans-pt1-2266278.html
https://docs.oracle.com/cd/E15289_01/doc.40/e15058/underst_jit.htm

That's all for this topic Just In Time Compiler (JIT) in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Synchronization in Java multithreading
  2. Race condition in Java multi-threading
  3. How to compile Java program at runtime
  4. How to run javap programmatically from Java Program

You may also like -

>>>Go to Java advance topics page

Wednesday, 11 October 2017

If Given String Sub-Sequence of Another String - Java Program

I recently remembered one interview 6-7 years back where I was asked to write a Java program to find if given string is the subsequence of another string. I started writing the program but my approach was wrong as I was getting confused between subsequence and substring.

What I wrote was to ensure that given string is the substring of another string and my assumption was that the characters should come continuously. As example if I have to find "net" exists in "netjs", then it is true as all the characters n, e, t are coming continuously in netjs.

But that’s not what subsequence means so before writing the program to ensure that given string is the subsequence of another string first let’s have a proper definition of what subsequence means.

A subsequence is a sequence where all the characters of the subsequence are present in another sequence, are in order but may not be continuous. As example – If our subsequence is “net” and we have to find if that subsequence exists in the string “npeght” then it should return true as all the characters of the subsequence (n, e, t) are present in the given string and characters are in the same order. If we delete the extra elements in the second string (p, g, h) then we get the same string.

Approach for the Java program

We can have both iterative and recursive logic for this program. Approach remains same for both if we have to find that String-1 is subsequence of String-2 then we start from one end of the string, it can be leftmost or rightmost (In the program here I started from the leftmost character of the strings). If character of String-1 is found in String-2 then we increment the index by 1 for both strings, if character of String-1 is not found in String-2 then we increment the index by 1 only for String-2.

Java code to find subsequence

This code has both iterative and recursive solutions.

  • Method isStringSequenceFound(String str1, String str2, int i, int j)is for recursive solution.
  • Method isStringSequenceFound(String str1, String str2) is for iterative solution.
public class SubSequenceFinder {

 public static void main(String[] args) {
        // Iterative method call
        String str1 = "abc";
        String str2 = "asc";
        boolean flag = isStringSequenceFound(str1, str2);
        System.out.println(str1 + " is subsequence of " + str2 + " - " + flag);
        
        // Recursive method call
        str1 = "java";
        str2 = "javelina";
        flag = isStringSequenceFound(str1, str2, 0, 0);
        System.out.println(str1 + " is subsequence of " + str2 + " - " + flag);
        
        // Iterative method call
        str1 = "abc";
        str2 = "asbbdfc";
        flag = isStringSequenceFound(str1, str2);
        System.out.println(str1 + " is subsequence of " + str2 + " - " + flag);

 }
 
 // Recursive method to find sub-sequence
 static boolean isStringSequenceFound(String str1, String str2, int i, int j){
  // Exit condition - if i becomes equal to length 
  // of string-1 that means all the characters are found in the second string
  if(str1.length() == i){
   return true;
  }
  //if length of String-2 becomes equal to j that means string 2 is completely
  // traversed and all the characters of string-1 are not found
  if(str2.length() == j){
   System.out.println();
   return false;
  }
  //
  if(str1.charAt(i) == str2.charAt(j)){
   // increase both i and j by 1, if char is found
   return isStringSequenceFound(str1, str2, ++i, ++j);
  }else{
   return isStringSequenceFound(str1, str2, i, ++j);
  }
 }
 
 // iterative method to find sub-sequence
 static boolean isStringSequenceFound(String str1, String str2){
  int j = 0;
  for(int i = 0; i < str2.length(); i++){
   if(str1.charAt(j) == str2.charAt(i)){
    ++j;
   }
   // All the characters of String-1 are found in String-2
   if(j == str1.length()){
    return true;
   }
  }
  // If it comes here that means all the characters of String-1
  // are not found in string-2
  return false;
 }

}

Output

abc is subsequence of asc - false
java is subsequence of javelina - true
abc is subsequence of asbbdfc - true

That's all for this topic If Given String Sub-Sequence of Another String - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Count total number of times each character appears in a String
  2. Check whether a given String/Number is a palindrome or not
  3. How to find all the permutations of the given String
  4. How to reverse a string in Java
  5. Lambda Expression Callable example

You may also like -

>>>Go to Java Programs page

Thursday, 5 October 2017

How to Format Time in AM-PM Format - Java Program

In this post I’ll show how you can format time in AM-PM format.

In order to get time in AM-PM format, in the format you are creating using SimpleDateFormat (if you are not using Java 8) or DateFormatter (if you are using Java 8) just add the pattern letter ‘a’ which denotes AM-PM of the day.

Example Code using SimpleDateFormat

If you are using the java.util.Date and SimpleDateFormat

Date date = new Date();
// Pattern 
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss a");
System.out.println("TIME - " + sdf.format(date));

Output

TIME - 13:09:55 PM

Example code using DateFormatter

If you are using the new Date and Time API in Java 8, then you can use the DateFormatter class, pattern remains the same.
//Getting time
LocalTime t2 = LocalTime.now();
// Pattern
DateTimeFormatter df = DateTimeFormatter.ofPattern("HH:mm:ss a");
String text = t2.format(df);
System.out.println("Time - " + text);

Output

Time - 13:11:15 PM

Another example – Showing AM

LocalTime t1 = LocalTime.of(5, 30, 56);
DateTimeFormatter df = DateTimeFormatter.ofPattern("HH:mm:ss a");
String text = t1.format(df);
System.out.println("Time - " + text);

Output

Time - 05:30:56 AM

That's all for this topic How to format time in AM-PM format. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to format date in Java using SimpleDateFormat
  2. How to convert String to Date in Java
  3. How to convert date and time between different time-zones in Java
  4. How to find last modified date of a file in Java
  5. Converting int to string - Java Program

You may also like -

>>>Go to Java Programs page

Tuesday, 3 October 2017

How to Create Your Own BlockingQueue - Java Program

This post shows how you can create your own BlockingQueue using ReentrantLock and Condition interface. Condition interface provides method await and signal which work the same way as wait and notify.

Example code

Here we have a class called BufferClass which has an array of type Object, whose length is 5. So, 5 is the bound for buffer, if 5 values are already added to the array it will be blocked until at least one value is retrieved from the array.

put() and take() method are used to add value to an array and retrieve value from an array respectively.

BufferClass

 
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class BufferClass {
 final Lock lock = new ReentrantLock();
 // Conditions
 final Condition produce  = lock.newCondition(); 
 final Condition consume = lock.newCondition(); 

 final Object[] valueArr = new Object[5];
 int putIndex, takeIndex;
 int count;

 public void put(Object x) throws InterruptedException {
  //System.out.println("count -- " + count);
  //System.out.println("Array length -- " + valueArr.length);
  lock.lock();
  try {
   while (count == valueArr.length){
    
    produce.await();
    //System.out.println("Awaiting");
      }
   
   valueArr[putIndex] = x;
   System.out.println("Adding - " + x);
       if (++putIndex == valueArr.length){
        putIndex = 0;
       }
       // increment count
       ++count;
       consume.signal();
     } finally {
      lock.unlock();
  }
 }

    public Object take() throws InterruptedException {
      lock.lock();
      try {
        while (count == 0){
         consume.await();
        }
        Object x = valueArr[takeIndex];
        System.out.println("Retrieving - " + x);
        if (++takeIndex == valueArr.length){
         takeIndex = 0;
        }
        // reduce the count
        --count;
        // signal producer
        produce.signal();
        return x;
      } finally {
        lock.unlock();
      }
    }
}

To test this BufferClass we have another class BufferClassDemo where two threads are created, one will add values to the buffer and another will retrieve values from the buffer. Here 10 values are added, BufferClass should ensure if 5 values are already added any attempt to add any further value should be blocked. Same way if the buffer is empty any attempt to retrieve value should be blocked.

 
public class BufferClassDemo {
 
 public static void main(String[] args) {
  BufferClass bufferClass = new BufferClass();
  // Creating two threads
  Thread producer = new Thread(new Producer(bufferClass));
  Thread consumer = new Thread(new Consumer(bufferClass)); 
  // starting threads
  producer.start();
  consumer.start();
 }
}

class Producer implements Runnable {

    private BufferClass bufferClass;
    
    public Producer(BufferClass bufferClass){
        this.bufferClass = bufferClass;
    }
    @Override
    public void run() {
      for (int i = 1; i <= 10; i++) {
            try {
                //Thread.sleep(10);                            
             bufferClass.put(i);                            
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}

class Consumer implements Runnable {
 private BufferClass bufferClass;
    
    public Consumer(BufferClass bufferClass){
        this.bufferClass = bufferClass;
    }
    @Override
    public void run() {
      for (int i = 1; i <= 10; i++) {
            try {
               // Thread.sleep(500);
             bufferClass.take();               
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}

Output

Output from one of the run. Note that output may vary but the condition of not having more than 5 elements and blocking any attempt to add should hold.

Adding - 1
Adding - 2
Adding - 3
Adding - 4
Adding - 5
Retrieving - 1
Retrieving - 2
Retrieving - 3
Retrieving - 4
Retrieving - 5
Adding - 6
Adding - 7
Adding - 8
Retrieving - 6
Retrieving - 7
Retrieving - 8
Adding - 9
Retrieving - 9
Adding - 10
Retrieving - 10

That's all for this topic How to Create Your Own BlockingQueue - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. ArrayBlockingQueue in Java Concurrency
  2. How to run threads in sequence - Java Program
  3. How to create deadlock in Java multi-threading - Java Program
  4. Print odd-even numbers using threads and wait-notify
  5. Producer-Consumer Java program using ArrayBlockingQueue

You may also like -

>>>Go to Java Programs page

Wednesday, 13 September 2017

Java Stream API Interview Questions

  1. What is Stream API in Java?

    Stream API is added in Java 8 and works very well in conjunction with lambda expressions. You can create a pipeline of stream operations to manipulate data by performing operations like search, filter, sort, count, map etc.

    Read more about Stream API in Java here.

  2. What is stream in Stream API?

    A stream can be visualized as a pipeline. A stream pipeline consists of a source (which might be an array, a collection, a generator function, an I/O channel, etc.), zero or more intermediate operations (which transform a stream into another stream, such as filter(Predicate)), and a terminal operation (which produces a result or side-effect, such as count() or forEach(Consumer)).

    Read more about Stream API in Java here.

  3. Explain stream operations with an example?

    In this example let's take an ArrayList as an input. There are two operations - take only those elements of the list which are greater than 5 and then sort the result. After that print the elements of the list.

    // Creating the list
    List<Integer> numList = Arrays.asList(34, 6, 3, 12, 65, 1, 8);
    numList.stream().filter((n) -> n > 5).sorted().forEach(System.out::println); 
    
    Here ArrayList is the data source for the stream and there are two intermediate operations –
    • filter - Filter condition here is; take only those elements of the list which are greater than 5.
    • sorted - sort that filtered output of the last stream.
    Terminal operation here is forEach statement (provided in Java 8) which iterates the sorted result and displays them. Read more about forEach statement in Java 8 here.

  4. How many types of Stream operations are there?

    Stream operations are divided into intermediate and terminal operations, and are combined to form stream pipelines.

    • Intermediate operations return a new stream. They are always lazy; executing an intermediate operation does not actually perform any filtering, but instead creates a new stream that, when traversed, contains the elements of the initial stream that match the given predicate.
    • Terminal operations such as Stream.forEach or IntStream.sum, may traverse the stream to produce a result or a side-effect. After the terminal operation is performed, the stream pipeline is considered consumed, and can no longer be used.
    See some Stream API examples here.

  5. What are Stateless and Stateful operations in Java stream?

    Intermediate operations are further divided into stateless and stateful operations.

    • Stateless operations, such as filter and map, retain no state from previously seen element when processing a new element, each element can be processed independently of operations on other elements.
    • Stateful operations, such as distinct and sorted, may incorporate state from previously seen elements when processing new elements. Stateful operations may need to process the entire input before producing a result. For example, one cannot produce any results from sorting a stream until one has seen all elements of the stream.
    See some Stream API examples here.

  6. What is Parallel Stream in Java Stream API?

    You can execute streams in serial or in parallel. When a stream executes in parallel, the Java runtime partitions the stream into multiple sub-streams.

    As example - Collection has methods Collection.stream() and Collection.parallelStream(), which produce sequential and parallel streams respectively.

    Read more about parallel stream here.

  7. What is the benefit of using parallel stream?

    When parallel stream is used the Java runtime partitions the stream into multiple sub-streams. This parallel execution of data, with each sub-stream running in a separate thread, will result in increase in performance.

    Read more about parallel stream here.

  8. Can you use streams with primitives?

    Streams work only on object references. They can’t work on primitive types so you have two options to use primitives.

    • You can wrap primitive types into a wrapper object. As example Stream<Integer>, Stream<Long> or Stream<Double>.
    • Second and better option is to use primitive specializations of Stream like IntStream, LongStream, and DoubleStream that can store primitive values.
    • As example - IntStream is = IntStream.of(3, 4, 5, 6);

    Read more about Primitive type streams in Java here.

  9. How can you transform Stream to primitive type Stream?

    Stream interface provides methods mapToInt, mapToDouble and mapToLong that can be used to transform stream of objects to a stream of primitive types.

    As example - If you have a list of employee objects and you want to get the maximum salary. In that case you can take the salary field and use mapToInt method to get a stream of primitive types. Then you can use max method on that primmitive type stream.

    OptionalInt maxSalary = empList.parallelStream().mapToInt(e -> e.getSalary()).max();
    
    Read more about Primitive type streams in Java Stream API here.

  10. What are Reduction Operations in Java Stream API?

    Stream API contains many terminal operations (such as average, sum, min, max, and count) that return one value by combining the contents of a stream. These operations are called reduction operations because these operations reduce the stream to a single non-stream value.

    Read more about Reduction Operations in Java Stream API here.

  11. What are Map operation in Java Stream API?

    Map operations are used to do the element mapping from one stream to another. Map operation will return a stream consisting of the results of applying the given function to the elements of this stream. So, whatever function is provided is applied on all the elements of the stream.

    Since new stream is returned map operation is an intermediate operation.

    Read more about Map operation in Java Stream API here.

  12. What is a mutable reduction operation?

    A mutable reduction operation can be defined as an operation that accumulates input elements into a mutable result container, such as a Collection or StringBuilder.

    Read more about Reduction operation in Java Stream API here.

  13. What is a collect method in Java stream?

    Using collect method you can store the result of the stream operation into a collection. This is a terminal operation.

    As example - If you have employee objects and you want a list having names of all the employees you can use the toList method of the Collectors class.

    List<String> nameList = empList.stream().map(Employee::getName).collect(Collectors.toList());
    
    Read more about Collecting in Java Stream API here.

  14. What is FlatMap in Java?

    In mapping operation the given function is applied to all the elements of the stream. Where as flattening a structure, means bringing all the nested structures at the same level.

    As example if you have a list of Strings, list<String> like - [[“a”, “b”, “c”], [“c”, “d”], [“c”, “e”, “f”]] then flattening it will bring everything to the same level and the structure you will have be like this -

    [“a”, “b”, “c”, “c”, “d”, “c”, “e”, “f”]
    
    Read more about FlatMap in Java here.

  15. What is FlatMap in Java?

    In mapping operation the given function is applied to all the elements of the stream. Where as flattening a structure, means bringing all the nested structures at the same level.

    As example if you have a list of Strings, list<String> like - [[“a”, “b”, “c”], [“c”, “d”], [“c”, “e”, “f”]] then flattening it will bring everything to the same level and the structure you will have be like this -

    [“a”, “b”, “c”, “c”, “d”, “c”, “e”, “f”]
    

    flatMap() method means you are bringing both of them together, function will be applied to all the elements of the stream and then it will be flatten to have a single level structure.

    Read more about FlatMap in Java here.

  16. What is Spliterator in Java??

    Spliterators, like iterators, are for traversing the elements of a source. Spliterator can split the source and iterate the splitted parts in parallel. That way a huge data source can be divided into small sized units that can be traversed and processed parallely.

    You can also use spliterator even if you are not using parallel execution.

    Read more about Spliterator in Java here.

Related Topics

  1. Java Exception Handling interview questions
  2. Java Multi-threading interview questions
  3. Java Collections interview questions
  4. Java Concurrency interview questions
  5. Java Lambda Expressions Interview Questions

Monday, 4 September 2017

How to read 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. A properties store data in a form of key/value pair.

In this tutorial you will see how to read a properties file.

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.

Steps

  1. Create an instance of Properties class.
  2. Read the properties file.
  3. Load the file to the instance of Properties class using the load method.

Content of the properties file

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

user=TestUser
url=https://netjs.blogspot.com

Loading properties file from the file system

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

Example code

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

public class PropDemo {
 private Properties appProp = 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");   
   appProp.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 - " + appProp.getProperty("user"));
    System.out.println("URL - " + appProp.getProperty("url"));
    // reading property which is not there
    System.out.println("City - " + appProp.getProperty("city"));
   
  }

}

Output

User name - TestUser
URL - https://netjs.blogspot.coms
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.

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

public class PropDemo {
 private Properties appProp = 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");
    }
    appProp.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 - " + appProp.getProperty("user"));
   System.out.println("URL - " + appProp.getProperty("url"));
 }
}

Output

User name - TestUser
URL - https://netjs.blogspot.com

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!


Related Topics

  1. How to read file from the last line in Java
  2. Unzipping files in Java
  3. Reading file in Java 8
  4. Writing file in Java
  5. How to read properties file in Spring Framework

You may also like -

>>>Go to Java Programs page