HTML

How Constructor Chaining works in Java - Example

How to call one constructor from another constructor in Java or What is Constructor Chaining in Java is one of the tricky questions in Java interviews. Well, you can use this keyword to call one constructor from another constructor of the same class if you want to call a constructor from based class or super class then you can use super keyword. Calling one constructor from other is called Constructor chaining in Java. Constructors can call each other automatically or explicitly using this() and super() keywords. this() denotes a no-argument constructor of the same class and super() denotes a no argument or default constructor of parent class. Also having multiple constructors in the same class is known as constructor overloading in Java.

Producer Consumer Problem with Wait and Notify Example

Producer Consumer Problem is a classical concurrency problem and in fact it is one of the concurrency design pattern. In last article we have seen solving Producer Consumer problem in Java using blocking Queue but one of my reader emailed me and requested code example and explanation of solving Producer Consumer problem in Java  with wait and notify method as well, Since its often asked as one of the top coding question in Java. In this Java tutorial, I have put the code example of wait notify version of earlier producer consumer concurrency design pattern. You can see this is much longer code with explicit handling blocking conditions like when shared queue is full and when queue is empty. Since we have replaced BlockingQueue with Vector we need to implement blocking using wait and notify and that's why we have introduced produce(int i) and consume() method. If you see I have kept consumer thread little slow by allowing it to sleep for 50 Milli second to give an opportunity to producer to fill the queue, which helps to understand that Producer thread is also waiting when Queue is full.

What is public private protected and package or default access modifier in Java

public, private, protected and package or default are four access modifier available in Java. These access modifiers provide Java programmer to control accessibility or visibility of class, method or any field of a class. Good understanding of public, private or protected modifier is required in order to implement proper encapsulation in Java and create a Java program which is easier to maintain. In this Java tutorial, we will see what is public, private, protected and default modifiers are, which modifier can be used with top level class and nested class and what are the difference between public, private, protected and default modifier in Java. We In next section we will discuss all four access modifier in decreasing order of accessibility, starting from the public which is most accessible and going down to private which is least accessible.

What Java developer Should Know about Object and java.lang.Object

Java is an object oriented programming language and core of Java API is java.lang.Object class. In order to work properly in Java platform its important to learn fundamentals of Object in Java e.g. What is an Object in Java and How to use Object in Java. There are two meaning of Object in Java one which is used to refer object of Object oriented programming language or OOPS and other is java.lang.Object class. Every class in Java which explicitly doesn’t extend any class, implicitly extends java.lang.Object class. Crucial methods like finalize and wait and notify are declared in Object class, which is source of one of the java question Why wait and notify are declared in Object class and not on java.lang.Thread class. In this Java tutorial we will some important properties of Object in Java and OOPS which is worth learning for all Java programmers. By the way if you want to learn about OOPS and SOLID design principles, you can also check 10 Object oriented design principles for Java programmer.

When to use ArrayList vs LinkedList in Java

ArrayList and LinkedList are two popular concrete implementations of List interface from Java's popular Collection framework. Being List implementation both ArrayList and LinkedList are ordered, the index based and allows duplicate. Despite being from same type hierarchy there are a lot of differences between these two classes which makes them popular among Java interviewers. The main difference between ArrayList vs LinkedList is that former is backed by an array while later is based upon linked list data structure, which makes the performance of add(), remove(), contains() and iterator() different for both ArrayList and LinkedList. The difference between ArrayList and LinkedList is also an important  Java collection interview questions, as much popular as Vector vs ArrayList or HashMap vs HashSet in Java. Sometimes this is also asked as When to use LinkedList and When to use ArrayList in Java. In this Java collection tutorial, we will compare LinkedList vs ArrayList on the various parameter which will help us to decide when to use ArrayList over LinkedList in Java.

How to display date in multiple timezone in Java with Example - PST GMT

