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 – 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

Java – How to join Arrays

In this article, we will show you a few ways to join a Java Array. Apache Commons Lang – ArrayUtils Java API Java 8 Stream 1. Apache Commons Lang – ArrayUtils The simplest way is add the Apache Commons Lang library, and use ArrayUtils. addAll to join arrays. This method supports both primitive and object …

Read more

Java – Mutable and Immutable Objects

This article shows you the difference between Mutable and Immutable objects in Java 1. Mutable object – You can change the states and fields after the object is created. For examples: StringBuilder, java.util.Date and etc. 2. Immutable object – You cannot change anything after the object is created. For examples: String, boxed primitive objects like …

Read more

How to print an Array in Java

In this article, we will show you a few ways to print a Java Array. Table of contents. 1. JDK 1.5 Arrays.toString 2. Java 8 Stream APIs 3. Java 8 Stream APIs – Collectors.joining 4. Jackson APIs 5. References 1. JDK 1.5 Arrays.toString We can use Arrays.toString to print a simple array and Arrays.deepToString for …

Read more

Java RMI Hello World example

RMI stands for Remote Method Invocation and it is the object-oriented equivalent of RPC (Remote Procedure Calls). RMI was designed to make the interaction between applications using the object-oriented model and run on different machines seem like that of stand-alone programs. The code below will give you the basis to Java RMI with a very …

Read more

Java – How to delay few seconds

