Sunday, April 30, 2017

Difference between Struts ValidatorForm vs ValidatorActionForm - Interview Question

Struts provide two classes ValidatorForm and ValidatorActionForm for validating form fields. Instead of doing basic validation by using the validate() method in Action class, these classes allows you to leverage rich feature of validation framework provided by Jakarta Struts framework. You can do declarative validation by defining rules in XML config files like validation-rule.xml or validations.xml as well. Since Struts is one of the popular Web MVC frameworks, you can also use its validation framework on any Java web application implemented using Struts. Now, coming back to the question, what is the actual difference between ValidatorForm and ValidatorActionForm in Struts? They both look quite similar, right?

Saturday, April 29, 2017

Difference between PriorityQueue and TreeSet in Java?

The PriorityQueue and TreeSet collection classes has a lot of similarities e.g. both provide O(log(N)) time complexity for adding, removing, and searching elements, both are non-synchronized and you can get element from both PriorityQueue and TreeSet in sorted order, but there is fundamental difference between them, TreeSet is a Set and doesn't allow a duplicate element, while PriorityQueue is a queue and doesn't have such restriction. It can contain multiple elements with equal values and in that case head of the queue will be arbitrarily chosen from them.

Eclipse No Java Virtual Machine was found Windows JRE JDK 64 32 bit Error

One of my readers was installing Eclipse in his Windows 7 x86 machine and emailed me about this error "A java Runtime Environment (JRE) or Java Development kit (JDK) must be available in order to run Eclipse. No Java virtual machine was found". Before getting into details and trying to find root cause and solution of Eclipse Java Virtual Machine not found error, let's see some background about Eclipse. Eclipse is a popular Java IDE, which assists on coding, debugging and running Java program, but the key point is, Eclipse itself need Java to launch and run.

Friday, April 28, 2017

Difference between Transient, Persistent, and Detached Objects in Hibernate

In the Hibernate framework, an entity can be in three states, transient, persistent, and detached. When an object is in a transient state, it is commonly referred to as a transient object, similarly, if it is in persistence and detached state, it is known as a persistent and detached object. When an entity is first created using the new operator e.g. new User() and not associated with Hibernate session e.g. you haven't called session.save(user) method then it is known as a transient object. At this stage, Hibernate doesn't know anything about this object and the object doesn't have any representation in the database e.g. a corresponding row in the User table.

Difference Between java and javaw Commands from JDK

difference between java.exe and javaw.exe commands was the recent java question asked to one of my friends. while running java program on windows you might have noticed that they will appear in task manager as either java.exe or javaw.exe,  also in JAVA_HOME/bin we see these two java commands java.exe and javaw.exe, do you know the difference between java.exe and javaw.exe? surprisingly not many java programmers know the answer to this java interview question, maybe because java developers have not paid enough attention to these commands. anyway here we will see few differences between java and javaw commands:

Difference between Connected vs Disconnected RowSet in Java JDBC | RowSetProvider, RowSetFactory Example

RowSet interface is another key interface from JDBC API, which extends the ResultSet interface to provide support for the JavaBean component model. Along with convenient methods to set connection parameters like the setUrl(), setUsername(), setPassword() and setCommand(), it also defines getters and setters for different data types e.g. getLong() and setLong(). Another feature of RowSet is that it supports event listeners. You can attach listeners to RowSet object to listen for events, much like Observer design pattern. RowSet acts as Subject and notifies Observer on events like change in cursor location, change in a row, or change in the entire RowSet. There are two types of RowSet available in JDBC 4.1 API, connected and disconnected.

Wednesday, April 26, 2017

What is java.library.path , How to set in Eclipse IDE

java.library.path is a System property, which is used by Java programming language, mostly JVM, to search native libraries, required by a project. Similar to PATH and Classpath environment variable, java.library.path also includes a list of directory. When Java code loads a native library (a library or executable written in a language like C, C++, or native code) using System.loadLibrary("name of library") method, java.library.path is scanned for specified library. If JVM doesn't found the requested native library, then it throws java.lang.UnsatisfiedLinkError: no native library in java.library.path.

Tuesday, April 25, 2017

Difference between CAST, CONVERT, and PARSE function in Microsoft SQL Server

Though all three, CAST, CONVERT, and PARSE are used to convert one data type into another in SQL Server, there are some subtle differences between them. The  CAST method accepts just two parameters, expression, and target type, but CONVERT() also takes a third parameter representing the format of conversion, which is supported for some conversions, like between character strings and date-time values. For example, CONVERT(DATE, '2/7/2015', 101) converts the character string '2/7/2015' to DATE using DATE format 101, representing United States standard.

How to Convert Byte Array to InputStream and OutputStream in Java

Are you stuck with your coding because you have a byte array and the next method in the chain needs an InputStream? don't worry Java has a solution for that, You can use ByteArrayInputStream to convert byte array to InputStream in Java. This class takes a byte array as the source and since it's a subclass of InputStream, you can easily pass this to any method, which accepts InputStream as a parameter. Though most of the API like JDBC and File API allows you to read directly from InputStream because this allows you to process an arbitrary content with limited heap space. You should take advantage of this and directly read from InputStream instead of getting byte array and then converting them back to InputStream.