We can use SimpleDateFormat class to display a date in multiple Timezone in Java. While working in global Java application it's quite common to display dates in the different time zone, classical example is Server is running on either PST or GMT timezone and clients are global or at least running on global trading hubs like Hong-kong, Mumbai, Tokyo, London etc. Unfortunately, Date and Time API in Java is quite tricky and until you have a good understanding of Date and Time classes and methods e.g. Calendar, SimpleDateFormat and thread-safety issue , You can easily create bugs. One of misconception Java programmer has is converting a date in the different timezone. Actually, Date in Java is always in GMT and it represents a number of millisecond since 01-01-1970 00:00 and when we print Date, it calls the toString method and displays date time information in the local timezone. If we want to display a date in different timezone we can do this by using SimpleDateFormat class in Java. In this Java tutorial, we will see a couple of example of displaying a date in IST and PST timezone.

How to remove element from Array in Java with Example

There is no direct way to remove elements from Array in Java. Though Array in Java is objects, it doesn't provide any methods to add(), remove() or search an element in Array. This is the reason Collection classes like ArrayList and HashSet are very popular. Thanks to Apache Commons Utils, You can use there ArrayUtils class to remove an element from array more easily than by doing it yourself. One thing to remember is that Arrays are fixed size in Java, once you create an array you can not change their size, which means removing or deleting an item doesn't reduce the size of the array. This is in-fact main difference between Array and ArrayList in Java. What you need to do is create a new array and copy remaining content of this array into a new  array using System.arrayCopy() or any other means. For Object arrays, You can also convert Array to List and then remove a particular object and convert List back to the array. One way to avoid this hassle is using ArrayList instead of Array in the first place.

How to convert java.sql.Date to java.util.Date in Java with Example

How to convert java.sql.Date into a java.util.Date and vice-versa is a popular JDBC interview question which is also asked as follow-up question of the difference between java.sql.Date and java.util.Date which we have saw in our last article. Since both SQL date and Util date stores values as a long millisecond , it's easy to convert them back and forth. Both java.sql.Date and java.util.Date provides a convenient method called getTime() which returns long millisecond equivalent of wrapped date value. Here is a quick example of converting java.util.Date to java.sql.Date and then back to util Date. This article is in next of earlier post on Java Date and Time API  like How to convert Date to String and How to find current Date and Timestamp in Java on any timezone. if you haven't read them already you may find them useful.

JDBC Interview questions answers in Java - 2 to 4 years experienced programmer

JDBC Interview question forms one of the important section in Java Interviews. Similar to multithreading, Collection framework and Garbage collection interview question, JDBC question must be prepared by any Java programmer. Most of questions from JDBC or Java database connectivity comes from API and basic architecture of JDBC which also involves JDBC drivers. A good understanding of JDBC API along with database basics like transactions also help to do well in JDBC interviews. I have collected some of frequently asked JDBC Interview question for quick reference. This will help to revise some important JDBC concepts and also give a chance to explore JDBC API to newcomers. If you have any other JDBC interview question, which has been asked to you or friends, and you think it’s good to share among Java community then please share with us. Let's see my 11 questions from JDBC, not so tough but worth preparing.

How to check leap year in Java - program example

Write a Java program to find if a year is a leap year or not is a standard Java programming exercise during various Java programming course on school, colleges and various training institutes both online and offline,  along with other popular homework's e.g. printing Fibonacci numbers, checking palindromes or finding prime numbers. Just to recap a leap year is a year with 366 days which is 1 extra day than normal year. This extra day comes in month of February and on leap year Feb month has 29 days than normal 28 days. If you are following then you might know that leap year comes in a interval of 4 years. This year 2012 is a leap year and Feb has 29 days, you can check. Now if you are in programming before you might be familiar that there is standard logic to find leap year i.e. if an year is multiple of 400 or multiple of 4 but not multiple of 100 then its a leap year. In addition to this standard logic, you can also use Java's Date, Time and Calendar API to check how many days any year has and by comparing that number with 365 you can find whether that year is leap year or not . In this Java programming tutorial we will both of these example to check if a year is leap year or not.

Unix command to find IP address from hostname - Linux example

