Core java – Java2Blog https://java2blog.com A blog on Java, Python and C++ programming languages Thu, 26 Feb 2026 05:40:17 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.9 https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2022/09/cropped-ICON_LOGO_TRANSPARENT-32x32.png&nocache=1 Core java – Java2Blog https://java2blog.com 32 32 About US https://java2blog.com/about-us/?utm_source=rss&utm_medium=rss&utm_campaign=about-us https://java2blog.com/about-us/#respond Tue, 02 Sep 2025 05:58:49 +0000 https://java2blog.com/?p=26469 Welcome to Java2Blog – your go-to place for learning, exploring, and solving problems.

What started as a passion for sharing my knowledge of Java and Python has now grown into a platform that reaches thousands of readers every month. From in-depth programming tutorials to simple "how-to" guides, Java2Blog is here to help you learn step by step—whether you’re a beginner or an experienced developer looking to sharpen your skills.

But Java2Blog isn’t just about programming. Over time, the blog has expanded into guides, tips, and tutorials across a wide range of topics that make life easier for learners, tech enthusiasts, and problem-solvers alike.

At its core, Java2Blog is built on three principles:

  • Clarity : breaking down complex topics into easy-to-understand language.
  • Practicality : focusing on real-world use cases and solutions.
  • Community : helping people from all backgrounds gain the confidence to learn and grow.

If you’re ready to start learning, improving, or just exploring something new—you’re in the right place.

]]>
https://java2blog.com/about-us/feed/ 0
Count Files in Directory in Java https://java2blog.com/count-files-in-directory-java/?utm_source=rss&utm_medium=rss&utm_campaign=count-files-in-directory-java https://java2blog.com/count-files-in-directory-java/#respond Tue, 14 Feb 2023 08:02:07 +0000 https://java2blog.com/?p=22457 Using java.io.File Class

Before moving forwards, it is important to know the available items in the current directory. You may also create the same structure to follow along with this article. Our current directory (E:\Test) has the following structure:

  • E:\Test – It has seven items, four text files and three folders (FolderA, FolderB, FolderC, File1.txt, File2.txt, File3.txt, and File4.txt).
  • E:\Test\FolderA – It contains four text files ( File1.txt, File2.txt, File3.txt, and File4.txt).
  • E:\Test\FolderB – It has two text files (File1.txt and File2.txt).
  • E:\Test\FolderC – Only one text file lives here (File1.txt).

Use File.listFiles() Method

We can use File.listFiles() method in the following four scenarios:

  1. To count files in the current directory, excluding sub-directories.
  2. To count files in the current directory, including sub-directories.
  3. To count files and folders in the current directory, excluding sub-directories.
  4. To count files and folders in the current directory, including sub-directories.

Note that the code will be similar to one another for all the above situations except for small changes. So, we will thoroughly learn the first code example and later only discuss the part different from the previous one. So, let’s start with the first example code below.

Count Files in the Current Directory (Excluding Sub-directories)

To count files in the current directory, excluding sub-directories:

  • Instantiate the File class by specifying the directory.
  • Call a function we defined to count the files only in the current parent directory.
  • Inside the function, we invoked in the previous step, use a for loop to iterate over all items in the specified directory.
  • Use the if statement to check whether it is a file. If it is, increment the counter by 1; otherwise, move to the next iteration.
import java.io.File;
import java.io.IOException;

public class CountFilesInDirectory {
    public static void main(String[] args) throws IOException {
        File directory = new File("E:\\Test");
        int fileCount = countFilesInCurrentDirectory(directory);
        System.out.println("Number of Files:" + fileCount);
    }

    public static int countFilesInCurrentDirectory(File directory) {
      int count = 0;
      for (File file: directory.listFiles()) {
          if (file.isFile()) {
              count++;
          }
      }
      return count;
   }
}
Number of Files:4

In the main method of the CountFilesInDirectory class, we created an object of the File class (instantiated the File class) by specifying an E:\Test directory and saved its reference in directory variable.

Next, we called the countFilesInCurrentDirectory() method and passed the File object named directory we created in the previous step. On successful execution of this method, it returned a file counter that we saved in the fileCount variable. So, let’s see how this method counts the files.

The countFilesInCurrentDirectory() is a static method defined in the CountFilesInDirectory class to count files in the provided directory. We declared and initialized a count variable used to maintain a file counter inside this function.

Next, we used a for loop with the listFiles() method to iterate over every item in the specified directory. We used the if statement with the isFile() function for each iteration to check whether the current item is a file. We incremented the count variable by 1 if the if condition is fulfilled; otherwise, we moved to the next iteration.

Once the loop was over, we returned the count variable, whose value will be saved in the fileCount variable, which will be used to print a message on the console using the System.out.println() method.

Now, the point is what the listFiles() and isFile() methods are doing here. The listFiles() is one of the methods of the File class, which returns an array of abstract pathnames representing the directories and files in the specified directory denoted by this abstract pathname which satisfies the given filter (if any).

Remember, we will only get an array of files if the given path is a directory; otherwise, it will generate a java.lang.NullPointerException exception and return null.

The listFiles() method is an overloaded method, which means we can use it in the following three ways where the first method does not take any parameter, the second accepts the FilenameFilter object, and the third takes FileFilter object as their parameters (we used the first method in our code above).

public File[] listFiles()
public File[] listFiles(FilenameFilter filter)
public File[] listFiles(FileFilter filter)

Moving to the next method, which is isFile(). It is also a method of the File class, used to check whether the file represented by an abstract pathname is the normal file. This function returns a Boolean value, True if the current item is a file; otherwise, False.

Count Files in the Current Directory (Including Sub-directories)

import java.io.File;
import java.io.IOException;

public class CountFilesInDirectory {
    public static void main(String[] args) throws IOException {
        File directory = new File("E:\\Test");
        int fileCount = countFilesInDirectory(directory);
        System.out.println("Number of Files:" + fileCount);
    }

    public static int countFilesInDirectory(File directory) {
      int count = 0;
      for (File file: directory.listFiles()) {
          if (file.isFile()) {
              count++;
          }

          if (file.isDirectory()) {
              count += countFilesInDirectory(file);
          }
      }
      return count;
    }
}
Number of Files:11

This code example is the same, but we added another if statement inside the for loop in the countFilesInDirectory() method (line 19 to line 21). This if statement used the isDirectory() method to check whether the current item is a directory.

Like the isFile() method, it also returned a Boolean value, True if the condition is satisfied; otherwise, False. If the condition is fulfilled, the countFilesInDirectory() method calls a copy of itself, getting the current item (a directory) as a parameter.

NOTE: We used recursion here because countFilesInDirectory() method is calling a copy of itself.

Count Files & Folders in Current Directory (Excluding Sub-directories)

import java.io.File;
import java.io.IOException;

public class CountFilesInDirectory {
    public static void main(String[] args) throws IOException {
        File directory = new File("E:\\Test");
        int fileCount = countFilesInDirectory(directory);
        System.out.println("Number of Files:" + fileCount);
    }

    public static int countFilesInDirectory(File directory) {
      int count = 0;
      for (File file: directory.listFiles()) {
          count++;
      }
      return count;
  }
}
Number of Files:7

Inside the for loop in the countFilesInDirectory() method, we removed both if statements to count files and folders from the current parent directory. Note that we are still incrementing the count variable by 1 in each iteration. For example, we got 7 because E:\Test contains four text files and three folders (FolderA, FolderB, FolderC, File1.txt, File2.txt, File3.txt, and File4.txt).

Count Files & Folders in Current Directory (Including Sub-directories)

import java.io.File;
import java.io.IOException;

public class CountFilesInDirectory {
    public static void main(String[] args) throws IOException {
        File directory = new File("E:\\Test");
        int fileCount = countFilesInDirectory(directory);
        System.out.println("Number of Files:" + fileCount);
    }

    public static int countFilesInDirectory(File directory) {
      int count = 0;
      for (File file: directory.listFiles()) {
          count++
          if (file.isDirectory()) {
              count += countFilesInDirectory(file);
          }
      }
      return count;
  }
}
Number of Files:14

This code is similar to the immediate previous example. But, we have an if statement in the for loop (line 16 to line 18), which assesses if the current item is a directory or not using the isDirectory() method.

If it is, we also used recursion to count files in that directory. You can compare the above output by looking at the directory structure given at the beginning of this article.

If you are not concerned about sub-directories and only want to count files and folders in the current parent directory, then we can use the most straightforward solution using the File.list() method.

Use File.list() Method

To count files and folders in the current parent directory, excluding sub-directories:

  • Create an object of the File class by passing a directory as an argument.
  • Use the .list() method to get a String-type array containing filenames (files and folders).
  • Use the .length property of the String type array (received from the previous step) to get a count of the array elements.
import java.io.File;

public class CountFilesInDirectory {
    public static void main(String[] args) {
        File directory = new File("E:\\Test");
        String[] fileArray = directory.list();
        int fileCount = fileArray.length;
        System.out.println("Number of Files:" + fileCount);
    }
}
Number of Files:7

The above code fence is similar to the previous code examples except for one difference; we used the .list() method here. After instantiating the File class, we used the .list() method to get an array of strings with filenames (files and directories) in the directory represented by this abstract pathname.

We saved this array in the fileArray variable; after that, we accessed the .length property of the fileArray array to know the count of elements in it, which we used to print a message on the console using println() method.

