Friday, December 30, 2016

10 Programming Tips to Create Maintainable Java Applications

Hello all, today is 31st December, the last day of 2016 and this is probably the last post on Javarevisited for this year and I want to make it special. That's why I am going to share you some tips on creating maintainable Java applications which will help you not just in the new year, but also in all the coming years in your software development career.  One aspect of development, which is often overlooked by developers is to create applications which are both easy to maintain and support. Since a software spends 90% of its lifetime in maintenance mode, it's very important that your application is easy to configure, support, and maintain. Also, Java application is no different than any other software, you must pay attention to these key properties of writing production quality code, hence this tips also applies to any programming language which is used to create real-world software which is used by real users.

How to loop over HashMap in JSP using JSTL

Though there are a number of ways to loop over an HashMap in JSP, or any other Map implementation e.g. Hashtable, I personally prefer the JSTL foreach tag for iteration over HashMap in JSP. As a Java programmer, you will often have a strong urge to use Java code directly in JSP using scriptlet, but that's a bad coding practice and one should always avoid that. In fact, by smart use of expression language and JSTL core tag library, you can reduce a lot of Java code from your JSP page. In our last post, we have seen an example of JSTL foreach tag to loop over List, but not an  HashMap, and that creates a doubt in one of my readers mind that foreach tag doesn't support Map implementation like HashMap or Hashtable as they are not Collection, but that's not true. You can use the same technique to loop over an HashMap in JSP which we have used earlier to loop over a list in JSP.

Thursday, December 29, 2016

How to increase Heap memory of Apache Tomcat Server

Increasing Heap size of Tomcat
You can increase heap size of Tomcat by setting JAVA_OPTS or CATALINA_OPTS at the top of the, file if you are running Tomcat in Linux and by putting JAVA_OPTS or CATALINA_OPTS into the catalina.bat file if you are running Tomcat in Windows. This approach will work irrespective of tomcat version i.e. you can increase the heap memory of tomcat 5.5, tomcat 6, tomcat 7 and even tomcat 8 by using this technique. You can find the and catalina.bat file in the bin directory of tomcat installation folder e.g. in my machine and the catalina.bat file is located under C:\Program Files\Apache Software Foundation\Apache Tomcat 7.0.41\bin directory. If you open the catalina.bat property you will see the advice given by Tomcat creator itself on how to give additional JVM options to Tomcat process.

Wednesday, December 28, 2016

Top 10 Java Swing Interview Questions Answers asked in Investment banks

The Swing  API and toolkit are heavily used in developing trading application front end in Java on both large Investment banks and small broker firms. Doesn’t matter whether its front office or middle office application, you will find Java Swing GUI everywhere. The Swing-based GUI is used to develop Order entry system, Order monitoring GUI and for other tools which trader or operations can use on different trade life cycle in the front office. middle office and back office space. Due to its heavy usage, there are a lot of requirements of Java Swing developer in investment banks like Barclays, Citibank, Deutsche Bank, Nomura, JP Morgan, Morgan Stanley and Goldman Sachs etc. Though in the era of Java 8, Java FX is positioned to take over from Swing but there are still a lot of legacy application which means the requirements for Java Swing developers will not dry out soon.

Tuesday, December 27, 2016

Exception in thread "main" java.lang.NoClassDefFoundError: Running Java from Command line

The "Exception in thread "main" java.lang.NoClassDefFoundError: helloworldapp/HelloWorldApp" error comes when you are trying to run the HelloWorldApp Java program from the command line but either .class file is not there or Java is not able to find the class file due to incorrect classpath settings. The name of the class could be different in each case, it depends upon which class you are passing to java command for running from the command prompt. Another interesting thing to remember is that this error only comes in Java version less than or equal to Java 6 e.g. Java 1.5 or Java 1.4, if you are running in JDK 7 or Java 8 instead of this you will see "Error: could not able to find or load class HelloWorldApp". Technically, both errors come due to same reason and their solution is also exactly same.

Sunday, December 25, 2016

Spring Hello World Example using XML Config

In this Spring framework tutorial, you will learn how to write the hello world example in Spring framework. This should be the first tutorial to start learning Spring framework, as it gets the ball rolling. While coding and running this example, you learn a lot about Spring framework, Spring XSD files, necessary JAR files, and more importantly how Spring framework works.This HelloWorld program in Spring framework is an extension of classical Java hello world program, written using dependency Injection design pattern by using Spring Framework's IOC container.  Even though now you can configure Spring dependency using annotations and Java configuration, this example uses traditional XML way to configure dependency.

Friday, December 23, 2016 PKIX path building failed: unable to find valid certification path to requested target

If you are working in Java web or enterprise application which connect to any other web server using HTTPs you might have seen the "". This is one of the particular case of that error. If you know how SSL and HTTPS works that when a Java client connect to a Java server the SSL handshake happens. In this steps server return certificates to confirm it's identity, which then client validates against the root certificate he has in its truststore. If Server return a certificate which cannot be validated against the certificates a browser or Java client holds in its truststore then it throws the " PKIX path building failed: unable to find valid certification path to requested target".

Thursday, December 22, 2016

5 Tips to Prepare for Oracle Java Certifications (OCAJP and OCPJP)

