Tuesday, January 31, 2017

Where and How to download Spring Framework JAR file (Spring 4.0 or Spring 3.2) without Maven, Gradle

One of the easiest and oldest ways to run a Java program which depends on an external library or framework is to download dependency JAR files, put it on the classpath and then run the program by creating a Main class with the main() method. This is simple but not as easy as you think, there are many challenges down the road e.g. you need to find the right version of JAR files and their dependencies e.g. Spring might have a dependency on other third party libraries like Log4j. So, when the build tool like Maven and Gradle comes, everybody stopped downloading the JAR file manually. All they do is specify the Maven dependency and Maven will download the JAR file of specified version along with their dependencies. This greatly simplified the development and testing of Java application which uses a framework like Spring and Hibernate.

Monday, January 30, 2017

What is rt.jar in Java/JDK/JRE? Why it’s Important?

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.

How to Reverse String in Java Using Iteration and Recursion - Example

How to reverse string in java is popular core java interview question and asked on all levels from junior to senior java programming job. since Java has rich API most java programmer answer this question by using StringBuffer reverse() method which easily reverses an String in Java and its right way if you are programming in Java but most interview doesn't stop there and they ask interviewee to reverse String in Java without using StringBuffer or they will ask you to write an iterative reverse function which reverses string in Java. In this tutorial we will see how to reverse string in both iterative and recursive fashion. This example will help you to prepare better for using recursion in java which is often a weak area of Java programmer and exposed during a programming interview.

Sunday, January 29, 2017

Top 3 Servlet and JSP Books for Java Developers - Best of Lot

Unfortunately, there are not many good books to learn Servlet and JSP for Java web developers. Despite being the most popular Java Web technology, there are very few good books to learn Servlet and JSP. The one book, which everybody will suggest you is the Head First Servlet and JSP, which is indeed one of the best books but it's outdated now. It doesn't cover the latest development in Servlet API, particularly Servlet 3.0 and also not been updated for last 7 to 8 years, but considering others, it is still a good book to learn Servlet and JSP. The main advantage of this book is Head first style which is great for beginners. With lots of repetition, bullet points, fireside chats, Head First book make sure you understand things and not just read them. Since many readers ask me to suggest good books learn Servlet and JSP, I'll share a couple of title in this book, which I think is relevant and help you to learn Servlet and JSP better.

Saturday, January 28, 2017

Difference between for loop and Enhanced for loop in Java

Though you can use both for loop and enhanced for loop to iterate over arrays and collections like a list, set, or map. There are some key differences between them. In general, enhanced for loop is much more easy to use and less error prone than for loop, where you need to manage the steps manually. At the same time, for loop is much more powerful because you get the opportunity to control over looping process. All the difference, you will learn in this article, stems from this very fact that traditional for loop gives more control that enhanced for loop but on the other hand enhanced or advanced for loop gives more convenience.

How to Set Classpath for Java on Windows and Linux

What is CLASSPATH in Java 
Classpath in Java is the path to directory or list of the directory which is used by ClassLoaders to find and load class in Java program. Classpath can be specified using CLASSPATH environment variable which is case insensitive, -cp or -classpath command line option or Class-Path attribute in manifest.mf file inside JAR file in Java.  In this Java tutorial, we will learn What is Classpath in Java, how Java resolve classpath and how Classpath works in Java alongside How to set the classpath for Java in windows and UNIX environment.  I have experience in finance and insurance domain and Java is heavily used in this domain for writing sophisticated Equity, Fixed income trading applications. Most of these investment banks have written test as part of their core Java interview questions and I always find at least one question related to CLASSPATH in Java on those interviews.

How to Convert Binary Number to Decimal in Java - Algorithm

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.

Difference between IdentityHashMap and HashMap in Java

