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

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.

Further Learning
The Coding Interview Bootcamp: Algorithms + Data Structures
Data Structures and Algorithms: Deep Dive Using Java
Algorithms and Data Structures - Part 1 and 2

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.

Difference between transient vs volatile variable or modifier in Java

transient vs volatile modifier in Java
What is difference between transient and volatile variable or modifier in Java is one of the most common Serialization Interview Question in Java. Though volatile variables are not related to Serialization at all, this question is mostly asked in conjunction with other Serialization question. Both transient and volatile modifiers are completely different to each other. In fact this question is as popular as Serializable vs Externalizable in Java. Main difference between transient vs volatile variable is that transient variables are not serialized during Serialization process in Java while volatile variables are used to provide alternative synchronization in Java. By using volatile keyword or modifier on fields, signals compiler that this variable is accessed by multiple thread and any reordering or optimization by compiler should be avoided. In this Java article we will see some difference between transient and volatile variable by learning each of them and When to use transient and volatile variable in Java.

10 points about Static in Java

What is static in Java
Static in Java is related to class, if a field is static means it belongs to class, similarly static method belongs to classes and you can access both static method and field using class name e.g. if count field is static in Counter class than you can access it as Counter.count, of course subject to restriction applied by access modifier e.g. private fields are only accessible in class on which they are declared, protected fields are accessible to all classes in same package but only accessible in sub class outside package. See private vs protected vs public for complete details on access modifier. Similarly if you have a static method increment() in Counter class which increment counter than you can call it as Counter.increment(). There is no need to create an object of Counter class to access either static method or static field, this is main difference between static and non static members.

Difference between method and constructor in Java

What is difference between method and constructor in Java is very common questions on beginner level Java interviews with 2 to 3 year experience. Since constructor is kind of special and it has it's own properties which separates it from any normal Java method, this question make sense. Main difference between Constructor and Method is that, you need to call method explicitly but constructor is called implicitly by Java programming language during object instantiation. It doesn't mean you can not call Constructor; if you have overloaded constructor than you can call them using  this keyword as this() constructor, you can even call super class constructor using super() keyword, in-fact that is done automatically by Java compiler if no explicitly constructor is called and that is known as constructor chaining in Java. Like many other beginner level questions e.g. Vector vs ArrayList, We will see difference between method and constructor in Java in point form to understand important properties of each of them clearly.

Java ArrayList Examples For Programmers

ArrayList Example in Java
In this Java ArrayList Example we will see how to add elements in ArrayList, how to remove elements from ArrayList, ArrayList contains Example and several other ArrayList functions which we use daily. ArrayList is one of the most popular class from Java Collection framework along with HashSet and HashMap and a good understanding of ArrayList class and methods is imperative for Java developers. ArrayList is an implementation of List Collection which is ordered and allow duplicates.  ArrayList is alos index based and provides constant time performance for common methods e.g. get().Apart from very popular among Java programmers, ArrayList is also a very popular interview topic. Questions like Difference between Vector and ArrayList and LinkedList vs ArrayList is hugely popular on various Java interview specially with 2 to 3 years of experience. Along with Vector this is one of the first collection class many Java programmer use. By the way e have already seen some ArrayList tutorial e.g. ArrayList sorting example,  converting Array to ArrayList,  looping through ArrayList which is good to understand ArrayList in Java.

Java Enum Example with Constructor

Java Enum with Constructor
Java Enum can have Constructor to pass data while creating Enum constants. One example of passing arguments to enum Constructor is our TrafficLight Enum where we pass action to each Enum instance e.g. GREEN is associate with go, RED is associate with stop and ORANGE is associated with slow down. You can also provide one or more constructor to your Enum as it also support constructor overloading. Just note that modifier public and protected are not allowed to Enum constructor, it will result in compile time error. By the way We have covered see some enum examples in our previous posts e.g. Java Enum Switch Example, Java Enum valueOf Example and Enum to String Exmaple in Java, which is good to learn enum in Java.

