Pages

rt.jar stands for runtime JAR and contains the bootstrap classes, I mean all the classes from Core Java API. I have found that many Java programmer doesn't know what is rt.jar? and often confused with the role of rt.jar file or why we use of rt.jar file in Java? No surprise, the name is little bit cryptic. This file always reside inside lib directory of JRE, at least in Windows and Linux. In MacOSX it reside at different location and also has different name i.e. classes.jar, but that is only prior to JDK 1.7. From Java 7 release Apple has stopped distributing Java and if you separately install, it will have same name as rt.jar. Many developer thinks to include their classes inside rt.jar to solve classpath related problems, but that is a bad idea. You should never be messing with rt.jar, it contains class files which is trusted by JVM and loaded without stringent security check it does for other class files. In this article, we will learn some interesting things about this magical JAR from Java world. For those programmers, who are new to Java and not familiar with JAR file, it is a zip like file, precisely known as Java archive which stores Java class files and any resource needed by program. It can also contain mainfest file, which can include Main-Class entry to make it an executable JAR, which can be run by using java -jar command.

Problem : Write a Java program to convert a binary number into decimal format, without using any library method which can directly solve the problem. You are free to use basic Java functions though e.g. those defined in java.lang and all kinds of Java operator e.g. arithmetic and logical operator, bitwise and bitshift operator and relational operators.

Solution : Let's first revise some theory of number system, which is required to convert a number from binary to decimal format. There are four kind of number systems binary, octal, decimal and hexadecimal. Binary is base 2 and that's why any number is represented using only two digit, 0 and 1 also known as bits. Octal system is base 8 and you can use 8 digits to represent any number, from 0 to 7. Decimal system is what we human use, it uses 10 digits to represent any number from 0 to 9. Hexadecimal number is base 16 and uses 16 digit to represent a number. Binary is what computer and electronic devices use and Decimal is what we human use. If you remember the algorithm for converting a binary number to decimal in college, you would know that we multiply bits in respective position with 2 to the power of there position, which is zero based. We will use the same algorithm here to convert a binary number into decimal. Only difference is that now we will implement this algorithm in Java. One more thing to remember is that, in order to represent same number you would need more digits in lower base. For example, to represent 8 in binary you need three bits 111, while it only require one digit 8 to represent same number in decimal format. By the way this is the second part of binary to decimal conversion tutorial, in first part we have already seen how to convert a decimal number to binary, so if you have not read it already, check it out.

Future and FutureTask in Java allows you to write asynchronous code. Future is a general concurrency abstraction, also known as a promise, which promises to return a result in future. In asynchronous programming, main thread doesn't wait for any task to finished, rather it hand over the task to workers and move on. One way of asynchronous processing is using callback methods. Future is another way to write asynchronous code. By using Future and FutureTask, you can write a method which does long computation but returns immediately. Those methods, instead of returning a result, return a Future object. You can later get the result by calling Future.get() method, which will return an object of type T, where T is what Future object is holding.

In short, though Maven and ANT are build tool but main difference is that maven also provides dependency management, standard project layout and project management. On difference between Maven, ANT and Jenkins, later is a continuous integration tool which is much more than build tool. You can setup your CI environment using Jenkins or Hudson and automatically build, test and deploy your Java project. Now last, main difference between Jenkins and Hudson, both are originate from same source code but one is closed source while other is open source. You can read the details in this article. Now let's start long story, what is difference between Maven and ANT or difference between Maven and Jenkins, or Maven vs Hudson are some of the frequently discussed questions among Java when developers. Well all four e.g. ANT, Maven, Jenkins and Hudson are tools to help Java developers on build, unit testing, continues integration (CI) and project management. In this Java article we will explore each of Maven, ANT, Jenkins and Hudson to get basic idea of what they are, what benefit they offer and how they are used in Java JEE projects. Just to give you basic idea, ANT is a well known build tool, probably oldest among all. A build tool is used to create deliverable like JAR file or WAR file from Java source and resources for deployment.

Maven came after ANT and offers much more than a build tool. Main difference between ANT and Maven is that In ANT you need to define every thing i.e. source directory, build directory, target directory etc while Maven adopts principle of Convention over configuration. Which means Maven has predefined project structure i.e. standard directory for source files, test files and resources. On the other hand, Jenkins and Hudson are Continues Integration tool, which gives you power to automate your build and deployment process. By using Jenkins or Hudson you can trigger build whenever developer commit code, to see if project is compiling fine, to run unit tests, to create build or even deploy in QA or production environment. Similarly you can have daily build, nightly build or weekly build process established in Jenkins or Hudson. In next section we will understand Maven, ANT, Jenkins and Hudson in more detail and understand difference between them.