IdentityHashMap in Java was added in Java 1.4 but still it's one of those lesser known class in Java. The main difference between IdentityHashMap and HashMap in Java is that IdentityHashMap is a special implementation of Map interface which doesn't use equals() and hashCode() method for comparing object unlike other implementation of Map e.g. HashMap. Instead, IdentityHashMap uses equality operator "=="  to compare keys and values in Java which makes it faster compare to HashMap and suitable where you need reference equality check and instead of logical equality. By the way, IdentityHashMap is a special implementation of Map interface much like EnumMap but it also violates general contract of Map interface which mandates using equals method for comparing Object. Also, IdentityHashMap vs HashMap is a good Java question and have been asked a couple of times.  

Friday, January 27, 2017

How to use Future and FutureTask in Java Concurrency with Example

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.

Thursday, January 26, 2017

Spring - java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener Quick Solution

If you have worked in Spring MVC than you may be familiar with  
java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
which is common problem during deployment. Spring MVC throws  java.lang.ClassNotFoundException:                           org.springframework.web.context.ContextLoaderListener ,
when its not able to find org.springframework.web.context.ContextLoaderListener class which is used to load spring MVC configuration files like application-context.xml and other Spring Framework configuration files defined in context-param element of web.xml in an Spring MVC web application as:

What is difference between Maven, ANT, Jenkins and Hudson?

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.

How to get and set default Character encoding or Charset in Java

Default Character encoding in Java or charset is the character encoding used by JVM to convert bytes into Strings or characters when you don't define java system property "file.encoding". Java gets character encoding by calling System.getProperty("file.encoding","UTF-8") at the time of JVM start-up. So if Java doesn't get any file.encoding attribute it uses "UTF-8" character encoding for all practical purpose e.g. on String.getBytes() or Charset.defaultCharSet()Most important point to remember is that Java caches character encoding or value of system property "file.encoding" in most of its core classes like InputStreamReader which needs character encoding after JVM started. so if you change system property "file.encoding" programmatically you don't see desired effect and that's why you should always work with your own character encoding provided to your application and if its need to be set than set character encoding or charset while you start JVM. In this Java tutorial, we will see couple of different way by which we can set default character encoding or charset of Java and how to retrieve value of charset inside java program.

Wednesday, January 25, 2017

How to define Error page in Java Web Application - Servlet JSP

There are two ways to define Error page in Java web application written using Servlet and JSP. First way is page wise error page which is defined on each jsp page and if there is any unhanded exception thrown from that page, corresponding error page will be displayed. Second approach is an application wide general or default error page which is shown if any Exception is thrown from any Servlet or JSP and there is no page specific error page defined.

how do make error page in servlet jsp web application javaIn this java tutorial we will see both approach to declare error page in JSP and when should we use page specific error page and when should we choose generate default application wide error page in Java web application. This is in continuation of my earlier post on Servlet and JSP like top 10 Servlet interview questions and top 10 JSP interview questions.

How to fix java.sql.SQLException: Invalid column index

"java.sql.SQLException: Invalid column index" is a frequent error while working in Java Database Connectivity (JDBC). As the name suggests "Invalid column index" its related to accessing or setting column in your SQL Query using prepared statement in Java. I have seen "java.sql.SQLException: Invalid column index" coming mostly due to two reason:

1) Setting column data using setXXXX(int coloumIndex) e.g. setInt(0) setString(0)
2) Getting column data using getXXX(int columnIndex) e.g. getInt(0) getString(0)

Most common cause of "java.sql.SQLException: Invalid column index" is a misconception that column index started with "0" like array or String index but that's not true instead column index starts with "1" so whenever you try to get or Set column data with column index "0" you will get "java.sql.SQLException: Invalid column index".

How to create LocalDateTime in Java 8 - Example

The LocalDateTime is a new class introduced in Java 8 new Date and Time API. This class is in java.time package and it represents both date and time information without timezone. In this example, you will learn different ways to create an instance of LocalDateTime class in Java 8 e.g. by using the static factory method, or by combining LocalDate and LocalTime instances together, which are subsequently used to denote date without time and time without the date in Java 8. As their name suggests they are local, so they don't contain timezone information.  They are always bound to local timezone i.e. the timezone of the machine on which your Java program is running. The class which contains the date, time and timezone information is known as ZonedDateTime in Java 8.