We can also replace line 7 with File[] fileArray = directory.listFiles(); and get the same results. Now, the question is, how does the File.list() method differ from File.listFiles()? Both methods essentially do the same but:

  • File.list() method returns a String array containing filenames (directories and files).
  • File.listFiles() returns an array of the File class of the same.

Now, where to choose which method? We must choose between these two methods wherever we are concerned about speed and memory consumption. Usually, a String array (returned by File.list()) would be faster and consume less memory as compared to the File array (returned by File.listFiles()). To dive into more details, you can check this page.

Using java.nio.file.DirectoryStream Class

The StreamAPI approach is useful when we:

  • Do not want to use the Java.io.File class.
  • Look for a solution using fewer resources while working with large directories.
  • More responsive while working with remote directories.

In this article, we are using the DirectorySteam class to do the following:

  1. To count files in the current directory, excluding sub-directories.
  2. To count files in the current directory, including sub-directories.
  3. To count files and folders in the current directory, excluding sub-directories.
  4. To count files and folders in the current directory, including sub-directories.

Again, the code sample will be similar to one another for all the above scenarios so that we will learn each step for the first example code, later, will explain the newly added piece of code only.

Count Files in the Current Directory (Excluding Sub-directories)

To count files in the current directory, excluding sub-directories:

  • Create an ArrayList of Strings.
  • Create a directory stream to access the contents of the given directory.
  • Use the for loop to iterate over the directory steam created in the previous step.
  • For every iteration of the for loop, use the if to check if the current item is not a directory. If not, use the .add method to add the current string item to ArrayList.
  • Use the .size() method to get the size of the ArrayList.
  • Use the try-catch method to handle exceptions.
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class CountFilesInDirectory {

    public static void main(String[] args) {
        List<String> fileNames = new ArrayList<>();

        try {
            DirectoryStream<Path> directoryStream = Files
                .newDirectoryStream(Paths.get("E:\\Test"));

            for (Path path: directoryStream) {    
                if(!Files.isDirectory(path))
                    fileNames.add(path.toString());
            }
        } catch (IOException exception){
            exception.printStackTrace();
        }
        System.out.println("Number of Files:" + fileNames.size());
    }
}
Number of Files:4

Inside the main method of the CountFilesInDirectory class, we created a new ArrayList of Strings called fileNames. The ArrayList is a class in Java that implements the List interface and provides an array-like data structure for storing elements. The diamond operator is a shorthand notation specifying the type of elements the ArrayList will hold. In this case, it is a list of Strings.

Inside the try block, we created a new DirectoryStream called directoryStream that was used to access the directory’s contents. Note that the DirectoryStream is of type Path. The Files.newDirectoryStream method created a new directory stream bound to the specified directory. Here, the Paths.get("E:\\Test") was used to obtain a Path object representing the file system directory E:\Test.

Next, we used a for loop to iterate over each element in the directoryStream object and assigned it to the variable path of type Path. For each iteration, we checked if the path is not a directory by calling the Files.isDirectory(path) method in the if statement; if it is not a directory, it will add the path to the fileNames list. Finally, the path.toString() method was used to get the string representation of the path.

The for loop was used to iterate over the contents of the directory and only added the file names to the fileNames list, not the directory names.

Here, if the try block generates the IOException (a type of exception thrown when an input/output operation fails), the catch block will be executed. The exception.printStackTrace() method was called inside the catch block, which printed the stack trace of the exception to the console. The stack trace shows the sequence of method calls that led to the exception, which can be helpful for debugging.

Finally, we used the .size() method to get the size of the fileNames list and print it on the console.

Count Files in the Current Directory (Including Sub-directories)

import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class CountFilesInDirectory {

    public static void main(String[] args) {
        List<String> fileNames = new ArrayList<>();

        try {
            DirectoryStream<Path> directoryStream = Files
                .newDirectoryStream(Paths.get("E:\\Test"));

            for (Path path: directoryStream) {
                if(Files.isDirectory(path)){
                    DirectoryStream<Path> subDirectoryStream = Files
                          .newDirectoryStream(Paths.get(path.toString()));
                    for (Path p: subDirectoryStream)
                        fileNames.add(p.toString());
                }
                else{
                    fileNames.add(path.toString());
                }
            }
        } catch (IOException exception){
            exception.printStackTrace();
        }

        System.out.println("Number of Files:" + fileNames.size());
    }
}
Number of Files:11

This code is similar to the immediate previous example, but we replaced the following

if(!Files.isDirectory(path))
  fileNames.add(path.toString());

with

if(Files.isDirectory(path)){
    DirectoryStream<Path> subDirectoryStream = Files
        .newDirectoryStream(Paths.get(path.toString()));
    for (Path p: subDirectoryStream)
         fileNames.add(p.toString());
}
else{
    fileNames.add(path.toString());
}

inside the for loop. We did so to check if the current path is a directory or not using the Files.isDirectory(path) method. If it is a directory, we created a new subDirectoryStream using Files.newDirectoryStream(Paths.get(path.toString())), which was used to access the contents/items of the sub-directory represented by the current path.

Next, we iterated over each element in the subDirectoryStream object and assigned it to the variable p of type Path and added the path to the fileNames list using the .add() method. On the other hand, in the else part, we directly added the path to fileNames.

Note that this code was used to recursively iterate over the contents of the directory/subdirectories and add the file names to the fileNames list, not the directory names.

Count Files & Folders in the Current Directory (Excluding Sub-directories)

import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class CountFilesInDirectory {

    public static void main(String[] args) {
        List<String> fileNames = new ArrayList<>();

        try {
            DirectoryStream<Path> directoryStream = Files
                .newDirectoryStream(Paths.get("E:\\Test"));

            for (Path path: directoryStream) {
                fileNames.add(path.toString());
            }
        } catch (IOException exception){
            exception.printStackTrace();
        }

        System.out.println("Number of Files:" + fileNames.size());
    }
}
Number of Files:7

For this code, we removed all the conditionals from the for loop located in the main method to count files and folders from the current parent directory.

Count Files & Folders in the Current Directory (Including Sub-directories)

import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class CountFilesInDirectory {

    public static void main(String[] args) {
        List<String> fileNames = new ArrayList<>();

        try {
            DirectoryStream<Path> directoryStream = Files
                .newDirectoryStream(Paths.get("E:\\Test"));

            for (Path path: directoryStream) {
                fileNames.add(path.toString());
                if(Files.isDirectory(path)){
                    DirectoryStream<Path> subDirectoryStream = Files
                          .newDirectoryStream(Paths.get(path.toString()));
                    for (Path p: subDirectoryStream)
                        fileNames.add(p.toString());
                }
            }
        } catch (IOException exception){
            exception.printStackTrace();
        }

        System.out.println("Number of Files:" + fileNames.size());
    }
}
Number of Files:14

This code is similar to the code where we were counting files in the current directory, including sub-directories; here, we eliminated the else block to count files and folders from the current directory/sub-directories.’

That’s all about how to count files in Directory in Java.

]]>
https://java2blog.com/count-files-in-directory-java/feed/ 0
Convert System.nanoTime to Seconds in Java https://java2blog.com/convert-system-nanotime-to-seconds-java/?utm_source=rss&utm_medium=rss&utm_campaign=convert-system-nanotime-to-seconds-java https://java2blog.com/convert-system-nanotime-to-seconds-java/#respond Wed, 21 Dec 2022 13:06:03 +0000 https://java2blog.com/?p=21715 1. Introduction

In this article, we will look into How to Convert System.nanoTime() to Seconds in Java. We will look at different solutions to this problem in detail with working examples. Let us first have a quick look into the System.nanoTime() method in Java.

2. System.nanoTime() Method

The System.nanoTime() method is a static method of the System class and it gives the current value of the JVM’s most precise or high-resolution time source in nanoseconds. The value returned is of very high precision around 1/1000000th of a second.

The syntax of the method:

public static long nanoTime()

It returns the value of type Long. It is not thread-safe, the accuracy decreases if used between more than two threads.

Now, we outline different ways to Convert System.nanoTime() to Seconds in Java.

3. Dividing the System.nanoTime() with a Constant Value

To convert System.nanoTime to Seconds, we can divide the nanoseconds value returned by the nanoTime() method with a constant value of  1_000_000_000, this division will give the resultant value including decimals which must be typecasted to type double.

Let us look into the code.

public class ConvertNanotimeToSeconds{

    public static void main(String[] args) {
    // get current system timestamp in nanoseconds
    long nanoSeconds = System.nanoTime();
    System.out.println("The current system timestamp in nanoseconds: "+nanoSeconds+"\n");

    // divide to seconds and typecast to double
    double seconds = (double) nanoSeconds/1_000_000_000;
    System.out.println("The current system timestamp in seconds: "+seconds);

 }   
}

Output:

The current system timestamp in nanoseconds: 2343310746135100

The current system timestamp in seconds: 2343310.7461351

4. Using the convert() Method of TimeUnit Class in Java

The TimeUnit class in Java represents time durations at a given unit and provides useful utility methods to convert across these units. It allows conversions to  Minutes , Seconds, Milliseconds, Nanoseconds and other units. It provides the convert() method that different durations across these time units.

The syntax of method:

public long convert(long sourceDuration, TimeUnit sourceUnit)

  • Use the Static reference to the TimeUnit class to convert the System.nanoTime() and specify the timeunit to convert in this case we provide it as : SECONDS.
  • Pass sourceDuration as System.nanoTime() to convert() method.
  • Pass sourceUnit as TimeUnit.NANOSECONDS as SourceDuration is in Nano seconds Timeunit.