JDOM Example : Reading and Parsing XML with SAX parser in Java

XML parsing with JDOM parser
JDOM is an open source library which allow XML parsing and reading in Java program. JDOM is designed by using Java programming technique and customized for Java programmers, so that Java programmer with  very little knowledge of XML documents can use JDOM to read XML files. Unlike DOM Parser of Java API , which uses Factory design pattern to create instance of parser e.g DocumentBuilderFactory and DocumentBuilder, as seen in our last example of parsing XML documents in Java, JDOM uses new() operator to create its parser instances. In fact JDOM is very easy to understand and most of the time its self explanatory. While trying this Java program to parse XML file, you can explore JDOM API. JDOM API also allows to use XPATH expression to query XML documents with package org.jdom2.xpath. In next section we will see complete code example of How to read an XML file using JDOM parser in Java program.

How to Search Element in Java Array with Example

find an index of the object in Array
While programming in Java, many times we need to check if a String array contains a particular String or an int array contains a number or not. Though array is an object in Java but it does not provide any convenient method to perform these kinds of operation. Sometimes you even need an index of an item stored in Array, unfortunately, Java API does not provide any direct method. Thanks to open Source Apache Commons provides a utility class called ArrayUtils which allows you to check for an Item in Array, find its index in the array, find its lastIndex in Array and perform several other common operations. In fact, ArrayUtils has overloaded methods for different kind of Array e.g. String, int, float, double, Object etc, which makes this kind of programming task trivial. In this article, we will see an Apache commons example of How to use ArrayUtils class to search an item in Array and find its index.

Difference between Serializable vs Externalizable in Java - Interview Question

Serializable vs Externalizable
What is difference between Serializable and Externalizable in Java is famous core Java interview questions and for some of them its one of those difficult Java question, which no one want to see in Java interview. I was on that category until I explored How Serialization works in Java and find out more about Serialization process. What makes Serialization questions tricky is , Serialization as persistence mechanism is not very popular. Many programmer prefer database, memory mapped file or simple text file over Serialization. But Serialization has a distinguished advantage over these mechanism. Java provides default mechanism to preserver object state and your job many time would be as simple as adding implements Serializable on any class.In this article we will compare Serializable to Externalizable and see some common difference between Serializable vs Externalizable to tackle this Java question.

Top 10 Servlet JSP Interview Questions for Java J2EE programmer - FAQ

Servlets and JSP Interview Questions are core of any J2EE Interview. Its expected from candidate to have good knowledge of Servlet, JSP, EJB , Struts or Spring in any J2EE interview. Consequently Servlets and JSP Interview Questions are very common in any J2EE Interviews along with some questions from core Java, Some interview Questions from Spring and Some EJB interview questions. Since J2EE is main platform for building enterprise and web application using Java programming language, its important to prepare well for J2EE interview, especially If you are in application development space. Servlet and JSP forms web layer of J2EE framework where Java Server pages is main view technology and Servlets are main Controller component of standard MVC architecture. In this article we will see couple of most common or frequently asked JSP and Servlet Interview questions and answers, which can help you on your J2EE interview preparation and understanding some key concept of Java web applications.

Difference between throw vs throws in Java

throw vs throws in Java
throw vs throws in Java programming Exceptionthrow and throws are two Java keyword related to Exception feature of Java programming language. If you are writing Java program and familiar with What is Exception in Java, its good chance that you are aware of What is throw and throws in Java. In this Java tutorial, we will compare throw vs throws and see some worth noting difference between throw and throws in Java. Exception handling is an important part of Java programming language which enables you to write robust programs. There are five keywords related to Exception handling in Java e.g. try, catch, finally, throw and throws. Apart from the difference between final, finally and finalize,  throw vs throws is one of the frequently asked Java interview questions. Difference listed here will not only help you to answer this interview question but also understand concept behind throw and throws better.

Java Interview Questions for 2 to 3 years experience - Answered