In this article, I am going to share you some tips to prepare for the Oracle Java certification like OCAJP and OCPJP, both associate and programmer level certification. If you are completely new to Java then you need to first read Head first Java and learn how to program in Java, because getting certified without knowing how to program in Java is of no use. Any certification or degree is only valuable if you know the subject well and back them up with your knowledge, work, and experience. It's ideal for Programmer who has some Java experience, not necessarily work experience but you should have coded a good number of Java programs in your college days, internship or programming courses. Ok, now, let's move to the main topic, how to prepare for the Oracle Java certifications.

Wednesday, December 21, 2016

How to convert java.util.Date to java.sql.Timestamp?

You can convert a java.util.Date to java.sql.Timestamp value by using the getTime() method of Date class. This method return the long millisecond value from Epoch (1st January 1970 midnight) which you can pass to java.sql.Timestamp to create a new instance of Timestamp object in JDBC. Remember, java.sql.TimeStamp class is a wrapper around java.util.Date to allow JDBC to view it as SQL TIMESTAMP value. Only way to create a Timestamp instance is by passing the long time value because the second constructor of Timestamp class, which accepts individual fields e.g. year, month, date, hour, minute, second and nano is deprecated. Timestamp class can also hold up-to nano second value. 

Tuesday, December 20, 2016

Difference between a Thread and an Executor in Java

Even though both Thread and Executor, both are used to executed some code in parallel, there are some key differences between them.The main difference between a Thread and an Executor in Java is that later provides a thread pool in Java. Along with several concurrency utilities like CountDownLatch, CyclicBarrier, Semaphore, FutureTask, Callable interface, and Conditions, JDK 5 also introduced built-in thread pool, which provides set of working threads to run your code in parallel. Since creating, starting, and running a thread is a time-consuming and expensive operation, many Java applications create a pool of thread at start-up and leverage that for executing the task in parallel until Java introduced the built-in thread pool.  This thread-pool is known as Executor framework which relieved Java application developers from the responsibility of creating and managing threads

Friday, December 16, 2016

How to Count Number of Leaf Nodes in Binary Tree - Java Iterative and Recursive Algorithm

You can use the same algorithm to count a number of leaf nodes in the binary tree which we have used in the last article, while printing all leaf nodes of a binary tree in Java, using both recursion and iteration. The logic is same for leaf node, any node whose left and right children is null is known as leaf node in binary tree. They are the nodes which resides in the last level of binary tree and they don't have any children. In order to count total number of leaf nodes in binary tree, you need to traverse the tree and increase the count variable whenever you see a leaf node. Since binary tree is an essential data structure and algorithm topics for programming interviews, its better to prepare these kind of questions. I'll show how to solve this using both recursion and iteration in Java in this article.

Thursday, December 15, 2016

3 Best Gifts for Programmers and Developers in Christmas and New Year

Happy New year 2017 and Seasons greetings to everyone. May god bless you with success and whatever you want this year. This is festival time and I have a couple of friends asking me what to gift to a programmer friend or colleague? This is a common confusion you face when buying a gift for tech geeks, software engineers, programmers, and web developers. Everybody wants that their gift is well received and make the person excited and happy. Being a Java programmer myself, I am going to suggest a couple of things which I have recently bought for my programmer friends, colleagues, and relatives. If you are in doubt, you can take some inspiration from my list. At times, I have really spent a good amount of time searching for gifts for fellow programmers and I know, we'll keep doing it, so expect this list to grow.

Tuesday, December 13, 2016

Is "Java Concurrency in Practice" still valid in era of Java 8?

One of my reader Shobhit asked this question on my blog post about 12 must read advanced Java books for intermediate programmers - part1. I really like the question and thought that many Java programmers might have the same doubt whenever someone recommends them to read Java concurrency in Practice. When this book came first in 2006, Java world was still not sure of about new concurrency changes made in Java 1.5, I think the first big attempt to improve Java's built-in support for multi-threading and concurrency. Many Java programmers were even not aware of new tools introduced in the API e.g. CountDownLatch, CyclicBarrier, ConcurrentHashMap and much more. The book offered them the seamless introduction of those tools and how they can use them to write high-performance concurrent Java applications.

Saturday, December 10, 2016

How to Print Pyramid Pattern of Alphabets in Java program

In earlier programming tutorials, I have taught you how to print pyramid pattern of stars and numbers in Java, and in this tutorial, you will learn printing pyramid pattern of alphabets. If you understand the logic of previous programs then this one won't be difficult for you because we will use the same logic of printing rows and columns using nested loop in Java. Actually, pyramid pattern is nothing but a matrix where you need to print rows and columns. Though, you need to learn where to print those values and when to move to next row. Once you know this trick of advancing, you can print any kind of pyramid pattern in Java. The one, we'll see in this tutorial is the simplest of one but I'll give you some tough one for exercise to develop your creativity and coding skill.

Wednesday, December 7, 2016

Integer vs floating point arithmetic - Java Coding Question

I am starting a new series called Java Coding Quiz, in which I'll show you subtle Java concepts hidden in the code. This is an OCAJP or OCPJP style question but focused on teaching subtle details of Java programming language. In today's puzzle, you will learn about one of the key concepts about how floating point and integer arithmetic works in Java. This is a very important concept for any Java developer because Java behaves differently when the same operation is performed by different types of variable but of the same value.