Difference between Thread vs Runnable interface in Java

Thread vs Runnable in Java is always been a confusing decision for beginners  in java. Thread in Java seems easy in comparison of Runnable because you just deal with one class java.lang.Thread while in case of using Runnable to implement Thread you need to deal with both Thread and Runnable two classes. though decision of using Runnable or Thread should be taken considering differences between Runnable and Thread and pros and cons of both approaches. This is also a very popular thread interview questions and most of interviewer are really interested to know what is your point of view while choosing Thread vs Runnable or opposite. In this java article we will try to point out some differences between Thread and Runnable in Java which will help you to take an informed decision.

Difference between FIX 4.2 vs FIX 4.4 in FIX connectivity

FIX 4.2 vs FIX 4.4
FIX protocol has evolved over time; it’s now more than a decade it’s started by Fidelity and Solomon Brothers. FIX connectivity is the most popular connectivity solution exists for trading whether its equities, futures, options or fixed income or even foreign exchange (FX). FIX protocol has dominated the market and become as standard solution for any market or broker which is trying to develop connectivity with market within a short period of time because of complexity of native exchange api and lack of support FIX protocol come as handy.

Tuesday, January 24, 2017

Java Comparator Example for Custom Sorting Employee by Name, Age and Salary

In this tutorial, we will see Java Comparator example to sort an Employee object by name, age and salary. In order to sort Employee object on different criterion, we need to create multiple comparators e.g. NameComparator, AgeComparator and SalaryComparator, this is known as custom sorting in Java. This is different then natural ordering of object, provided by compareTo() method of java.lang.Comparable interface. Though both compare() and compareTo() method looks similar they are different in a sense that, former accept one parameter, while later accept two parameter. Former compare passed object to current object, on the other hand compare() method compares two different object passed to it.

JAXB XML Binding tutorial - Marshalling UnMarshalling Java Object to XML

XML binding is a concept of generating Java objects from XML and opposite  i.e. XML documents from Java object. Along with parsing XML documents using DOM and SAX parser, XML binding is a key concept to learn if you are working in a Java application which uses XML in any way e.g. for storing persistence data like user preferences or for transmitting messages between two systems etc. XML binding is also a popular XML Interview question in Java. JAXB and XMLBeans are two common ways to achieve XML binding in Java.  XML binding, also known as XML marshaling and marshaling has two sides, first converting XML document to Java object, modify Java object and then converting back to an XML file. Once you have XML document as Java object, You can use the power of Java programming language to process and manipulate the XML elements, attributes etc. In last couple of Java XML tutorials, we have seen How to parse XML using DOM parser and How to evaluate XPATH expression in Java

Monday, January 23, 2017

How to Split String based on delimiter in Java? Example Tutorial

You can use the split() method of String class from JDK to split a String based on a delimiter e.g. splitting a comma separated String on a comma, breaking a pipe delimited String on a pipe or splitting a pipe delimited String on a pipe. It's very similar to earlier examples where you have learned how to split String in Java. The only point which is important to remember is little bit knowledge of regular expression, especially when the delimiter is also a special character in regular expression e.g. pipe (|) or dot (.), as seen in how to split String by dot in Java. In those cases, you need to escape these characters e.g. instead of |, you need to pass \\| to the split method.

Solaris Command to Show Long argument list of a Running Process

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 ps and 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.

Sunday, January 22, 2017

How to find if JVM is 32 or 64 bit from Java program.

You can find JVM bit size e.g. 32 bit or 64 bit by using either running java command from the command prompt or by using System.getProperty() from Java program. The question is why do you want to know hardware or platform configuration while writing Java code which is supposed to write once and read anywhere(32 bit, 64 bit etc)? Yes we don't really need to know whether JVM is 32 bit or 64 bit more often but there are many situations when this matters

