Monday, March 15, 2021

Java LinkedBlockingQueue With Examples

LinkedBlockingQueue in Java is an implementation of BlockingQueue interface. It is added in Java 5 along with other concurrent utilities like CyclicBarrier, Phaser, ConcurentHashMap, CopyOnWriteArraySet etc.

LinkedBlockingQueue in Java internally uses linked nodes to store elements. It is optionally bounded and that's where it differs from another implementation of BlockingQueue, ArrayBlockingQueue which is a bounded queue, another difference between the two is how elements are stored internally ArrayBlockingQueue uses array internally whereas LinkedBlockingQueue uses linked nodes. Since LinkedBlockingQueue is optionally bounded so it has both types of constructors

  • one where initial capacity can be passed thus making it bounded.
  • Or
  • without any capacity thus making it unbounded. Note that in case no initial capacity is defined capacity of LinkedBlockingQueue is Integer.MAX_VALUE.

How to Compile Java Program at Runtime

This post talks about how you can compile a java program at runtime. You may have a case where you get a Java file path by reading a property file and you need to compile and run that Java file or you may have a scenario where at run time a program file is created rather than some script which you need to compile and run.

In such cases you need to compile your code at run time from another Java program. It can be done using JavaCompiler interface and ToolProvider class. Note that these classes are provided from Java 6.

Also note that you will need JDK to run it not JRE, so you need to have JDK libraries not JRE. If you are using eclipse and your JRE System library is pointing to JRE path make sure it points to JDK. You can do that by right clicking on your project and going to Java Build Path through properties. There click on Libraries tab and select the JRE System Library which points to jre path and click Edit.

Wednesday, March 10, 2021

Difference Between CountDownLatch And CyclicBarrier in Java

Though both CountDownLatch and CyclicBarrier are used as a synchronization aid that allows one or more threads to wait but there are certain differences between them. Knowing those differences between CountDownLatch and CyclicBarrier in Java will help you to decide when one of these utilities will serve you better and of course it is a good java interview question too.

CountDownLatch Vs CyclicBarrier in Java

  1. One of the most important difference is When you are using a CountDownLatch, you specify the number of calls to the countdown() method when creating a CountDownLatch object. So a CountDownLatch initialized to N can be used to make one thread wait until N threads have completed some action, or some action has been completed N times.
    What this means is you can use CountDownLatch with only a single thread and using countdown() to decrement as and when the specified event occur.

    When you are using CyclicBarrier in Java you specify the number of threads that should call await() method in order to trip the barrier. That means if you have a CyclicBarrier initialized to 3 that means you should have at least 3 threads to call await().

Thursday, March 4, 2021

Matrix Multiplication Java Program

In this post we'll see a Java program to multiply two matrices which also gives you an idea about working with two dimensional arrays.

When you multiply two matrices with each other, you actually do a "dot product" of rows and columns. For example if you are multipying a 3X3 matrix with a 3X2 matrix-

matrix multiplication in Java
Matrix multiplication

The result you get can be explained as follows-

s11 = r11Xp11 + r12Xp21 + r13Xp31
s12 = r11Xp12 + r12Xp22 + r13Xp32
s21 = r21Xp11 + r22Xp21 + r23Xp31
s22 = r21Xp12 + r22Xp22 + r23Xp32
s31 = r31Xp11 + r32Xp21 + r33Xp31
s32 = r31Xp12 + r32Xp22 + r33Xp32

When you are writing a Java program to multiply two matrices-

You need an outer loop that will run as many times as there are rows in the first matrix.
Then you’ll have a second loop that will run as many times as the number of columns in the second matrix.
Then you’ll have a third loop that will run as many times as there are columns in the first matrix.

Also remember these points when multiplying one matrix with another-

  1. The number of columns of the first matrix is equal to the number of rows of the second matrix.
  2. The resultant matrix will have the same number of rows as in the first matrix and same number of columns as in the second matrix.

Matrix multiplication Java program

 
import java.util.Scanner;

public class MatixMultiplication {