Sunday, December 4, 2016

Top 5 Spring and Hibernate Training Courses for Java JEE Programmers

Spring and Hibernate are two of the hottest and most in-demand web frameworks in Java world and also two of the most essential skill for any Java programmer to get a Job in web development space. The Spring framework is in around from 2004 and established itself as the leading framework to develop Java applications both in core Java and web development area. The Spring framework comes with a lot of modules to support a different kind of developments e.g Spring Security to address the security requirements of most web and enterprise Java applications. It supports single sign-on, LDAP authentication, Role-based access control, and much more such essential features. Spring also supports the development of REST services which is no become standard way to provide web services.

Thursday, December 1, 2016

Difference between Executor Framework and ForkJoinPool in Java?

Java 5 added Executor Framework to provide out-of-box thread pool to Java programmers and Java 7 added ForkJoinPool an implementation of ExecutorService which specifically designed to execute ForkJoinTask. The Executor Framework provides several classes e.g. Executor, ExecutorService, and Executors for execution and creating thread pools. It also provides several built-in, ready to use thread pools like a pool of fixed threads, cached thread pool which can expand itself, spawn new threads if required due to heavy load.

Sunday, November 27, 2016

Top 5 Java 8 Practice Test and Exam Simulators (OCAJP and OCPJP) - Best of lot

Apart from books, exam simulators are another essential tool to prepare for Java certifications. They not only give you the opportunity to test you knowledge topic wise but also provide the helpful explanation to clear your doubt and misconception, which means you can learn on the fly. Actually, when I prepared for my SCJP exam, I learned a lot of new concept by just giving mock exams and solving practice question. Since most of the Java certification aspirants are Java developer with some experience i.e. they have done a good amount of coding, they can easily understand the code but they might not be familiar with exam format.

Thursday, November 24, 2016

5 Software Development and Project Management Books - Best of Lot, Must Read

Some of you might ask, Why software project manager should read books? Isn't they are experienced enough to become a project manager and handle software development? A genuine question but Software management is harder than any other management purely because every software is different than the previous one. Many other streams of engineering e.g. Civil or Mechanical got better in terms of estimation and management with the help of software but software development is still run on experience.

Monday, October 24, 2016

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.

Sunday, October 23, 2016

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:

Saturday, October 22, 2016

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.

Friday, October 21, 2016

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

Thursday, October 20, 2016

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.

Wednesday, October 19, 2016

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.

Tuesday, October 18, 2016

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

Monday, October 17, 2016

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".

Sunday, October 16, 2016

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.

Saturday, October 15, 2016

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.

Friday, October 14, 2016

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.

Thursday, October 13, 2016

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.

Tuesday, October 11, 2016

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.

Monday, October 10, 2016

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.

Sunday, October 9, 2016

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.

Saturday, October 8, 2016

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.

Friday, October 7, 2016

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.

Thursday, October 6, 2016

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.

Wednesday, October 5, 2016

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.

Tuesday, October 4, 2016

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.

Monday, October 3, 2016

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.

Sunday, October 2, 2016

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.

Saturday, October 1, 2016

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.

Friday, September 30, 2016

3 Ways to Solve "No JVM installation found. Please install a 64-bit JDK" - Android Studio

You are an enthusiastic Java programmer who just learned about developing Android apps in Java. To start with you have installed Android Studio, which is the official Integrated Development Environment (IDE) for Android app development, based on IntelliJ IDEA, but as soon as you click on the Android Studio Desktop Icon to start Android Studio you are getting "No JVM installation found. Please install a 64-bit JDK" error? How do you solve this problem? Well, even though the error message is same, every problem is different depending upon your machine, the Java version, whether your desktop or laptop has 32-bit or 64-bit OS e.g. Windows 8.1 or Windows 10. Whether you have installed 32-bit Java or 64-bit JDK e.g. JDK 1.8.0 and what is the value of JAVA_HOME environment variable or whether you have defined it or not.

Thursday, September 29, 2016

How to Serialize Object in Java - Serialization Example

Serialization is one of the important but confusing concept in Java. Even experienced Java developer struggle to implement Serialization correctly. The Serialiation mechamism is provided by Java to save and restore state of an object programatically. Java provides two classes Serializable and Externalizable in package to facilitate this process, both are marker interface i.e. an interface without any methods. Serializing an Object in Java means converting into a wire format so that you can either persists its state in a file locally or transfer it to another client via the network, hence it become an extrememly important concept in distributed applications running across several JVMs. There are other features in Java e.g. Remote Method Invocation (RMI) or HttpSession in Servlet API which mandates the participating object should impelment Serializable interface because they may be transffered and saved across the network.

Wednesday, September 28, 2016

Iterative QuickSort Example in Java - without Recursion

The quicksort algorithm is one of the important sorting algorithms. Similar to merge sort, quicksort also uses divide-and-conquer hence it's easy to implement quicksort algorithm using recursion in Java, but it's slightly more difficult to write an iterative version of quicksort. That's why Interviewers are now asking to implement QuickSort without using recursion. The interview will start with something like writing a program to sort an array using quicksort algorithm in Java and most likely you will come up with a recursive implementation of quicksort as shown here. As a  follow-up, Interviewer will now ask you to code the same algorithm using Iteration.

