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. Another key difference between TreeSet and PriorityQueue is iteration order, though you can access elements from the head in a sorted order e.g. head always give you lowest or highest priority element depending upon your Comparable or Comparator implementation but iterator returned by PriorityQueue doesn't provide any ordering guarantee.

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 key point is, Eclipse itself need Java to launch and run. By default, Eclipse scans your PATH and look for any JRE if it founds suitable JRE then it runs otherwise it throws "A java Runtime Environment (JRE) or Java Development kit (JDK) must be available in order to run Eclipse. No Java virtual machine was found". Now, In order to install JRE, you can either download JDK or a JRE from Oracle's Java download site. 

Friday, April 28, 2017

Difference between Transient, Persistent, and Detached Objects in Hibernate

In Hibernate framework, an entity can be in three states, transient, persistent, and detached. When an object is in transient state, it is commonly refereed as transient object, similarly if it is in persistence and detached state, it is known as 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 transient object. At this stage, Hibernate doesn't know anything about this object and the object doesn't have any representation in database e.g. a corresponding row in the User table. Hibernate will not run any SQL query to reflect any changes on this object. You can move this object into persistent state by associating it with an hibernate session e.g. by calling save() or saveOrUpdate() method from an hibernate Session.

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 friend. 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 difference between java.exe and javaw.exe ? surprisingly not many java programmer know answer of this java interview question, may be because java developers has not paid enough attention to these commands. any way 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 e.g. 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 row or change in the entire RowSet. There are two types of RowSet available in JDBC 4.1 API, connected and disconnected.

Thursday, April 27, 2017

Top 5 FREE eBooks to Learn jQuery Online or download PDF

Everybody loves free resources, don't you? Well, I do and that's why I am always in search of good free resources e.g. eBooks and training courses. In the last article, I have shared some of the free JavaScript books and this time I am sharing a couple of good free eBooks to learn jQuery. The jQuery is one of the most important skills in today's internet world. It is the JavaScript library which has changed the face of websites, they are now more interactive and smooth than ever before. The Internet is also not short of free resources and when it comes to learning jQuery, you will find thousands of articles and tens of eBooks, but not all resources are good. Some of them are not up-to-date and many of them contain incorrect information, hence choosing the good resource is vital.

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 requested native library, then it throws java.lang.UnsatisfiedLinkError: no native library in java.library.path. Now someone may argue that, why does Java program should depend on a native library, doesn't this make a Java application platform dependent? Well, he would be right, but there are situations, where most of the code are already written in native languages, and you are just writing some Java code on top of that. In that scenario, instead of rewriting whole stuff, you tend to use native libraries. 

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. By using the PARSE function, you can also indicate the culture by using any culture supported by the Microsoft's  dot NET framework. For example, PARSE('7/8/2015' AS DATE USING 'en-US') parse the input literal as a DATE by using a United State English Culture, similar to 101 formatting style.

How to Convert Byte Array to InputStream and OutputStream in Java

Are you stuck with your coding because you have a byte array and next method in chain needs an InputStream? don't worry Java has solution for that, You can use ByteArrayInputStream to convert byte array to InputStream in Java. This class takes a byte array as source and since it's a sub-class of InputStream, you can easily pass this to any method, which accepts InputStream as 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 instruct LayoutManager to recalculate layout and often called once new components are added or removed from Container. The revalidate() can also trigger to call to the repaint() method to repaint components which 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 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 company and its dream for many software developers to work for google, but at 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 developer 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. We have searched a lot on the internet on google interview questions and answers for him and us and then make a note of some of the best questions for preparation. I am listing down some google interview questions from that list. 

OCAJP 1Z0-808 - Best Books and Mock Exams for Java 8 OCA Certification