One of the problem with ps command, which is a popular tool to find any processes along with grep command in Solaris operating system is that it doesn't show full command line argument of process. This means if you are doing grep on any text which appear at tail end of long command line, you will likely not able to capture that process by using psand grep. This is dangerous because it may lead you to assume that certain process is not running and you may restart it again, despite its being running and only because you didn't find the process. This is quite common while running Java process in any UNIX operating system e.g. Solaris, Linux, IBM AIX etc because Java process usually has long list of arguments e.g. system properties, JVM options, and name of main class. I have faced this problem quite few time even after using ps -ef option. Until now I have not found any compelling solution for this problem which will work on all UNIX systems, except for Solaris, which I am going to share with you guys. So, my only advice is to put the keyword in head of long command line argument and try to keep Java command line as small as possible. Also prefer using ps -auxww over ps -ef, former better display long command line than later and you have higher chance of capturing the process by using grep with tail keywords.

Gathering the correct and complete requirement is one of the most important thing in software development. Incorrect and incomplete requirement are main reason of why project fails. If you are in software development, you may have come across terms like functional and non-functional requirement. If you are wondering why a prototype take a 2 weeks but actual application development requires around 3 to 4 months of development; think of non-functional requirement. When someone told you to build a software, what they tell you is what that software should do e.g. allow you to trade on certain market, but they don't tell you about security, performance, load and other stuff, this is what I called non functional requirement. Obvious difference between functional and non-functional requirement is, former is specified by its users, business analyst and its part of software's feature list, for example functional requirement of a trading application is to receive order, enrich, transform and send it to Stock Exchange, but non-functional requirement is not specified by user, its rather thought by Software architect, Subject Matter Experts, Technical lead and Support peoples. For example, for this same trading application non-functional requirement could be Failover and Recovery, logging, auditing, latency and other performance characteristic that, application should be able to run continuous, can process 5K orders per second etc. Support people can also ask functionality require to add user, give access, revoke access, monitoring etc. Every application in software development has one or other kind of non-functional requirements. In this article, we will learn more about difference between functional and non-functional requirements in software and product development.

This is the second part of Java tutorial on Cloning, In first part we have seen how clone method works in Java with a simple example of cloning object, with primitives and Immutable. In this tutorial, we will take one step further and override clone method for creating clone of object with mutable field. In our case mutable field is a Collection here, to be precise a List. Since default implementation of clone() method only does shallow copy of objects, it can create issue, if original object contains mutable object or Collection classes. In our example, we have a class called Programmer, with String name, int age and List of Certifications. When we override clone() method inside Programmer class, we need to explicitly take care of this List, otherwise, both original and cloned object will point to same Collection in Java heap, which means, any change e.g. adding a new Certification in original object will also reflect in cloned object or vice-versa. Since an object should be independent of it's clone, we need to fix this issue by applying deep cloning techniques. Along with this example of overriding clone in Java, In this Java clone tutorial part 2, we will also take a look at some Java best practices for implementing correct clone method, disadvantages and shortcomings of cloning in Java and in particular clone method and finally, when to use clone in Java.

Printing Fibonacci Series In Java or writing a program to generate Fibonacci number is one of the interesting coding problem, used to teach college kids recursion, an important concept where function calls itself. It is also used a lot as coding problems while interviewing graduate programmers, as it presents lots of interesting follow-up questions as well. In Fibonacci series, next number is equal to sum of previous two numbers. First two numbers of series are always 1 and 1, third number becomes 1 + 1 = 2, subsequently fourth number becomes 2 + 1 = 3. So a Fibonacci series looks like 1, 1, 2, 3, 5, 8, 11, 19 and so on, as shown in the image as well. This problem is quite easy to solve by using recursion and a greater example that how recursion can simply solution in some cases e.g. linked list and binary tree, where part behaves like whole. For example, when you remove a node from linked list, its another list, similarly if you take a part of tree, is another tree, which means same algorithm can be applied to them. Any way, If you get this question on interview, you are more likely to come up with recursive version first, as it's natural. Interviewer will now ask you to generate Fibonacci series without recursion. Which means you have to come up with Iterative solution using loops. You can also clarify whether additional data structure is allowed or not, as many recursive solution can be converted into iterative one by using Stack data structure. In this case, probably you don't need it.