In Java, we can use TimeUnit.SECONDS.sleep() or Thread.sleep() to delay few seconds. 1. TimeUnit JavaDelayExample.java package com.mkyong; import java.util.Date; import java.util.concurrent.TimeUnit; public class JavaDelayExample { public static void main(String[] args) { try { System.out.println("Start…" + new Date()); // delay 5 seconds TimeUnit.SECONDS.sleep(5); System.out.println("End…" + new Date()); // delay 0.5 second //TimeUnit.MICROSECONDS.sleep(500); // delay 1 minute …

Read more

Java – Check if key exists in HashMap

In Java, you can use Map.containsKey() to check if a key exists in a Map. TestMap.java package com.mkyong.examples; import java.util.HashMap; import java.util.Map; public class TestMap { public static void main(String[] args) { Map<String, Integer> fruits = new HashMap<>(); fruits.put("apple", 1); fruits.put("orange", 2); fruits.put("banana", 3); fruits.put("watermelon", null); System.out.println("1. Is key ‘apple’ exists?"); if (fruits.containsKey("apple")) { //key …

Read more

Java – Display double in 2 decimal places

In Java, there are few ways to display double in 2 decimal places. Table of contents. 1. DecimalFormat("0.00") 2. String.format("%.2f") 3. BigDecimal 4. References Possible Duplicate How to round double / float value to 2 decimal places 1. DecimalFormat(“0.00”) We can use DecimalFormat("0.00") to ensure the number is round to 2 decimal places. DecimalExample.java package …

Read more

Java – Math.pow example

A simple Math.pow example, display 2 to the power of 8. In Math 2^8 = 2x2x2x2x2x2x2x2 =256 In Java Math.pow(2, 8) Note In Java, the symbol ^ is a XOR operator, DON’T use this for the power calculation. TestPower.java package com.mkyong.test; import java.text.DecimalFormat; public class TestPower { static DecimalFormat df = new DecimalFormat(".00"); public static …

Read more

Java – Get number of available processors

A code snippet to show you how to get the number of available processors / cores / CPUs in your environment. int processors = Runtime.getRuntime().availableProcessors(); System.out.println(processors); Output 8 P.S Tested with Intel(R) Core(TM) i7-4770 CPU @3.40GHz

Java – Convert Date to Calendar example

In Java, you can use calendar.setTime(date) to convert a Date object to a Calendar object. Calendar calendar = Calendar.getInstance(); Date newDate = calendar.setTime(date); A Full example DateAndCalendar.java import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class DateAndCalendar { public static void main(String[] argv) throws ParseException { //1. Create a Date from String SimpleDateFormat sdf …

Read more

Java – Convert String to Enum object

In Java, you can use Enum valueOf() to convert a String to an Enum object, review the following case study : 1. Java Enum example WhoisRIR.java package com.mkyong.whois.utils; public enum WhoisRIR { ARIN("whois.arin.net"), RIPE("whois.ripe.net"), APNIC("whois.apnic.net"), AFRINIC("whois.afrinic.net"), LACNIC("whois.lacnic.net"), JPNIC("whois.nic.ad.jp"), KRNIC("whois.nic.or.kr"), CNNIC("ipwhois.cnnic.cn"), UNKNOWN(""); private String url; WhoisRIR(String url) { this.url = url; } public String url() { …

Read more

Java : Return a random item from a List

Normally, we are using the following ways to generate a random number in Java. 1. ThreadLocalRandom (JDK 1.7) //Generate number between 0-9 int index = ThreadLocalRandom.current().nextInt(10); 2. Random() //Generate number between 0-9 Random random = new Random(); int index = random.nextInt(10); 3. Math.random() //Generate number between 0-9 int index = (int)(Math.random()*10); Note 1. For single …

Read more

Java – Read a file from resources folder

In Java, we can use getResourceAsStream or getResource to read a file or multiple files from a resources folder or root of the classpath. The getResourceAsStream method returns an InputStream. // the stream holding the file content InputStream is = getClass().getClassLoader().getResourceAsStream("file.txt"); // for static access, uses the class name directly InputStream is = JavaClassName.class.getClassLoader().getResourceAsStream("file.txt"); The …

Read more

Java – Get nameservers of a website

In this tutorial, we will show you how to get the nameservers of a website using Java + dig command. 1. Using Dig Command 1.1 On Linux, we can use dig command to query a DNS lookup of a website, for example : $ dig any mkyong.com //… mkyong.com. 299 IN A 162.159.x.x mkyong.com. 299 …

Read more

Java and “& 0xFF” example

Before you understand what is & 0xFF, make sure you know following stuffs : Bitwise AND operator, link. Converts hex to/from binary, and decimal to/from binary. In short, & 0xFF is used to make sure you always get the last 8 bits. Let’s see an example to convert an IP address to/from decimal number. 1. …

Read more

Java – find location using Ip Address

In this example, we show you how to find a location (country, city, latitude, longitude) using an IP address. 1. GeoLite Database The MaxMind provides a free GeoLite database (IP Address to Location). Get a free GeoLite free Databases – here Get a GeoIP client Java APIs – here Start code it. 2. GeoLite Java …

Read more

How to join two Lists in Java

In this article, we show you 2 examples to join two lists in Java. JDK – List.addAll() Apache Common – ListUtils.union() 1. List.addAll() example Just combine two lists with List.addAll(). JoinListsExample.java package com.mkyong.example; import java.util.ArrayList; import java.util.List; public class JoinListsExample { public static void main(String[] args) { List<String> listA = new ArrayList<String>(); listA.add("A"); List<String> listB …

Read more

Convert String with commas to Long – Java

A short guide to show you how to convert a String with commas to a long type. 1. For a normal String, you can use Long.valueOf to convert it directly. String bigNumber = "1234567899"; long result = Long.valueOf(bigNumber); 2. For a String with commas, you can use java.text.NumberFormat to convert it. String bigNumber = "1,234,567,899"; …

Read more

How to send HTTP request GET/POST in Java

In this article, we will show you a few examples to make HTTP GET/POST requests via the following APIs Apache HttpClient 4.5.10 OkHttp 4.2.2 Java 11 HttpClient Java 1.1 HttpURLConnection (Not recommend) 1. Apache HttpClient In the old days, this Apache HttpClient is the de facto standard to send an HTTP GET/POST request in Java. …

Read more

Apache HttpClient Examples

This article shows you how to use Apache HttpClient to send an HTTP GET/POST requests, JSON, authentication, timeout, redirection and some frequent used examples. P.S Tested with HttpClient 4.5.10 pom.xml <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.10</version> </dependency> 1. Send GET Request 1.1 Close manually. HttpClientExample1_1.java package com.mkyong.http; import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; …

Read more

ASCII Art Java example

A funny Java example to create an ASCII art graphic. The concept is simple, get the image’s rgb color in “integer mode”, later, replace the color’s integer with ascii text. P.S This example is credited for this post ASCIIArtService.java package com.mkyong.service; import java.awt.*; import java.awt.image.BufferedImage; import java.io.IOException; public class ASCIIArtService { public static void main(String[] …

Read more

Display a list of countries in Java

In this article, we show you how to use the Locale class to play around the list of countries. P.S Tested with JDK 1.6 1. List of Countries The Locale.getISOCountries() will return a list of all 2-letter country codes defined in ISO 3166. ListCountry.java package com.webmitta.model; import java.util.Locale; public class ListCountry { public static void …

Read more

How to get client Ip Address in Java

In Java, you can use HttpServletRequest.getRemoteAddr() to get the client’s IP address that’s accessing your Java web application. import javax.servlet.http.HttpServletRequest; String ipAddress = request.getRemoteAddr(); 1. Proxy Server or Cloudflare For web application which is behind a proxy server, load balancer or the popular Cloudflare solution, you should get the client IP address via the HTTP …

Read more

How to get Google PageRank (PR) in Java

In this example, we will show you how to get Google PageRank (PR) in Java. To request a PageRank for “mkyong.com”, you just need to send following HTTP request : http://toolbarqueries.google.com/tbr?client=navclient-auto&hl=en&ch=6236440745 &ie=UTF-8&oe=UTF-8&features=Rank&q=info:mkyong.com P.S Above URL is used by Google toolbar plugin. The tricky part is following hashing value : ch=6236440745 Google is using Bob Jenkins …

Read more

Search directories recursively for file in Java

Here’s an example to show you how to search a file named “post.php” from directory “/Users/mkyong/websites” and all its subdirectories recursively. FileSearch.java package com.mkyong; import java.io.File; import java.util.ArrayList; import java.util.List; public class FileSearch { private String fileNameToSearch; private List<String> result = new ArrayList<String>(); public String getFileNameToSearch() { return fileNameToSearch; } public void setFileNameToSearch(String fileNameToSearch) { …

Read more

How to count duplicated items in Java List

A Java example to show you how to count the total number of duplicated entries in a List, using Collections.frequency and Map. CountDuplicatedList.java package com.mkyong; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; public class CountDuplicatedList { public static void main(String[] args) { List<String> list = new …

Read more

Java : getResourceAsStream in static method

To call getResourceAsStream in a static method, we use ClassName.class instead of getClass() 1. In non static method getClass().getClassLoader().getResourceAsStream("config.properties")) 2. In static method ClassName.class.class.getClassLoader().getResourceAsStream("config.properties")) 1. Non Static Method A .properties file in project classpath. src/main/resources/config.properties #config file json.filepath = /Users/mkyong/Documents/workspace/SnakeCrawler/data/ FileHelper.java package com.mkyong; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class FileHelper { public static …

Read more

How to work with Java 6’s NavigableSet and NavigableMap

You can use latest Java 6’s Collection API to navigate a set and Map collections. These API gives a lot of flexibility to find out required result from the collection. 1. NavigableMap Example package com.example.collection; import java.util.NavigableMap; import java.util.TreeMap; public class NavigableMapDemo { public static void main(String[] args) { NavigableMap<String,Integer> navigableMap=new TreeMap<String, Integer>(); navigableMap.put("X", 500); …

Read more

How to use reflection to copy properties from Pojo to other Java Beans

Sometimes we need copy properties from a Java class to other, we can do it this manually or with our own reflection implementation, but in this case use us reflection for automate it with a utility from apache Requirements commons-beanutils , you can download from here http://commons.apache.org/beanutils/ commons-loging , you can download from here http://commons.apache.org/logging/ …

Read more

How to run a task periodically in Java

Some java application need to execute a method between a regular interval of time. For example GUI application should update some information from database. 1. Scheduler Task For this functionality, You should create a class extending TimerTask(available in java.util package). TimerTask is a abstract class. Write your code in public void run() method that you …

Read more

Java and zip code example

Recently, answered an question about leading zero problem ZipCode, what is the most proper data type for country’s zip code? 1. ZipCode – int In Java, some claimed it should declare as “int”, and use DecimalFormat to format and display the leading zero. For example, package com.mkyong; import java.text.DecimalFormat; public class ZipCodeExample { public static …

Read more

How to get URL content in Java

In this Java example, we show you how to get content of a page from URL “mkyong.com” and save it into local file drive, named “test.html”. package com.mkyong; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; public class GetURLContent { public static void main(String[] args) …

Read more