Java – Convert negative binary to Integer

Review the following Java example to convert a negative integer in binary string back to an integer type. String binary = Integer.toBinaryString(-1); // convert -1 to binary // 11111111 11111111 11111111 11111111 (two’s complement) int number = Integer.parseInt(binary, 2); // convert negative binary back to integer System.out.println(number); // output ?? The result is NumberFormatException! Exception …

Read more

Java >> and >>> bitwise shift operators

In programming, bitwise shift operators, >> means arithmetic right shift, >>> means logical right shift, the differences: >>, it preserves the sign (positive or negative numbers) after right shift by n bit, sign extension. >>>, it ignores the sign after right shift by n bit, zero extension. To work with bitwise shift operators >> and …

Read more

Java AES encryption and decryption

The Advanced Encryption Standard (AES, Rijndael) is a block cipher encryption and decryption algorithm, the most used encryption algorithm in the worldwide. The AES processes block of 128 bits using a secret key of 128, 192, or 256 bits. This article shows you a few of Java AES encryption and decryption examples: AES String encryption …

Read more

What is new in Java 12

Java 12 reached General Availability on 19 March 2019, download Java 12 here or this openJDK archived. Java 12 features. 1. JEP 189: Shenandoah: A Low-Pause-Time Garbage Collector (Experimental) 2. JEP 230: Microbenchmark Suite 3. JEP 325: Switch Expressions (Preview) 4. JEP 334: JVM Constants API 5. JEP 340: One AArch64 Port, Not Two 6. …

Read more

How to exit JShell in Java?

To exit JShell, type /exit. I stuck in JShell for minutes, commands like exit, ctrl + c, end, q!, q, quit all failed, the correct syntax to quit or exit the JShell is /exit. Terminal C:\Users\mkyong>jshell | Welcome to JShell — Version 11.0.1 | For an introduction type: /help intro jshell> exit | Error: | …

Read more

What is new in Java 11

Java 11 reached General Availability on 25 September 2018, this is a Long Term Support (LTS) version, download Java 11 here or this openJDK archived. Java 11 features. 1. JEP 181: Nest-Based Access Control 2. JEP 309: Dynamic Class-File Constants 3. JEP 315: Improve Aarch64 Intrinsics 4. JEP 318: Epsilon: A No-Op Garbage Collector (Experimental) …

Read more

Java SSLSocket TLS 1.3 example

This Java 11 JEP 332 adds support for TLS 1.3 protocol. SSLSocket + TLS 1.3 An SSLSocket client with TLS1.3 protocol and TLS_AES_128_GCM_SHA256 stream cipher, to send a request to https://google.com and print the response. JavaTLS13.java package com.mkyong.java11.jep332; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import java.io.*; // Java 11 public class JavaTLS13 { private static final String[] …

Read more

Java – How to generate a random 12 bytes?