Let us look at the implementation in code.

import java.util.concurrent.TimeUnit;

public class ConvertNanotimeToSeconds{
 
    public static void main(String[] args) {
    // get current system timestamp in nanoseconds
    long nanoSeconds = System.nanoTime();
    System.out.println("The current system timestamp in nanoseconds: "+nanoSeconds+"\n");
    
    // Use TimeUnit.SECONDS to convert in seconds.
    long seconds = TimeUnit.SECONDS.convert(nanoSeconds, TimeUnit.NANOSECONDS);
    System.out.println("The current system timestamp in seconds: "+seconds);
    
 }   

}

Output:

The current system timestamp in nanoseconds: 2463358120387600

The current system timestamp in seconds: 2463358

In order to obtain a high precision value than integer, we can convert this value to type double to get higher precision up to 3 decimal places.

  • In such case we need to get this value in format TimeUnit.MILLISECONDS.
  • Then divide the value by 1000.0 to convert it into seconds and get the value with precision of up to 3 decimal places.

Let us look at the code snippet.

import java.util.concurrent.TimeUnit;

public class ConvertNanotimeToSeconds{
 
    public static void main(String[] args) {
    // get current system timestamp in nanoseconds
    long nanoSeconds = System.nanoTime();
    System.out.println("The current system timestamp in nanoseconds: "+nanoSeconds+"\n");
    
    // Use TimeUnit.MILLISECONDS and divide by 1000.0 to convert in seconds.
    double seconds = TimeUnit.MILLISECONDS.convert(nanoSeconds, TimeUnit.NANOSECONDS)/1000.0;
    System.out.println("The current system timestamp in seconds: "+seconds);
    
 }   

}

Output:

The current system timestamp in nanoseconds: 2503502543334700

The current system timestamp in seconds: 2503502.543

5. Using the toSeconds() Method of TimeUnit Class in Java

The TimeUnit class also provides the toSeconds() method that converts a given time duration unit to seconds. In order to convert the value, we need to specify the type of Source Time duration for e.g. NANOSECONDS , MILLISECONDS, etc.

The syntax of the method:

public long toSeconds(long duration)

Let us look into the code.

import java.util.concurrent.TimeUnit;

public class ConvertNanotimeToSeconds{
 
    public static void main(String[] args) {
    // get current system timestamp in nanoseconds
    long nanoSeconds = System.nanoTime();
    System.out.println("The current system timestamp in nanoseconds: "+nanoSeconds+"\n");
    
    // use the toSeconds() method and specify the source type of argument.
    long seconds = TimeUnit.NANOSECONDS.toSeconds(nanoSeconds);
    System.out.println("The current system timestamp in seconds: "+seconds);
        
 }   

}

Output:

The current system timestamp in nanoseconds: 2510279744152400

The current system timestamp in seconds: 2510279

6. Using the Utility Methods of Duration Class in Java

With the advent of Java 9, the Duration class was modified and some new features were introduced, this class models a unit of time in terms of seconds and nanoseconds and provides useful and common utility methods to perform operation on these time units.

It is present in java.time package library. Here, we can use the utility methods of these class to Convert System.nanoTime() to seconds.

  • The Duration class provides the getSeconds() method and toSeconds() method respectively to convert a time unit to its equivalent value in seconds.
  • Use the ofNanos() method of the Duration class to specify our time unit to be in format of Nanoseconds and pass the System.nanotime() as a argument to this method.

The syntax of the methods :

public long getSeconds()

public long toSeconds​()

Let us look at the implementation of this approach in code.

import java.time.Duration;

public class ConvertNanotimeToSeconds{
 
    public static void main(String[] args) {
    // get current system timestamp in nanoseconds
    long nanoSeconds = System.nanoTime();
    System.out.println("The current system timestamp in nanoseconds: "+nanoSeconds+"\n");
    
    // use the toSeconds() method and ofNanos() to specify Nanoseconds unit
    long seconds1 = Duration.ofNanos(nanoSeconds).toSeconds();
    System.out.println("The current system timestamp in seconds using toSeconds() method: "+seconds1+"\n");
    
    // use the getSeconds() method
    long seconds2 = Duration.ofNanos(nanoSeconds).getSeconds();
    System.out.println("The current system timestamp in seconds using getSeconds() method: "+seconds2+"\n");
        
 }   

}

Output:

The current system timestamp in nanoseconds: 2514023646228500

The current system timestamp in seconds using toSeconds() method: 2514023

The current system timestamp in seconds using getSeconds() method: 2514023

7. Conclusion

We listed 4 different ways on How to Convert System.nanoTime() to Seconds in Java in detail with working examples. You can try them out with code in your Local IDE for a clear understanding.

Feel free to reach out to us for any queries/suggestions.

]]>
https://java2blog.com/convert-system-nanotime-to-seconds-java/feed/ 0
Update Value of Key in HashMap in Java https://java2blog.com/update-value-of-key-hashmap-java/?utm_source=rss&utm_medium=rss&utm_campaign=update-value-of-key-hashmap-java https://java2blog.com/update-value-of-key-hashmap-java/#respond Tue, 06 Dec 2022 13:03:54 +0000 https://java2blog.com/?p=21284 In this article, we will look at How to Update the Value of a Key in HashMap in Java. We will look at different solutions to this problem in detail with working examples.

It is recommended to learn about the concept of collections particularly HashMaps in Java and their working for a seamless understanding. Now, we outline different ways How to Update the Value of a Key in HashMap in Java. These approaches would also work for different maps like TreeMap, LinkedHashMap, etc.

Using the put() Method of HashMap Collection in Java

We can use the conventional put() method of HashMap collection to update a specific key. To use this method the key must be present within the HashMap but can also be modified for the default case.

Essential points :

  • In a HashMap of Integer values, either directly put the value for a key or get the existing value for the key using the getKey() method and increment/decrement the value.
  • If a key is not present and to avoid a Null-Pointer Exception use the getOrDefault() method to update the key, if it is not present assign a default value.

Let us look at the code.

import java.util.HashMap;

public class UpdateHashMapKeyUsingPut {
 
    public static void main(String[] args) {
     
    //Create HashMap of String keys and Integer values.
    HashMap<String,Integer> hm = new HashMap<String,Integer>();
		
    hm.put("Adam", 1);
    hm.put("Steve", 2);
    hm.put("James", 3);
    hm.put("Amanda", 4);
    hm.put("Carol", 5);
	
    System.out.println("HashMap before Update : "+hm);
	
    // Update key and assign new value.
    hm.put("James", 6);
	
    // Update key by incrementing its past value.
    hm.put("Steve",hm.get("Steve") + 1);
	
    // Update key with getOrDefault
    // Assigns default value : 7 if key is not present
    hm.put("Jones", hm.getOrDefault("Jones", 7));
	
    // If key present increment original value by 1. 
    hm.put("Carol", hm.getOrDefault("Carol", 7) + 1);
	
    System.out.println("HashMap after Update : "+hm);
	
    }
}

Output:

HashMap before Update : {Adam=1, Steve=2, James=3, Carol=5, Amanda=4}
HashMap after Update : {Adam=1, Jones=7, Steve=3, James=6, Carol=6, Amanda=4}

Using the compute() Method of HashMap Collection in Java

The HashMap collection provides the compute() method that is useful in computing the key and values of a HashMap based on a BiFunction. We will understand this with some examples.

The syntax of the method:

default V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)

The method commonly accepts two parameters:

  • The Key to update.
  • The Remapping function or BiFunction – To compute the value of the Key.

Example

The method declaration : compute(“John”, (key, value) -> value + 1) 

  • Gets the value of key “John” and updates the key by incrementing the original value by 1.