From the last couple of months, I have been helping few developers to prepare for Java 8 associate certification with exam code 1Z0-808, also known as OCAJP 8. From my experience, both for preparing for Sun certification and helping other developers to get Java certified, I can say that two keys to be successful in Oracle Java certification are choosing a good study guide and buying one or two top quality mock exam simulators. When I say success, it doesn't just passing the exam but scoring above 90% because passing score 65% is not very difficult to achieve and anybody can pass OCAJP8 by just a couple of month of practice but to score 90% and above is not that easy, you need to prepare and prepare hard. Since just passing OCAJP8 will not make the desired impact, I always suggest my students aim for 100%, so the n worst case then can still score above 90%.

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 difference between them. Though both State and Strategy design patterns has 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. Strategy design pattern in Java is used to encapsulate related set of algorithms to provide runtime flexibility to client. Client can choose any algorithm at runtime, without changing Context class, which uses Strategy object. Some of the popular example 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 in 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 comparison required by the linear search algorithm. Only thing is that the list must be sorted before you can use 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 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 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 must for anyone working in 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. It gives you the flexibility of changing the symlink or soft link without making any change on your tried and tested scripts. I have worked on many different core Java projects which run on Linux and UNIX machine and make extensive use of UNIX symbolic links or symlinks. 

Top 10 Java books of last 5 Years For Experienced Programmers

If you think you have read all important books on Java and don't have anything new to read then hang on. Java is changing continuously, now Java 9 is on the way, but more importantly, it has already changed a lot in last 5 to 6 years with major releases like Java 8 and some useful features introduced in Java 7. Not only, the language is changing but also the Java virtual machine, Garbage collector, and other tools involved in Java development is changing, hence, it is now a right time to look at some of the newer Java books which are released in last 5 years to learn new features and tools of Java. Since I often receive emails and Facebook messages about some good books to read on Java, I thought to jot down books I have read in last a couple of years.

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 which is not inside another class. It may or may not be public i.e. you can have more than one class in a Java source file and only needs to be public, whose name must be 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 school, 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. In last couple of Java programming tutorial we have seen some basic programming exercises like how to reverse string in Java using recursion and how to check if a number is prime or not, while in this Java tutorial we will see a simple example of Java program to reverse number by just using basic Java operators like division operator(/) and remainder operator(%). division operator returns quotient while modules or remainder operator % returns the remainder.

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 which 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 do 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 . Earlier we have seen 5 ways to convert InputStream to String in Java , we can use some of the techniques from there while getting the yte array from InputStream in Java. If you like to use Apache commons library, which I think you should, there is a utility class called IOUtils, which can be used to easily convert InputStream to byte array in Java

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 event in Java. Calculating elapsed time is one of the first thing 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 of Java programmer are familiar with System.currentTimeInMillis()which is there from 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 language like Generics, Enum types, auto boxing and variable arguments or varargs. You can use any of them to measure execution time of method in Java. Though its better to use System.nanoTime() for more precise measurement of time intervals.

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 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 an interface is more common, because of its popularity among designers but questions from abstract class also pops up now and then. Interview questions from 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 object using equals(), as two XML which contains different comment 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 has 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 developer 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 which will help to understand both of them better.

This Java tutorial is in continuation of our earlier post on java.util.Date like How to convert String to Date in Java and how to get current Date and Time value in GMT timezone.  if you haven't read them already you may find them interesting and useful. If you like JDBC articles then checkout some JDBC Performance tips and  Benefits of PreparedStatement in Java.

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 commands tutorial and tips for beginners.
Hi, this is a kind of revision post where I would like share some of my earlier posted UNIX commands tutorial. Purpose of this post is to put together all UNIX commands tutorial in one place for easy access to anyone. These are collection of my favorite UNIX commands which you guys may find it interesting. I have been working in UNIX from almost 4 years and I have learned many UNIX commands during these year which has helped me a lot during by day 2 day working on Unix shell. These UNIX command s tutorials are based on my experience; I have shared UNIX command which I used so these are quite practical tips and tricks. It may not be in proper tutorial format like any other UNIX commands tutorial but I am sure this will be useful. This list is by no means complete so please share your UNIX commands experience so that we both can benefit from each others experience.

Top 5 books to Learn Object Oriented Programming - Must Read, Best of Lot

The OOP or Object Oriented Programming is one of the most popular  programming paradigms which helps you to organize code in re the l world system. It's a tool which helps you to write complex software by thinking in terms of objects. Unlike its predecessor procedural programming paradigm which is implemented most notably by C, which solves the problem and complete task by writing code for computers, OOP style of programming allows you to think in terms of real world objects which has both state and behavior. You can view anything as objects and then find their state and behaviors, this will help you to simulate that object in code.

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

