Java – Global variable examples

In Java, there is no global keyword, but we can use public static variable to referring a global variable. For example : MagicUtils.java package com.mkyong.example; public class MagicUtils { public static final String NAME = "mkyong"; // global public static final int LUCKY_NUMBER = 7; // global } JavaExample.java package com.mkyong.example; public class JavaExample { …

Read more

Java – How to get the first item from Set

In Java, we can use Set.iterator().next() to get the first item from a java.util.Set JavaExample.java package com.mkyong; import java.util.HashSet; import java.util.Set; public class JavaExample { public static void main(String[] args) { Set<String> examples = new HashSet<>(); examples.add("1"); examples.add("2"); examples.add("3"); examples.add("4"); examples.add("5"); System.out.println(examples.iterator().next()); // java 8 System.out.println(examples.stream().findFirst().get()); } } Output 1 1 References Oracle doc – …

Read more

Java – How to convert int to BigInteger?

In Java, we can use BigInteger.valueOf(int) to convert int to a BigInteger JavaExample.java package com.mkyong; import java.math.BigInteger; public class JavaExample { public static void main(String[] args) { int n = 100; System.out.println(n); // convert int to Integer Integer integer = Integer.valueOf(n); System.out.println(integer); // convert int to BigInteger BigInteger bigInteger = BigInteger.valueOf(n); System.out.println(bigInteger); // convert Integer …

Read more

Java – Find the length of BigInteger?

In Java, we can convert the BigInteger to a String object and get the length of the String. JavaExample.java package com.mkyong; import java.math.BigInteger; public class JavaExample { public static void main(String[] args) { BigInteger bigInteger = BigInteger.valueOf(100000000000000000L); //18 System.out.println(bigInteger.toString().length()); } } Output 18 References BigInteger JavaDoc Quora – What are the limits of String Size …

Read more

Java – List of available MessageDigest Algorithms

In Java, you can use the Security.getAlgorithms(“MessageDigest”) to list all the available MessageDigest algorithms. ListMessageDigest.java package com.mkyong.hashing; import java.security.Security; import java.util.Set; public class ListMessageDigest { public static void main(String[] args) { Set<String> messageDigest = Security.getAlgorithms("MessageDigest"); messageDigest.forEach(x -> System.out.println(x)); } } Output SHA3-512 SHA-384 SHA SHA3-384 SHA-224 SHA-512/256 SHA-256 MD2 SHA-512/224 SHA3-256 SHA-512 MD5 SHA3-224 P.S …

Read more

Java – How to convert byte arrays to Hex

This article shows you a few ways to convert byte arrays or byte[] to a hexadecimal (base 16 or hex) string representative. String.format Integer.toHexString Apache Commons Codec – commons-codec Spring Security Crypto – spring-security-crypto Bitwise shifting and masking. (educational purposes) Note Both Apache Commons-Codec and Spring Security Crypto modules are using the similar 5. Bitwise …

Read more

Java – How to join List String with commas

In Java, we can use String.join(“,”, list) to join a List String with commas. 1. Java 8 1.1 String.join JavaStringExample1.java package com.mkyong; import java.util.Arrays; import java.util.List; public class JavaStringExample1 { public static void main(String[] args) { List<String> list = Arrays.asList("a","b","c"); String result = String.join(",", list); System.out.println(result); } } Output a,b,c 1.2 Stream Collectors.joining JavaStringExample2.java package …

Read more

Java – How to convert System.nanoTime to Seconds

We can just divide the nanoTime by 1_000_000_000, or use the TimeUnit.SECONDS.convert to convert it. Note 1 second = 1_000_000_000 nanosecond JavaExample.java package com.mkyong; import java.util.concurrent.TimeUnit; public class JavaExample { public static void main(String[] args) throws InterruptedException { long start = System.nanoTime(); Thread.sleep(5000); long end = System.nanoTime(); long elapsedTime = end – start; System.out.println(elapsedTime); // …

Read more

Java – Count the number of items in a List

In Java, we can use List.size() to count the number of items in a List package com.mkyong.example; import java.util.Arrays; import java.util.List; public class JavaExample { public static void main(String[] args) { List<String> list = Arrays.asList("a", "b", "c"); System.out.println(list.size()); } } Output 3 References Java doc – List

Java Selection sort example

Selection sort is an in-place comparison sort. It loops and find the first smallest value, swaps it with the first element; loop and find the second smallest value again, swaps it with the second element, repeats third, fourth, fifth smallest values and swaps it, until everything is in correct order. P.S Selection sort is inefficient …

Read more

Java Bubble sort example

Bubble sort is the simplest sorting algorithm, it compares the first two elements, if the first is greater than the second, swaps them, continues doing (compares and swaps) for the next pair of adjacent elements. It then starts again with the first two elements, compares, swaps until no more swaps are required. 1. Explanation #unsorted …

Read more

Java – How to print a Pyramid

A Java example to print half and full pyramid, for fun. CreatePyramid.java package com.mkyong; import java.util.Collections; public class CreatePyramid { public static void main(String[] args) { int rows = 5; System.out.println("\n1. Half Pyramid\n"); for (int i = 0; i < rows; i++) { for (int j = 0; j <= i; j++) { System.out.print("*"); } …

Read more

PDFBox – How to read PDF file in Java

This article shows you how to use Apache PDFBox to read a PDF file in Java. 1. Get PDFBox pom.xml <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>2.0.6</version> </dependency> 2. Print PDF file Example to extract all text from a PDF file. ReadPdf.java package com.mkyong; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.text.PDFTextStripper; import org.apache.pdfbox.text.PDFTextStripperByArea; import java.io.File; import java.io.IOException; public class ReadPdf { …

Read more

Java – Convert comma-separated String to a List

Java examples to show you how to convert a comma-separated String into a List and vice versa. 1. Comma-separated String to List TestApp1.java package com.mkyong.utils; import java.util.Arrays; import java.util.List; public class TestApp1 { public static void main(String[] args) { String alpha = "A, B, C, D"; //Remove whitespace and split by comma List<String> result = …

Read more

Java – How to shuffle an ArrayList

In Java, you can use Collections.shuffle to shuffle or randomize a ArrayList TestApp.java package com.mkyong.utils; import java.util.Arrays; import java.util.Collections; import java.util.List; public class TestApp { public static void main(String[] args) { List<String> list = Arrays.asList("A", "B", "C", "D", "1", "2", "3"); //before shuffle System.out.println(list); // again, same insert order System.out.println(list); // shuffle or randomize Collections.shuffle(list); …

Read more

Java RMI – Distributed objects example

Image Source: Wikimedia.org In Java RMI Hello World example we introduced the Java Remote Method Invocation with a very basic String-based communication between Server-Client. In this example we will take it one small step further and introduce Server-Client communication using Distributed Objects. 1. The Remote Interface First we will develop the Remote Interface which contains …

Read more

Java – Digital Signatures example

In Asymmetric Cryptography example we discussed the use of Public Key Pair in Cryptography. Another important use of the Public Key Infrastructure is in Digital Signatures. Digital Signatures are the digital equivalent of handwritten signatures with one important difference; they are not unique but come as a product of the message. A valid digital signature …

Read more

How to copy an Array in Java

The methods described below are only applicable to one dimensional arrays. Before we talk about the different ways to copy an array in Java we will show you how NOT to copy an Array. How NOT to copy an Array in Java Arrays in Java are Objects. If you try to treat them as variables… …

Read more

iText – Read and Write PDF in Java

This article talks about reading and writing PDF using iText PDF library. pom.xml <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.10</version> </dependency> P.S Tested with iTextPdf 5.5.10 1. iText – Write PDF iText PdfWriter example to write content to a PDF file. PdfWriteExample.java package com.mkyong; import com.itextpdf.text.*; import com.itextpdf.text.pdf.PdfWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class …

Read more

Java – Hybrid Cryptography example

Hybrid Cryptography is the silver lining between safe, but slow cryptography over big data (Asymmetric Cryptography) and unsafe but fast cryptography (Symmetric Cryptography). Hybrid Cryptography combines the speed of One-Key encryption and decryption along with the security that the Public-Private Key pair provides and thus considered a highly secure type of encryption. The most common …

Read more

Java – Asymmetric Cryptography example

Asymmetric Cryptography, also known as Public Key Cryptography, is an encryption system in which two different but uniquely related cryptographic keys are used. The data encrypted using one key can be decrypted with the other. These keys are known as Public and Private Key Pair, and as the name implies the private key must remain …

Read more

Java – Symmetric-Key Cryptography example

Symmetric-Key Cryptography is an encryption system in which the same key is used for the encoding and decoding of the data. The safe distribution of the key is one of the drawbacks of this method, but what it lacks in security it gains in time complexity. One should always assume that the encryption algorithms are …

Read more

Java – How to create strong random numbers

SecureRandom class in Java provides a cryptographically secure pseudo – random number generator and its intended use is for security sensitive applications. In this example, we will not use it for its intended purpose, but rather present its methods in a simple password generator. 1.Password Generator Using Secure Random A convention, we made for our …

Read more

Java – Check if Array contains a certain value?

Java examples to check if an Array (String or Primitive type) contains a certain values, updated with Java 8 stream APIs. 1. String Arrays 1.1 Check if a String Array contains a certain value “A”. StringArrayExample1.java package com.mkyong.core; import java.util.Arrays; import java.util.List; public class StringArrayExample1 { public static void main(String[] args) { String[] alphabet = …

Read more

Java – How to add days to current date

This article shows you how to add days to the current date, using the classic java.util.Calendar and the new Java 8 date and time APIs. 1. Calendar.add Example to add 1 year, 1 month, 1 day, 1 hour, 1 minute and 1 second to the current date. DateExample.java package com.mkyong.time; import java.text.DateFormat; import java.text.SimpleDateFormat; import …

Read more

Java – Convert Object to Map example

In Java, you can use the Jackson library to convert a Java object into a Map easily. 1. Get Jackson pom.xml <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.6.3</version> </dependency> 2. Convert Object to Map 2.1 A Jackson 2 example to convert a Student object into a java.util.Map Student.java package com.mkyong.examples; import java.util.List; public class Student { private String …

Read more

Java Static keyword example

The static keyword in Java is a modifier used to create memory efficient code. It helps in managing the memory occupied by objects, variables and method definitions. The static keyword makes sure that there is only one instance of the concerned method, object or variable created in memory. It is used when one needs to …

Read more

Java – How to compare two Sets

In Java, there is no ready make API to compare two java.util.Set 1. Solution Here’s my implementation, combine check size + containsAll : SetUtils.java package com.mkyong.core.utils; import java.util.Set; public class SetUtils { public static boolean equals(Set<?> set1, Set<?> set2){ if(set1 == null || set2 ==null){ return false; } if(set1.size()!=set2.size()){ return false; } return set1.containsAll(set2); } …

Read more

Java – ResourceBundle example

The java.util.ResourceBundle is a library used for internationalization (multiple languages). It is able to return messages as per the default Locale configured for the system. Such a functionality is used when one develops systems to be used all over the world. 1. How it works? The library reads a property file based on the locale and name …

Read more

Java Final keyword example

Final keyword in Java is a modifier used to restrict the user from doing unwanted code or preventing from the code or value from being changed. It is possible to use this keyword in 3 contexts. They are: Final keyword as a variable modifier Final keyword as a method modifier Final keyword as a class …

Read more

Java Custom Exception Examples

In Java, there are two types of exceptions – checked and unchecked exception. Here’s the summary : Checked – Extends java.lang.Exception, for recoverable condition, try-catch the exception explicitly, compile error. Unchecked – Extends java.lang.RuntimeException, for unrecoverable condition, like programming errors, no need try-catch, runtime error. 1. Custom Checked Exception Note Some popular checked exception : …

Read more

Java – find class fields with specified data type

Some Java reflection API examples. 1. Display all fields and data type A Java reflection example to loop over all the fields declared by a class. 1.1 A POJO. CompanyA.java package com.mkyong.test; import java.util.List; import java.util.Map; import java.util.Set; public class CompanyA { String orgName; int count; List<String> comments; Set<String> branches; Map<String, String> extra; //… } …

Read more

Java – How to override equals and hashCode

Some Java examples to show you how to override equals and hashCode. 1. POJO To compare two Java objects, we need to override both equals and hashCode (Good practice). User.java public class User { private String name; private int age; private String passport; //getters and setters, constructor } User user1 = new User("mkyong", 35, "111222333"); …

Read more