Java Interview Questions 2 to 4 years experienced
If you are a Java programmer with 2 to 3 years experience of working in Java and looking for job change then its better to know what is expected from a 2 to 3 years experienced Java programmer in a typical core Java or J2EE interview. Since 2 to 3 years is not a huge experience and you still fall under beginner to intermediate category , its not expected from you to have done profiling, Garbage collection tuning or designing complex Java applications or even creating concurrent Java design pattern. What is expected from a 2 to 4 years experience guy in Java programming is sound knowledge of Java fundamental including OOPS concepts like Abstraction, Encapsulation, Polymorphism, Composition and Inheritance, good knowledge of Java collection API and familiarity with different kinds of collection e.g. List, Set and Map with some familiarity with popular Collection classes e.g. ArrayList, HashMap, Vector and HashSet etc. Fundamental knowledge of Java threading API, wait-notify mechanism and Exception handling in Java is also something Interviewer look in a intermediate Java programmer and of-course some basic programming and coding exercise e.g. finding length of linked List in one pass or reversing String in Java etc. If you manage to prepare these topics well, you are most likely to do well in Java interviews on service based companies e.g. Tech Mahindra, CapeGemini, CTS, Wipro, TCS etc.

How to iterate over HashSet in Java - loop or traverse Example

Iterating over HashSet in Java
Java program to Iterate over HashSet in Java with ExampleIn our last Java collection tutorial, we have seen How to iterate over ArrayList in Java and in this tutorial we will see How to iterate over HashSet in Java. There are two ways to iterate, loop or traverse over HashSet in Java, first using advanced for-each loop added on Java 5 and second using Iterator which is a more conventional way of iterating over HashSet in Java. Now questions are When should you use for loop and when Iterator is an appropriate option. Well I usually use for loop If I only read from HashSet and doesn't remove any element, while Iterator is preferred approach. You should not remove elements from HashSet while iterating over it in for loop, Use Iterator to do that.

How to convert Hexadecimal to Decimal, Binary and Octal in Java program - Example

Hexadecimal to decimal and binary conversion in Java
This Java program will convert Hexadecimal number to decimal, binary and Octal in Java programming language using JDK standard API methods. For beginners hexadecimal is base 16 number, while decimal is base 10, Octal is base 8 and binary is base 2 numbers in Number systems. Binary only contains 0 and 1 bits, octal contains 0 to 7, decimal contains 0 to 9 and Hexadecimal contains 0-9,A,B,C,D,E,F where F represent 16. Thankfully Java library provides convenient method to convert any integer from one number system to another. In our last article we have seen How to convert decimal number to binary in Java and in this article we will convert Hexadecimal numbers to binary, octal and decimal numbers.If you are going for programming interviews, then its better to prepare How to do this exercise without using Java API as well, as interviewer commonly expect programmer to create there own method during interviews e.g. reversing String without using StringBuffer reverse() method.

How to convert ArrayList to String in Java - Spring Example

Some time we need to convert ArrayList to String in Java programming language in order to pass that String to stored procedure, any method or any other program. Unfortunately Java collection framework doesn't provide any direct utility method to convert ArrayList to String in Java. But Spring framework which is famous for dependency Injection and its IOC container also provides API with common utilities like method to convert Collection to String in Java. You can convert ArrayList to String using Spring Framework's StringUtils class. StringUtils class provide three methods to convert any collection e.g. ArrayList to String in Java, as shown below:

How to find swap space and usage in Solaris - UNIX command

Swap space in Solaris or any UNIX host is an important disk space which is used for swapping process from physical memory (RAM)  to disk. Virtual memory allowed a process to run even if physical memory gets full by using swap space (which is located on your hard disk) to swap out memory pages which are not currently in use. In this UNIX command tutorial, we will see some Solaris commands to find configured and current usage of swap space. Remember if your machine runs out of swap space then you can not start a new process and also an old process which will try to expand themselves will likely to fail. 

UNIX command to find symbolic link or soft link in Linux

