Difference between PUT and POST in REST WebService in Java

If you remember REST WebServices uses HTTP methods to map CRUD (create, retrieve, update, delete) operations to HTTP requests. Even though both PUT and POST methods can be used to perform create and update operation in REST WebServices, Idempotency is the main difference between PUT and POST. Similar to the GET request, PUT request is also idempotent in HTTP, which means it will produce the same results if executed once more multiple times. Another practical difference PUT and POST method in the context of REST WebService are that POST is often used to create a new entity, and PUT is often used to update an existing entity. If you replace an existing entity using PUT than you should be aware that if only a subset of data elements is passed then the rest will be replaced by empty or null.

How to enable SSL debugging in Java JVM?

Dealing with SSL issues in Java web application is no fun, especially when you have no debug logs and all you see is an ugly ‘Page Cannot be displayed’ error message in your browser. Thankfully you can easily enable SSL to debug on your Application to start seeing verbose logs that will clearly show what happens during the SSL handshake process. You can enable SSL debugging logs in your Application Server JVM config by adding the following JVM command line parameter and restart the Application Server:


Restlet HelloWorld Example in Java and Eclipse

The Restlet is one of the first open source frameworks to create and deploy RESTful web service in Java. After the release of JAX-RS (Java API for RESTful Web Services) JSR - 317, Restlet also supports JAX-RS annotation and provides a consistent way to create both RESTful Server and Client. HelloWorld program is the traditional way to start with a new technology and continuing to the tradition, we'll write our first Restlet program as HelloWorld. Since Restlet can be used to create on both client and server side, we'll first expose a resource as RESTful web service using Restlet server and then consumer the same RESTful web service by creating a RESTful client. I'll use Maven and Eclipse to create this RESTlet HelloWorld example, if you are not familiar with Maven, it's a build automation tool like ANT for Java projects but also provides dependency management i.e. you don't need to download Restlet JAR manually, Maven will do it for you. To learn more about Maven see here.

How to get the last modified date and time of a file or directory in Java

Sometimes before processing a file, you want to check it's last modified date to avoid processing an old file. Though some programmers prefer to attach date in the file name itself, I don't find it a cleaner approach. For example, suppose you are downloading closing prices of stocks and processing at the start of the day and loading into the database. In order to accidently process an old file, you can check the last modified date before processing and if it's in the acceptable range, you can process the file. You can get the last modified date of a file in Java by using java.io.File class. This is a class which represents both file and directory in Java. It contains a method called lastModified() which returns the last modified date of the file. This method returns a long millisecond epoch value, which you can convert to more readable dd MM yyyy HH:mm:sss format by using the SimpleDateFormat class of JDK.  In this article, I'll tell you how to get the last modified date of file and directory in Java.

Difference between GETDATE() vs SYSDATETIME() vs GETUTCDATE() in SQL Server

One of the common question on Microsoft SQL Server interview is, what is the difference between GETDATE(), SYSDATETIME(), and GETUTCDATE(). Even though all three SQL Sever function returns the current date time in SQL Server, there are some subtle differences between them. The main difference between GETDATE() and SYSDATETIME() is that GETDATE returns current date and time as DATETIME but SYSDATETIME returns a DATETIME2 value, which is more precise. The difference between GETDATE() and GETUTCDATE() is in timezone, the GETDATE() function return current date and time in the local timezone, the timezone where your database server is running, but GETUTCDATE() return current time and date in UTC (Universal Time Coordinate) or GMT timezone.

Top 2 Books for OCPJP8 Certification - Java 8 1Z0-809, 810, 813 Exam

This is the second part of best books for Java 8 certifications. Since you need to pass two exams, OCAJP8 and OCPJP8 to become a Java SE 8 certified developer, I have shared some of the best OCAJP8 books in the last article. In this article, I will tell you more about the second exam OCPJP8 and suggest best books prepare OCPJP8. This exam is known as professional level exam and it's tougher than the associate level exam. The OCPJP8 stands for Oracle Certified Professional Java Programmer. The exam code for this certification is 1Z0-809. This is if you don't have any prior Java certifications but you can still become a Java SE 8 certified developer by giving upgrade exams e.g. 1Z0-810 if you already passed the OCJPJP7 exam and 1z0-813 if you have passed OCPJP6 exams. The books suggested in this article is primarily for the 1Z0-809 exam but it can also be used for upgrade exams e.g. 1Z0-810 (upgrade from Java SE 7 to Java SE 8) and 1Z0-813 (upgrade from Java SE 6 to Java SE 8) certifications.