Difference between valueOf and parseInt method in Java

Both valueOf and parseInt methods are used to convert String to Integer in Java, but there are subtle difference between them. If you look at code of valueOf() method, you will find that internally it calls parseInt() method to convert String to Integer, but it also maintains a pool of Integers from -128 to 127 and if requested integer is in pool, it returns object from pool. Which means two integer objects returned using valueOf() method can be same by equality operator. This caching of Immutable object, does help in reducing garbage and help garbage collector. Another difference between parseInt() and valueOf() method is there return type. valueOf() of java.lang.Integer returns an Integer object, while parseInt() method returns an int primitive. Though, after introducing Autoboxing in Java 1.5, this doesn't count as a difference, but it's worth knowing.

Monday, April 24, 2017

Difference between ConcurrentHashMap, Hashtable and Synchronized Map in Java

ConcurrentHashMap vs Hashtable vs Synchronized Map
Though all three collection classes are thread-safe and can be used in multi-threaded, concurrent Java application, there is a significant difference between them, which arise from the fact that how they achieve their thread-safety. Hashtable is a legacy class from JDK 1.1 itself, which uses synchronized methods to achieve thread-safety. All methods of Hashtable are synchronized which makes them quite slow due to contention if a number of thread increases. Synchronized Map is also not very different than Hashtable and provides similar performance in concurrent Java programs. The only difference between Hashtable and Synchronized Map is that later is not a legacy and you can wrap any Map to create it's synchronized version by using Collections.synchronizedMap() method.

Difference between repaint and revalidate method in Java Swing

What is the difference between revalidate() and repaint() in Java Swing is one of the popular Swing Interview Questions especially on Investment banks? Though both methods sound similar, there is a subtle difference between them. the revalidate() method instructs LayoutManager to recalculate layout and often called once new components are added or removed from Container. The revalidate() can also trigger to call the repaint() method to repaint components that have changed i.e. width, height, or any other visible property, which can affect layout. On the other hand repaint() method puts a paint request in AWT thread, for the repainting of a component on which it has called.

Sunday, April 23, 2017

Top 10 Google Interview Questions for Software Engineer - Books, Resources

These Google interview questions are some of my favorites collected from different sources. Every Programmer knows that Google is one of the best technology companies and its dream for many software developers to work for Google, but at the same time interview process at Google is very tough and only a few genuine intelligent programmers get through their interview process. Google interview questions have always been a good topic of discussion when few young software developers gathered around, I can still remember when one of my friends got a call from google for an interview then how the whole bunch was got excited.

Saturday, April 22, 2017

Difference between State and Strategy Design Pattern in Java

In order to make proper use of State and Strategy design Pattern in Core Java application, its important for a Java developer to clearly understand the difference between them. Though both State and Strategy design patterns have a similar structure, and both of them are based upon Open closed design principle, represents 'O' from SOLID design principles, they are totally different on there intent. The strategy design pattern in Java is used to encapsulate a related set of algorithms to provide runtime flexibility to the client. The client can choose any algorithm at runtime, without changing Context class, which uses a Strategy object. Some of the popular examples of Strategy pattern is writing code, which uses algorithms e.g. encryption, compression, or sorting algorithm.

Recursive Binary Search Algorithm in Java - Example Tutorial

The binary search algorithm is one of the most famous search algorithms in computer science. It allows you to search a value in logarithmic time i.e. O(logN), which makes it ideal to search a number on a huge list. For example, in order to search a number in a list of 1 million number will take around 210 comparisons compared to 1 million comparisons required by the linear search algorithm. The only thing is that the list must be sorted before you can use a binary search algorithm and it must support index-based search. That's why binary search is often implemented using an array because doing a binary search with a linked list will not be fast because it doesn't provide index-based access i.e. O(1) access. You have to traverse to that element to read its value in the linked list which is O(n), effectively reducing the performance of binary search to a sequential search algorithm.

What is String args[] Argument in Java Main method

What is String args is used for or Why we use String arg[] in main method is a common doubt among Java beginners. First thing newbies exposed while learning Java programming language is writing HelloWorldprogram in Java, Though HelloWorld is smallest sort of program, it contains lot of useful information and concept for newbies Java programmers, one of them is main method and it's different attribute. Though I covered bit of String args[], while discussing Why main is public static in Java, I thought to write this article to explain String args array in more detail. Let's see a simple Java HelloWorld again to understand more about String args in Java.

Friday, April 21, 2017

How to Create, Update and Remove Soft link in UNIX

Symbolic links, Symlink or Soft link in Unix are a very important concept to understand and use in various UNIX operating systems e.g. Linux, Solaris, or IBM AIX. Symlinks give you so much power and flexibility that you can maintain things quite easily. I personally feel that along with find, grep and other UNIX commands, the command to create a soft link and update soft link i.e. ln -s is also a must for anyone working in the UNIX machine. Whenever I do scripting or write any UNIX script I always write for symlinks rather than pointing to the absolute path of directories in UNIX.

FIX Protocol Tutorial for beginners