Tuesday, September 27, 2016

Top 5 JSON Library Java JEE Developers Should Know

The JSON format is one of the most popular formats to transfer and exchange data in web. Almost all RESTful web services take JSON input and provide JSON output but unfortunately JDK doesn't have built-in support for one of the most common web standard like JSON. As a Java developer if you want to develop RESTful web service and produce JSON data or if you are developing a client to an existing RESTFul web services and want to consume JSON response, you don't need to be disappointed. Fortunately, there are so many open source libraries and API available for creating, parsing and processing JSON response in Java e.g. Jackson, Google GSon, json-simple etc.

Monday, September 26, 2016

How to get just DATE or TIME from GETDATE() in SQL Sever

The GETDATE is one of the most popular built-in methods of  Microsoft SQL Server, but unlike its name suggest, it doesn't return just date, instead it returns date with time information e.g. 2015-07-31 15:42:54.470 , quite similar to our own java.util.Date from Java world. If you want just date like 2015-07-31, or just time like 15:42:54.470 then you need to either CAST or CONVERT output of GETDATE function into DATE or TIME data type. From SQL Server 2008 onward, apart from DATETIME, which is used to store both date and time, You also have a DATE data type to store date without time e.g. 2015-07-31, and a TIME data type to store time without any date information e.g. 15:42:54.470. Since GETDATE() function return a DATETIME value, You have to use either CAST or CONVERT method to convert a DATETIME value to DATE or TIME in SQL Server.

Sunday, September 25, 2016

10 basic differences between Java and Groovy Programming

If you are working in Java, you might have heard about Scala, Groovy, and Closure. Out of these three Groovy seems to be gaining a place in Java projects more rapidly than others. Groovy is a Scripting language but runs on Java virtual machine. Every Java program can run on Groovy platform. As per official Groovy website, "Apache Groovy is a powerful, optionally typed and dynamic language, with static typing and static compilation capabilities, for the Java platform aimed at improving developer productivity thanks to a concise, familiar and easy to learn syntax". I think, they have highlighted the key capabilities of Groovy very well in that sentence. It basically further reduce the burden from Java developer with respect to coding. Now, you can put more focus on business logic and get your work done quickly without wasting time on writing more code.

Saturday, September 24, 2016

How to Remove CTRL-M characters From a File in UNIX and Linux

I wanted to transfer some files from Windows to Unix using FileZilla, but the problem arises when these files are transferred (Ascii or Binary mode both) and opened using VI we get ^M characters, also known as CTRL-M characters. I searched about this but the solutions were to remove these ^M characters when files are transferred using utilities. Is there any way that these ^M characters do not appear in the first place? Well, my search continues but I will share the solution which worked for me for removing control M characters i.e. CTRL-M or ^M characters. There are several UNIX commands e.g. dos2unix which can be used to convert a Windows or DOS generated files to UNIX one. You can also use sed command (stream editor) to remove CTRL-M characters without opening the file, very useful if you are removing CTRL-M characters from a large file. Alternatively, you can use VI command to open the file and replace ^M characters with nothing.

Friday, September 23, 2016

Top 21 Java Final Modifier (Keyword) Interview Questions and Answers

The final modifier is one of the important keywords in Java. You can use this with a class, method, and variable as well. A good knowledge of final keyword is not only essential for writing good, performant and secure Java programs but also to clear any  Java interview. Interviewer pays special attention to final keyword and expects candidates knows how and when to use the final modifier with variables, methods, and classes. In this article, I have collected Java interview questions which are based upon the concept of final modifier. You might have seen many of these questions on both telephonic and face-to-face round. You can use this collection not only to check your knowledge about final keyword but also to prepare for final modifier from Java interview's perspective.  If you have come across any interesting final modifier question which is not in this list, please share with us as a comment and I'll add into this list.

Thursday, September 22, 2016

3 Maven Eclipse Tips for Java Developers

If you are using Maven inside Eclipse IDE via M2Eclipse plugin then following tips can help you a lot.

1) Setup Dependency as Java Project in Eclipse
If your POM dependencies is another project in Eclipse then your project will automatically get updated whenever you build the dependent project. For example, let's say you have a project, ABC, which is dependent on two core modules e.g. framework.jar and persistence.jar, if you have checked out these project and has set up them as Maven Eclipse project, M2Eclipse can directly add them as dependency, instead of loading their JAR files from repository, be it local or remote.

Wednesday, September 21, 2016

How to Print all Leaf Nodes of Binary tree in Java - Recursion and Stack

Binary tree based questions are very common in Java or any other Programming job interviews. One of the frequently asked binary tree questions is "write a program to print all leaf nodes of a binary tree". In order to solve this problem, you must know what is a leaf node? A leaf node in a binary tree is a node whose left and right child is null. They are actually the last nodes of any binary tree. In a typical programming interview, you would be given a binary tree and asked to write a program to print all leaf nodes. Usually, all binary tree related questions can be solved easily using recursion because a tree is a recursive data structure, but you should also know how to solve them without recursion.

Sunday, September 11, 2016

2 Reasons of org.springframework.beans.factory.BeanCreationException: Error creating bean with name [Solution]