IP address from hostname in UNIX
In this Unix command tutorial, we will see How to find IP address of any host in a UNIX based system e.g. Linux, Solaris or IBM AIX. In general hostname and IP address are two important things about any host in a UNIX based network.  You always need either hostname or IP address to connect to any host. Some time you want to find IP address of localhost, some time IP address of another host on network etc. We have shown some techniques to find IP address from hostname in UNIX and here we will see is particular list of UNIX commands to get IP address of localhost or host on which you are working along with any other host for which we know hostname. 

Difference between RuntimeException and checked Exception in Java

RuntimeException vs Checked Exception in Java
Java Exceptions are divided in two categories RuntimeException also known as unchecked Exception and checked Exception. Main difference between RuntimeException and checked Exception is that, It is mandatory to provide try catch or try finally block to handle checked Exception and failure to do so will result in compile time error, while in case of RuntimeException this is not mandatory. Difference between checked and unchecked exception is one of the most popular question on Java interview for 2 to years experienced developer especially related to Exception concepts. Answer to this question is rather similar as mentioned in previous lines and they are mostly asked along with other Java Exception interview questions like difference between throw and throws and Error vs Exception. Any Exception which is subclass of RuntimeException are called unchecked and mandatory exception handling is not requirement for them.

Difference between GenericServlet vs HttpServlet in Servlet JSP - J2EE question

Difference between GenericServlet and HttpServlet is one of the classic Servlet Interview Question, asked on many Servlet and JSP Interviews on 2 to 4 years experience developers. Since both GenericServlet and HttpServlet forms basis of Servlets its important to know What are they and What is main difference between them. From common sense and there names, its obvious that GenericServlet is a generic and protocol independent implementation of Servlet interface while HttpServlet implements HTTP protocol specifics. If you are working in Java web application or J2EE projects, you are most likely to deal with HttpServlet all time as HTTP is main communication protocol of web. In this Servlet JSP article we will outline some important difference between HttpServlet and GenericServlet which is worth knowing and remembering.

Bubble sort in Java - program to sort integer array

Bubble sort is one of the classic sorting algorithm which is used to explain sorting during various computer and engineering courses. Because of its algorithmic nature and simplicity its often used in various Java and C++ programming exercises. You may expect questions like Write Java program to sort integer array using bubble sort during any programming interview. Since algorithmic questions are always tricky question and not easy to code. Even simplest of them can lead to confusion, especially if you are not gifted with a natural programming head. I have seen many developers fumble if asked to code on the spot. That's why its advisable to do algorithmic and logical programming during training and learning programming and OOPS to get this skill of converting logic into code. Let's come back to Bubble sort, In Bubble sort algorithm we sort an unsorted array by starting from first element and comparing with adjacent element. If former is greater than later then we swap and by doing this we get the largest number at the end after first iteration. So in order to sort n elements you require n-1 iteration and almost n-1 comparison. For recap here is the logic for bubble sort sorting algorithm :

Difference between Array vs ArrayList in Java

What is the difference between Array and ArrayList is quite a common question among beginners especially who started coding in C and C++ and prefer to use Array? Both Array and Array List are used to store elements, which can be either primitive or objects in case of Array and only objects in case of ArrayList in Java. Main difference between Array vs ArrayList in Java is static nature of Array and dynamic nature of ArrayList. Once created you can not change size of Array but ArrayList can re-size itself when needed. Another notable difference between ArrayList and Array is that Array is part of core Java programming and has special syntax and semantics support in Java, While ArrayList is part of Collection framework along with other popular classes e.g. Vector, Hashtable, HashMap or LinkedList. Let's see some more difference between Array and ArrayList in Java in point form for better understanding.

How to remove all white space from String in Java - beginning end and between words

String API in Java provides several utility method to remove white space from String in Java, from beginning, end and between words. White space means blank space including tab characters. One of the classic method to remove white space from beginning and end of a string in Java is trim() method, which removes white space from beginning and end. While using trim() method, key thing to remember is that trim() returns a different String object than older one because String is immutable in Java. On the other hand if you want to remove all white spaces from string i.e. white space from beginning, end and between words then you can use replaceAll() method of String and pass regular expression \s to find and replace all white spaces including tab with empty string "". This is the quickest ways of removing all white space from String in Java. Removing white spaces is not only common programming requirement in Java development but also one of the common String Interview question in Java. Once again just remember that every time you modify a String, even if you remove white space it generate a new String and remember to store and use that. In this Java tutorial we will see Java program to remove all white space from String in Java including beginning and end.