It's been almost a month 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 feature, it was all about JVM changes and performance, but JDK 7 did introduced some cool features which improved 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 which 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 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 need for many Java programmer, though there are lot of framework available which has simplified JDBC development e.g hibernate, Spring JdbcTempate and many more, but creating Java program to connect to oracle database from plain old Java is still most easy and quickest method for testing and debugging database connectivity. Database connection program is also a common Java programming exercise in many Java programming courses on school, colleges and various training institutes. We have been exploring  some advanced concepts and best practices on JDBC in my previous articles like  Why should you use PreparedStatement in Java and 4 JDBC performance tips for Java application , which you may like if you are on more advanced level. This simple java program is intended for beginners in Java which have just started learning JDBC API.

If you like to read tutorials on database then you may find difference between truncate and delete10 example of SQL SELECT queries and how to manage database transaction useful and interesting.

Java PropertyUtils Example - getting and setting properties by name

PropertyUtils class of Apache commons beanutils library is very useful and provides you ability to modify properties of Java object at runtime. PropertyUtils enables you to write highly configurable code where you can provide name of bean properties and there values from configuration rather than coded 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 rich tabular display for JSP pages, it uses PropertyUtils class to get values of object at runtime and than display it. You can setup properties as column and only selected columns will be displayed. Even larger web framework like Struts and Spring also uses Apache commons beanutils library for getting and setting java properties by name.

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 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 printing a range of factorial as well. Let’s talk about logic, the factorial of a number is calculated by formula number*(number -1) till zero and since the value of factorial zero is 1, it acts as a base case in the recursive version of the factorial method. the logic to find the factorial of a number is encapsulated inside factorial(int number) and fact(int number) method.

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 prime number if its 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 number which are 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 which checks if a number is prime or not.

This Java tutorial is in conjunction with my earlier tutorial for beginners like How to set Path in Java on windows and Unix , Java Program to reverse String in Java with recursion and recently  how to read file in Java etc, if you haven’t read them you may find them useful.

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 few minutes to few hours looking at 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. After some goggling I eventually find that, it was an incorrect import which was causing this error.

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? This questions not just test 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 professional don't really know how Linux converts an 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. Since network application only works with IP address and names are for us humans, who find it easier to remember a name than IP address, it makes sense to understand how this name resolution happens. Sometimes, this question also asks as for how nslookup or host command works, which are two of the popular command to convert hostname to 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 junior level i.e. 2 to 4 years. These kinds of puzzles, if asked at the beginning of the interview, can make or break the interview. It’s not easy to solve them, especially when you see them the first time, but what is surely not to do is give up without a try, even if you can't think of an answer, try to show rational approach. Remember it's OK if you don't answer any puzzle question, but your approach towards unknown problem get noticed.

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 given character. For example, if given String is "aaaaa" and String to remove is "a" then 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. Most important thing is, you must code the logic to solve the problem by yourself. You should also write the solution using both Iterative and Recursive algorithms. An Iterative algorithm is the one which make use of loops e.g. for loop, while loop or do while loop, which recursive solution should not use any loop. Now let's think how can we solve this problem? Most simple solution which comes in my mind is to iterate over String by converting into character array and check if current character is same as given character to remove or not, if it is then ignore it otherwise add character into StringBuilder. At the end of iteration you will have a StringBuilder with all character except the one which is asked to remove, just convert this StringBuilder to String and your solution is ready. This solution should have space complexity of O(n) because you need an extra buffer of same size as original String and time complexity will also be O(n) because you need to loop over all elements of String. Can you make it better? because this solution will not work for large String, especially if you have memory constraint. Now, let's see how to remove character from String recursively?BTW, this is one of the good coding question and has been asked in companies like Goldman Sachs, Amazon and Microsoft. So if you are preparing for programming job interviews, make sure you include this question in your list as well.

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 % operator, this nice little trick does put them into thinking mode, which is what 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. Anyway, now, it's your turn to show off how good are you with different operators in Java and how quickly you can think of alternative solutions. Well, there are a couple of ways to check if a number is even or odd without using modulus operator. 

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 has changed now. Java SE 8 style of coding is rapidly becoming the de-facto coding style in many companies and as a Java developer you should also learn and embrace the good things of Java 8 e.g. lambda expression, streams and of course the Optional.

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, Angualr 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. In this article, you will see some of the most common reasons of "Uncaught ReferenceError: $ is not defined" error and how to solve them, but before that let's learn some basic about the dreaded Uncaught ReferenceError: $ is not defined error.

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.