FIX Protocol Tutorial for beginnersI have been writing FIX Protocol Tutorial from last few months and today I thought about doing a revision on all those tutorials. It’s very easy to read and forget about anything you have learn so periodic revision is very important and I see its important here as well. In this article I will put summary of each of my previous FIX Protocol Tutorials and give a link back to original article for further reading. This will allow any beginner or new comer to get an idea of what topics from FIX has been already covered in these tutorials and helps them to quickly navigate between those. With growing use of  online trading and electronic trading for various Asset classes such as futures ,options, equities , Fixed Income and Commodities and growing number of online stock trading companies and broker in world market demand of FIX Protocol developers  are increasing day by day and now I can see more jobs for FIX developer than few years back. This  is a niche area and these online stock trading companies or brokers pay very good for any one who is very good knowledge of  FIX simply because it’s very difficult to find a good FIX Protocol developer

Thursday, April 20, 2017

Can we declare a class Static in Java?

The answer to this question is both Yes and No, depending on whether you are talking about a top-level class or a nested class in Java. You cannot make a top-level class static in Java, the compiler will not allow it, but you can make a nested class static in Java. A top-level class is a class that is not inside another class. It may or may not be public like you can have more than one class in a Java source file and only needs to be public, whose name must be the same as the name of the file, rest of the class or interface on that file may or may not be public. On the other hand, a nested class is a class inside a top-level class. It is also known as the inner class or member class in Java.

Wednesday, April 19, 2017

Java Program to Reverse an Integer Number - Example tutorial

How to reverse a number in Java without using any API or write a simple Java program to reverse a number is common programming questions asked on fresher level software engineer interviews. Reversing a number is also popular homework questions on many Java programming courses in schools, colleges, and training institutes. I personally feel java program to reverse number is good programming exercise for someone who is just started learning to program in Java or any other programming language because of its simplicity and a little bit of trickiness which shows how to use operators for programming purposes rather than arithmetic purpose.

Log4j Tips : Use MDC or Mapped Dignostic Context to distinguish logging per Client or Request

The MDC or Mapped Diagnostic Context is a concept or feature of Log4j logging library which can be used to group related log messages together. For example, by using MDC you can stamp a unique identification String like clientId or orderId on each log message and then by using grep command in Linux, you can extract all log messages for a particular client or order to understand exactly what happened to a particular order. This is especially very useful in multi-threaded, concurrent Java applications where multiple threads are simultaneously processing multiple orders from multiple clients.  In such applications, searching for relevant log messages in a big log file where log messages for multiple orders or clients are overlapping is a big task.

How to Convert InputStream to Byte Array in Java - 2 Examples

Sometimes we need to convert InputStream to byte array in Java, or you can say reading InputStream as a byte array, In order to pass output to a method that accepts byte array rather than InputStream. One popular example of this, I have seen is an older version of Apache commons-codec, while converting byte array to the hex string. Though, a later version of the same library does provide an overloaded method, to accept InputStream. Java File API provides excellent support to read files like image, text as InputStream in Java program, but as I said, sometimes you need String or byte array, instead of InputStream .

Tuesday, April 18, 2017

How to Measure Elapsed Execution Time in Java - Spring Framework's StopWatch Example

There are two ways to measure elapsed execution time in Java either by using System.currentTimeinMillis()or by using  System.nanoTime(). These two methods can be used to measure elapsed or execution time between two method calls or events in Java. Calculating elapsed time is one of the first things Java programmer do to find out how many seconds or millisecond a method is taking to execute or how much time a particular code block is taking. Most Java programmers are familiar with System.currentTimeInMillis()which is there from the beginning while a new version of more precise time measurement utility System.nanoTime is introduced in Java 1.5, along with several new features in a language like Generics, Enum types, autoboxing and variable arguments or varargs.

Difference between ArrayList and ArrayList<?> in Java - Raw Type vs Wildcard

One of my readers asked me about the difference between ArrayList vs ArrayList< in Java?>, which was actually asked to him on a recent Java development interview. The key difference between them is that ArrayList is not using generics while ArrayList is a generic ArrayList but they looks very similar. If a method accepts ArrayList or ArrayList<?> as a parameter then it can accept any type of ArrayList e.g. ArrayList of String, Integer, Date, or Object, but if you look closely you will find that one is raw type while other is using an unbounded wildcard. What difference that could make? Well, that makes a significant difference because ArrayList with raw type is not type safe but ArrayList<?> with the unbounded wildcard is type safe.

Monday, April 17, 2017

Difference between Abstraction and Encapsulation in Java - OOP

Both Abstraction and Encapsulation are two of the four basic OOP concepts which allow you to model real-world things into objects so that you can implement them in your program and code. Many beginners get confused between Abstraction and Encapsulation because they both look very similar. If you ask someone what is Abstraction, he will tell that it's an OOP concept which focuses on relevant information by hiding unnecessary detail, and when you ask about Encapsulation, many will tell that it's another OOP concept which hides data from the outside world. The definitions are not wrong as both Abstraction and Encapsulation does hide something, but the key difference is on intent.

Difference between List and Set in Java Collection