Difference between trustStore vs keyStore in Java SSL

Main difference between trustStore vs keyStore is that trustStore (as name suggest) is used to store certificates from trusted Certificate authorities(CA) which are used to verify certificate presented by Server in SSL Connection while keyStore is used to store private key and own identity certificate which program should present to other parties (Server or client) to verify its identity. That was one liner difference between trustStore vs  keyStore in Java but no doubt these two terms are quite a confusion not just for anyone who is the first time doing SSL connection in Java but also many intermediate and senior level programmer. One reason of this could be SSL setup being a one-time job and not many programmers get opportunity to do that. In this Java article, we will explore both keystore and trust stores and understand key differences between them. By the way, you can use a keytool command to view certificates from truststore and keystore. keytool command comes with Java installation and its available in the bin directory of JAVA_HOME.

How to convert String from lowercase to uppercase and lowercase in Java

Convert String from uppercase to lowercase in Java
Sometime we need to convert String from lowercase to uppercase or from uppercase to lowercase e.g. before printing or storing into database etc. String class in Java provides some utility method to perform this case conversion. You can use toUpperCase() to convert any lower case String to uppercase and toLowerCase() to convert any uppercase String to lowercase. Key thing to remember while using toUpperCase() and toLowerCase() is that they return a different String rather than modifying same String because String is immutable in Java. So if you use old String, assuming it has been converted into uppercase or lowercase then you may create but, instead just store new String returned by these methods into same variable which is hold to store old String. Once again getting familiar with key classes like java.lang.String is very important for Java programmer as we often need to Split String, replace String or remove white space from String etc. String provides several convenient method to do this without using external library. In this Java tutorial we will also see complete Java program to convert String to lowercase and uppercase in Java.

How to Read Input From Console in Java using Scanner Example

Apart from reading file, Scanner can also read user input from Console in Java. Just like in case of reading file, we have provided File as source for scanning, We need to provide System.in as source to scan for user input in Console. Once you created and initialized java.util.Scanner, you can use its various read method to read input from user. If you want to read String, you can use nextLine(), if you want to read integer numbers, you can use nextInt(). Subsequently you can use nextFloat() to read float input, nextDouble() to read double input etc. Scanner class also allows you to define your own pattern and scan for that.

How to reverse String in Java with or without StringBuffer Example

Reverse String in Java
There are many ways to reverse String in Java. You can use rich Java API to quickly reverse contents of any String object. Java library provides StringBuffer and StringBuilder class with reverse() method which can be used to reverse String in Java. Since converting between String and StringBuffer or StringBuilder is very easy it's the most easy way available to reverse String in Java. At the same time Writing Java program to reverse String in Java without StringBuffer is one of the popular Java String interview question, which requires you to reverse String by applying logic and by not using API methods. Since reverse is a recursive job, you can use recursion as well as loop to reverse String in Java. In this Java tutorial I have shown How to reverse String using StringBuffer, StringBuilder and using pure loop with logic. You can also check How to reverse String with recursion in Java, if you want to see recursive code. let's see complete Java program for this beautiful Java programming exercise.



Java program to reverse String in Java

Java program to reverse String in Java without StringBuffer or StringBuilderHere is my complete code program to reverse any String in Java. In main method we have first used StringBuffer and StringBuilder to reverse contents of String and then we wrote our own logic to reverse String. This uses toCharArray() method of String class which return character array of String. By looping through character array and appending it into empty String we can get reversed String in Java, as shown in following example.