2 Ways to find Tomcat and Java Version in Linux and Windows

You can find Tomcat and java version running on Linux either by executing the org.apache.catalina.util.ServerInfo class from catalina.jar or by executing version.sh shell script. The first solution will work on any operating system including Windows and UNIX because it's using a Java class from a catalina.jar file, which is platform independent. Though, if you don't know how to run a class from JAR file, you can check the steps here. Alternatively, you also have a version.bat file inside tomcat/bin directory to check the version of Tomcat in Windows. When you run this script in Linux or Windows it prints information about tomcat version, the java version used to run tomcat, Server built date, OS name, OS Version, architecture, JVM version and JVM vendor etc.

How to replace a substring in Java?

You can replace a substring using replace() method in Java. The String class provides the overloaded version of the replace() method, but you need to use the replace(CharSequence target, CharSequence replacement). This version of the replace() method replaces each substring of this string (on which you call the replace() method) that matches the literal target sequence with the specified literal replacement sequence. For example, if you call "Effective Java".replace("Effective", "Head First") then it will replace "Effective" with "Head First" in the String "Effective Java". Since String is Immutable in Java, this call will produce a new String "Head First Java".

Base64 Encoding Decoding Example in Java 8

Until Java 8, there was no standard way to Base64 encode a String in Java or decode a base64 encoded String. Java Programmers either use Apache Commons library and it's Base64 class to encode or decode binary data into base 64 encoding, as shown here, or rely on internal Sun classes e.g. sun.misc.BASE64Encoder and sun.misc.BASE64Decoder(), which were not officially part of JDK and can be removed without notification. Java 8 solves this problem by providing standard support for base64 encoding and decoding by providing a java.util.Base64 class. This class contains methods like getEncoder() and getDecoder() to provide Base64 encoder and decoder to carry out base 64 encoding of String or binary data. In this article, I'll show you some example of how to base64 encode String in Java 8.

Java Program to print pyramid pattern of stars and numbers

You can print Pyramid pattern of stars or numbers using loops and print methods in Java. There are two print method you need to know, System.out.print() and System.out.println(), the difference between print() and println() is that println adds a new line character at the end i.e. it appends \n automatically. which means next time you write something will begin at the new line. On the other hand, if you use print() then the text is appended to the same line. By using these two methods, you can print any kind of pattern in Java program e.g. pattern involving multiple stars in one line, a pattern involving stars at different lines, pyramid of numbers, a pyramid of stars, inverted pyramid pattern of numbers, stars and alphabets, and so on.

Difference between mvn install, release and deploy in Maven

Even though there are a couple of powerful build and deployment tools exists for Java applications e.g. Gradle or ANT, It seems Maven is the king of them. I have used in several Java projects over the years and it was initially ANT, but now they all use Maven with few Scala projects using Gradle. When you work with Maven you know that there are lots of commands to remember, especially if you are working on the command line. The thee Maven build commands which often confuses Java developers are mvn install, mvn release, and mvn deploy. Many Java developers are never sure which one put the artifact on the remote repository, local repository, and tag the source code in SCM like SVN. In this article, I'll explain the purpose of mvn install, mvn release, and mvn deploy command and some key difference between them.

Best books to Learn Java 8

I often receive emails and queries asking about some good books to learn Java 8. Since Java 8 is very different from any other JDK release, in terms of language and API enhancement you really need a good book to learn fundamentals. In short, based upon my 2 years of learning and reading Java 8 books, I can say that Java SE 8 for Really Impatient is hands down the best book to learn Java 8. It covers all the essential things released in JDK 8, not just lambda expression and streams but also new Date and Time API and several other minor enhancement yet important features, which often goes un-noticed. It doesn't scare you with comprehensive detail as well and tell you what you need to know as an application developer. It's not going to teach you fundamentals of functional programming, but it will teach you how to use the map and flatMap operations.