In this article, we are going to see top 20 String based coding interview question and their solution to help programmers better prepare for interviews. The string is one of the most important data structure and available in almost every programming language e.g. Java, C, C++, Python, Perl, and Ruby. Though there implement differ but the essence remains same e.g. String is NULL terminated character array in C but String is an object in Java, again backed by character array. The string is also available on weekly typed language e.g. Python and Perl. This is why you will always find some String based coding question on programming interview. Even in your college days, you would have solved lots of coding problems based upon String like reversing String in place, checking if String is a palindrome, checking if two strings are an anagram of each other, calculating permutations of String etc.

Before Java 8, Anonymous class was the only way you can implement functional idiom in Java. Since prior to Java 8 you cannot pass function to another function, you would have to wrap it into object, as seen in Strategy Pattern. Those are also known as function objects in Java. Anonymous class was also handy to create a throw-away implementation of SAM (Single Abstract Methods) interfaces like Runnable, Callable, CommandListener or ActionListener. Despite all these goodies and flexibility Anonymous class adds too much boiler plate code, making it hard to read and understand. Now with Java 8, you have got the ability to pass function to another function in form of lambda expression, you an easily replace your Anonymous class with lambda expression in Java. Even if you don't want to do it for your older project, you shouldn't use Anonymous class anymore for the purpose described above, instead you should learn lambda expression and use it in place of Anonymous class. To get the ball rolling, I will show how you can use lambda expression instead of Anonymous class to implement ActionListener in Java Swing code. Since lambda expression is of SAM type in Java and ActionListener only contains one method actionPerformed(ActionEvent ae) you can use lambdas to implement ActionListener, result is a much cleaner and concise code. By the way, you cannot always use lambda expression in place of Anonymous class, because of it's limitation of being SAM type. If you are using anonymous class to implement an interface with two abstract methods then you cannot replace with lambda of Java 8.

One reason of Java's great success as a programming language is that it has dominated Enterprise space. Earlier J2EE used to be the popular platform, but now we have more modern and improved Java EE platform, with the latest release of Java EE 7. Java Platform, Enterprise Edition 7 provides new features that include enhanced HTML5 support, increases developer productivity, and further improves how enterprise demands can be met. One of the biggest advantages of Java EE 7 is a reduction of boilerplate code. Java EE 7 developers will write less boilerplate code, have better support for the latest Web applications and frameworks and gain access to enhanced scalability and richer, simpler functionality and enterprises will benefit from improved scalability and new features that enable portable batch processing. One of the biggest challenges of Java EE developer or any programmer is to keep himself updated with latest technological development in this area. Blogs are a good source to learn new technologies and keep yourself updated. With that view in mind, I am sharing some of the best blogs on Java EE space. I personally follow these blogs and they are written by authorities on Java EE. Personalities like Arun Gupta, Adam Bien doesn't need any introduction.

Couple of questions, which are often asked to me was why do we need to override equals() and hashcode() method, Why should I implement toString(), What will happen if I don't override them or in a different way, I have never overridden equals and hashcode and not faced any problem, why should I override them now. You guessed it correct, almost all of these questions comes from beginners, who have either taken some Java programming classes, or started learning Java by their own. Though concept of equality is something you cannot ignore, correct understanding of equals(), hashcode(), toString() and some other method from java.lang.Object class, often goes unnoticed, at least until they self-realize it or Interviewer force them to explore that part. I have already written couple of articles on equals and hashcode, e.g. equals vs ==, hashcode tips, equals and hashcode interview questions and one of my personal favorite, 5 tips to override equals in Java, which already touches this subject but I thought to explain it clearly here for once and all.

Java beginners often ask same type of questions, and of them is what is difference between & and && operator in Java or difference between | and || operators? Standard answer of this question is well, main difference between & and && is that former is a bitwise operator and && is a logical operator in Java. That's academic, until you clearly explains difference in working of & and && or | and ||. For absolute beginners, & is used to represent AND logic operation in Java and | is used to represent OR logic operation. If we use only one & or | then it's known as “bitwise AND” and bitwise OR operators and if we use double && or || then it's known as logical or short-circuit AND and OR operators. From name, you can guess bitwise operates at bit level and perform AND logical operation to each bit, while logical operators operate on boolean variables only. Main difference lies in there short circuit behavior, which means if there are two or more conditions, which are joined using && or || operator then not all conditions are tested as soon as you have enough data to determine result. For example in case of AND operation involving multiple condition, rest are not checked as soon as one of them becomes false, because result will always be false. Similarly in case of OR short circuit operator ||, remaining conditions are not executed if one of them is true, because as soon as one operand becomes true, result of operation will be true, regardless of result of remaining condition. This short circuit nature is another reason, why logical operators are also known as short-circuit operator. In order to solve programming problems e.g. how to count number of set bits or 1s on Integer, good understanding of bitwise operator is required.I think, we have enough theory, let's see some real examples.

