Java – String vs StringBuffer

This article shows the difference in time taken for similar operations on a String object and StringBuffer object. String being an immutable class, it instantiates a new object each time an operation is performed on it StringBuffer being a mutable class, the overhead of object instantiation during operations is removed. Hence, the time taken for …

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 Date and Calendar examples

This tutorial shows you how to work with java.util.Date and java.util.Calendar. 1. Java Date Examples Few examples to work with Date APIs. Example 1.1 – Convert Date to String. SimpleDateFormat sdf = new SimpleDateFormat("dd/M/yyyy"); String date = sdf.format(new Date()); System.out.println(date); //15/10/2013 Example 1.2 – Convert String to Date. SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss"); String …

Read more

Where to download Java JDK source code ?

The JDK source code is inside the src.zip, this article shows you how to get it on Windows, Ubuntu (Linux) and Mac OSX. 1. Windows In Windows, visit the Oracle website and download the JDK (not JRE). Install the JDK and the src.zip is inside the JDK installed folder, for example : C:\Program Files\Java\jdk1.7.0_40\src.zip 2. …

Read more

Java – How to calculate leap year

A leap year is a year containing one additional day (366 days a year). Review the leap year algorithm : if year is divisible by 400 then is_leap_year else if year is divisible by 100 then not_leap_year else if year is divisible by 4 then is_leap_year else not_leap_year P.S Algorithm from wikipedia leap year. 1. …

Read more

Java – Time elapsed in days, hours, minutes, seconds