How to check if String contains another SubString in Java? contains() and indexOf() example

You can use contains(), indexOf() and lastIndexOf() method to check if one String contains another String in Java or not. If a String contains another String then it's known as a substring. The indexOf() method accept a String and return starting position of the string if it exists, otherwise it will return -1. For example "fastfood".indexOf("food") will return 4 but "fastfood".indexOf("Pizza") will return -1. This is the easiest way to test if one String contains another substring or not. The second method is lastIndexOf() which is similar to indexOf() but start the search from the tail, but it will also return -1 if substring not found in the String or the last position of the substring, which could be anything between 0 and length -1.

How to find square root of a number in Java - Algorithm Interview question

Write a program to calculate the square root of a number in Java or C++ is one of the popular coding interview questions from Programming job interviews both on tech companies like Facebook, Amazon, and investment banks like Citibank and Bank Of America etc. The problem may look easy because you might know how to find the square root of a number but it's not. In fact, it's one of the tricky questions you would encounter in programming job interviews. The first hurdle is do you really remember how to calculate square root by hand? Many programmers don't. I know they have learned it past but when you ask them to calculate square root by hand, many won't remember the algorithm they have learned in school or college.

How to check if a String is numeric in Java? Use isNumeric() or isNumber()

In day-to-day programming, you often need to check if a given String  is numeric or not. It's also a good interview question but that's a separate topic of discussion. Even though you can use a Regular expression to check if given String is empty or not, as shown here, they are not full proof to handle all kinds of scenarios, which common third party library like Apache commons lang will handle e.g. hexadecimal and octal String. Hence, In Java application, the simplest way to determine if a String is a number or not is by using Apache Commons lang's isNumber() method, which checks whether the String a valid number in Java or not. Valid numbers include hexadecimal marked with the 0x or 0X qualifier, octal numbers, scientific notation and numbers marked with a type qualifier (e.g. 123L). Non-hexadecimal strings beginning with a leading zero are treated as octal values. Thus the string 09 will return false since 9 is not a valid octal value. However, numbers beginning with 0. are treated as decimal.null and empty/blank String will return false.

How to check if ResultSet is empty in JDBC - Java Example

The JDBC ResultSet doesn't provide any isEmpty(), length() or size() method to check if its empty or not. Hence, when a Java programmer needs to determine if ResultSet is empty or not, it just calls the next() method and if next() return false it means ResultSet is empty. This is correct but the main problem with this approach is if the ResultSet is not empty then you may miss the first row if you follow the standard idiom to iterate over ResultSet and get the rows which involve calling next() method of ResultSet in a while loop. The key thing, which you need to remember is that initially the ResultSet's cursor points to before the first row when you call the next() method it points to the first row and if you don't get this data and calls the next() method again then you will lose the first row.

Post Order binary tree traversal in Java - Recursion and Iteration

This is the third article on tree traversal. In the last couple of articles, I have shown you how to implement preorder and inorder traversal in Java, both recursively and iteratively and today, you will learn about the post order traversal. Out of these three main tree traversal algorithms, the post-order traversal is most difficult to implement, especially the iterative version. In post order traversal, you first visit left subtree, then right subtree and at last you print the value of root or not. So, the value of root is always printed at last in the post-order traversal. As I told you before, all three preOrder, inOrder, and postOrder are depth-first algorithms so they go down in the binary tree first before visiting nodes of the same level. The implementation of the recursive algorithm is very simple, you just need to adjust the order of recursive call according to the algorithm and you are done, but iterative algorithm requires some effort to get it right, which you will see in this article.

How to split String in Java by WhiteSpace or tabs? Example Tutorial

You can split a String by whitespaces or tabs in Java by using the split() method of java.lang.String class. This method accepts a regular expression and you can pass a regex matching with whitespace to split the String where words are separated by spaces. Though this is not as straightforward as it seems, especially if you are not coding in Java regularly. Input String may contain leading and trailing spaces, it may contain multiple white spaces between words and words may also be separated by tabs. Your solution needs to take care of all these conditions if you just wants words and no empty String. In this article, I am going to show you a couple of examples to demonstrate how you can split String in Java by space. By splitting I mean getting individual words as String array or ArrayList of String, whatever you need.