There are two ways you can find a symbolic link or soft link in UNIX based operating system e.g. Linux, Solaris, BSD or IBM AIX. The first way is by using ls command in UNIX which displays files, directories, and links in any directory and other way is by using UNIX find command which has the ability to search any kind of files e.g. file, directory or link. In this UNIX command tutorial, we will see examples both of these UNIX commands for finding a soft link in any directory. If you are new to UNIX operating system and not familiar with the concept of the soft link and hard link, I would recommend getting a good hand on it, as it is one of the most powerful features of UNIX based system.

Difference between static and non static nested class in Java - Inner class

Static vs non Static class in Java
In Java you can make a class either static or non static. Now what is difference between making a class static vs non static? well there is lot of difference between them. First of all there are two kinds of class in Java, one is called top level class and other is called nested class. As name suggested top level class is a class which is declared in .java file and not enclosed under any other class. On other hand nested class is declared inside another class. The class which enclosed nested class is known as Outer class. Now let's come back to static vs non static class. In Java programming language you can not make a top level class static. You can only make nested class either static or non static. If you make a nested class non static then it also referred as Inner class. Now let's come to the point regarding Difference between static and non static nested class in Java

20 EJB 3.0 Interview Questions and Answers - Java J2EE

EJB interview questions are core part of any Java J2EE interview. As EJB forms business layer for modern J2EE enterprise application, Good knowledge of EJB is expected from J2EE programmer. Purpose of these EJB interview questions is to give an Idea about what kind of questions you can expect on J2EE and EJB interviews. EJB was always tough for Java programmer because of heavy weight architecture comprised with many interfaces e.g. home interface, remote interface, local interface, bean class etc. It take too much time and knowledge to implement and use EJB in your Java web and enterprise application forget about challenges posed by application servers like WebLogic or IBM WebSphere. All these problem persist till EJB 2.0 which makes EJB infamous along with J2EE and created path for Spring framework which is based on POJO. But with EJB 3.0, Enterprise Java Beans are back again and they are back with bang. In this article I will share some EJB Interview questions from my collection. These EJB questions are from EJB 2.0 and EJB 3.0 and also related to fundamental concept of using Enterprise Java beans. By the way I don't have answer of these Enterprise Java beans questions but I will update the post once I have answers of all these interview questions asked on EJB interviews. This article is divided in two category, in first category we will see some common EJB interview questions and in second category we will see EJB 3.0 interview question, which is more popular now days. I have seen EJB question on companies like Capegemini, TCS, CTS, Infosys and Wipro and mostly on finance domain projects

Java program to read File in Java - Windows UNIX

Java provides java.io  package in JDK API for reading File in Java from File system e.g. C:\ or D:\ drive in Windows or any other directory in UNIX. First, you can use FileInputStream to open a file for reading. FileInputStream takes a String parameter which is a path for the file you want to read. Be careful while specifying File path as path separator is different on Window and UNIX. Windows uses back slash while UNIX uses forward slash as a path separator. By the way, Java supports forward slash in Windows, It means if use forward slash your program will work on both Windows and UNIX. Alternatively, you can also get PATH separator from System property path.separator. In this Java tutorial, we will code example of How to read File in Java.

How to use Java Enum in Switch Case Statement - Exampel Tutorial

Java Enum in Switch Case Statement
Yesterday, some one ask me Can we use Java Enum in Switch case ? Obviously, he was learning Enum and not aware that How powerful Enum in Java is. Yes, You can use Enum in Switch case statement in Java like int primitive. If you are familiar with enum int pattern, where integers represent enum values prior to Java 5 then you already knows how to  use Switch case with Enum. Using Java Enum in Switch case is pretty straightforward, Just use Enum reference variable in Switch and Enum constants or instances in CASE statement. In this Java tutorial we will see one example of How to use Enum in Switch statement in Java. By the way Enum is feature rich in Java, Enum can implement interface in Java, Enum can override method in Java, Enum can have constructor in Java and Enum is full functional Type like class or interface. Programmers use Enum with different ways. One of the best example of Enum in Java is replace enum int pattern and enum String pattern. You can also use Enum to write Thread-safe Singleton in Java.