Top 10 Excuses Programmers Gives to Avoid Unit Testing

Though everyone loves unit tests and everyone agree with benefits they bring in, when the time comes to write them, you will see a lot of excuses, even from some of the more experienced and senior developers. At the heart of the problem of not writing unit tests or enough unit tests they are two things, first is time pressure i.e. you don't have enough time to complete coding forget about writing unit tests. This problem comes due to erroneous estimation i.e. only estimating time for coding and not including unit testing as part of development. This is also our first excuse, so we'll see it in a short while. The second reason is laziness and ignorance i.e. you don't know to write unit tests but don't put enough effort to learn the tips and tricks.  In this article, I have shared some of the most common excuses given by programmers for not writing unit tests.

Saturday, January 21, 2017

How many characters is allowed on VARCHAR(n) columns in SQL Server? How much memory VARCHAR variable takes in disk?

One of the frequently ask SQL questions in any programming interviews is what is the difference between VARCHAR and CHAR data type in SQL? particularly when your project is using Microsoft SQL Server. You might have seen this couple of times, but given its popularity, nowadays people are asking this question differently e.g. they will ask you how much space a column of VARCHAR(2) data type will take? How many characters can it take? How do you minimize the space? Is it better to use a CHAR variable instead of VARCHAR(2) and why? These are some of the really interesting question and more meaningful than classical SQL questions like the difference between char vs varchar data type question.

10 Tips to Improve Programming Skill and become better Programmer, Developer

Many Java developers ask me How to become a better programmer, how do I improve my programming skills, or I am good at Java but not so good on problem-solving skill etc. This is a reality, today's era is full of language expert than real programmers. It's easy to understand keywords, methods, and API of Java programming language, but same time it's difficult to solve real problems, design reusable and robust software and get the maximum of data structure and algorithm. I have often seen Java programmers are not doing so well when asked to design and code a solution in limited time, but same time they are really good with Java concepts and all theory. Even senior programmers of 4 to 6 years experience in Java programming, sometimes fail to solve questions like designing

Difference between Functional and Non-Functional Requirements in Software development

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.

Top 20 Tibco Rendezvous and EMS Interview questions and answers

Hi Guys, in this part of my Tibco Rendezvous tutorial series I am sharing some Tibco RV interview questions and answers most often asked in any TIBCO messaging interviews. These are based on fundamental TIBCO concepts and also offer some new way of learning TIBCO RV or TIBCO Rendezvous technology. Some of the TIBCO Interview questions I have already discussed in my TIBCO command series.

TIBCO Rendezvous Interview Questions

Here is the list of TIBCO interview question, I am not putting answer for these interview questions right now but will put together in some other post but these questions are really great in terms of any Tibco messaging interview. For better organization and quick access I will divide TIBCO Interview questions on various category e.g. TIBCO Rendezvous Interview questions, TIBCO EMS Interview questions, TIBCO Certified Messaging questions, TIBCO Hawk Interview questions and Miscellaneous TIBCO Interview questions. Please let me know if you want some more categories. Answers of these Tibco Interview questions can be found in different tutorials available in my blog; I will also try to post relevant links here.

This article is in continuation of my interview articles 10 Interview questions on Singleton Pattern in Java , Top 20 FIX Protocol Interview questions and Top 20 Core Java interview questions asked in Investment banks and Top 10 Java Serialization Interview questions

Display Tag Export Example in JSP – Issue Fix Java Tutorial

Display tag provides export options to export page into PDF, CSV, Excel and XML in Java web application written using JSP, Servlet, Struts or Spring MVC framework. Display tag is a tag library and you just need to use it in your JSP page to display tabular data or generate HTML tables dynamically. Earlier we have seen 10 display tag tips for getting most out of display tag and in this JSP Servlet tutorial we will see one display tag export issue, which prevent display tag export functionality to work properly. Display tag experience is considered good in various JSP Interview and some questions related to sorting, paging, both internal paging and external paging and exporting on display tag also appear as various J2EE and Servlet Interview questions. In my opinion, after JSTL core tag library, display tag is most popular tag library and every Servlet and JSP developer should familiar with display tag.