The Spring framework is one of the most popular frameworks for developing Java application. Apart from many goodies, it also provides a DI and IOC container which initialize objects and their dependencies and assemble them together. The Java classes created and maintained by Spring are called Spring bean. At the startup, when Spring framework initializes system by creating objects and their dependencies depending upon @Autowired annotation or spring configuration XML file, it throws "org.springframework.beans.factory.BeanCreationException: Error creating a bean with name X" error if it is not able to instantiate a particular Spring bean. There could be numerous reasons why Spring could not able to create a bean with name X, but clue always lies on the detailed stack trace. This error always has some underlying cause e.g. a ClassNotFoundException or a NoClassDefFoundError, which potentially signal a missing JAR file in the classpath.

Friday, September 9, 2016

Best Book to Learn Java for C and C++ Programmer?

In the last 2 decade many Java programmers started programming with C and C++ but the situation is changed now, you have more choices e.g. you can choose Python or you can even start with Java. It seems Academia is preferring Python in USA and Java in India, but there are still many programmers who know C and C++ and wants to learn Java for one or other reasons. I often receive emails from my readers about book recommendation and recently a couple of them asked me to suggest best Java books for C and C++ programmer. I can relate those beginners to myself because I have also gone through the same phase but those days the university text books are our only source to learn new thing. We didn't have broadband and unlimited access to Internet and eBooks was not popular at that time but things have changed. The good thing is now I know a couple of really good books which can help to utilize most of his C and C++ knowledge to learn Java e.g. Core Java Volume 1 - Fundamentals by Cay S. Horstmann which provides comparative analysis with C++ time to time.

Thursday, September 8, 2016

Why use Spaces over Tabs for Indentation in Code Editors - Eclipse

When I started coding in Eclipse, I was not aware that by default Eclipse uses tabs for indentation and tabs can have varied with e.g. 1 tab can be equal to 2 spaces or 4 spaces or even 8 spaces. Sometimes, It's all up to you how you configure tabs in your code editor and other times just the mercy of the tool you don't know how to configure e.g. VI in UNIX. I only realize the problem when I found too many difference in a file while check-in into SVN. Apparently, other people was using different indentation (spaces) and that's why the file was showing so many differences when I reformatted them in Eclipse. This happens to many programmers, some pay attention, some didn't and go ahead with the check-in the code, only to revert it back later. There is no clear guideline upon which one is better and whether a programmer should use tabs or spaces, even the Clean Code doesn't  help here.

Tuesday, September 6, 2016

Java Comparable Interface and compareTo() Example

Hello, guys, today I am going to talk about one of the fundamental concepts in Java, defining the natural ordering of the objects e.g. lexicographical order for String and numerical order for Number classes e.g. Integer, Double, Float etc. The compareTo() method is defined in the java.lang.Comparable interface. It is used to define the natural ordering of an object e.g. String class override compareTo() to define the lexicographical order for String objects. Integer class override compareTo() to define the numeric ordering of integer objects. Similarly, you can override compareTo() method by implementing Comparable interface to define the natural order on which you want to order your object. For example, an Order should be ordered by order id hence compareTo() must provide logic for that.

Saturday, September 3, 2016

How to solve java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/test

The error "java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/test" occurs when you try to connect MySQL database running on your localhost, listening on port 3306 port from Java program but either you don't have MySQL JDBC driver in your classpath or driver is not registered before calling the getConnection() method. Since JDBC API is part of JDK itself, when you write a Java program to connect any database like MySQL, SQL Server or Oracle, everything compiles fine, as you only use classes from JDK but at runtime, when the JDBC driver which is required to connect to database is not available, JDBC API either throws this error or "java.lang.ClassNotFoundException: com.mysql.jdbc.Driver".

Tuesday, August 30, 2016

Adapter Design Pattern in Java with Example

Adapter design pattern in Java, also known as the Wrapper pattern is another very useful GOF pattern, which helps to bridge the gap between two classes in Java. As per the list of Gang of Four patterns, Adapter is a structural pattern, much like Proxy, Flyweight, Facade, and Decorator pattern in Java. As the name suggest, Adapter allows two classes of a different interface to work together, without changing any code on either side. You can view Adapter pattern is a central piece of the puzzle, which joins two pieces, which can not be directly joined because of different interfaces. I see a couple of reference of Adapter design pattern in one of my favorite book Clean Code, but the idea is very well explained in Head First Design Pattern, the image which they show to illustrate Adapter design pattern is worth all the talk.

Saturday, August 27, 2016