In Java, we can use SecureRandom.nextBytes(byte[] bytes) to generate a user-specified number of random bytes. This SecureRandom is a cryptographically secure random number generator (RNG). 1. Random 12 bytes (96 bits) 1.1 Generates a random 12 bytes (96 bits) nonce. HelloCryptoApp.java package com.mkyong.crypto; import java.security.SecureRandom; public class HelloCryptoApp { public static void main(String[] args) { …

Read more

Java 11 – ChaCha20-Poly1305 encryption examples

This article shows you how to encrypt and decrypt a message with the ChaCha20-Poly1305 algorithm, defined in RFC 7539. P.S The ChaCha20-Poly1305 encryption algorithm is available at Java 11. 1. FAQs Some commonly asked questions: 1.1 What is ChaCha20-Poly1305? ChaCha20-Poly1305 means the ChaCha20 (encryption and decryption algorithm) running in AEAD mode with the Poly1305 authenticator. …

Read more

Java – How to join and split byte arrays, byte[]

In this example, we will show you how to join and split byte arrays with ByteBuffer and System.arraycopy. ByteBuffer public static byte[] joinByteArray(byte[] byte1, byte[] byte2) { return ByteBuffer.allocate(byte1.length + byte2.length) .put(byte1) .put(byte2) .array(); } public static void splitByteArray(byte[] input) { ByteBuffer bb = ByteBuffer.wrap(input); byte[] cipher = new byte[8]; byte[] nonce = new byte[4]; …

Read more

Java – Convert byte[] to int and vice versa

In Java, we can use ByteBuffer to convert int to byte[] and vice versa. int to byte[] int num = 1; // int need 4 bytes, default ByteOrder.BIG_ENDIAN byte[] result = ByteBuffer.allocate(4).putInt(number).array(); byte[] to int byte[] byteArray = new byte[] {00, 00, 00, 01}; int num = ByteBuffer.wrap(bytes).getInt(); 1. int to byte[] This Java example …

Read more

Java Serialization and Deserialization Examples

In Java, Serialization means converting Java objects into a byte stream; Deserialization means converting the serialized object’s byte stream back to the original Java object. Table of contents. 1. Hello World Java Serialization 2. java.io.NotSerializableException 3. What is serialVersionUID? 4. What is transient? 5. Serialize Object to File 6. Why need Serialization in Java? 7. …

Read more

Java 11 – Java Flight Recorder

Java Flight Recorder (JFR) is a Java profiling tool that used to monitor and diagnose a running Java application, it collects data about the running environment, JVM and Java application and dumps the recorded data into a .jfr file, and we can use Java Mission Control (JMC) to analyze and visualize the .jfr file. Tested …

Read more

Java – What is transient fields?

In Java, transient fields are excluded in the serialization process. In short, when we save an object into a file (serialization), all transient fields are ignored. 1. POJO + transient Review the following Person class; the salary field is transient. public class Person implements Serializable { private static final long serialVersionUID = 1L; private String …

Read more

Java – jcmd not found?

The jcmd is available at the JDK/bin, not JRE. Make sure the installed Java is JDK, not JRE. Let review the following example, try to use jcmd to enable Java Flight Recorder inside a docker container. 1. DockerFile A simple Dokcerfile. Dockerfile FROM adoptopenjdk/openjdk11:alpine-jre ARG JAR_FILE=target/markdown.jar WORKDIR /opt/app COPY ${JAR_FILE} app.jar ENTRYPOINT ["java","-jar","app.jar"] 2. Docker …

Read more

Java 11 – Nest-Based Access Control

This JEP 181: Nest-Based Access Control, supports private access within nest members directly, no more via an auto-generated bridge method access$000. Furthermore, new nest APIs for validation and allowed private reflection access within nest members. P.S No need to change the code, it is a Java compiler’s optimization to remove the bridge method access. 1. …

Read more

Java Iterator examples

A few of Java Iterator and ListIterator examples. 1. Iterator 1.1 Get Iterator from a List or Set, and loop over it. JavaIteratorExample1a.java package com.mkyong; import java.util.Arrays; import java.util.Iterator; import java.util.List; public class JavaIteratorExample1a { public static void main(String[] args) { /* Set<Integer> set = new HashSet<>(); set.add(1); set.add(2); set.add(3); set.add(4); set.add(5); Iterator<Integer> iterator = …

Read more

What is new in Java 14

Java 14 reached General Availability on 17 March 2020, download Java 14 here. Java 14 features. 1. JEP 305: Pattern Matching for instanceof (Preview) 2. JEP 343: Packaging Tool (Incubator) 3. JEP 345: NUMA-Aware Memory Allocation for G1 4. JEP 349: JFR Event Streaming 5. JEP 352: Non-Volatile Mapped Byte Buffers 6. JEP 358: Helpful …

Read more

Java List throws UnsupportedOperationException

Typically, we use Arrays.asList or the new Java 9 List.of to create a List. However, both methods return a fixed size or immutable List, it means we can’t modify it, else it throws UnsupportedOperationException. JavaListExample.java package com.mkyong; import java.util.Arrays; import java.util.List; public class JavaListExample { public static void main(String[] args) { // immutable list, cant …

Read more

What is java.util.Arrays$ArrayList?

The java.util.Arrays$ArrayList is a nested class inside the Arrays class. It is a fixed size or immutable list backed by an array. Arrays.java public static <T> List<T> asList(T… a) { return new ArrayList<>(a); } /** * @serial include */ private static class ArrayList<E> extends AbstractList<E> implements RandomAccess, java.io.Serializable { private static final long serialVersionUID = …

Read more

Java – How to display % in String.Format?

This example shows you how to display a percentage % in String.format. JavaStringFormat1.java package com.mkyong; public class JavaStringFormat1 { public static void main(String[] args) { String result = String.format("%d%", 100); System.out.println(result); } } Output Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = ‘%’ at java.base/java.util.Formatter.checkText(Formatter.java:2732) at java.base/java.util.Formatter.parse(Formatter.java:2718) at java.base/java.util.Formatter.format(Formatter.java:2655) at java.base/java.util.Formatter.format(Formatter.java:2609) at java.base/java.lang.String.format(String.java:2897) Solution To display …

Read more

How to pad a String in Java?

This article shows you how to use the JDK1.5 String.format() and Apache Common Lang to left or right pad a String in Java. 1. String.format By default, the String.format() fills extra with spaces \u0020. Normally, we use replace() to pad with other chars, but it will replace the spaces in between the given string. JavaPadString1.java …

Read more

Java String Format Examples

This article shows you how to format a string in Java, via String.format(). Here is the summary. Conversion Category Description %b, %B general true of false %h, %H general hash code value of the object %s, %S general string %c, %C character unicode character %d integral decimal integer %o integral octal integer, base 8 %x, …

Read more

Java mod examples

Both remainder and modulo are two similar operations; they act the same when the numbers are positive but much differently when the numbers are negative. In Java, we can use Math.floorMod() to describe a modulo (or modulus) operation and % operator for the remainder operation. See the result: | rem & +divisor| rem & -divisor …

Read more

How to add JAVA_HOME on Ubuntu?

On Ubuntu, we can add JAVA_HOME environment variable in /etc/environment file. Note /etc/environment system-wide environment variable settings, which means all users use it. It is not a script file, but rather consists of assignment expressions, one per line. We need admin or sudo to modify this it. Further Reading Ubuntu – EnvironmentVariables 1. JAVA_HOME 1.1 …

Read more

How to install Java JDK on macOS

This article shows how to install Java JDK on macOS, Homebrew package manager, manual installation, and switch between different JDK versions. Tested with macOS 11 Big Sur Homebrew 2.7.4 JDK 8, 14, 16, 16 (AdoptOpenJDK and OpenJDK) Topics Homebrew install latest Java (OpenJDK) on macOS Homebrew install Java 8 (OpenJDK) on macOS Homebrew install a …

Read more

Java Map with Insertion Order

In Java, we can use LinkedHashMap to keep the insertion order. P.S HashMap does not guarantee insertion order. 1. HashMap Generate a HashMap, UUID as key, index 0, 1, 2, 3, 4… as value. JavaHashMap.java package com.mkyong.samples; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.stream.IntStream; public class JavaHashMap { public static void main(String[] args) { …

Read more

Java Trap – Autoboxing and Unboxing

The below program is a typical Java trap, and also a popular Java interview question. It has no compiler error or warning but running very slow. Can you spot the problem? JavaSum.java package com.mkyong; import java.time.Duration; import java.time.Instant; public class JavaSum { public static void main(String[] args) { Instant start = Instant.now(); Long total = …

Read more

How to change the JVM default locale?

In Java, we can use Locale.setDefault() to change the JVM default locale. JavaLocaleExample.java package com.mkyong.locale; import java.util.Locale; public class JavaLocaleExample { public static void main(String[] args) { // get jvm default locale Locale defaultLocale = Locale.getDefault(); System.out.println(defaultLocale); // set jvm locale to china Locale.setDefault(Locale.CHINA); // or like this //Locale.setDefault(new Locale("zh", "cn"); Locale chinaLocale = Locale.getDefault(); …

Read more

Java Scanner examples

Long live the Scanner class, a few examples for self-reference. 1. Read Input 1.1 Read input from the console. JavaScanner1.java package com.mkyong.io; import java.util.Scanner; public class JavaScanner1 { public static void main(String[] args) { try (Scanner scanner = new Scanner(System.in)) { System.out.print("Please enter your name: "); String input = scanner.nextLine(); System.out.println("name : " + input); …

Read more

Java – How to print a name 10 times?

This article shows you different ways to print a name ten times. 1. Looping 1.1 For loop JavaSample1.java package com.mkyong.samples; public class JavaSample1 { public static void main(String[] args) { for (int i = 0; i < 10; i++) { System.out.println("Java "); } } } Output Java Java Java Java Java Java Java Java Java …

Read more

Java – How to download web page from internet?

A simple Java source code to download a web page from the internet. JavaDownloadWebPage.java package com.mkyong; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; public class JavaDownloadWebPage { public static void main(String[] args) throws IOException { String result = downloadWebPage("https://mkyong.com"); System.out.println(result); } private static String downloadWebPage(String url) throws IOException { StringBuilder …

Read more