Similarly, the method declaration : compute(“John”, (key, value) -> (value == null) ? 1 : value + 1

  • Checks if the value of key “John” is present and assign a default value of 1  if the key is absent.

Let us look at the implementation of these examples in code.

import java.util.HashMap;

public class UpdateHashMapKeyUsingCompute {
 
    public static void main(String[] args) {
     
    //Create HashMap of String keys and Integer values.
    HashMap<String,Integer> hm = new HashMap<String,Integer>();
		
    hm.put("Adam", 1);
    hm.put("Steve", 2);
    hm.put("James", 3);
    hm.put("Amanda", 4);
    hm.put("Carol", 5);
	
    System.out.println("HashMap before Update : "+hm);
	
    // Remap value using compute() method.
    // If key is present increment value.
    hm.compute("James", (key,value) -> value + 1);
	
    // If key absent assigns a default value
    hm.compute("Angel", (key,value) -> (value == null) ? 1 : value + 1);
	
    System.out.println("HashMap after Update : "+hm);
	
    }
}

Output:

HashMap before Update : {Adam=1, Steve=2, James=3, Carol=5, Amanda=4}
HashMap after Update : {Adam=1, Steve=2, James=4, Angel=1, Carol=5, Amanda=4}

Using the merge() Method of the HashMap Collection in Java

The merge() method of HashMap is basically used to merge two HashMaps based on Mapping criteria. However, we can also use this to Update the Value of a Key in HashMap. We will understand with some examples.

The syntax of the method:

public V merge(K key, V value, BiFunction remappingFunction)

The method accepts three parameters:

  • Key to update.
  • Value: Here, it corresponds to the default value for the key if absent.
  • Re-Mapping or BiFunction: To compute the value of the key based on the rule and the default Value

Example:

The method declaration: merge((“Steve”,  2, (v1, v2) -> v1 + v2))

  • Updates the value of the Key “Steve” with 4 as rule v1 + v2 with the default value of 2 gives result 4.
  • If the Key is absent, it creates the Key “Steve” and assigns a default value of 2

Let us look at the code.

import java.util.HashMap;

public class UpdateHashMapKeyUsingMerge {
 
    public static void main(String[] args) {
     
    //Create HashMap of String keys and Integer values.
    HashMap<String,Integer> hm = new HashMap<String,Integer>();
		
    hm.put("Adam", 1);
    hm.put("Steve", 2);
    hm.put("James", 3);
    hm.put("Amanda", 4);
    hm.put("Carol", 5);
	
    System.out.println("HashMap before Update : "+hm);
    System.out.println();
	
    // Remap value using merge() method.
    // If key is present calculate new value based on rule
    hm.merge("Steve", 2, (v1, v2) -> v1 + v2);
	
    // If key absent assign default value.
    hm.merge("Stark", 2, (v1, v2) -> v1 + v2);
	
    System.out.println("HashMap after Update : "+hm);
	
    }
}

Output:

HashMap before Update : {Adam=1, Steve=2, James=3, Carol=5, Amanda=4}

HashMap after Update : {Adam=1, Steve=4, James=3, Carol=5, Stark=2, Amanda=4}

Using the computeIfPresent() Method of The HashMap Collection in Java

The computeIfPresent() method of the HashMap follows the same resemblance to the compute() method in working aspects as discussed above. We can use it to Update the Value of a Key in HashMap. We will understand with some examples.

The syntax of the method:

public Object computeIfPresent(Object key, BiFunction remappingFunction)

The computeIfPresent method() accepts the same parameters with their type as in the compute() method. The only catch is for this method to work the Key must be present within the HashMap.

Example

The method declaration : computeIfPresent(“John”, (key,value) -> value + 1)

  • Updates the Key “John” only if it is present and increments the associated value by 1. If key is not present no update is done and no Errors/Exceptions are thrown.

Let us look at the code snippet.

import java.util.HashMap;

public class UpdateHashMapKeyUsingComputeIfPresent {
 
    public static void main(String[] args) {
     
    //Create HashMap of String keys and Integer values.
    HashMap<String,Integer> hm = new HashMap<String,Integer>();
		
    hm.put("Adam", 1);
    hm.put("Steve", 2);
    hm.put("James", 3);
    hm.put("Amanda", 4);
    hm.put("Carol", 5);
	
    System.out.println("HashMap before Update : "+hm);
    System.out.println();
	
    // Remap value using computeIfPresent() method.
    // Increments value by 2 only if key present
    hm.computeIfPresent("Steve", (key,value) -> value + 2);
	
    System.out.println("HashMap after Update : "+hm);
	
    }
}

Output:

HashMap before Update : {Adam=1, Steve=2, James=3, Carol=5, Amanda=4}

HashMap after Update : {Adam=1, Steve=4, James=3, Carol=5, Amanda=4}

Using the replace() Method of The HashMap Collection in Java

The replace() method of the Map interface implemented by the HashMap class is used to replace the value of a given key and Update the Key of the HashMap. The syntax of the method:

public V replace(K key, V value)

The replace() method has another variant where we specify the old and new values and then update the Map by replacing them. The syntax :

public boolean replace(K key, V oldValue, V newValue)

Let us look at the implementation in the code.

import java.util.HashMap;

public class UpdateHashMapKeyUsingReplace {
 
    public static void main(String[] args) {
     
    //Create HashMap of String keys and Integer values.
    HashMap<String,String> hm = new HashMap<String,String>();
		
    hm.put("Adam", "Computers");
    hm.put("Steve", "Accounts");
    hm.put("James", "Finance");
    hm.put("Amanda", "Admin");
    hm.put("Carol", "Finance");
	
    System.out.println("HashMap before Update : "+hm);
    System.out.println();
	
    // Direct replace value using replace() method
    hm.replace("Adam", "Developer");
	
    // Updating key value by concating strings
    hm.replace("Carol", hm.get("Carol").concat(" & Computers"));
	
    // Specifying old and new values to Update
    hm.replace("James", "Accounts", "Finance");
	
    System.out.println("HashMap after Update : "+hm);
	
    }
}

Output:

HashMap before Update : {Adam=Computers, Steve=Accounts, James=Finance, Carol=Finance, Amanda=Admin}

HashMap after Update : {Adam=Developer, Steve=Accounts, James=Finance, Carol=Finance & Computers, Amanda=Admin}

Using the TObjectIntHashMap Class of Gnu.Trove Package in Java

The gnu.trove package provides powerful and reusable components as dependencies that we can embed into our applications and programs. Here, to update the Value of a Key in HashMap we use the map library inbuilt functionality of this package library.

The Trove package provides the TObjectIntHashMap class which we will use in our examples. The HashMap is declared as follows:

// Map having keys of type String
TObjectIntHashMap<String> hm = new TObjectIntHashMap<String>();

// Map having keys of type Integer 
TObjectIntHashMap<Integer> hm = new TObjectIntHashMap<Integer>();

Package Specification: gnu.trove.map.hash.TObjectIntHashMap

We specify only the Key Data type(String, Integer, Float, Object, etc) while declaring the Map, the Value Data type is by default the Integer type in TObjectIntHashMap

There are two ways we can update the key of a TObjectIntHashMap :

  • Using increment() method of TObjectIntHashMap Class.
  • Using put() method of TObjectIntHashMap Class.

You can use the gnu.trove package and the inbuilt functionality in your Java application by importing with the following dependency.

<dependency>
    <groupId>gnu.trove</groupId>
    <artifactId>trove</artifactId>
    <version>3.0.3</version>
</dependency>

For ease, we use the JAR component of this package in our code which is available to download from here. Now, let us look into the steps:

  • We will call the increment() method and provide the key as a parameter the value of which needs to be updated. The method by default increments the value by 1.
  • We use the put() method and specify the key to update along with the value.

Note: Only Integer values are allowed as the value to be associated with each key while creating the Map.

Let us look at the implementation in the code.

import gnu.trove.map.hash.TObjectIntHashMap;

public class UpdateHashMapKeyUsingTrove {
 
    public static void main(String[] args) {
     
    //Create HashMap of String keys.
    TObjectIntHashMap<String> hm = new TObjectIntHashMap<String>();
    
    //Only Integer values to be provided.	
    hm.put("Adam", 1);
    hm.put("Steve", 2);
    hm.put("James", 3);
    hm.put("Amanda", 4);
    hm.put("Carol", 5);
	
    System.out.println("HashMap before Update : "+hm);
    System.out.println();
	
    // Increments value of key by 1.
    hm.increment("Adam");
	
    // Updates value of key using put() method
    hm.put("Amanda", 10);
	
    System.out.println("HashMap after Update : "+hm);
	
    }
}

Output:

HashMap before Update : {Steve=2,Adam=1,Carol=5,James=3,Amanda=4}

HashMap after Update : {Steve=2,Adam=2,Carol=5,James=3,Amanda=10}

Using the Atomic Integer class in Java

The AtomicInteger class is present in java.util.concurrent package and is very useful in providing components for automatic operations on Integral values. Here, we will declare a HashMap having the Value field of type AtomicInteger.

Here we highlight 4 ways to update the value of a key in a HashMap using AtomicInteger class:

  • Using updateAndGet() method.
  • Using incrementAndGet() method.
  • Using addAndGet() method.
  • Using decrementAndGet() method.

Now let us look into each method step by step.

  • We call the updateAndGet() method with the key to be updated. It accepts an IntUnaryOperator function which we specify using a rule. Ex: hm.get(“John”).updateAndGet((value) -> value + 1) updates the value of Key “John” by adding 1 to it.
  • We call the incrementAndGet() with a particular key that increments and updates the key’s value by 1.
  • We call the addAndGet() method with the key to update and provide a number to add to the original value associated with the key.
  • We call the decrementAndGet() with a particular key that by default decrements the key’s value by 1.

Let us look at the code for this approach as well.

import java.util.HashMap;
import java.util.concurrent.atomic.AtomicInteger;

public class UpdateHashMapKeyUsingAtomicInteger {
 
    public static void main(String[] args) {
     
    //Create HashMap of String keys and Atomic Integer Values.
    HashMap<String,AtomicInteger> hm = new HashMap<String,AtomicInteger>();
    
    //Create AtomicInteger and instantiate with integral values.	
    hm.put("Adam", new AtomicInteger(1));
    hm.put("Steve", new AtomicInteger(2));
    hm.put("James", new AtomicInteger(3));
    hm.put("Amanda", new AtomicInteger(4));
	
    System.out.println("HashMap before Update : "+hm);
    System.out.println();
	
    // Update Key Value and add 10 to it.
    hm.get("Adam").updateAndGet((value) -> value + 10);
	
    //Increments value of key by 1
    hm.get("Steve").incrementAndGet();
	
    // Adds and updates 5 to the key value
    hm.get("James").addAndGet(5);
	
    //Decrements value of key by 1.
    hm.get("Amanda").decrementAndGet();
	
    System.out.println("HashMap after Update : "+hm);
	
    }
}

Output:

HashMap before Update : {Adam=1, Steve=2, James=3, Amanda=4}

HashMap after Update : {Adam=11, Steve=3, James=8, Amanda=3}

That’s all for the article, we discussed 7 ways How to Update the Value of a Key in HashMap in java in great depth and detail with code and working examples. You can try these examples out in your Local IDE for a clear understanding.

Feel free to reach out to us for any queries/suggestions.

]]>
https://java2blog.com/update-value-of-key-hashmap-java/feed/ 0
How to Get Variable From Another Class in Java https://java2blog.com/get-variable-from-another-class-java/?utm_source=rss&utm_medium=rss&utm_campaign=get-variable-from-another-class-java https://java2blog.com/get-variable-from-another-class-java/#respond Tue, 29 Nov 2022 12:31:08 +0000 https://java2blog.com/?p=20241 In this article, you will learn about accessing a variable from another class in a Java Program.