How to increase heap size of Eclipse - Solving OutOfMemoryError

If you are running lots of Java projects in Eclipse and it's throwing OutOfMemoryError every now and then it's time to increase the heap memory of Eclipse. Since Eclipse is a Java program, you can increase heap size of Eclipse by using JVM memory options -Xms and -Xmx. There are two ways to provide JVM options to eclipse either updating Eclipse shortcut or adding -vmargs on eclipse.ini file. I prefer the second option because it's clean. I'll tell you the exact steps to increase the java heap space in Eclipse but before that some background why I had to increase heap memory of Eclipse. I was getting "an internal error occurred during repository search . java heap space" while using Maven in Eclipse. Eclipse keep throwing java.lang.OutOfMemory:Java Heap Space while updating the index or searching for maven artifacts.

How to convert java.util.Date to java.time.LocalDate in Java 8 - Example

The easiest way to convert a java.util.Date to java.time.LocalDate is via Instant, which is the equivalent class of java.util.Date in JDK 8. You can first convert util Date to Instant and then create a LocalDateTime object from that instant at your default timezone. Once you have an instant of LocalDateTime, you can easily convert that to LocalDate or LocalTime in Java. If you are not living under the rock in last two years that its 2016 and Java 8 has been around for more than 2 years, 18th March 2014 Java SE 8 GA happened. In the third attempt of designing a robust date and time API, JDK 8 has come up with JSR 318 new Date and Time API and many programmers have already started using it.

How to Compare Date in SQL Server Query? Finding All Rows Between Two Dates

It's tricky to use dates in SQL server query, especially if you don't have good knowledge of how DateTime type works in SQL server. For example, one of the frequently asked SQL queries on the interview is to "select all rows where the date is 20151007?" How would you do that? Does following SQL Query will work correctly

select * from table where date = '20151007'

It may or may not, it entirely depends on upon data in your table. When you only provide date part of a DateTime variable, it uses '00:00:00.000' for time part.

How to check if two Rectangle Overlap in Java - Algorithm

Can you write a Java program to check if two rectangles are overlapping with each other or not? is one of the frequently asked coding questions on tech giants like Facebook, Amazon, Microsoft and others. This is also a kind of problem where it's easy to find opposite or negative conditions e.g. when rectangles are not overlapping and then inverting the result to prove that rectangles are colliding with each other. I first heard about this problem from one of my friend who was on Android game development space. He was asked to write an algorithm to find if given rectangles are intersecting or not. He was given the choice to implement the algorithm in any programming language e.g. Java, C, C++ or even pseudo code was fine, so don't worry about language here, it's more about algorithm and logic. He is a genius so he came successful from that interview, impressing the interviewer, talking about efficiency and accuracy of the algorithm as well.

3 ways to get number of months and year between two dates in Java?

Earlier I have talked about how to calculate a number of days between two dates in Java (see here), and now you will learn how to get the number of months and years between dates. Though it may look easy, it's not that easy to calculate months and years between dates, unless you take care of all kinds of nuisances like Daylight saving time and when daylight change occurs, leap seconds, and an extra day added in a leap year. Unfortunately, JDK doesn't have a standard method like Period.between() method of Java 8 before to solve this problem. So, if you have to calculate the number of months and years between given dates, you have three main options, first, use Calendar class to write your method to find a number of months and year between given dates, second, use Joda-time library and the third option is to upgrade to Java 8.

5 Best books for OCAJP8 Exam 1Z0-808 - Java8

It's been more than 2 years since Java SE 8 was launched on 17th March 2014 and almost 2 years since we have OCAJP8 live. You might know that in order to become a Java SE 8 certified developer you need to pass two examples, the OCAJP8 (Exam 1Z0-808) and OCPJP8 (Exam 1Z0-809). The first one is called associate level certification and the second one is called professional level certification. When OCAJP8 first comes, there were not enough good books to prepare this exam and many candidates rely heavily on Java 8 books and professional exam simulators like Whizlabs and Enthuware, but if you are going to appear for the OCAJP8 exam now, there are no such problems. In this article, you will find some of the best books to prepare for OCAJP8 exams.