What is difference between List and Set in Java is a very popular Java collection interview questions and an important fundamental concept to remember while using Collections class in Java. Both List and Set are two of most important Collection classes Java Program use along with various Map implementation. Basic feature of List and Set are abstracted in List and Set interface in Java and then various implementation of List and Set adds specific feature on top of that e.g. ArrayList in Java is a List implementation backed by Array while LinkedList is another List implementation which works like linked list data-structure. In this Java tutorial we will see some fundamental difference between List and Set collections. Since List and Set are generified with introduction of Generics in Java5 these difference also application to List and Set.

This article is in continuation of my earlier post on Collection e.g. Difference between HashMap vs HashSet, Difference between HashMap and Hashtable and Difference between Concurrent Collection and Synchronized Collection. If you haven't read them already you may find them useful.

Sunday, April 16, 2017

How to Invoke Method by Name in Java Dynamically Using Reflection

In Java you can invoke any method by its string name dynamically using reflection API. java.lang.reflect API provides powerful reflection mechanism which can load classes by its name even if classes are not available at compile time, Can get all methods including private and public from class and allow you to invoke any method dynamically using reflection. For those who are new in Java this sound pretty strange that at runtime you provide a method name using string and Java can run that method without any code for calling the method during compilation, but Reflection is such a powerful mechanism it allows to do lot of stuff dynamically and if you been using IDE like Netbeans or Eclipse , J2EE framework like Spring and Struts, these all used reflection to provide powerful configuration module and several other useful feature like code assist etc. Reflection is very comprehensive topic and there is a lot to learn but we will start with simple Java program example to invoke a method using reflection in  by providing name of method as String value.  

This Java article is continuation of my post on covering basic concepts like static and dynamic binding in Javawhen to use Interface in Java and why use PreparedStaement in Java. If you are new here or haven’t read them already then you may find them useful.

10 Abstract Class and Interface Interview Questions Answers in Java

Abstract class and interface are very popular in any object-oriented programming language or Java interview, and there are always one or more questions from this. The interface is more common, because of its popularity among designers but questions from abstract class also pop up now and then. Interview questions from the abstract class are more common on junior level or you say under 2 years experience of  Java programmers while interface-related questions are mostly asked on senior-level Java interview e.g. 4 or 6 years of experience. They are mostly asked along with other Java design pattern questions, e.g. Decorator pattern or Factory pattern.

How to compare two XML files in Java - XMLUnit Example

The XMLUnit library can be used to compare two XML files in Java. Similar to JUnit, XMLUnit can also be used to test XML files for comparison by extending the XMLTestcase class. It is a rich library and provides a detailed comparison of XML files. Btw, comparing XML is completely different than comparing String in Java or comparing objects using equals(), as two XML which contains different comments and whitespace can be equals, which is not true for String or character comparison. Also while comparing XML files, it's very important to know exactly which content or part is different and XMLUnit not only shows the content which is different but also XPath of elements which is getting compared.

Top 10 Java Serialization Interview Questions and Answers

What is Serialization in Java
Java Serialization is one of important concept but it’s been rarely used as persistence solution and developer mostly overlooked Java serialization API. As per my experience Java Serialization is quite an important topic in any core Java interview, In almost all the interview I have faced there are one or two Java serialization questions and I have seen an interview where after few question on serialization candidate start feeling uncomfortable because of lack of experience in this area. They don’t know How to serialize an object in Java or they are not familiar with any Java Serialization example to explain, forget about questions like how Serialization works in Java,  Difference between transient and volatile variable, How many methods Serializable interface has? what is maker interface? what is the purpose of marker interface? What is the difference between Externalizable and Serializable in Java, or after the introduction of annotation, why not java replaced Serializable with @Serializable annotation or.

Saturday, April 15, 2017

Difference Between java.util.Date and java.sql.Date in Java - JDBC Interview Question

Difference between java.util.Date and java.sql.Date in Java or why does Java have java.sql.Date if there is already a Date class in java util package is a common java interview question. There is always confusion among many Java developers familiar with both java.util.Date and java.sql.Date. Though many of them already using java.sql.Date to interface with DATE type of any relational database like MySQL, Oracle, or any other database. In this Java tutorial, we will see some differences between java.sql.Date and java.util.Date will help to understand both of them better.

How to Convert JSON array to String array in Java - GSon example

JSON array is an ordered collection of values, which are enclosed within brackets e.g. [] and separated by a comma. In this Java tutorial, we will convert JSON Array to String array in Java and subsequently create JSON from Java String Array. This tutorial is similar to our last article in JSON about How to convert JSON object to Java object, instead of JSON object, here we will convert JSON array to String array or List in Java. As I said earlier, there are lot's of open source library out there which can help to parse JSON data format and we have already seen Jackson library in our last example. In this tutorial, we will use GSON to parse JSON data format and create Java String array or List from JSON array representation. Given the popularity of JSON as a lightweight alternative to XML to transfer data from Server to client in web applications, it's becoming imperative to know about JSON data format and parsing JSON string, much like parsing XML documents and knowing about different XML parsers e.g. DOM or SAX

UNIX Command Tutorial, Tips and Examples for Beginners.