What is Constructor Overloading in Java? - Interview Question

Constructor overloading in java allows having more than one constructor inside one Class. in the last article we have discussed method overloading and overriding and constructor, overloading is not much different than method overloading. Just like in the case of method overloading you have multiple methods with the same name but different signature, in Constructor overloading you have multiple constructors with a different signature with the only difference that Constructor doesn't have a return type in Java. That constructor will be called as an overloaded constructor . Overloading is also another form of polymorphism in Java which allows having multiple constructors with a different name in one Class in java.

Friday, January 20, 2017

Java Clone Tutorial Part 2 - Example to Override with Mutable field

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.

Difference between Serializable and Externalizable in Java Serialization

Difference between serializable and externalizable is popular java interview question which we have touched on my earlier post on Serialization: Top 10 java serialization interview questions. knowing differences between externalizable and serializable is not just important from interview point of view but also getting control of serialization process and optimizing performance of serialization. both serializable and extenalizable used to serialize or persist java objects but the way they do is little different. In case of Serializable Java Virtual machine has full control for serializing object while in case of Externalizable, application gets control for persisting objects. writeExternal() and readExternal() method provides complete control on format and content of Serialization process to application which can be leverage to increase performance and speed of serialization process.

Thursday, January 19, 2017

Can You Make an Array or ArrayList Volatile in Java?

This is one of the many interesting multi-threading questions I have shared in my post 50 multi-threading interview questions. Yes, you can make an array volatile in Java, there is no problem with that, neither compiler will flag any error not JVM will throw any exception but the tricky part is why you want to make an array volatile and what is the effect of making an array volatile in Java? In order to answer this question you must be familiar with both volatile modifier and Java memory model, otherwise, it would be difficult to answer, and that's why it's also one of the trick questions from Java interviews. Before answering this question in detail, let's first revise what is a volatile keyword in Java and what kind of guarantee it provides in the context of multithreading and concurrency.

Difference between URL-rewriting URL-encoding in Servlet JSP

URL-rewriting vs URL-encoding in Servlet JSP

Main difference between URL-rewriting and URL-encoding is that URL-rewriting is a technique to maintain user session if cookies are not enabled on client browser or browser doesn't support cookie while URL-encoding is a way to pass string to server containing special characters  by converting special characters like space into some other characters like + . people often confuse between URL encoding and URL rewriting because of there names which sounds quite similar for new guys but functionality wise they are totally different to each other, Also servlet encodeURL() method adds more confusion because its sounds like its used for URL Encoding but indeed used for URL Rewriting. This is also a very popular servlet and JSP interview questions , I have also shared some more questions on my posts 10 Servlet Interview questions answers and 10 JSP interview questions and answers for Java programmer.

3 ways to loop over Set or HashSet in Java? Examples

Since Set interface or HashSet class doesn't provide a get() method to retrieve elements, the only way to take out elements from a Set is to iterate over it by using Iterator, or loop over Set using advanced for loop of Java 5. You can get the iterator by calling the iterator() method of Set interface. This method returns an iterator over the elements in the sets but they are returned in no particular order, as Set doesn't guarantee any order. Though individual Set implementations e.g. LinkedHashSet or TreeSet can impose ordering and in such iterator will return elements on that order. You can only traverse in one direction using iterator i.e. from first to last elements, there is no backward traversing allowed as was the case with List interface and ListIterator. Similarly, if you use advanced for loop, then also you can traverse in only one direction.

Print Fibonacci Series in Java Using Recursion and For Loop

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.

How to fix Failed to load Main-Class manifest attribute from jar - Java Eclipse Netbeans Tutorial