To be able to program in any programming language, it is very critical to be able to understand how to use the variables according to your need, and thus it makes it very important to be able to understand how to access variables.

Classes and Objects in Java

Classes and Objects are fundamental to Java as it is an object-oriented programming language. Classes are nothing but a basic layout of an entity that could represent a real-life object.

Classes create an object. Classes are general whereas an Object is specific. For example, a class of Vehicles can become the blueprint of any real-world object such as a bike, car, truck, or bus.

Access Modifiers in Java

As the name suggests Java provides access modifiers that can help change the scope of variables, member functions, constructors, etc.

There are four types of access modifiers provided by the Java Language Specification, these are Private, Public, Protected, and Default.

It is important for you to understand the basics of access modifiers as it is one of the helpful methods to get variables from another class that we will discuss further in this article.

Get Variable From Another Class in Java

There are multiple ways to get variable from another class in Java.

Using the Default or Public Access Modifier of the Other Class

The public access modifier has the largest scope out of all the access modifiers of Java. Thus if a variable is declared using the public access modifier it can even be accessed outside of the package as well.

However, in the same package, the default access modifier can also provide unrestricted access to variables within different classes.

When you declare a variable without using any specific access modifier such as public, protected, or private, Java considers it as a default scope.

In the following code, you will observe how the usage of a public access modifier can help in accessing the variable from another class.

public class Sample {

    public static void main(String[] args) {
        AnotherClass Ac=new AnotherClass();

        System.out.println(Ac.thevariable+2);
    }
}
class AnotherClass
{
    public int thevariable=2;
}

You can note that the AnotherClass instance cab be accessed in the Sample class because it was declared as public.

Output:

4

Note that if the package of both of your classes is the same, in essence, both classes are inside the same directory, you may even skip the public keyword and nothing would change.

This is due to the fact that by default, Java gives package-level access to all the variables without any modifier.

Using the Static Member of Another Class

Java enables you to define variables that can be static, instance, or maybe local.

Declaring a variable as static means that the variable’s data will be held inside the static memory of the program, and it will be destroyed after the execution of the program.

In case you do not want to create an instance of the class, you still have an option to use variables of other classes in your class. This can happen if your variable is declared as static in nature.

To understand how you can use the static variable, let us have a look at the following sample code.

public class Sample {

    public static void main(String[] args) {

        System.out.println(AnotherClass.thevariable+2);
    }
}
class AnotherClass
{
    static int thevariable=2;
}

Output:

4

As you can see, the static variable can be used by using the class name. This allows us to use the static variable in any class.

Using the Inheritance Concept of Java

Inheritance is one of the pillars of object-oriented programming as implemented in Java.

Inheritance essentially provides all the variables and methods of the parent class to the base class except the private methods and variables.

An example of inheritance can be a class cars that will inherit from the class vehicle, having wheels and engine but specifics involves four wheels and roof, etc.

Java provides the extend keyword to inherit the elements of the base class that are not private.

To understand this concept let us look at the following sample code.

class AnotherClass
{
    int thevariable=2;
}
public class Sample extends AnotherClass{

    public static void main(String[] args) {
        Sample sp=new Sample();
        System.out.println(sp.thevariable+2);
    }
}

Output:

4

Using the Getters and Setters of Another Class

Like Inheritance, Encapsulation is also one of the pillars of Object-Oriented Programming.

One way to implement encapsulation in the Java Language is by making explicit functions to modify private members of the class.

These explicit functions are generally called getters and setters of that particular member variable.

Implementing getters and setters is fairly simple, easy, and straightforward. You can also modify getters and setters according to some conditions as it is explicitly defined.

To understand how you can get a variable of a class from another class, let us look at the following piece of code.

class AnotherClass
{
    private int thevariable=2;

    public int get()
    {
        return thevariable;
    }
    public void set(int newnum)
    {
        thevariable=newnum;
    }
}
public class Sample {

    public static void main(String[] args) {
        AnotherClass Ac=new AnotherClass();
        System.out.println(Ac.get()+2);
    }
}

Output :

4

The get() method of the AnotherClass acts as the getter that provides indirect access to the member variable.

Note that accessing the variable in this way is indirect. It is also safer than other methods.

Using the Singleton Pattern Design for Declaring Global Variables

Singleton Classes in Java are classes that only have one instance of themselves. It has numerous advantages in terms of performance and efficiency in the memory of the program.

You can also implement the Singleton Pattern Design to access variables from another class. This code basically provides a global variable to an entire project, a single line acts as the declaration of a global variable.

Singleton Classes can be instantiated in two ways:

  • Early instantiation.
  • Lazy instantiation.

You can know more about early and lazy instantiation here.

In the following code, we will use the Lazy instantiation. To understand this whole concept let us look at the following sample code.

//Class Sample

public class Sample {

    public static void main(String[] args) {

        System.out.println(SingletonClass.getinstance().thevariable+2);
    }
}

// Class Singleton

public class SingletonClass
{
    private static SingletonClass instance=null;

    public int thevariable=2;

    static public SingletonClass getinstance()
    {
        if(instance==null)
        {
            instance=new SingletonClass();
        }
        return instance;
    }
}

Output :

4

If you examine carefully, you would notice that you would need two different files of class as both of them are public classes. This is because you can have at most one public class in each file.

The main advantage of using the concept of Singleton Design Pattern is that by using only one single line of code (which in this case is SingletonClass.getinstance().thevariable) anywhere in the project you will directly be able to access the variable making it a go-around of declaring a global variable.

Conclusion

The access modifiers concept is one of the core concepts that may come in very handy for you. However, it should be used with care as it can cause security issues.

Declaring the variable to be static is another shortcut for accessing a member without even creating an instance of a class, however as you can observe it comes with its own set of disadvantages as it will become a very vulnerable variable.

This is all about how to get a variable from another class in Java

Hope you have learned something new and enjoyed reading the article. Stay tuned for more such articles. Happy learning!

]]>
https://java2blog.com/get-variable-from-another-class-java/feed/ 0
Create Array of Linked Lists in Java https://java2blog.com/create-array-of-linked-lists-java/?utm_source=rss&utm_medium=rss&utm_campaign=create-array-of-linked-lists-java https://java2blog.com/create-array-of-linked-lists-java/#respond Tue, 29 Nov 2022 07:35:53 +0000 https://java2blog.com/?p=21070 Introduction

In this article, we will look at how to Create an Array of Linked Lists in Java. We will look at ways to create an Array of Linked Lists or a List of Linked Lists in detail with working examples. Let us first have a quick peek into the concept of Linked Lists in Java.

Linked List in Java

A Linked List is a linear, dynamic Data Structure that stores homogenous data(data of the same type) following a sequence in non-contiguous memory locations. Each value in the List is represented as a Node that holds the reference to its next consecutive Node in a different memory location.

Example of Linked List:

In Java, the implementation of Linked List is defined in the LinkedList class in java.util package as part of the Collection framework introduced in Java 8.

Application of Array of Linked Lists

There is a crucial need to create an Array of Linked Lists, they have wide use in representing the relationship between the nodes and edges of Graph Data Structure.

Although an Adjacency List using ArrayList is preferred, we can represent the Adjacency matrix representation of a Graph using this Array of Linked Lists. Each index of the array gives us information about the nodes and the Linked List at each index row gives information about the connected edges to the respective node.

Example of Adjacency Matrix or List:

Here, each row starting index indicates the array index which holds a Linked List within itself. The Linked List shows the corresponding edges connected to each of the starting indexes in a connected and directed graph.

Create Array of Linked Lists in Java

Without further ado, we outline different ways to create an Array of Linked Lists in Java.

Using Object[] array of Linked Lists in Java

We can create an Array of Linked Lists by using the Object[] type array.

Important points to note:

  • We will create LinkedList objects and initialize each list with dummy values using the add() method.
  • We will then create an Object class-type array and initialize the array with the lists.
  • As the Object class is the direct parent to all Java classes, it will readily accept the Linked Lists as input.
  • Then, we print each List in the Object[] array using the toString() method.

Note: The advantage of using Object[] arr is that it allows us to store Linked Lists having elements of any data type as the Object class is a parent to all classes.

Let us look at the implementation code.

import java.util.LinkedList;

public class ObjectArrayOfLinkedLists {

    public static void main(String[] args) {

          // We create a Linked List of String type.
          LinkedList list1 = new LinkedList();
          list1.add("Welcome");
          list1.add("to");
          list1.add("Java2Blog");

          LinkedList list2 = new LinkedList();
          list2.add("Enjoy");
          list2.add("Learning");

          // We create a Linked List of Integer type.
          LinkedList list3 = new LinkedList();
          list3.add(1);
          list3.add(2);
          list3.add(3);

          // We can add all types of list into Object array.
          Object[] arr = {list1, list2, list3};

          System.out.println("The array of Linked Lists using Object[] array:");
          System.out.println();
          for(Object list : arr)
          {
              System.out.println(list.toString());
          }

    }
}