UNIX and Linux command tutorials and tips for beginners.
Hi, this is a kind of revision post where I would like to share some of my earlier posted UNIX commands tutorial. The purpose of this post is to put together all UNIX commands tutorial in one place for easy access to anyone. These are a collection of my favorite UNIX commands which you guys may find interesting. I have been working in UNIX for almost 4 years and I have learned many UNIX commands during these years which has helped me a lot during my day 2 days working on Unix shell.

10 JDK 7 Features to Revisit, Before You Welcome Java 8

It's been almost a month since Java 8 is released and I am sure all of you are exploring new features of JDK 8. But, before you completely delve into Java 8, it’s time to revisit some of the cool features introduced on Java 7. If you remember, Java 6 was nothing on the feature, it was all about JVM changes and performance, but JDK 7 did introduce some cool features which improved the developer's day to day task. Why I am writing this post now? Why I am talking about Java 1. 7, when everybody is talking about Java 8? Well I think, not all Java developers are familiar with changes introduced in JDK 7, and what time can be better to revisit earlier version than before welcoming a new version.

Friday, April 14, 2017

How to Convert Local Time to GMT in Java - Example Tutorial

Converting local time into GMT or any other timezone in Java is easy as Java has support for time zones. JDK has a class called java.util.Timezone which represents timezone and Java also has classes like SimpleDateFormat which can use Time zone while parsing or formatting dates. By using java.uti.TimeZone and java.text.SimpleDateFormat we can write simple Java program to convert local time to GMT or any other time zone in Java. We have already seen example of How to get current date and time in GMT and this Java program is extension of that in order to convert time form one timezone to other timezone.

This article is in continuation of my previous basic Java tutorials like How to convert Double to String in Java , How to convert char to String in Java and how to write hashcode in Java. If you haven’t read them already you may find them useful.

10 Examples of CUT command in UNIX and Linux

The cut command in UNIX is a nice utility program that allows you to cut data from a text file. The Linux cut command allows you to cut data by character, by field, or by column. if used correctly along with sed, find, or grep in UNIX, the cut can do lots of reporting stuff. For example, you can extract columns from a comma-separated file or a pipe or colon-delimited file using cut command. For example, if you are only interested in the first two columns you can show them using this command.  In this Linux cut command tutorial we will see different options of cut command, different examples of Linux cut command, and some important points about cut in UNIX.

Thursday, April 13, 2017

Java Program to connect Oracle Database with Example - JDBC Tutorial Sample Code

How to connect to Oracle database from Java Program using JDBC API is common to need for many Java programmer, though there is a lot of framework available which has simplified JDBC development e.g Hibernate, Spring JdbcTempate and many more, creating Java program to connect to oracle database from plain old Java is still the easiest and quickest method for testing and debugging database connectivity. The database connection program is also a common Java programming exercise in many Java programming courses on school, colleges, and various training institutes.

Java PropertyUtils Example - getting and setting properties by name

PropertyUtils class of Apache commons beanutils library is very useful and provides you the ability to modify properties of Java object at runtime. PropertyUtils enables you to write highly configurable code where you can provide the name of bean properties and their values from configuration rather than coding in Java program and Apache PropertyUtils can set those properties on Java object at runtime. One popular example of how powerful PropertyUtils can be is display tag which provides a rich tabular display for JSP pages, it uses PropertyUtils class to get values of an object at runtime and then display it.

Java Program to find factorial of number in Java - Example Tutorial

How to find the factorial of a number in Java on both recursive and iterative way is a common Java interview question mostly asked at the fresher level. It’s not just popular on Java interview but also on other programming languages like C or C++. It's also famous  In our last article we have seen how to check if a number is prime or not and in this Java programming tutorial, we will see a simple Java program to find factorial of a number in Java by using recursion and iteration. The same program can also be used to print factorial of any number or print a range of factorial as well.

Java Program to Multiply Two Matrices - Matrix Multiplication Example

How to write a Java program to multiply two matrices in Java is a very good programming exercise to get familiar with the two-dimensional array in Java. this example teaches about how to multiply arrays, how to access elements from a multi-dimensional array, how to pass them to a function etc. Since the matrix is a natural representation of multi-dimensional array in Java, they are often used to illustrate real word matrix exercises e.g. the calculating sum of two matrices or calculating the difference of two matrices etc. By the way, before writing the program, let's recap how to multiply two matrices in mathematics first. If you remember, you can only multiply two matrices if, and only if, the number of columns in the first matrix equals the number of rows in the second matrix. That is known as matrix multiplication criterion.

Java Program to print Prime numbers in Java - Example Tutorial and Code

How to print Prime numbers in Java or how to check if a number is prime or not is classical Java programming questions, mostly taught in Java programming courses. A number is called a prime number if it's not divisible by any number other than 1 or itself and you can use this logic to check whether a number is prime or not. This program is slightly difficult than printing even or odd numbers which is relatively easier Java exercises. This Simple Java program print prime number starting from 1 to 100 or any specified number. It also has a method that checks if a number is prime or not.

Wednesday, April 12, 2017

How to fix org.hibernate.MappingException: Unknown entity Exception in Java

