Java – Compare Enum value

In Java, you can use == operator to compare Enum value. 1. Java Enum example Language.java package com.mkyong.java public enum Language { JAVA, PYTHON, NODE, NET, RUBY } 2. Compare with == Example to compare enum value with == operator. Test.java package com.mkyong.java public class Test { public static void main(String[] args) { // Covert …

Read more

How to read and write Java object to a file

Java object Serialization is an API provided by Java Library stack as a means to serialize Java objects. Serialization is a process to convert objects into a writable byte stream. Once converted into a byte-stream, these objects can be written to a file. The reverse process of this is called de-serialization. A Java object is …

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

How to get the environment variables in Java

In Java, the System.getenv() returns an unmodifiable string Map view of the current system environment. Map<String, String> env = System.getenv(); // get PATH environment variable String path = System.getenv("PATH"); Table of contents. 1. Get a specified environment variable 2. UnsupportedOperationException 3. Display all environment variables 4. Sort the environment variables 5. Download Source Code 6. …

Read more

Jackson 2 – Convert Java Object to / from JSON

In this tutorial, we will show you how to use Jackson 2.x to convert Java objects to / from a JSON. 1. Basic 1.1 Convert a Staff object to from JSON. writeValue(…) – Java Objects to JSON ObjectMapper mapper = new ObjectMapper(); // Java object to JSON file mapper.writeValue(new File("c:\\test\\staff.json"), new Staff()); // Java object …

Read more

How to split a string in Java

In Java, we can use String#split() to split a string. String phone = "012-3456789"; // String#split(string regex) accepts regex as the argument String[] output = phone.split("-"); String part1 = output[0]; // 012 String part2 = output[1]; // 3456789 Table of contents 1. Split a string (default) 2. Split a string and retain the delimiter 3. …

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 – Generate random integers in a range

In this article, we will show you three ways to generate random integers in a range. java.util.Random.nextInt Math.random java.util.Random.ints (Java 8) 1. java.util.Random This Random().nextInt(int bound) generates a random integer from 0 (inclusive) to bound (exclusive). 1.1 Code snippet. For getRandomNumberInRange(5, 10), this will generates a random integer between 5 (inclusive) and 10 (inclusive). private …

Read more

How to convert String to int in Java

In Java, we can use Integer.parseInt(String) to convert a String to an int; For unparsable String, it throws NumberFormatException. Integer.parseInt("1"); // ok Integer.parseInt("+1"); // ok, result = 1 Integer.parseInt("-1"); // ok, result = -1 Integer.parseInt("100"); // ok Integer.parseInt(" 1"); // NumberFormatException (contains space) Integer.parseInt("1 "); // NumberFormatException (contains space) Integer.parseInt("2147483648"); // NumberFormatException (Integer max 2,147,483,647) …

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

Jsoup – Check Redirect URL

In this article, we will show you how to use Jsoup to check if an URL is going to redirect. 1. URL Redirection Normally, a redirect URL will return an HTTP code of 301 or 307, and the target URL will be existed in the response header “location” field. Review a sample of HTTP Response …

Read more

Java – Convert date and time between timezone

In this tutorial, we will show you few examples (ZonedDateTime (Java 8), Date, Calendar and Joda Time) to convert a date and time between different time zones. All examples will be converting the date and time from (UTC+8:00) Asia/Singapore – Singapore Time Date : 22-1-2015 10:15:55 AM to (UTC-5:00) America/New_York – Eastern Standard Time Date …

Read more

Java – Display list of TimeZone with GMT

This Java example shows you how to display a list of TimeZone with GMT in front. P.S Tested with JDK 1.7 Java 8 You may interest at this example – Display all ZoneId and its UTC offset TimeZoneExample.java package com.mkyong.test; import java.util.TimeZone; import java.util.concurrent.TimeUnit; public class TimeZoneExample { public static void main(String[] args) { String[] …

Read more

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

Convert DateTime to Date, but TimeZone is missing?

A code snippet to use Joda Time to convert a java.util.Date to different timezone : //java.util.Date : 22-1-2015 10:15:55 AM //System TimeZone : Asia/Singapore //Convert java.util.Date to America/New_York TimeZone DateTime dt = new DateTime(date); DateTimeZone dtZone = DateTimeZone.forID("America/New_York"); DateTime dtus = dt.withZone(dtZone); //21-1-2015 09:15:55 PM – Correct! //Convert Joda DateTime back to java.util.Date, and print …

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 – Cron job to run a jar file

Quartz is good, but often times we just need a simple scheduler system to run a jar file periodically. On *unix system, you can use the build-in cron to schedule a scheduler job easily. In this example, we will show you how to create a cron job on *nix to run a jar file, by …

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

jsoup : Send search query to Google

This example shows you how to use jsoup to send a search query to Google. Document doc = Jsoup .connect("https://www.google.com/search?q=mario"); .userAgent("Mozilla/5.0") .timeout(5000).get(); Unusual traffic from your computer network Don’t use this example to spam Google, you will get above message from Google, read this Google answer. 1. jsoup example Example to send a “mario” search …

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

servlet-api-2.5.jar – jar not loaded

Deployed a “war” file on Tomcat, and hits following error messages : Jul 17, 2014 7:59:55 PM org.apache.catalina.loader.WebappClassLoader validateJarFile INFO: validateJarFile(D:\apache-tomcat-7.0.53\webapps\hc\WEB-INF\lib\servlet-api-2.5.jar) – jar not loaded. See Servlet Spec 3.0, section 10.7.2. Offending class: javax/servlet/Servlet.class Tools used : JDK1.7 Maven 3 Tomcat 7 1. Reason The Tomcat’s container comes with own version of servlet-api.jar, and 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

Find out your Java heap memory size

In this article, we will show you how to use the -XX:+PrintFlagsFinal to find out your heap size detail. In Java, the default and maximum heap size are allocated based on this – ergonomics algorithm. Heap sizes Initial heap size of 1/64 of physical memory up to 1Gbyte Maximum heap size of 1/4 of physical …

Read more

Java – Append values into an Object[] array

In this example, we will show you how to append values in Object[] and int[] array. Object[] obj = new Object[] { "a", "b", "c" }; ArrayList<Object> newObj = new ArrayList<Object>(Arrays.asList(obj)); newObj.add("new value"); newObj.add("new value 2"); 1. Object[] Array Example Example to append values with ArrayList : TestApp.java package com.mkyong.test; import java.util.ArrayList; import java.util.Arrays; public …

Read more

Java – Convert int[] to Integer[] example

Examples show you how to convert between int[] and its’ wrapper class Integer[]. 1. Convert int[] to Integer[] public static Integer[] toObject(int[] intArray) { Integer[] result = new Integer[intArray.length]; for (int i = 0; i < intArray.length; i++) { result[i] = Integer.valueOf(intArray[i]); } return result; } 2. Convert Integer[] to int[] public static int[] toPrimitive(Integer[] …

Read more

The type DefaultHttpClient is deprecated

Eclipse IDE prompts warning on new DefaultHttpClient, mark this class as deprecated. package com.mkyong.web.controller; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; public class WebCrawler { public static void main(String[] args) throws Exception { HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet("https://mkyong.com"); HttpResponse response = client.execute(request); //… } } Solution Dive …

Read more

Java – Check if web request is from Google crawler

If a web request is coming from Google crawler or Google bot, the requested “user agent” should look similar like this : Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html) or (rarely used): Googlebot/2.1 (+http://www.google.com/bot.html) Source : Google crawlers 1. Java Example In Java, you can get the “user agent” from HttpServletRequest. Example : Service hosted at abcdefg.com @Autowired …

Read more

How To Get HTTP Request Header In Java

This example shows you how to get the HTTP request headers in Java. To get the HTTP request headers, you need this class HttpServletRequest : 1. HttpServletRequest Examples 1.1 Loop over the request header’s name and print out its value. WebUtils.java package com.mkyong.web.utils; import javax.servlet.http.HttpServletRequest; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; public class WebUtils { …

Read more

Java – Write directly to memory

You have been told a lot that you can’t manage memory in Java. Well, it has changed since HotSpot release of the Java VM. There is a way to directly allocate and deallocate memory as well as write and read it… Of course we are talking about the JVM memory where the Java program runs. …

Read more

Java Custom Annotations Example

In this tutorial, we will show you how to create two custom annotations – @Test and @TestInfo, to simulate a simple unit test framework. P.S This unit test example is inspired by this official Java annotation article. 1. @Test Annotation This @interface tells Java this is a custom annotation. Later, you can annotate it on …

Read more