5 Free OCAJP 7 and OCPJP7 Mock Exams - Online Practice Test (1Z0-803 and 1Z0-804

Hello guys, today I am going to share a list of free OCAJP7 and OCPJP7 mock exams and online practice tests. If you are preparing for Java SE 7 Programmer 1 or 2 certification or upgrading your existing OCJP 6 exam then this will help you to gauge your progress. As per my experience, the three keys to success in any Java certification is a selection of good books, writing small Java programs to understand concepts, and practicing mock exams. You can see that mock exams are very important to do well on the real exam. They give you much-needed practice as well as some idea about what kind of questions you can expect on real exams. Unfortunately, there are not many good quality free mock exams available for OCAJP7 but I have managed to collect some of them. Earlier, I have shared some OCAJP8 mock exams and received a lot of feedback from my readers about a similar list for OCAJP7 and OCPJP7 exams. This is a smaller list as compared to the previous one but I'll keep adding new mock exams if I come across.

java.lang.numberformatexception for input string null - Cause and Solution

The java.lang.NumberFormatException comes when you try to parse a non-numeric String to Number e.g. Short, Integer, Float, Double etc. For example, if you try to convert . "null" to an integer then you will get NumberFormatException. The error "Exception in thread "main" java.lang.NumberFormatException: For input string: "null" is specifically saying that the String you receive for parsing is not numeric and it's true, "null" is not numeric. Many Java methods which convert String to numeric type e.g. Integer.parseInt() which convert String to int, Double.parseDoble() which convert String to double, and Long.parseLong() which convert String to long throws NumberFormatException to inform that the input String is not numeric.

Saturday, August 20, 2016

5 Essential difference between Callable and Runnable interface in Java?

The difference between Callable and Runnable is one of the most frequently asked multi-threading and concurrency interview question in Java world. I remember, it was 2007 when I first heard about Callable interface and that too on a telephonic interview. Till then, I was happy using Runnable to implement threads and just started paying attention to Java 1.5, as most of the application by then using Java 1.4. That one interview question encouraged me to learn more about several other useful features introduced in Java 5 concurrency library e.g. CountDownLatch, CyclicBarrier, Semaphore, Atomic variables, and Thread pool. This is one of the reasons I always encourage Java developer to give/take regular interviews, just to update your knowledge.

Wednesday, August 17, 2016

InOrder traversal of Binary tree in Java using Recursion and Iteration

This is the second article about tree traversal algorithms using Java. In the first part, we have seen the pre-order algorithm for visiting all nodes of the binary tree and today we'll learn about the InOrder traversal. As I told you before, unlike array and linked list, binary tree has several ways of traversal. The traversal algorithms are broadly divided into depth first and breadth first traversal algorithms depending upon how algorithm actually works. As the name suggest, depth first explores binary tree towards depth before visiting sibling, while breath first visits all nodes in the same level before going to next level, hence it is also known as level order traversal. Both PreOrder and InOrder tree traversal algorithms are depth first and the only difference between pre-order and in-order algorithm is the order on which root, left node, and right node of the binary tree is visited.

Monday, August 15, 2016

Why Timestamp cannot be used in place of Date in Java?

One of the tricky question from Java Interview is, "Can we pass a Timestamp instance to a method expecting java.util.Date?", it's a tricky question because the answer is both Yes and No. You can, of course, pass a Timestamp object to a method with the argument as Date because first, Timestamp is a subclass of java.util.Date and second it contains both date and time values which are missing in either java.sql.Date and java.sql.Time. So there is more reason to pass a Timestamp value to Date but you should not be doing that. Why? because Timestamp is not exactly Date. It's a composite type of java.util.Date and an additional nanosecond value which is fitted there to confirm database DATETIME data type, which supports nanosecond precision. If you look at the implementation of java.sql.Timestamp class, you will find that the long value supplied by Date is stored separately then this nanosecond value.

Monday, August 8, 2016

How to Iterate through ConcurrentHashMap and print all keys and values in Java

Suppose you have a ConcurrentHashMap of String and Integer and you want to print all keys and values, how do you that? This is a common, day to day programming task for Java programmer and there are many ways to do it. The Map interface provides several view methods e.g. keySet(), values(), and entrySet() to retrieve all keys, values, and all key and value pairs as entries. You can use respective methods to print all keys, all values, or all key values pairs. For printing, you also have multiple choice e.g. you can either use enhanced for loop or Iterator, though later also provide you the facility to remove key value pairs while printing if needed. Though you should remember that these views are backed by Map, so when you remove a key-value pair from entry set it will also be removed by the ConcurrentHashMap.

Tuesday, August 2, 2016

Top 10 Maven Plugins Every Java Developer Should Know

In the last couple of years, Maven has become the de-facto build tool for Java applications. Though there are challenges exists from tools like Gradle, but I think the dominance of Maven will help it to win the final battle. When I started with Maven, I was happy with just dependency management but then I come to know about maven plugins which let you customize your build up to the level you can do with ANT. These plugins provide true power to Maven to automate most of the build related task e.g. compilation, testing, packaging, deployment, and even committing the source code into the remote source repository. Many Java developers who use Maven daily are usually not aware of these essential Maven plugins mostly because  Maven just works, or someone has already done the hard work for them.

Saturday, July 30, 2016

How to find the 3rd element from end in linked list in Java

The problem to find the 3rd element from the end in a singly linked list or nth node from the tail is one of the tricky but frequently asked linked list problems in programming job interviews. The challenge here is to solve the problem in just one pass, i.e. you can not traverse the linked list again and you cannot traverse backward because it's a singly linked list. If you have practiced some linked list problems e.g. finding length, inserting elements, or deleting elements then you should be familiar with traversal. Here, we'll use the same algorithm which we have used to find the middle element of linked list in one pass. The algorithm is also known as tortoise and hare algorithm because of the speed of two pointers used by the algorithm to traverse the singly linked list.

Sunday, July 24, 2016

How to read a text file using Scanner in Java? Example Tutorial

As I told you before that there are multiple ways to read a file in Java e.g. FileReader, BufferedReader, and FileInputStream. You chose the Reader or InputStream depending upon whether you are reading text data or binary data, for example, the BufferedReader class is mostly used to read a text file in Java. The Scanner class is also another way to read a text file in java. Even though Scanner is more popular as a utility to read user input from the command prompt, you will be glad to know that you can also read a file using Scanner. Similar to BufferedReader, it provides buffering but with a smaller buffer size of 1KB and you can also use the Scanner to read a file line by line in Java. Similar to readLine(), Scanner class also have nextLine() method which return the next line of the file. Scanner also provides parsing functionality e.g. you can not only read text but parse it into correct data type e.g. nextInt() can read integer and nextFloat() can read float and so on.

Saturday, July 23, 2016

Difference between row_number(), rank() and dense_rank() in SQL Server, Oracle.

Though all three are ranking functions in SQL, also known as window function in Microsoft SQL Server, the difference between rank(), dense_rank(), and row_number() comes when you have ties on ranking i.e. duplicate records. For example, if you are ranking employees by their salaries then what would be the rank of two employees of same salaries? It depends on upon which ranking function you are using e.g. row_number, rank, or dense_rank. The row_number() function always generates a unique ranking even with duplicate records i.e. if the ORDER BY clause cannot distinguish between two rows, it will still give them different rankings, though which record will come earlier or later is decided randomly e.g. in our example two employees Shane and Rick have the same salary and has row number 4 and 5, this is random, if you run again, Shane might come 5th.

Monday, July 18, 2016

How to calculate GCF and LCM of two numbers in Java? Example

This week's programming exercise is to write a Java program to calculate GCF and LCM of two numbers. The GCF, stands for Greatest common factor and LCM stands for Lowest common multiplier, both are popular mathematical operation and related to each other. The GCF is the largest number which divides both the number without leaving any remainder e.g. if two numbers are 24 and 40 then their GCF is 8 because 8 is the largest number which divides both 24 and 40 perfectly, without leaving any remainder. Similarly, LCM is the lowest number which is perfectly divisible by the two number, for example, if given number is 40 and 24 then their LCM is 120 because this is the lowest number which is perfectly divisible by both 40 and 24.

Friday, July 15, 2016

Difference in String pool between Java 6 and 7

String pool in Java is a pool of String literals and interned Strings in JVM for efficient use of String object. Since String is immutable in Java, it makes sense to cache and shares them in JVM. The String pool has gone through an important change in Java 7 release when it was relocated from PermGen space to heap space. Till Java 1.6, interned String and literals are stored in the PermGen space of JVM memory, which was a fixed size area for storing class metadata. The biggest issue of having String pool in PermGen is the small and fixed size of PermGen space. In some JVM it ranges from 32M to 96M, which is quite small for a large program. Since String is extensively used in both small and large Java application, Java designers thought String pool is the best way optimize the use of String object in Java.

Monday, July 11, 2016

Binary Tree PreOrder Traversal in Java - Recursion and Iteration Example

Unlike linked list and array which can only be traversed linearly, there are several ways to traverse a binary tree. The tree traversal algorithms are mainly divided into two parts, depth first and breadth first. As their name suggests, in depth first, the tree is traversed downwards (towards the depth) before the next sibling is visited, the PreOrder, InOrder and PostOrder traversal of a binary tree are actually depth-first traversals. On the breadth first, the entire breadth of the tree is traversed before moving to next level, hence it is also known as level order traversal. There are other algorithms to traverse a binary tree as well e.g. Monte Carlo tree search, which concentrates on analyzing the most promising moves, but the pre-order, post-order, and in-order traversal are the most popular ways to traverse a binary tree in Java. They are also the most popular data structure and algorithm questions at beginner and intermediate level.

Saturday, July 9, 2016

Eclipse - How to add/remove external JAR into Java Project's Classpath

There are multiple ways you can add an external JAR into the classpath of a Java project in Eclipse, but all goes via adding them into build path. Many beginner's struggles to add JARs into classpath and we will try to address that problem in this tutorial. You will learn step by step tutorial to add an internal or third party JAR in your application's CLASSPATH in Eclipse Indigo. Since this feature has hardly changed in any Eclipse version, you can follow same steps in Eclipse Kepler, Indigo, and Juno version to add JARs into classpath. Since Eclipse is the most popular Java IDE and used by many companies, it's important for a Java developer to know Eclipse in and out. It will not only help to work better but also to create the better impression among your teammates.

Thursday, July 7, 2016

How to remove duplicate rows from a table in SQL

There are a couple of ways to remove duplicate rows from a table in SQL e.g. you can use a temp tables or a window function like row_number() to generate artificial ranking and remove the duplicates. By using a temp table, you can first copy all unique records into a temp table and then delete all data from the original table and then copy unique records again to the original table. This way, all duplicate rows will be removed, but with large tables, this solution will require additional space of the same magnitude of the original table. The second approach doesn't require extra space as it removes duplicate rows directly from the table. It uses a ranking function like row_number() to assign a row number to each row.

Tuesday, July 5, 2016

10 Examples to read a text file in Java

The Java IO API provides two kinds of interfaces for reading files, streams and readers. The streams are used to read binary data and readers to read character data. Since a text file is full of characters, you should be using a Reader implementations to read it. There are several ways to read a plain text file in Java e.g. you can use FileReader, BufferedReader or Scanner to read a text file. Every utility provides something special e.g. BufferedReader provides buffering of data for fast reading, and Scanner provides parsing ability. You can also use both BufferedReader and Scanner to read a text file line by line in Java. Then Java SE 8 introduces another Stream class which provides a lazy and more efficient way to read a file.

Saturday, July 2, 2016

Printing Largest and Smallest of N numbers without using Array in Java

One of the common programming questions is, how do you find the largest and smallest number in N numbers without using arrays in Java? Can you write a program to solve this problem? Well, it's very similar to the problem we have seen before, find the largest and smallest of 3 integers. You can use the same approach and generalize it for N numbers. All you need to do is start with largest as Integer.MIN_VALUE and smallest number as Integer.MAX_VALUE and loop through N numbers. At each iteration, compare the number with the largest and smallest number, if the current number is larger than largest than its a new largest and if the current number is smaller than smallest than its a new smallest number.

How to take array input from command line in Java using Scanner - Example

There is no direct way to take array input in Java using Scanner or any other utility, but it's pretty easy to achieve the same by using standard Scanner methods and asking some questions to the user. For example, if you want to take a one-dimensional array of String as input then you can first ask the user about the length of the array and then you can use a for loop to retrieve that many elements from user and store them in an array. You can use the next() to take a String input from the user. Similarly, if you need to take an integer array or double array, you can use nextInt() or nextDouble() method of Scanner class. Some programmer may still stuck and ask, how about taking a two-dimensional array as input? Well isn't that pretty easy by applying some maths?

Wednesday, June 29, 2016

Top 5 Books for Programming/Coding Interviews - Best of lot

If you are preparing for Programming Job interviews and looking for some of the best books for programming questions then you have come to the right place. In this article, I am going to share a couple of good books to prepare coding, software design, and data structure algorithm questions, which are essential for any coding interviews. Though a programming interview also explores other areas of software development e.g. the programming language you would be mainly using in your project e.g. C++ or Java. The database and SQL based questions, the operating systems and UNIX related questions, some of the software design and object oriented design pattern questions and much more, but coding based questions forms the core of programming interviews.

Monday, June 27, 2016

How to convert java.sql.Date to java.util.Date in Java - JDBC Example

You often need to convert java.sql.Date to java.util.Date while interacting with databases from Java application. Since JDBC the Java API for database connectivity uses java.sql.Date to represent and most of the java code accepts java.util.Date, you have no choice but to convert SQL date to util date in Java. Though, there is some fundamental difference between them e.g. java.sql.Date only contains date part e.g. day, month, and year, it doesn't contain any time attributes, but java.util.Date contains both date and time attributes e.g. hour, minutes, seconds and milliseconds. So, when you convert a java.sql.Date to java.util.Date, the resultant java.util.Date instance has the time part as zero i.e 00:00:00 to reflect midnight.

Saturday, June 25, 2016

How to close telnet terminal in Linux and Windows (quit, exit not working)

The telnet is one of the most useful networking commands, which is used to check if a server is listening on a particular port on the remote host, but it's a little bit tricky to use, especially, if you are not using it daily. Though I have used telnet before, but when I use it after a long time, I actually forget how to close the telnet terminal and how to get out of it. I tried every possible command I can think of which is used to close, cancel a command, or exit from VIM editor in UNIX, e.g. Ctrl + C, quit, exit, q! and even the escape character '^]', only to realize that nothing is working. I finally managed to come out from telnet command prompt after a bit of struggle, and trial and error but I was surprised how difficult it can be  to use one of the top 10 networking commands in UNIX.