If you have tried creating JAR file and running Java program form command line you may have encountered "Failed to load Main-Class manifest attribute from jar" , This error which haunts many Java programmer when they enter into command line arena and tries to create JAR file in command line or IDE like Netbeans and Eclipse. Major problem with "Failed to load Main-Class manifest attribute from jar" error is that, it’s unnecessary creates panic which it doesn't deserve, may be because process involves of creating and running JAR is not that common like running Java program using "java" command. Anyway in this Java tutorial we will see Why  "Failed to load Main-Class manifest attribute from jar" comes and How to fix  Failed to load Main-Class manifest attribute from jar error.

Wednesday, January 18, 2017

String replaceAll() example - How to replace all characters and substring from String

You can replace all occurrence of a single character, or a substring of a given String in Java using the replaceAll() method of java.lang.String class. This method also allows you to specify the target substring using the regular expression, which means you can use this to remove all white space from String. The replaceAll() function is very useful, versatile and powerful method and as a Java developer, you must know about it. Even though Java provides separate methods for replacing characters and replacing substring, you can do all that just by using this single method. The replaceAll() method replaces each substring of this string (the String on which it is called) that matches the given regular expression with the given replacement. It internally uses classes like Pattern and Matcher from java.util.regex package for searching and replacing matching characters or substring.

How to get max memory, free memory and total memory in Java

Getting free memory, total memory and max memory on JVM is using Runtime class in Java. and many java programmer is interested to know whether they have any relationship with JVM argument -Xms and -Xmx which is used to specify starting heap size and maximum heap size of JVM. I have touched this on 10 Points on Java heap and how to set heap size in ANT and Maven but here we will see some way to find out starting and maximum heap size from Java program.

Eclipse Not Able To Connect Internet, Market Place - Configure Connection Proxy Settings

If you are using Eclipse in your company, you might have faced issues, where Eclipse is not able to connect to internet. Since most of companies uses proxy for connecting to Internet, its important to configure proxy settings in Eclipse to allow Eclipse to access Internet behind organization's firewall. If your company regularly changes there internet proxy settings then this also needs to be updated whenever your Proxy server changes. Since Eclipse needs internet connection for connecting to Eclipse Market place, installing and updating plugins, downloading Maven dependencies from remote maven repository, it's really frustrating when Eclipse just hung up, shows connecting and time out after a long time.

Tuesday, January 17, 2017

10 examples of grep command in UNIX and Linux

The grep command is one of the most frequently used UNIX command stands for "Global Regular Expression Print" along with find, chmod, and tar command in UNIX. grep command in Unix operating system e.g. Linux, Solaris, BSD, Ubuntu or IBM AIX is used to search files for matching patterns, by using grep command in Unix you can search a file which contains a particular word or particular pattern. UNIX grep command also provides several useful command line option which can be used to enhance the functionality of grep command e.g. by using grep -v you can list down all files which don't contain a word i.e. excluding files which matches a pattern, grep -c will print count of matching pattern in a file etc. One of the popular examples of grep command is to find empty files and directories in Unix.

Top 10 UNIX and Linux System Programming Books- Best of Lot, Must Read

I have been sharing programming books in this blog from a long time, starting with core Java, I moved to other related technology e.g. Spring, Design patterns, Data Structure and Algorithms etc. Today, I am going to share some of the best UNIX and Linux programming books. The list contains some of the must read UNIX books from great writers like Sir Richard. Stevens, Sir Brain Kernighan, who has contributed so much to the development of UNIX operating system. Most of the books in this list are timeless,  classics and don't age with time, much like UNIX, which is around from last 40 years and I am sure will be around for next 40 years, or maybe forever.

5 books to learn Spring framework and Spring MVC for Java Programmers