When you face a Java problem where do you go? StackOverflow, Coderanch or Official Java forums? Yes there are lots of online resources to help a Java programmer when he stuck. Being one of the most popular programming language ever, Java has huge community. There are lots of blogs, websites and forums to help you on minute detail of Java programming. It doesn't matter if you are beginner facing problem or an expert looking for best possible way to do certain things in Java, forums always provide a good support. When I first started Java programming, there was no StackOverFlow but there was Javaranch forum, which is now known as Coderanch. That forum has lots of good people to help you, I have personally benefited a lot from that forum especially when I was preparing for SCJP. There Java beginners forum is also very useful for anyone who has just started with Java and don't have anyone to seek help. By communicating with forum members you will not only learn how to describe your problem but also learn lot of extra knowledge about subject which you have not expected. Since I love to find good resource, today I am going to share 5 most useful Java forums for any Java programmer. If you are in Java development for more than couple of months, I am sure you already know these places but for those who are looking to become Java developer, it pays off to know these Java forums in advance.

String concatenation is the process of joining two or more small String to create a big String. For example you can create full name by concatenating first and last name of a person. Java provides multiple ways to concatenate String, but the easiest of them is by using + operator. It is one of the magical operator in Java, though Java doesn't support operator overloading, it has made an exception in case of String and + operator. Plus operator is a binary operator and primarily used to add two numbers if both operands are integer but it can also used to concatenate String if either both or first operand is String. For example "Java" + "Programming" will produce "JavaProgramming". You can use this operator even to convert integer to String in Java by concatenating an empty String with an integer. For example "" + 123 will produce String "123". Other two ways to concatenate String in Java is by using StringBuffer and StringBuilder. Both these classes are mutable counterpart of String class and used to modify mutable String. Since String is Immutable in Java, any operation on String, including concatenation always produce a new String object. If you use Plus operator to concatenate String in a loop, you will end up with lots of small String object which can fill up your heap and can create lot of work for your garbage collector. To avoid such issues, Java designers have provided StringBuffer and StringBuilder, both of which can be used to create mutable String which will not produce a new String object if you do concatenation. There is one more method to concatenate String in Java is by using String.concat() function. You can use this one for String concatenation.

There is some striking similarity between Adapter, Decorator, Facade and Proxy design pattern, in the sense that they all use Composition and delegation to solve the problem. Adapter pattern wraps an interface, and delegates call to it. Decorator wraps an object and implement behaviour on top of that, Facade wraps one or more interface to provide a central interface, which is easy to use and Proxy Pattern also wraps Subject and delegates calls to it. Then questions comes, why they are different patterns? What is difference between Adapter, Decorator, Facade or Proxy pattern, if there structure is same. Answer is Intent. Yes, all of these Java design pattern has similar structure and class diagrams but there intents are totally different to each other. Main purpose of Adapter pattern is to convert interfaces. Adapter let's two components working together, which wouldn't be working because of incompatible interfaces. Decorator pattern, adds new functionalities at runtime. It allows you to enrich object, even after it's creation. Facade design pattern neither converts interfaces nor adds new functionality, instead it just provide simpler interfaces. So instead of client directly accessing individual components of a system, it uses facade. Facade design pattern allows client to interact with complex system with much simpler interface and less work. Facade will then call individual components. Proxy pattern is also quite similar to Adapter and Decorator, but it's purpose is to control access of object. Proxy prevents client's to directly accessing object, instead it act as real object and can provide alternate behavior or forward request to original object. Proxy is most versatile pattern of all these, and it can be used in different ways e.g. remote proxy for communicating with remote object, virtual proxy to control access of expensive object, protection proxy to provide access to object based on roles, Caching proxy, which can return cached object etc. In this Java design pattern article, we will try to examine some similarities and differences between Adapter vs Decorator vs Facade vs Proxy patterns in Java.