Friday, June 24, 2016

How to make Eclipse use spaces instead of tabs in Java editor

I use Eclipse IDE extensively to write Java programs for testing and example purpose, but when I copy those program in any text editors e.g. VIM, Notepad, TextPad or Edit plus, the indentation goes weird. I see a lot of white spaces which makes the program wider than expected. This happens because when you copy Java program from Eclipse to a text editor, tabs are converted to spaces and different editor has the different settings of tabs. UNIX text editors prefer tab is 8 spaces, Windows text editors, and IDEs  e.g. Eclipse treat tabs as 4 spaces. If you are like many Java programmer who is more comfortable with space than tabs because they give a true sense of spacing, you can always change the Java editor settings to use space instead of tabs in Eclipse. In this article, I am going to share how to make Eclipse uses spaces instead of tabs for Java editor, which you use while writing Java programs.

Wednesday, June 22, 2016

10 Examples of Joining String in Java 8 - StringJoiner and String.join()

It's quite common in day to day programming to join Strings e.g. if you have an array or List of String let's say {Sony, Apple, Google} and you want to join them by comma to produce another String "Sony, Apple, Google", there is not an easy way to do it in Java. You need to iterate through array or list and then use a StringBuilder to append a comma after each element and finally to remove the last comma because you don't want a comma after the last element. A JavaScript-like Array.join() method or join() method of Android's TextUtils class is what you need in this situation, but you won't find any of such method on String, StringBuffer, StringBuilder, Arrays, or Collections class until Java 8. Now, you have a class called StringJoiner which allows you to join multiple String by a delimiter.