Tuesday, April 30, 2013

How to Find Runtime of a Process in UNIX and Linux

So you checked your process is running in Linux operating system and it's running find, by using ps command. But now you want to know, from how long process is running, What is start date of that process etc. Unfortunately PS command in Linux or any UNIX based operating system doesn't provide that information. But as said, UNIX has commands for everything, there is a nice UNIX tip, which you can use to check from how long a process is running. It’s been a long time, I have posted any UNIX or Linux command tutorial, after sharing some UNIX productivity tips . So I thought to share this nice little tip about finding runtime of a process in UNIX based systems e.g. Linux and Solaris. In this UNIX command tutorial, we will see step by step guide to find, since when a particular process is running in a server.

Monday, April 29, 2013

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 26, 2013

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. 

Thursday, April 25, 2013

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.

Tuesday, April 23, 2013

10 Reasons to Learn Java Programming Language and Why Java is Best

Java is one of the best programming language created ever, and I am not saying this because I am a passionate Java developer, but Java has proved it in last 20 years. Two decades is a big time for any Programming language, and Java has gained strength every passing day. Though there are times, when Java development slows down, but Java has responded well. Earlier with groundbreaking changes in the form of Enum, Generics, and Autoboxing in Java 5, performance improvement with Java 6, and Google's choice of language for Android apps development, keeps Java as front line programming language.

Monday, April 22, 2013

What is String args[] 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 19, 2013

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 16, 2013

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.

Monday, April 15, 2013

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

Friday, April 12, 2013

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.

Thursday, April 11, 2013

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. 

Tuesday, April 9, 2013

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.

Monday, April 8, 2013

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. 

Friday, April 5, 2013

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 procedure 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 second approach to call stored procedure. It's more object oriented, but same time requires more coding. StoredProcedure class allows you to declare IN and OUT parameters and call stored procedure using its various execute() method, which has protected access and can only be called from sub class. I personally prefer to implement StoredProcedure class as Inner class, if its tied up with one of DAO Object, e.g. in this case it nicely fit inside EmployeeDAO. Then you can provide convenient method to wrap stored procedure calls. In order to demonstrate, how to call stored procedures from spring based application, we will first create a simple stored proc using MySQL database, as shown below.

Thursday, April 4, 2013

How to add, substract days in current date in Java | Increment, decrement date by days with example, tutorial

While working in Java projects, we often needs to increment or decrement date e.g. adding one days to current date to get tomorrow's date, subtracting one day to get yesterday's date etc. Since date in Java is maintained as long millisecond value, Sometime, programmer tend to add 24 hours as one day, which could be wrong if day falls on a day light saving time zone, where a day could be either 23 or 25 hour long. When you add or subtract days from date, other components' of date e.g. month and year must roll. In this Java date tutorial, we will see two ways to increment and decrement date in Java. One approach uses java.util.Calendar from JDK and other uses DateUtils class from Apache commons lang library. DateUtils class provides convenient addDays(Date, int days) method, which accept a date and number of days to add, you can subtract days by passing negative value. Similarly java.util.Calendar provides Calendar.add() method, which accept a calendar field, for adding days, you need to use Calendar.DAY_OF_MONTH. Similar to DateUtils, you can pass positive number to increment date, and negative integer to decrement date in Java.

Wednesday, April 3, 2013

Difference between trunk, tags and branches in SVN or Subversion source control system

SVN or Subversion is one of the popular source control system used in Java world for source code management. There are a lot of source control system available e.g. Git, Perforce, CVS, ClearCase, VSS, but SVN has its own place among Java developer and open source communities. Knowledge of source control system is a must for any professional programmer. New users of subversion often confused between three things trunk, tags, and branches. Questions like, what is the difference between a tag and a branch in subversion is frequently asked in various Java forums and chat rooms. In this article, we will see what is trunk, tags or branches in SVN and understand difference between trunk, tag, and branch. In short, when you first upload your project to SVN it creates a trunk, It's analogous to the trunk of a tree. this trunk forms the main development line. 

Tuesday, April 2, 2013

What is the maximum Heap Size of 32 bit or 64-bit JVM in Windows and Linux?

Maximum heap size  for 32 bit or 64 bit JVM looks easy to determine by looking at addressable memory space like 2^32 (4GB) for 32 bit JVM and 2^64 for 64 bit JVM. Confusion starts here because you can not really set 4GB as maximum heap size for 32 bit JVM using -Xmx JVM heap options. You will get could not create the Java virtual machine Invalid maximum heap size: -Xmx  error. There could be many different reason why maximum heap space for JVM is less than there theoretical limit and vary from one operating system to other e.g. different in Windows, Linux and Solaris. I have seen couple of comments on my post 10 points on Java Heap Space regarding what is maximum heap space for Java or 32 bit JVM or 64 bit JVM and why Windows allows only upto 1.6G memory as maximum heap space etc. In this Java article, I have collected some of the frequently asked questions around maximum heap space on both 32 and 64 bit JVM and tried to explain them.

Monday, April 1, 2013

JUnit 4 Tutorial - Test Exception thrown by Java Method with Example

One part of unit testing a Java method is checking exception thrown by that method. A Java unit test should verify correct exception thrown in exceptional case and no exception should be thrown in normal case. In JUnit 3.XX, there was no direct support to pass or fail a test based upon exception thrown by a Java method. JUnit4 address this issue and provides an easy, and readable way to test exception thrown by a Java method. There are many situations when you need to  test exception thrown by any method in Java. Classical example of this is testing API methods which should throw IllegalArgumentException if arguments passed to method are not matching to pre-conditions. In order to test exception thrown by any method in JUnit 4 you need to use @Test(expected=IllegalArgumentException.class) annotation. You can replace IllegalArgumentException.class with any other exception e.g. NullPointerException.class or ArithmeticException.class etc.