Output:

Using the Linked List array in Java

We can create an Array of Linked Lists by declaring an Array of LinkedList class type. It will follow the same declaration as an array using the new keyword with a fixed size.

Important points to note:

  • Each index of an array holds a Linked List, it is to be ensured that while accessing the array we need to initialize each Linked List object.
  • We cannot declare an Array of Linked Lists belonging to a specific type so we declare the LinkedList array of raw or generic type.
  • Hence, We initialize each LinkedList of Integer type while accessing the array, like this: arr[i] = new LinkedList<Integer>();
  • We fill each list with dummy values and print them accordingly.

Let us look at the code snippet.

import java.util.LinkedList;

public class LinkedListArraysExample {

	public static void main(String[] args) {
	     
		// We create a Linked List of Generic type.
		LinkedList linkedList[] = new LinkedList[5];
		System.out.println("The Array of Linked List is: \n");
        for (int i = 0; i < 5; i++) 
        {
           // Initialize each Linked List of Integer type within array 
           linkedList[i] = new LinkedList<Integer>();
           for (int j = 1; j <= 5; j++) 
           {
            linkedList[i].add(j);
           }
            System.out.print(linkedList[i]);
            System.out.println();
        }
		
	}
}

Output:

Using the ArrayList of Linked Lists in Java

Instead of creating an Array of Linked Lists, we can also resolve to create an ArrayList of LinkedList Objects. We will create individual Linked Lists and fill them with sample values. Then, add the Linked Lists to an ArrayList of type LinkedList.

Let us have a quick look at the implementation.

import java.util.ArrayList;
import java.util.LinkedList;

public class ArrayListOfLinkedListExample {

	public static void main(String[] args) {
	     
		// We create a Linked List of String type.
		LinkedList<String> l1 = new LinkedList<String>();
        l1.add("Hello!");
        l1.add("Welcome to Java2Blog");

        LinkedList<String> l2 = new LinkedList<String>();
        l2.add("Have Fun");
        l2.add("Learning");

        ArrayList<LinkedList> arrayList = new ArrayList<LinkedList>();
        // we add the Linked Lists
        arrayList.add(l1);
        arrayList.add(l2);
        System.out.println("The ArrayList of Linked List is: \n");
        // Use the for each method to print each Linked list
        arrayList.forEach(System.out::println);
		
	}
}

Output:

Using the Apache Commons Collections Package

The Apache Commons API provides powerful and reusable Java components and dependencies that we can embed into our applications and programs. Here, to create an Array of Linked Lists in we can use the inbuilt functionality of this package.

We will use the collections4 package of the Apache Commons Library by importing with the following dependency.

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
<dependency org="org.apache.commons" name="commons-collections4" rev="4.4"/>

Important points to note:

  • We will create a Linked List reference of the AbstractLinkedList type and then instantiate it using the CursorableLinkedList class.
  • We then insert these Linked lists into an Object[] type array.
  • Then, we print these Linked Lists using the toString() method.

Let us look at the implementation code for this approach.

import org.apache.commons.collections4.list.AbstractLinkedList;
import org.apache.commons.collections4.list.CursorableLinkedList;

public class ApacheCommonExample {

	public static void main(String[] args) {
	     
		// We create a AbstractLinkedList reference l1
	    // Instantiate l1 using the CursorableLinkedList Class.
		AbstractLinkedList<Integer> l1 = new CursorableLinkedList<Integer>(); 
		l1.add(1);
		l1.add(2);
		l1.add(3);
				
		// We create another Linked List of same type
		AbstractLinkedList<Integer> l2 = new CursorableLinkedList<Integer>();
		l2.add(4);
		l2.add(5);
		l2.add(6);
				
		// We create a Object Array with the Linked Lists.
		Object arr[] = {l1,l2};
		System.out.println("The Array of Linked Lists using Apache Commons Collections Package: ");
				
		// Iterate through each list and print its equivalent toString()
		for(Object list : arr)
		{
	    	System.out.println(list.toString());
		}
		
	}
}

Output:

That’s all for the article we had a look at 4 different ways to Create an Array of Linked Lists in Java with working examples in detail. You can try out the examples in your Local Compiler/IDE for a clear understanding.

Feel free to reach out to us for any suggestions/doubts.

]]>
https://java2blog.com/create-array-of-linked-lists-java/feed/ 0
Check if Date Is Between Two Dates in Java https://java2blog.com/check-if-date-is-between-two-dates-java/?utm_source=rss&utm_medium=rss&utm_campaign=check-if-date-is-between-two-dates-java https://java2blog.com/check-if-date-is-between-two-dates-java/#respond Sat, 26 Nov 2022 16:07:44 +0000 https://java2blog.com/?p=21152 Introduction

In this article, we will discuss and dwell on how to compare dates in Java. The problem statement is : Check if a Date is between two dates in Java. This roughly translates to Given a date, we need to check if it lies between the range of two dates. Let us understand this with a sample input example.

Input:

Date_1 : 21/10/18

Date_2 : 22/11/18

Date to Validate: 13/11/18

Output:

The date 13/11/18 lies between the dates 21/10/18 and 22/11/18

We will discuss different solutions to this problem in great depth and detail to make it captivating. Let us first have a quick look at how Dates are represented in Java.

Date & Local Date Class in Java

In Java, we can represent Dates as text in a Stringtype variable. But using a String would make formatting the date for different operations very resilient. So, to avoid this Java provides the Date and LocalDate class to perform operations on a Date meta type easily.

Date Class in Java

It is present in java.util package. We can create a date of any format (DD/MM/YYYYY, MM/DD/YYYY, YYYY/MM/DD, etc.) using the SimpleDateFormat class and instantiate it to a Date class object using the parse() method of the SimpleDateFormat class.

LocalDate class in Java

It is present in java.time package. We can create a date of only a specific format i.e. YYYY-MM-DD. We instantiate the LocalDate object using the of() method and pass the relevant parameters to it.

We can also create a LocalDate object using the parse() method where we need to pass the required Date as a String in the format YYYY-MM-DD.

Let us see the sample code to create custom dates using the classes above. It is important to get an idea as we will look at more examples related to this.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;

public class DateExamples {

    public static void main(String[] args) throws ParseException {

        // Date class example
        // Create a SimpleDateFormat reference with different formats
        SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy/MM/dd");

        //Create date with format dd/mm/yyyy
        Date t1 = sdf1.parse("21/12/2018");
        //Create date with format yyyy/mm/dd
        Date t2 = sdf2.parse("2019/11/11");
        //Print the dates using the format() method     
        System.out.println("-----------Date Class Example -------------");
        System.out.println(t1);
        System.out.println(sdf1.format(t1));
        System.out.println();
        System.out.println(t2);
        System.out.println(sdf2.format(t2));

        // LocalDate class example
        // Create using of() method.
        LocalDate ld1 = LocalDate.of(2021, 10, 30);
        // Create using  parse() method
        LocalDate ld2 = LocalDate.parse("2010-12-20");
        System.out.println("-----------LocalDate Class Example -----------");
        System.out.println(ld1);
        System.out.println(ld2);

    }
}

-----------Date Class Example -------------
Fri Dec 21 00:00:00 IST 2018
21/12/2018

Mon Nov 11 00:00:00 IST 2019
2019/11/11
-----------LocalDate Class Example -----------
2021-10-30
2010-12-20

Check if The Date Is Between Two Dates in Java

Now, we outline different approaches for the solution to this problem. For some of the approaches, we will undertake the Date values only in the format: DD/MM/YYYY. However, it will support other date formats.

Using the isAfter() and isBefore() Methods of the Local Date Class in Java

The LocalDate class in Java provides the isAfter() method to check if a date lies after the given date and the isBefore() method to check if the date lies before. We call these methods with the date to check and pass the argument date.

We can combine these two methods to Check if a date is between two given dates.

Important points to note:

  • We will take three variables startDate, endDate, and dateToValidate as LocalDate instances and create them using the of() method.
  • We check if the dateToValidate lies after the startDate and if dateToValidate lies before the endDate. If the condition satisfies we print the date is validated.
  • We call the isAfter() and isBefore() methods with the dateToValidate object providing the start and end dates respectively to ensure the check.

Let us look at the code for this approach.

import java.time.LocalDate; 

public class CheckDateBetweenLocalDateMain {

    public static void main(String[] args) throws ParseException {

        //Create the Lower and Upper Bound Local Date 
                //Format: YYYY-MM-DD
        LocalDate startDate = LocalDate.of(2018, 9, 21);
        LocalDate endDate = LocalDate.of(2018, 10, 22);

        //Create the date object to check
        LocalDate dateToValidate = LocalDate.of(2018, 10, 13);

        //Use the isAfter() and isBefore() method to check date
        if(dateToValidate.isAfter(startDate) && dateToValidate.isBefore(endDate))
        {
			System.out.println("The date "+dateToValidate+" lies between the two dates");
        }
        else
        {
			System.out.println(dateToValidate+" does not lie between the two dates");
        }
    }
}

The date 2018-10-13 lies between the two dates

If we need to include the endpoints of the start dates and end dates respectively, we can replace the if condition with this line of code:

if(!(dateToValidate.isAfter(endDate) || dateToValidate.isBefore(startDate)))

Using the compareTo() Method of the Local Date Class in Java