If you have used Hibernate with JPA and using annotation to declare your entity bean then you might have seen this confusing error called "org.hibernate.MappingException: Unknown entity". This error message is so misleading that you could easily lose anywhere between a few minutes to a few hours looking at the wrong places. I was using Spring 3 and Hibernate 3.6 when I got this error, which occurs when addEntity() method was executed. I checked everything, from Spring configuration file applicationContext.xml, Hibernate config file, my Entity class, and DAO class to see whether my Entity class is annotated or not, but I was still getting this error message.

How hostname to IP address Conversion or Name Resolution works in Linux?

One of my favorite Linux Interview questions is about how to convert hostname to IP address in Linux? These questions not just test the candidate's basic Linux command skills but also shows his understanding of how name resolution works in UNIX or Linux? Many developers, software engineers, and support professionals don't really know how Linux converts a hostname into IP address or what happens when they type http://www.amazon.com in their browser in UNIX? They are not really familiar with how the name amazon.com is resolved to an IP address.

Top 10 Puzzles, Riddles, Logical, and Lateral Thinking Questions Asked in Programming Job Interviews

Puzzles, riddles, logical questions, and lateral thinking questions are an integral part of any programming job interviews. I missed to include some puzzles when I shared my list of top 30 programming interview questions earlier, and a couple of my friends requested to share some puzzles as well. These puzzles and lateral thinking questions are mostly collected from various Java programming interviews on Investment banks, but they are equally useful for any programming job interviews. I have seen more puzzles and logical questions at the junior level i.e. 2 to 4 years.

Tuesday, April 11, 2017

How to Remove Given Character From String in Java - Recursion

Write a program to remove a given character from String in Java. Your program must remove all occurrences of a given character. For example, if given String is "aaaaa" and String to remove is "a" then the output should be an empty String. Similarly, if input String is "abc" and character to remove is "b" then your program must return "ac" as output. You are not allowed to use any JDK method or third party method which solves this method directly, but you can use basic String manipulation method like indexOf(), toChar() or substring() from java.lang.String class.

How to Check If Number is Even or Odd without using Modulus or Remainder Operator

Write a Java program to find if a number is odd or even is one of the basic programming exercises, and anyone will be happy to see this in actual Java Interviews, wouldn't you? By the way, did I said easy, well there is a little twist there, you need to check odd and even without using modulus (%) or remainder operator in Java. Since many programmers, especially freshers are familiar with % operators, this nice little trick does put them into thinking mode, which is what the interviewer wants. This question is on a similar level of checking if a number is a palindrome or not if you have practiced such questions, it would be easy to find a solution.

JAXB Date Format Example using Annotation | Java Date to XML DateTime String Conversion

One of the common problem while marshaling Java object to XML String using JAXB is the default format of date and time provided by JAXB. When JAXB converts any Date type object or XMLGregorianCalendar to XML String, precisely xsd:dateTime element, it by default prints unformatted date e.g. 2012-05-17T09:20:00-04:30. Since most of the real world, Java application has a requirement to print date in a particular format like dd-MM-yyyy or include date and time in format dd-MM-yyyy HH:mm:ss, it becomes a problem. Thankfully, JAXB is very extensible and provides hooks and adapters to customize marshaling and unmarshaling process. You can define an extension of XmlAdapter to control and customize marshaling and unmarshaling or any Java type depending upon yours need.

Monday, April 10, 2017

10 Examples of Optional in Java 8

Null is bad, it can crash your program. Even it's creator called it a billion-dollar mistake hence you should always try to avoid using nulls whenever you can. For example, you should not return a null String when you can return an empty String, similarly never return null collections when you can return an empty collection. I have shared many such tips in my earlier article, 10 tips to avoid NullPointerException and my reader liked that a lot. But, I wrote that article a couple of years ago when Java 8 was not around and there was no Optional, a new way to avoid NullPointerException in Java, but, things have changed now.

Difference between FileInputStream and FileReader in Java | InputStream vs Reader

Before going to explain specific difference between FileInputStream and FileReader in Java, I would like to state fundamental difference between an InputStream and a Reader in Java, and when to use InputStream and when to go for Reader. Actually, Both InputStream and Reader are abstractions to read data from source, which can be either file or socket, but main difference between them is, InputStream is used to read binary data, while Reader is used to read text data, precisely Unicode characters. So what is difference between binary and text data? well everything you read is essentially bytes, but to convert a byte to text, you need a character encoding scheme. Reader classes uses character encoding to decode bytes and return characters to caller.

Sunday, April 9, 2017

How to Compare Two Enum in Java - Equals vs == vs CompareTo

How do I compare two enum in Java? Should I use == operator or equals() method? What is difference between comparing enum with == and equals() method are some of the tricky Java questions. Until you have solid knowledge of Enum in Java, It can be difficult to answer these question with confidence. By the way unlike comparing String in Java, you can use both == and equals() method to compare Enum, they will produce same result because equals() method of Java.lang.Enum internally uses == to compare enum in Java. Since every Enum in Java implicitly extends java.lang.Enum ,and since equals() method is declared final, there is no chance of overriding equals method in user defined enum. If you are not just checking whether two enum are equal or not, and rather interested in order of different instance of Enum, than you can use compareTo() method of enum to compare two enums. Java.lang.Enum implements Comparable interface and implements compareTo() method. Natural order of enum is defined by the order they are declared in Java code and same order is returned by ordinal() method.