  public static void main(String[] args) {
    int rowM1, colM1;
    int rowM2, colM2;
    
    Scanner in = new Scanner(System.in);
    System.out.print("Enter Number of Rows and Columns of First Matrix : ");
    rowM1 = in.nextInt();
    colM1 = in.nextInt();
    
    System.out.print("Enter elements of First Matrix : ");
    int M1[][] = new int[rowM1][colM1];
    for(int i = 0; i < rowM1; i++){
      for(int j = 0; j < colM1; j++){
        M1[i][j] = in.nextInt();
      }
    }
    System.out.println("First Matrix : " );
    for(int i = 0; i < rowM1; i++){
      for(int j = 0; j < colM1; j++){
        System.out.print(" " +M1[i][j]+"\t");
      }
      System.out.println();
    }
        
    System.out.print("Enter Number of Rows and Columns of Second Matrix : ");
    rowM2 = in.nextInt();
    colM2 = in.nextInt();
    if(colM1 != rowM2){
      throw new IllegalArgumentException("The number of columns of the first matrix should equal the number of rows of the second matrix.");
    }
    System.out.print("Enter elements of Second Matrix : ");
    int M2[][] = new int[rowM2][colM2];
    for(int i = 0; i < rowM2; i++){
      for(int j = 0; j < colM2; j++){
        M2[i][j] = in.nextInt();
      }
    }
    System.out.println("Second Matrix : " );
    for(int i = 0; i < rowM2; i++){
      for(int j = 0; j < colM2; j++){
        System.out.print(" " +M2[i][j] + "\t");
      }
      System.out.println();
    }
    //same number of rows as in the first matrix and 
    //same number of columns as in the second matrix
    int resMatrix[][] = new int[rowM1][colM2];
    int sum = 0;
    int row = 0;
    for(int i = 0; i < rowM1; i++){
      for(int j = 0; j < colM2; j++){
        sum = 0;
        for(int k = 0; k < colM1; k++){
          sum = sum + M1[i][k] * M2[k][j];
        }
        resMatrix[i][j] = sum;
      }
    }
        
    System.out.println("Result Matrix : " );
    for(int i = 0; i < resMatrix.length; i++){
      for(int j = 0; j < colM2; j++){
        System.out.print(" " +resMatrix[i][j]+"\t");
      }
      System.out.println();
    }
  }
}

Output

 
Enter Number of Rows and Columns of First Matrix : 2
3
Enter elements of First Matrix : 1
2
3
4
5
6
First Matrix : 
 1  2  3 
 4  5  6 
Enter Number of Rows and Columns of Second Matrix : 3
2
Enter elements of Second Matrix : 7
8
9
10
11
12
Second Matrix : 
 7   8 
 9   10 
 11  12 
Result Matrix : 
 58   64 
 139  154 

That's all for this topic Matrix Multiplication Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Array in Java With Examples
  2. Matrix Subtraction Java Program
  3. Find Maximum And Minimum Numbers in a Given Matrix Java Program
  4. Find Duplicate Elements in an Array Java Program
  5. Check Given Strings Anagram or Not Java Program

You may also like-

  1. How to Display Pyramid Patterns in Java - Part1
  2. How to Convert String to Date in Java
  3. Java Program to Convert a File to Byte Array
  4. Print Odd-Even Numbers Using Threads And wait-notify Java Program
  5. Marker interface in Java
  6. Switch Case Statement in Java With Examples
  7. String in Java Tutorial
  8. Dependency Injection in Spring Framework

Wednesday, March 3, 2021

Check Given Strings Anagram or Not Java Program

Write a Java program to check whether the given strings are anagrams or not is a frequently asked Java interview question. Some other frequently asked Java programs are counting chars in a string and given string is a palindrome or not.

What is anagram

Before going into the Java code for checking whether the given strings are anagaram or not let's first see what exactly is Anagram.

Two strings are called anagram if you can rearrange the letters of one string to produce the second string, using all the letters of the first string only once. While doing that, usually, you don't consider spaces and punctuation marks.

Some Examples- "keep" and "peek", "School Master" and "The Classroom".

Logic for Anagram program

Java program to check whether the given strings are anagrams or not can be written by-

  • Sorting both the strings
  • or
  • By iterating one of the string char by char and making sure that the second string has the same character present

Tuesday, March 2, 2021

Reading File in Java Using Scanner

Though reading file using BufferedReader remains one of the most used way to read a file in Java but there are other ways too like using Scanner class. This post shows how you can read a file in Java using Scanner class.

Scanner is used widely to read input from console as it has a constructor which takes InputStream as argument. But it also has a constructor which takes File as argument and also has methods hasNextLine() and nextLine() to find if there is another line of input and reading the line from input respectively. Using that constructor you can read a file in Java using Scanner.

One other benefit of using Scanner is that it has a useDelimiter() method, using this method file delimiter can be set thus making Scanner a good choice for reading and parsing CSV, tab delimited or pipe symbol separated files in Java.

Monday, March 1, 2021

Association, Aggregation And Composition in Java

When you model a system you can see that most of the classes collaborate with each other in many ways. In object-oriented modelling there are broadly three kind of relationships.

  1. Dependencies
  2. Generalizations
  3. Associations
This post is about association and two types of associations:
  • Aggregation
  • Composition

Many people get confused about these terms so I’ll try to define Association, Aggregation and composition with Java examples, how these terms relate to each other and what are the differences among Association, Aggregation and Composition.