The LocalDate class in Java provides the compareTo() method with which we can compare dates easily based on the return value. Here, we can use this method to Check if the date lies between two dates.

The syntax of the method:

public int compareTo(Date anotherDate)

The compareTo() method has the following restrictions:

  • It returns the value 0 if the argument anotherDate is equal to this Date.
  • It returns value < 0 (i.e. -1) if this Date is before the anotherDate argument.
  • It returns a value > 0 (i.e. +1) if this Date is after the anotherDate argument.

Important points to note:

  • We compare the startDate with the dateToValidate and the dateToValidate with the endDate.
  • It returns values +1(if greater) or -1(if smaller) based on the comparison. We then multiply the returned values from both expressions.
  • If the resultant value is greater than 0 it means the date lies within the range otherwise it is not valid.

Let us look at the code.

import java.time.LocalDate;

public class CheckDateBetweenLocalDateMain {

public static void main(String[] args) {

      //Create the Lower and Upper Bound Date object
      LocalDate startDate = LocalDate.of(2019,7,18);
      LocalDate endDate = LocalDate.of(2019,12,28);

      //Create the date object to check
      LocalDate dateToValidate = LocalDate.of(2019,8,25);

      //Compare each date and multiply the returned values
      if(startDate.compareTo(dateToValidate) * dateToValidate.compareTo(endDate) > 0)
      {
        System.out.println("The date "+dateToValidate+" lies between the two dates");
      }
      else
      {
        System.out.println(dateToValidate+" does not lie between the two dates");
      }
	}
}

Output:

The date 2019-8-25 lies between the two dates

Using the after() and before() Methods of the Date Class in Java

The Date class in Java provides the after() method to check if a date lies after the given date and the before() method to check if the date lies before. We can combine these two methods to Check if a date is between two dates.

Important points to note:

  • We will take three variables startDate, endDate, and dateToValidate as Date objects using the parse() method of SimpleDateFormat class.
  • We check if the dateToValidate lies after the startDate and if dateToValidate lies before the endDate. If the condition satisfies we print the date is validated.
  • We call the after() and before() methods with the dateToValidate object providing the start and end dates respectively to ensure the check.

Note: The parse() method of SimpleDateFormat throws ParseException so ensure that the throws declaration is given in the calling method or implemented.

Let us look at the code snippet for this approach.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CheckDateBetweenTwoDatesMain {

    public static void main(String[] args) throws ParseException {

        // Create a SimpleDateFormat reference with different formats
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

        //Create the Lower and Upper Bound Date object
        Date startDate = sdf.parse("21/10/2018");
        Date endDate = sdf.parse("22/11/2018");

        //Create the date object to check
        Date dateToValidate = sdf.parse("13/11/2018");

        //Use the after() and before() method to check date
        if(dateToValidate.after(startDate) && dateToValidate.before(endDate))
        {
            System.out.println("The date "+sdf.format(dateToValidate)+" lies between the two dates");
        }
        else
        {
			System.out.println(sdf.format(dateToValidate)+" does not lie between the two dates");
        }
    }
}

Output:

While validating, If we need to include the endpoints of the start dates and end dates respectively, we can replace the if condition with this line of code:

if(!(dateToValidate.after(endDate) || dateToValidate.before(startDate)))

Using the compare To() Method of the Date Class in Java

Similar to the LocalDate class, the Date class in Java also provides the compareTo() method which we can use to compare dates easily and Check if the date lies between two dates.

The syntax of the method:

public int compareTo(Date anotherDate)

The compareTo() method has the same restrictions as discussed above for the LocalDate class.

Important points to note:

  • We compare the startDate with the dateToValidate and the dateToValidate with the endDate.
  • It returns values +1(if greater) or -1(is smaller) based on the comparison. We then multiply the returned values from both expressions.
  • If the value is greater than 0 it means the date lies within the range otherwise it is not valid.

Let us look at the code snippet for this approach as well.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CheckDateBetweenTwoDatesMain {

public static void main(String[] args) throws ParseException {

      // Create a SimpleDateFormat reference with different formats
      SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

      //Create the Lower and Upper Bound Date object
      Date startDate = sdf.parse("11/07/2019");
      Date endDate = sdf.parse("30/12/2019");

      //Create the date object to check
      Date dateToValidate = sdf.parse("22/08/2019");
      //Compare each date and multiply the returned values
      if(startDate.compareTo(dateToValidate) * dateToValidate.compareTo(endDate) > 0)
      {
        System.out.println("The date "+sdf.format(dateToValidate)+" lies between the two dates");
      }
      else
      {
        System.out.println(sdf.format(dateToValidate)+" does not lie between the two dates");
      }
 }
}

Output:

Using the getTime() Method of The Date Class in Java

We can also use the getTime() method of the Date class to check if the date is between two dates. The getTime() method converts a Date into its equivalent milliseconds since January 1, 1970. The return value is of type Long.

There are two ways we can solve this using the getTime() method:

  1. We can compute the total millisecond value for each of the dates and compare the dateToValidate with the startDate and endDate respectively.
  2. To validate the dates, we can subtract the millisecond value of dateToValidate with and from the start and end dates respectively.

Note: This approach would not work as expected if we compare dates before January 1, 1970. In such case, the getTime() method will give a negative value on crossing the Long limit.

Let us look at the implementation of these approaches in code.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CheckDateUsingGetTimeMain {

    public static void main(String[] args) throws ParseException {

        // Create a SimpleDateFormat reference with different formats
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

        //Create the Lower and Upper Bound Date object
        Date startDate = sdf.parse("11/07/2019");
        Date endDate = sdf.parse("30/12/2019");

        //Create the date object to check
        Date dateToValidate = sdf.parse("22/08/2019");

        // Using getTime() method to get each date in milliseconds
        long startDateInMillis = startDate.getTime();
        long endDateInMillis = endDate.getTime();
        long dateInMillis = dateToValidate.getTime();

        // Approach 1: Comparing the millisecond value of each date.
        if(startDateInMillis <= dateInMillis && dateInMillis <= endDateInMillis )
        {
			System.out.println("The date "+sdf.format(dateToValidate)+" lies between the two dates\n");
        }
        else
        {
			System.out.println(sdf.format(dateToValidate)+" does not lie between the two dates\n");
        }

        // Approach 2: Subtracting the millisecond values of each date  
        // Create new date to check
        dateToValidate = sdf.parse("21/08/2017");
        dateInMillis = dateToValidate.getTime();

        if(dateInMillis - startDateInMillis >=0 && endDateInMillis - dateInMillis >= 0 )
        {
			System.out.println("The date "+sdf.format(dateToValidate)+" lies between the two dates");   
        }
        else
        {
			System.out.println(sdf.format(dateToValidate)+" does not lie between the two dates");   
        }

    }
}

Output:

Using the Joda-Time Library

Before Java 8, The legacy date and time classes in Java were equipped poorly with minimal utilities. The Joda-Time provides a quality replacement for these Java Date and Time classes. Here, to Check if the date lies between two dates we can use the inbuilt functionality of this package.

We can use the DateTime class and its utility methods of the JodaTime Library by importing with the following maven dependency.

<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.1</version>
</dependency>

For ease, we will use the JAR file component of the Joda-Time package in our code. You can download the Joda-Time Library JAR from the embedded link. Now, let us look into the steps.

  • We will create three instances of the DateTime class initializing it with the Date objects startDate, endDate, and dateToValidate respectively.
  • The DateTime class provides the isAfter() and isBefore() utility methods, we then compare the Datetime instance of dateToValidate Date object and validate the same using these methods.

Let us have a quick look at the implementation of this approach as well.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.joda.time.DateTime;

public class CheckDateJodaTime {

    public static void main(String[] args) throws ParseException {

        // Create a SimpleDateFormat reference with different formats
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

        //Create the Lower and Upper Bound Date object
        Date startDate = sdf.parse("11/07/2019");
        Date endDate = sdf.parse("30/12/2019");

        //Create the date object to check
        Date dateToValidate = sdf.parse("22/08/2019");

        // Create Joda Datetime instance using Date objects
        DateTime dateTime1 = new DateTime(startDate);
        DateTime dateTime2 = new DateTime(endDate);
        DateTime dateTime3 = new DateTime(dateToValidate);

        // compare datetime3 with datetime1 and datetime2 using the methods
        if(( dateTime3.isAfter( dateTime1 ) ) && ( dateTime3.isBefore( dateTime2 ) ))
        {
			System.out.println("The date "+sdf.format(dateToValidate)+" lies between the two dates\n");
        }
        else
        {
			System.out.println(sdf.format(dateToValidate)+" does not lie between the two dates\n");
        }

    }
}

Output:

Using the Apache Commons Net Library – Time Stamp Class

The Apache Commons API provides powerful and reusable Java components and dependencies that we can embed into our applications and programs. Here, to check if the Date lies between two dates we can use the inbuilt functionality of this package.

We can use the TimeStamp class of the Net package of Apache Commons Library by importing with the following maven dependency.

<dependency>
  <groupId>commons-net</groupId>
  <artifactId>commons-net</artifactId>
  <version>3.8.0</version>
</dependency>

For ease, we will use the JAR file component of the Apache Commons Net package in our code. We can download the Apache Commons Net JAR to set up the JAR file component for this package.