Two Java examples show you how to print the elapsed time in days, hours, minutes and seconds format. 1. Standard JDK Date APIs You need to calculate the elapsed time manually. DateTimeUtils.java package com.mkyong.dateUtils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class DateTimeUtils { public static void main(String[] args) { DateTimeUtils obj = new DateTimeUtils(); …

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

Jsoup – Get favicon from html page

There are many ways the favicon can be recognized by the web browser : Example 1 <head> <link rel="icon" href="http://example.com/image.ico" /> </head> Example 2 <head> <link rel="icon" href="http://example.com/image.png" /> </head> Example 3 – weird, but Google use it. <head> <meta content="/images/google_favicon_128.png" itemprop="image" /> </head> 1. Jsoup Example Code snippets to get above favicon with Jsoup. …

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

Jackson : was expecting double-quote to start field name

A simple example to use Jackson to convert a JSON string to a Map. String json = "{name:\"mkyong\"}"; Map<String,String> map = new HashMap<String,String>(); ObjectMapper mapper = new ObjectMapper(); map = mapper.readValue(json, new TypeReference<HashMap<String,String>>(){}); Problem When the program is executed, it hits following error message org.codehaus.jackson.JsonParseException: Unexpected character (‘n’ (code 110)): was expecting double-quote to start …

Read more

How to convert String to Date – Java

In this tutorial, we will show you how to convert a String to java.util.Date. Many Java beginners are stuck in the Date conversion, hope this summary guide will helps you in some ways. // String -> Date SimpleDateFormat.parse(String); // Date -> String SimpleDateFormat.format(date); Refer to table below for some of the common date and time …

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

Java Whois example

In this tutorial, we will show you how to use Java library – “Apache Commons Net” to get WHOIS data of a domain. 1. Simple Java Whois Example For domain registered under internic.net, you can get the whois data directly. WhoisTest.java package com.mkyong.whois.bo; import java.io.IOException; import java.net.SocketException; import org.apache.commons.net.whois.WhoisClient; public class WhoisTest { public static …

Read more

Reporting in Java using DynamicReports and JasperReports

This example shows how to generate a simple report using DynamicReports and JasperReports. DynamicReports is a Java reporting library that allows you to produce report documents that can be exported into many popular formats. It is based on the well-known JasperReports library. Tools used in this article : DynamicReports 3.1.3 JasperReports 5.0.4 MySQL 5.5 Maven …

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

Java HttpURLConnection follow redirect example

The HttpURLConnection‘s follow redirect is just an indicator, in fact it won’t help you to do the “real” http redirection, you still need to handle it manually. URL obj = new URL(url); HttpURLConnection conn = (HttpURLConnection) obj.openConnection(); conn.setInstanceFollowRedirects(true); //you still need to handle redirect manully. HttpURLConnection.setFollowRedirects(true); 1. Java Http Redirect Example If a server is …

Read more

How to get HTTP Response Header in Java

This example shows you how to get the Http response header values in Java. 1. Standard JDK example. URL obj = new URL("https://mkyong.com"); URLConnection conn = obj.openConnection(); //get all headers Map<String, List<String>> map = conn.getHeaderFields(); for (Map.Entry<String, List<String>> entry : map.entrySet()) { System.out.println("Key : " + entry.getKey() + " ,Value : " + entry.getValue()); } …

Read more

Maven $JAVA_HOME is not defined correctly on Mac OS

This article shows how to fix the Maven error JAVA_HOME is not defined correctly. Terminal $ mvn -version Error: JAVA_HOME is not defined correctly. We cannot execute /usr/libexec/java_home/bin/java Further Reading How to set $JAVA_HOME environment variable on macOS 1. $JAVA_HOME and macOS 10.15 Catalina, macOS 11 Big Sur On macOS 10.15 Catalina and later, the …

Read more

Due to limitations of the BasicDBObject, you can’t add a second ‘$and’

Problem Using Spring data and Mongodb, below is a function to find data within a date range. public List<RequestAudit> findByIpAndDate(String ip, Date startDate, Date endDate) { Query query = new Query( Criteria.where("ip").is(ip) .andOperator(Criteria.where("createdDate").gte(startDate)) .andOperator(Criteria.where("createdDate").lt(endDate)) ); return mongoOperation.find(query, RequestAudit.class); } It hits following error message : org.springframework.data.mongodb.InvalidMongoDbApiUsageException: Due to limitations of the com.mongodb.BasicDBObject, you can’t add …

Read more

How to Set $JAVA_HOME environment variable on macOS

This article shows how to set the $JAVA_HOME environment variable on older Mac OS X and the latest macOS 11. Topics macOS release history What is /usr/libexec/java_home $JAVA_HOME and macOS 11 Big Sur $JAVA_HOME and Mac OS X 10.5 Leopard $JAVA_HOME and older Mac OS X Switch between different JDK versions Solution Steps to set …

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

Access restriction: The type BASE64Encoder is not accessible due to restriction

Problem Downloaded a Java sample from Alexa API on Amazon service, imports it into Eclipse, but unable to compile and hits following “Access restriction” errors : Access restriction: The type BASE64Encoder is not accessible due to restriction on required library /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/classes.jar P.S Using JDK 1.6 and Eclipse IDE 4.2 import sun.misc.BASE64Encoder; // Access restriction error …

Read more

How to get Alexa Ranking In Java

In this example, we show you how to use Java and DOM XML parser to get the Alexa ranking from below the undocumented API : http://data.alexa.com/data?cli=10&url=domainName 1. Alexa API For example, type following URL in your browser : http://data.alexa.com/data?cli=10&url=mkyong.com Alexa will return back following XML result : <ALEXA VER="0.9" URL="mkyong.com/" HOME="0" AID="="> <DMOZ> <SITE BASE="mkyong.com/" …

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

Convert Java Project to Web Project in Eclipse

This tutorial shows you how to convert a Java project to Java web application project in Eclipse 4.2, it should work in older version as well. 1. Java Project A simple Java project. 2. Project Facets Right click on the project properties. Select “Project Facets“, and click “convert to faceted form…” Check “Dynamic Web Module” …

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 execute shell command from Java

In Java, we can use ProcessBuilder or Runtime.getRuntime().exec to execute external shell command : 1. ProcessBuilder ProcessBuilder processBuilder = new ProcessBuilder(); // — Linux — // Run a shell command processBuilder.command("bash", "-c", "ls /home/mkyong/"); // Run a shell script //processBuilder.command("path/to/hello.sh"); // — Windows — // Run a command //processBuilder.command("cmd.exe", "/c", "dir C:\\Users\\mkyong"); // Run a …

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

Java enum example

Some of the Java enum examples, and how to use it, nothing special, just for self-reference. Note Consider the Enum type if your program consists of a fixed set of constants, like seasons of the year, operations calculator, user status and etc. 1. Basic Enum UserStatus.java public enum UserStatus { PENDING, ACTIVE, INACTIVE, DELETED; } …

Read more

How to list all Jobs in the Quartz Scheduler

Below are two code snippets to show you how to list all Quartz jobs. Quartz 2 APIs are changed a lot, so syntax is different from Quartz 1.x. 1. Quartz 2.1.5 example Scheduler scheduler = new StdSchedulerFactory().getScheduler(); for (String groupName : scheduler.getJobGroupNames()) { for (JobKey jobKey : scheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName))) { String jobName = jobKey.getName(); String jobGroup …

Read more