/**
 *
 * Java program to reverse String in Java. There are multiple ways to reverse
 * String in Java, you can either take help of standard Java API StringBuffer
 * to reverse String in Java. StringBuffer has a reverse() method which return StringBuffer
 * with reversed contents. On the other hand you can also reverse it by applying your
 * own logic, if asked to reverse String without using StringBuffer in Java. By the way
 * you can also use StringBuilder to reverse String in Java. StringBuilder is non thread-safe
 * version of StringBuffer and provides similar API. You can use StringBuilder's reverse()
 * method to reverse content and then convert it back to String
 *
 * @author http://java67.blogspot.com
 */

public class StringReverseExample {
 
 
    public static void main(String args[]) {
     
        //quick wasy to reverse String in Java - Use StringBuffer
        String word = "HelloWorld";
        String reverse = new StringBuffer(word).reverse().toString();
        System.out.printf(" original String : %s , reversed String %s  %n", word, reverse);
     
        //another quick to reverse String in Java - use StringBuilder
        word = "WakeUp";
        reverse = new StringBuilder(word).reverse().toString();
        System.out.printf(" original String : %s , reversed String %s %n", word, reverse);
     
        //one way to reverse String without using StringBuffer or StringBuilder is writing
        //own utility method
        word = "Band";
        reverse = reverse(word);
        System.out.printf(" original String : %s , reversed String %s %n", word, reverse);
    }  
 
 
    public static String reverse(String source){
        if(source == null || source.isEmpty()){
            return source;
        }      
        String reverse = "";
        for(int i = source.length() -1; i>=0; i--){
            reverse = reverse + source.charAt(i);
        }
     
        return reverse;
    }
   
}

Output:
original String : HelloWorld , reversed String dlroWolleH
original String : WakeUp , reversed String pUekaW
original String : Band , reversed String dnaB


That's all on How to reverse String in Java with and without StringBuffer and StringBuilder. Though being a Java programmer I prefer to use library and suggest any one to use StringBuffer or StringBuilder to reverse String for any production use. Though its also a good programming exercise and you should practice it before going for any Java programming interview.

Other Java tutorials you may like

Difference between Error vs Exception in Java - Interview question

Both Error and Exception are derived from java.lang.Throwable in Java but main difference between Error and Exception is kind of error they represent. java.lang.Error represent errors which are generally can not be handled and usually refer catastrophic failure e.g. running out of System resources, some examples of Error in Java are java.lang.OutOfMemoryError or Java.lang.NoClassDefFoundError and java.lang.UnSupportedClassVersionError. On the other hand java.lang.Exception represent errors which can be catch and dealt e.g. IOException which comes while performing I/O operations i.e. reading files and directories. Clear understanding of Error and Exception is must for any serious Java programmer and good programming and debugging skills are required to overcome issues which caused Error and Exception in Java. Apart from its must have knowledge in Java application development, difference between Error and Exception is also a popular questions on Java interviews related to Exception handling, similar to difference between throw and throws in Java. In this Java article we will briefly see major difference between Error and Exception in Java which include both syntactical and logical difference.

How to create and initialize List or ArrayList in one line in Java

creating and initializing List in same time
Sometime we want to create and initialize List like ArrayList or LinkedList in one line much like creating array and initializing it on same line. If you look Array on Java programming language you can create and initialize both primitive and object array e.g. String array very easily in just one line but in order to create a List equivalent of that array, you need to type lot of code. This is also one of the tricky Java question some time appears in Interview as Write Java code to create and initialize ArrayList in same line. In this Java tips we will see this trick which allow you to create and initialize List much like an Array. This tip can also save lot of time while creating test program or quickly trying some stuff.

What is difference between Thread vs Process in Java

Thread and Process are two closely related term in multi-threading and main difference between Thread and Process in Java is that Threads are part of process. i.e. one process can spawn multiple Threads. If you run a Java program in UNIX based system e.g. Linux and if that program creates 10 Threads, it still one process and you can find that by using ps -ef | grep identifier command which is one of most popular use of grep command in UNIX, Where identifier is unix text which can be used as regular expression to find that Java process. Another major difference between Process and Thread is that, each process has its own separate memory space but Threads from same process same memory space. Some linux command map Java thread with light weight process or lwp, e.g. if you use prstat command in Solaris, you can get how many light weight process or Thread a particular Java program is using.