Now, let us look into the steps:

  • We will create three instances of the TimeStamp class initializing it with the Date objects startDate, endDate, and dateToValidate respectively.
  • For each TimeStamp object that we create, we calculate the total seconds using the getSeconds() method.
  • The getseconds() calculates the total seconds from the given date to the present date and returns the value of type long.
  • Then compare the total second value of the TimeStamp instance of dateToValidate with other dates and validate it.

Let us look at the implementation of the approach in code.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.net.ntp.TimeStamp;

public class CheckDateApacheCommon {

    public static void main(String[] args) throws ParseException {

        // Create a SimpleDateFormat reference with different formats
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

        //Create the Lower and Upper Bound Date object
        Date startDate = sdf.parse("11/07/2019");
        Date endDate = sdf.parse("30/12/2019");

        //Create the date object to check
        Date dateToValidate = sdf.parse("22/08/2019");

        // Create TimeStamp instance using Date objects
        TimeStamp ts1 = new TimeStamp(startDate);
        TimeStamp ts2 = new TimeStamp(endDate);
        TimeStamp ts3 = new TimeStamp(dateToValidate);

        // Get the total seconds value for each date
        long time1 = ts1.getSeconds();
        long time2 = ts2.getSeconds();
        long time3 = ts3.getSeconds();

        // compare time3 with time1 and time2
        if( time1 < time3 && time3 < time2 )
        {
			System.out.println("The date "+sdf.format(dateToValidate)+" lies between the two dates\n");
        }
        else
        {
			System.out.println(sdf.format(dateToValidate)+" does not lie between the two dates\n");
        }

    }
}

Output:

That’s all for the article, we discussed 7 ways to Check if a Date lies between two dates in java in detail with code and working examples. You can try these examples out in your Local IDE for a clear understanding.

Feel free to reach out to us for any queries/suggestions.

]]>
https://java2blog.com/check-if-date-is-between-two-dates-java/feed/ 0
Convert UUID to String in Java https://java2blog.com/convert-uuid-to-string-java/?utm_source=rss&utm_medium=rss&utm_campaign=convert-uuid-to-string-java https://java2blog.com/convert-uuid-to-string-java/#respond Fri, 28 Oct 2022 09:34:23 +0000 https://java2blog.com/?p=20949 Introduction

In this article, we will have a look on How to Convert UUID to String in Java. We will also shed some light on the concept of UUID, its use, and its corresponding representation in Java class. Let us have a quick look at UUID.

UUID: UUID stands for Universally Unique Identifier which identifies a unique entity or resource in the computer systems. This resource can be a document, real-time object, file, and more. It is also known by the name GUID or Globally Unique Identifier for its extensive use.

It is a value of size 128 bits composed of 32 hexadecimal-based characters and 6 ‘-‘ i.e. hyphens that account for its total length of 36 characters. In programming, we generally represent this type of data as a String.

Example of a UUID: 123e4567-e89b-12d3-a456-426614174000

UUID follows universal standards set by the Internet Society to ensure the uniqueness of every resource that has a UUID.

Uses:

  • The Uniqueness of UUIDs makes them useful for being Associative keys in database tables.
  • They are also used as Identifiers for physical hardware within an organization.
  • They have applications in Cryptography and other hashing utilities.

UUID class in Java

With the advent of Java 7, the UUID class was introduced in Java which packed the different specifications and utilities of UUID into a single unit with some useful methods as well.

We can generate a random UUID or we can generate the UUID from an input String as well. We can generate it as a UUID object or convert it to a string as well. If we can convert a UUID to a String, then we can format and perform the same operations with the utility methods that are possible on a String.

Let us look at how we can generate UUIDs and print them:

import java.util.UUID;  

public class Java2Blog  
{ 
	
	public static void main(String[] args)   
	{  
		UUID uuid=UUID.randomUUID(); //Generates random UUID  
		System.out.println(uuid);  
	}  
}

Output:

Convert UUID to String in Java

We can print a UUID object directly or use the String representation of the UUID object. With the toString() method we can convert a UUID to its equivalent String representation. We can change the object type but the representation remains the same.

We will discuss two different examples where we generate a random UUID and another from a given string. Then we convert them to String using the toString() method.

Let us look at the code snippet for the two approaches.

import java.util.UUID;  

public class Java2Blog  
{ 
	
	public static void main(String[] args)   
	{  
		UUID uuid=UUID.randomUUID(); //Generates random UUID  
		
		String str = uuid.toString();
		
		System.out.println("String representation of Random generated UUID is :");  
		System.out.println();
		System.out.println(str);
	}  
}

Output:

Next, In the below example, we generate UUID from an input string using the fromString() method of the UUID class.

import java.util.UUID;  

public class Java2Blog  
{ 
	
	public static void main(String[] args)   
	{  
		UUID uuid=UUID.fromString("8745d341-966f-4b47-a313-0c5b0795e1bb"); //Generates random UUID  
		
		String str = uuid.toString();
		
		System.out.println("String representation of an Input generated UUID is :");  
		System.out.println();
		System.out.println(str);
	}  
}

Output:

That’s all for the article, we had a brief look at the UUID’s concept, and a brief look at its Java class. Along with this, we had a look at How to Convert a UUID to a String and its representation. You can try out the above examples in your local Java compiler/IDE.

Feel free to reach out to us for any suggestions/doubts.

]]>
https://java2blog.com/convert-uuid-to-string-java/feed/ 0
Tips to Pass the AWS DevOps Certification in 2022 https://java2blog.com/tips-to-pass-aws-devops-certification/?utm_source=rss&utm_medium=rss&utm_campaign=tips-to-pass-aws-devops-certification https://java2blog.com/tips-to-pass-aws-devops-certification/#respond Wed, 26 Oct 2022 11:11:46 +0000 https://java2blog.com/?p=21050 Before enrolling in an AWS DevOps Certification training program or exam, you should research the credential. The AWS DevOps Certification is a great way to boost your IT career, and when most people think of AWS- the first thing that comes to mind is the certification. It covers all areas a developer needs to get started in their field, but if you have questions, here are some things you may want answers to.

How to pass an AWS DevOps certification exam?

Here are some top tips for passing an AWS DevOps certification exam (or any other certification exam, for that matter).

Go through questions quickly and mark them for review

AWS cloud developer exams are always nerve-wracking, so try to work quickly, skimming the content of each question. If unsure about a question, flag it for review and move on to the next one. As you go through an exam, you may recall something you marked for review. On the second reading, almost always, the questions you’ve labelled for review are simpler to answer.

Don’t look at the answers first

It’s tempting to want to quickly see what the correct answer is for a question you’re struggling with but resist that urge. Once you’ve looked at the answer, it’s tough to "unsee" it and approach the question with a fresh perspective.

Read the questions carefully

Make sure you understand what the questions demand, before selecting an answer. Then, if you’re unsure, ask yourself whether the answer choice reflects what the question is asking.

Eliminate incorrect answers

For multiple-choice questions, there are often one or more incorrect answers. The process of elimination can help you narrow down your choices and arrive at the correct answer.

Practice with sample exams

Practice tests are a holistic way to prepare for an exam. This will give you a notion of the questions on the exam and help you identify areas where you need further study.

What does the AWS DevOps Engineer exam cover?

The AWS Certified DevOps Engineer – Professional exam covers a lot of ground. It tests your knowledge of both AWS and DevOps principles and practices.

To prepare for the exam, you should have a good understanding of the following topics:

AWS Services: You should be familiar with the various AWS services, such as EC2, S3, RDS, and DynamoDB.

AWS Command Line Interface: You should know how to use the AWS CLI to manage your AWS resources.

AWS CloudFormation:You should be able to create and manage templates using CloudFormation and ensure cloud security. One of the main aspects of this topic is cloud computing.

AWS CodePipeline: You should be able to create and configure pipelines using CodePipeline.

AWS CodeBuild: You should be able to create and configure build projects using CodeBuild.

AWS OpsWorks: You should be familiar with OpsWorks and how to use it to orchestrate your application deployments.

What are the requirements for AWS DevOps Cloud certification?

To obtain an AWS DevOps Certification, you must first pass an exam. You can choose from a few different exams, depending on your level of experience and expertise. The most popular exam for beginners is the Associate Level Exam. For more experienced professionals, the Professional Level Exam is recommended.

Advantages of having AWS DevOps Certification

There are plenty of benefits of undergoing AWS certification training prior to the test. If you go through the course and training program, here are the following things to expect.

It Gives you an edge over others

AWS training and certification would give you an added advantage over your competition as it is assumed that you understand the AWS platform and how to use it.

Helps You Get a Job

Having this certification on your resume will help you get noticed by potential employers. In addition, it shows that you are committed to your career and are willing to invest in your professional development.

Keeps Your Skills Up-To-Date

The AWS platform is constantly evolving, and as a certified professional, you will need to keep your skills up-to-date. Pursuing an AWS DevOps Certification will help you stay current with the latest changes and updates.

Boost Your Career

An AWS DevOps Certification can help boost your career by giving you the skills you need to succeed in this rapidly growing field. With this certification, you can take your career to the next level.

Earn More Money

AWS DevOps Certification can help you earn more money. Certified professionals are in high demand, and they command higher salaries. Pursuing an AWS DevOps Certification will help you get the salary you deserve.

Conclusion

In order to pass the AWS DevOps Certification in 2022, it is essential to start preparing now. The exam covers various topics related to DevOps, so gaining experience with these concepts is essential. We hope this blog post furthers you on your journey to certification and that you feel confident about taking the exam.

]]>
https://java2blog.com/tips-to-pass-aws-devops-certification/feed/ 0