Does making all fields Final makes the class Immutable in Java?

One of the common misconceptions among many Java Programmer is that a class with all final fields automatically becomes Immutable. This is not correct, you can easily break immutability of certain class if the final field it contains is a mutable one, as we'll see in this article. One of the most common examples of this is a java.util.Date fields e.g. birthDay, expirtyDate, or joiningDate sort of fields. You have to be extra cautious to keep your class' immutability intact with mutable fields. The most common mistake in this regard happens when Java programmer return reference of the original object when a client ask e.g. getBirthDay() returns the date object pointed by birthDay field. When you return a reference to a mutable object, you are sharing ownership of that reference with whoever receives it. This can break invariant, such as immutability.

3 Ways to Solve jQuery - Uncaught ReferenceError: $ is not defined Error

If you are using jQuery, Angular JS, or plain old JavaScript and getting "Uncaught ReferenceError: $ is not defined" error which means $ is either a variable or a method which you are trying to use before declaring it using var keyword. In jQuery, it's a short name of jQuery() function and most commonly used in $(document).ready(function()). If you are doing some jQuery stuff when DOM is loaded and getting this error it means your browser has a problem loading jQuery library either from the internet or local file system.

Saturday, April 8, 2017

Enhance For Loop Example and Puzzle in Java

From Java 5 onwards, we have a for-each loop for iterating over collection and array in Java. For each loop allows you to traverse over collection without keeping track of index like traditional for loop, or calling hasNext() method in while loop using Iterator or ListIterator. For-each loop indeed simplified iteration over any Collection or array in Java, but not every Java programmer is aware of some useful details of for-each loop, which we will see in this tutorial. Unlike other popular items from Java 5 release alias Generics, Autoboxing and variable arguments, Java developers tend to use for-each loop more often than any other feature, but when asked about how does advanced foreach loop works or what is basic requirement of using a Collection in for-each loop, not everyone can answer. This small tutorial and example aims to bridge that gap by going through some interesting foreach loop puzzles. So, without any further delay let's see our first puzzle on Java 5 for-each loop.

Replaying messages in FIX protocol

Replaying messages in FIX protocol
In FIX Protocol, two FIX engines communicate with each other using FIX messages and every FIX messages is assign with unique sequence number denoted by tag 34. Apparently every FIX engine has two sequence numbers Incoming Sequence Number (which FIX engine is expecting from a counter party) and Outgoing Sequence Number (which FIX engine is sending to counterparty). This sequence numbers along with rules specified in FIX protocol technical specification ensures that no FIX engine should lose any FIX messages in the event of any disconnect.
In this FIX Protocol Tutorial, we will discuss some scenarios where the disconnect between two FIX Engine occurs and how they recover from that situation. Normally disconnect and reconnect can cause a replay of messages which would be required from either party e.g. either client or broker based upon who has a higher sequence number.


This FIX Protocol Tutorial is in continuation of my earlier tutorial FIX Protocol Session or Admin messages tutorial and Difference between FIX 4.2 vs FIX 4.4 in FIX connectivity.

3 Ways to Prevent Method Overriding in Java - Private, Static and Final

Every Java programmer knows that final modifier can be used to prevent method overriding in Java because there is no way someone can override final methods; but, apart from final modifier, is there any other way to prevent method overriding in Java? This was the exact question, asked to one of my friend in a recent Java interview at one of the leading Investment bank. I guess, he was lucky to get this question because he already knows those tricks and was able to answer it quickly. When he told me about his experience,  I didn't understand why someone ask this question? What is the purpose? What they were trying to find out? I can understand if they have asked what's the best way to prevent method overriding in Java, or what is the risk of overriding? Anyway, It gives me an opportunity to recap some of the other technique (syntactically) to prevent a method from being overridden and write this blog post to share some mystery tricks from Java world. Some of you might be aware of those non obvious way to prevent method overriding, but if you don't, here is your opportunity to learn.

How to get current stack trace in Java for a Thread - Debugging Tutorial

The stack trace is very useful while debugging or troubleshooting any issue in Java. Thankfully Java provides a couple of ways to get a current stack trace of a Thread in Java, which can be really handy in debugging. When I was new to Java programming, and didn’t know how to remote debug a Java application, I used to put debug code as patch release, which uses classpath to pick debug code for printing stack trace and shows how a particular method is get called and that sometimes provide vital clue on missing or incorrect argument. Now, When I have a couple of Java debugging tips at my sleeve, I still think knowledge of  how to get a current stack trace in Java for any Thread, or simply print the stack trace from any point in code worth knowing. For those who are not very familiar with stack trace and wondering what is the stack trace in Java, here is the quick revision. The thread executes code in Java, they call methods, and when they call, they keep them in there stack memory. 

How to Convert Map to JSON to HashMap in Java? Example Tutorial