Spring and Spring MVC is one of the most popular Java frameworks and most of new Java projects uses Spring these days. Java programmer often asks questions like which books is good to learn Spring MVC or What is the best book to learn Spring framework etc. Actually, there are many books to learn Spring and Spring MVC but only certain books can be considered good because of  their content, examples or the way they explained concept involved in Spring framework. Similar to  Top 5 books on Java programming we will some good books on Spring in this article, which not only help beginners to start with Spring but also teaches some best practices.

Monday, January 16, 2017

How to check if a Number is Positive or Negative in Java - Interview Question

Write a Java program to check if a number is positive or negative is one of the popular Java coding interview questions, it may look easy but programmers often fumble on this question. One of the tricky parts of this question is that Java has multiple data type to support numbers like byte, short, char, int, long, float and double, out of those all are signed except char, which can not represent negative numbers. Some solution work for int and long but may not work for floating point number e.g. float and double. This is also a tricky Java question, another tricky point is considering  special cases like positive infinity, negative infinity or NaN in the case of checking floating point numbers. Things get more complicated when, as follow-up questions, interviewer put additional conditions such as you can not use relational operator etc. Nevertheless, Java provides several way to check if a number whether integer or floating point is positive or negative. In this Java tutorial, we will see such methods of checking the sign of the number in Java.

Top 20 String Algorithm Questions from Coding Interviews

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.

Sunday, January 15, 2017

5 Free OCEJWCD 6 Mock Exam 1Z0-899 Practice Test

The OCEJWCD is the Oracle's version of SCWCD (Sun Certified Web Component Developer) exam, which tests candidate's knowledge on Servlet, JSP, and other web technology. The OCEJWCD stands for Oracle Certified Enterprise Java Web Component Developer. Like other Java certifications e.g. OCAJP or OCPJP, the key to success is selecting a good book, practicing code daily, and then solving as many mock questions as possible. In the last article, I have shared some of the best OCEJWCD books and in this article, I am going to share of the best free OCEJWCD 6 mock tests you can online. These mock exams are good for self-assessment and practicing before real exams.

How to use Lambda Expression in Place of Anonymous Class in Java 8

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.

Why Default or No Argument Constructor is Important in Java Class

Almost all Java developers knows that compiler adds a default constructor or better known as no argument constructor in every Java class, but many of them forget that, it only does when you don't provide any other constructor. Which means it becomes developers responsibility to add a no argument constructor, if he is adding explicit constructor. Now, Why it's important to provide default constructor in Java, What happens if your class don't have a no argument constructor? Well, this is how it's asked in many Java interviews, most commonly as part of Spring and Hibernate interviews. It's not mandatory to define default constructor, but if you are writing Hibernate persistent class, JPA entities or using Spring framework to manage object creation and wiring dependencies, you need to be bit careful. Many of open source framework, uses reflection to create instance or Object at runtime, based upon name of class.

6 JDBC Performance Tips for Java Developers

JDBC Performance tips are collection of some tried and tested way of coding and applying process which improves performance of JDBC code. Performance of core Java application or J2EE web application is very important, especially if its using database in back end which tend to slow down performance drastically. do you experience your java j2ee web application to be very slow (taking few seconds to process simple requests which involves database access, paging, sorting etc) than below tips may improve performance of your Java application. these tips are simple in nature and can be applied to other programming language application which uses database as back-end. If you are interested learning how to use JDBC in right way I suggest you to take a look at Practical database programming with Java book by Ying Bai. It's one of the rare book in JDBC which not only explains how to use different JDBC classes but also the right way of using it. You can also find lots of JDBC performance tips there.

Saturday, January 14, 2017

How to Sort Array in Java Ascending and Descending Order of Elements With Example

Quite often we need to sort array in Java luckily java.util.Arrays class provide several utility method to sort java array of any type e.g. primitive, object or int, String etc. Arrays is in java.util package and exposed all sorting related method as static utility functions. you can access sort() as Arrays.sort() and just pass your array and it will sort that array object. You can sort array in ascending order, descending order or any custom order defined by custom comparator in Java. In last article we have seen how to Sort ArrayList in Java and in this java article we will see examples of sorting array in ascending order, descending order and sorting sub arrays in java.