In the last couple of years, JSON slowly took over XML as preferred format to transfer data from client to server and vice-versa. Because of increasing usage of JSON, Java developers are also getting a good exposure of JSON. If you are writing web services e.g. traditional GET based services, or modern RESTful web service, you also have to provide support for JSON format along with TEXT and XML. Though standard Java API doesn't support encoding and decoding of JSON from Java Object, there are a bunch of good open source JSON libraries available to Java developers. Jackson and GSON are two of the most popular such library to deal with JSON data in Java.   They not only allow you to parse JSON String to Java Object but also to create JSON formatted String from Java object. They also provide utilities to deal with formatting and other day-to-day features you need to deal with JSON formatted data.

Thursday, April 6, 2017

Error: Could not find or load main class in Java [Solved]

Error: Could not find or load main class HelloWorld comes when you are trying to run your Java program using java command with the main class as HelloWorld but Java is not able to find the class. In order to solve this error, you must know how Java find and loads the classes, that's a little bit complex topic for beginners, but we will touch the same base here. For the curious reader, I would suggest reading my post How Classpath works in Java, a must read for a beginner. For now, you just remember that there is an environment variable called CLASSPATH which includes directories where Java looks for all class files and if it doesn't find your main class there then it throws "Error: Could not find or load main class XXX", where XXX is the name of your main class.

Dealing with org.hibernate.LazyInitializationException: could not initialize proxy - no Session in Hibernate Java

If you are working in the Hibernate framework, then you know that one of the key features of Hibernate is "lazy initialization", which allows the framework to lazily initialize dependencies, relationships, or associations lazily from the database on need basis. For example, if you are dealing with a User object, which has a relationship with a Permission object like one user can have multiple permissions, then Hibernate may choose not to initialize the collection which holds all permissions at the time it initialized User object and instead returns a proxy object.

Wednesday, April 5, 2017

What is bounded and unbounded wildcards in Generics Java?

Bounded and unbounded wildcards in Generics are two types of wildcard available on Java. Any Type can be bounded either upper or lower of the class hierarchy in Generics by using bounded wildcards. In short <? extends T> and <? super T> represent bounded wildcards while <?> represent an unbounded wildcard in generics . In our last article How Generics works in Java , we have seen some basic details about bounded and unbounded wildcards in generics and In this Java tutorial, we will see bounded and unbounded generics wildcards in details. We will start from basics like what is bounded wildcard in generics and what is an unbounded wildcard  and then will some popular java interview questions on generics like Difference between ArrayList<? extends T>  and ArrayList<T super ?>.

What is interface in Java with Example - Tutorial

What is an interface in Java
Interface in java is a core part of Java programming language and one of the ways to achieve abstraction in Java along with the abstract class. Even though the interface is a fundamental object-oriented concept; Many Java programmers think Interface in Java as an advanced concept and refrain using the interface from early in a programming career. At a very basic level interface in java is a keyword but same time it is an object-oriented term to define contracts and abstraction, This contract is followed by any implementation of Interface in Java. Since multiple inheritances are not allowed in Java, the interface is the only way to implement multiple inheritances at the Type level.

Spring Framework Tutorial - How to call Stored Procedures from Java using IN and OUT parameter example

Spring Framework provides excellent support to call stored procedures from Java application. In fact, there are multiple ways to call stored procedures in Spring Framework, e.g. you can use one of the query() method from JdbcTemplate to call stored procedures, or you can extend abstract class StoredProcedure to call stored procedures from Java. In this Java Spring tutorial, we will see the second approach to call stored procedure. It's more object-oriented, but at the same time requires more coding. StoredProcedure class allows you to declare IN and OUT parameters and call stored procedure using it's various execute() method, which has protected access and can only be called from a subclass.

Tuesday, April 4, 2017

2 Free Oracle Certified Master Java Enterprise Architect (OCMJEA) 6 Mock Exams - 1Z0-807

The OCMJEA 6 or Oracle Certified Master Java Enterprise Architect Java EE 6 is one of the most respected Java certification. It is also the most toughest Java exam currently available. In order to get this certification, you need to pass not just one but a couple of exams, submit assignments and essays and also have to complete a mandatory training. The Java EE 6 Enterprise Architect Certified Master 1Z0-807 exam is the start of it. Once you pass this exam, you need to complete Java (EE) Enterprise Architect Certified Master Assignment (1Z0-865) and Java (EE) Enterprise Architect Certified Master Essay (1Z0-866) exams. After successfully completing these exams, you need to attend one mandatory training from the list of training programs, only then you will be awarded the Oracle Certified Master certification. Though, it's not necessary to take the training after completing exams, if you like, you can choose a relevant training which can help you to prepare well for OCMJEA 6 certification and take that first before appearing for any exam.

How to Replace Line Breaks , New Lines From String in Java.- Windows, Mac or Linux

We often need to replace line terminator characters, also known as line breaks e.g. new line \n and carriage return \r with different characters. One of the common case is to replace all line breaks with empty space in order to concatenate multiple lines into one long line of String. In order to replace line breaks, you must know line terminator or new line characters for that platform. For example, In Windows operating system e.g. Windows 7 and 8, lines are terminated by \n\r  also known as CR+LF, while in Unix environment e.g. Linux or Solaris line terminator is \n, known as line feed LF. You can also get line terminator pragmatically by using Java system property line.terminator.