Sort Array in Java on ascending and descending order

Sorting Java Array into Ascending Order:

how to sort array in java ascending descending order exampleIn order to sort an array (String, int or any type) in ascending order we don't need to to anything special. Arrays.sort() method by default sort elements in there natural order implemented by CompareTo method. String array in Java will be sorted lexicographically. integer will be sorted numerically ascending order. look on code section for complete example of how to sort java array into ascending order. You can also sort anonymous array in Java by this method but since you don’t have any name to refer that it doesn’t make much sense.


Sorting Java Array into Descending Order:

In order to sort a java array into descending order you need to provide an external Comparator in Java which can sort elements in there reverse order and luckily we have that built int as java.util.Collections.reverseOrder(), which returns a reverse order comparator which gives reverse of natural ordering of element objects. pass this reverse comparator to sort method and it will sort array into descending order as shown in code example on last section. There is another way in which you can convert Array into ArrayList and than sort the arraylist but that’s again a two step process so its better to sort array using Arrays.sort() method



Sorting Sub Array in Java

Arrays class also provide methods to sort part of java array or sub array. So in case if you have big array and you only need to sort a particular section than just provide start index and end index to java.util.Arrays.sort(array,index,index) and it will sort the array only for that range. this is much faster than sorting whole array and than getting a range of values out of it. here is code example of sorting part of array in Java:


Code Example of Sorting Array in Java

In this section of code example we will see how to sort Java array into ascending order, descending order and sorting sub arrays in Java:


import java.util.Arrays;
import java.util.Collections;

public class HashtableDemo {

public static void main(String args[]) {
String[] companies = { "Google", "Apple", "Sony" };

// sorting java array in ascending order
System.out.println("Sorting String Array in Ascending order in Java Example");
System.out.println("Unsorted String Array in Java: ");
printNumbers(companies);
Arrays.sort(companies);
System.out.println("Sorted String Array in ascending order : ");
printNumbers(companies);

// sorting java array in descending order
System.out.println("Sorting Array in Descending order in Java Example");
System.out.println("Unsorted int Array in Java: ");
printNumbers(companies);
Arrays.sort(companies, Collections.reverseOrder());
System.out.println("Sorted int Array in descending order : ");
printNumbers(companies);

System.out.println("Sorting part of array in java:");
int[] numbers = { 1, 3, 2, 5, 4 };
Arrays.sort(numbers, 0, 3);
System.out.println("Sorted sub array in Java: ");
for (int num : numbers) {
System.out.println(num);
}

}

public static void printNumbers(String[] companies) {
for (String company : companies) {
System.out.println(company);
}
}

}

Output:
Sorting String Array in Ascending order in Java Example
Unsorted String Array in Java:
Google
Apple
Sony

Sorted String Array in ascending order :
Apple
Google
Sony

Sorting Array in Descending order in Java Example
Unsorted int Array in Java:
Apple
Google
Sony
Sorted String Array in descending order :
Sony
Google
Apple
Sorting part of array in java:
Sorted sub array in Java:
1
2
3
5
4



Important points about Sort method of Arrays:

Here are some important and worth noting point about sort method of Arrays class for quick references:

1. Arrays.sort() is an overloaded method and can sort int, byte, short, char or object[] arrays.
2. Arrays.sort)( also allows you to sort a sub-array or part of array in Java.
3. Arrays class also contains utility methods e.g. binarySearch for performing search on array

That’s all on how to sort java array on ascending and descending order and part of array in Java. You can also use the workaround by converting array into arraylist and than sorting but I think Arrays.sort() is preferred method for sorting arrays in Java.

Further Learning
Data Structures and Algorithms: Deep Dive Using Java
Algorithms and Data Structures - Part 1 and 2
Data Structures in Java 9 by Heinz Kabutz

Java Tutorials you may like