Thursday, August 31, 2017

Difference between SOAP and RESTful Web Service in Java

Though both SOAP and RESTful web services allow a client to query the server for some information, but the way they are implemented and used is quite different. The main difference between SOAP and REST is that former provides a standard of communication between client, server and other parties and has restricted a set of rules and format, while REST leverages the ubiquity of HTTP protocol, in both client and servers, to allow them to communicate with each other regardless of their implementation. In short, getting data from a RESTful web service requires less headache then getting data from a SOAP web service. Since everybody is familiar with HTTP requests like GET or POST, it's easy to understand and correlated how RESTful web services are working and which URL of REST web service provides what kind of information. In SOAP, you need to understand lengthy WSDL document to find out right methods and the right way to call them.

Wednesday, August 30, 2017

How to use string in switch case in Jdk 7 with example

Have you ever feel that String should be used in switch cases as like int and char? JDK 7 has made an important enhancement in their support of String, now you can use String in switch and case statement, No doubt String is most widely used type in Java and in my opinion they should have made this enhancement long back when they provided support for enum in java and allowed enum to be used in switch statement. In this java tutorial, we will see how we can use String inside switch and case statement in JDK 7. This article is in continuation of my earlier post on JDK7 feature improved exception handling using multi-cache block in Java

string and switch in jdk7 example tutorial many times we want to switch based upon string output received from user or another part of program but before JDK7 we can't do it directly instead either we need to map those String to final integer constant or char constant to use them inside switch and case or you need to fall back on if-else statement which gets clumsy once number of cases getting increased. But now with jdk7, you can directly use String inside switch and case statement. Though it’s pretty straight forward feature let see an example of how to use String inside switch and case statement in JDK7.

Tuesday, August 29, 2017

2 ways to solve Unsupported major.minor version 51.0 error in Java

Unsupported major.minor version 51.0 error comes when you run a class file created using Java 1.7 (major version 51.0) into a lower JRE version e.g. JRE 6, 5 or 4. There are two ways to solve this problem, first make sure you run your Java program in same or higher version of JRE, on which it has compiled, and second use cross-compilation option to create a class file compatible to a lower JRE. You can use javac -target option to create a class file for all JRE up-to-the JDK version you are using for compilation. For example, if you are compiling your Java source file into JDK 1.7 then you can create class files to run on JDK 1.1, 1.2, 1.3, 1.4 , 1.5 and 1.6 version, but you cannot create class files compatible with Java 1.8. When you compile a Java source file, it creates a class file and add the class file version into it. In order to run that class file, your JRE must understand that version. When JRE or JVM which is running the class doesn't able to understand the class file version they throw java.lang.UnsupportedClassVersionError: XXX : Unsupported major.minor version 51.0 error, where XXX is the name of your class which has an incompatible version.

Monday, August 28, 2017

Difference between @RestController and @Controller Annotation in Spring MVC and REST

The @RestController annotation in Spring MVC is nothing but a combination of @Controller and @ResponseBody annotation. It was added into Spring 4.0 to make the development of RESTful Web Services in Spring framework easier. If you are familiar with the REST web services you know that the fundamental difference between a web application and a REST API is that the response from a web application is generally view (HTML + CSS + JavaScript) while REST API just return data in form of JSON or XML. This difference is also obvious in the @Controller and @RestController annotation. The job of @Controller is to create a Map of model object and find a view but @RestController simply return the object and object data is directly written into HTTP response as JSON or XML.

10 Equals and HashCode Interview Questions in Java

Equals and HashCode methods in Java are two fundamental methods from java.lang.Object class, which is used to compare equality of objects, primarily inside hash based collections such as Hashtable and HashMap. Both equals() and hashCode() are defined in java.lang.Object class and there default implementation is based upon Object information e.g. default equals() method return true if two objects are exactly same i.e. they are pointing to the same memory address while default implementation of hashcode method return int and implemented as a native method. The similar default implementation of toString() method, returns type of class, followed by memory address in hex String.

Top 10 JDBC Best Practices for Java Programmer

Java JDBC Best practices
JDBC Best Practices are some coding practices which Java programmer should follow while writing JDBC code. As discussed in how to connect to Oracle database from Java, JDBC API is used to connect and interact with a Database management System.  We have touched some of the JDBC best practices in our last article 4 JDBC Performance tips, On which we have discussed simple tips to improve performance of Java application with database. By using JDBC you can execute DDL, DML and Stored Procedures. JDBC Best practices is probably most significant set of coding practices in Java because it significantly affect performance of Java application. I have seen substantial performance gain by simply following common JDBC best practices like running queries with auto commit mode disable. One of the query which we used in our example of JDBC Batch update was taking almost 30 second to finish with auto commit mode enabled but it just took under one second with auto commit mode disable and using explicit commit. This JDBC tutorial is collection of such practices which help you to write better JDBC code and in most cases result in improved performance.

Quicksort Sorting Algorithm in Java

Quicksort algorithm is one of the most used sorting algorithm, especially to sort large list and most of the programming languages, library have implemented it in one or another way. In Java, Arrays.sort() method sorts primitive data types using double pivot Quicksort algorithm, authored by Joshua Bloach and others. This implementation provides better performance for lot of data sets, where traditional quicksort algorithm reduced into quadratic performance. This method also uses MergeSort, another good sorting algorithm, to sort objects. QuickSort implementations are also available in C++ STL library. Have you ever thought why quicksort is so popular? because on average it is one of the fastest sorting algorithm we have. On average quicksort is a O(n log n) algorithm, while it's worst case is O(n^2), which is much better comparing with Bubble Sort or Insertion Sort. It's also one of the popular algorithm interview question, so as a programmer you must know how QuickSort works as well as how to implement Quicksort in Java or any other programming language. One of the most important thing interviewer look in your quicksort implementation is choice of pivot and whether you are sorting in place or not. In "in-place" sorting, actual sorting takes place in same array and no additional space is needed. Due to this reason, quicksort is very efficient in sorting large list of numbers, as no additional memory is required, a very space efficient sorting algorithm. Quicksort is also one of the naturally recursive algorithm and serves a good exercise for Java programmers to master art of recursion.

Sunday, August 27, 2017

Why Java does not support Operator overloading

Unlike C++, Java doesn't support operator overloading. Java doesn't provide freedom to programmer, to overload the standard arithmetic operators e.g. +, -, * and / etc. If you have worked previously in C++, than you know that, Java has left lot of feature supported in C++ e.g.  Java doesn't support multiple inheritance, no pointers in Java, and no pass by reference in Java. Rarely this question asked in Java interviews, to check how programmer thinks about certain features, which is not supported in Java. Another similar questions is regarding Java being pass by reference, which is mostly appear as, whether Java is pass by value or reference. Though I don't know the real reason behind it, I think following observation make sense on, why Operator overloading is not supported in Java.


1) Simplicity and Cleanliness
Why operator overloading is not supported in JavaSimple and clear design was one of the goals of Java designers. They, just don't want to replicate the language, but wanted to have a clear, truly object oriented language. Adding Operator overloading would have definitely made design more complex than without it, and it might have lead to more complex compiler or slows the JVM ,because it needs to do extra work to identify the actual meaning of operators, and reduce the opportunity to optimize the language by guarantee behavior of operators in Java.

2) Avoid Programming Errors
Java doesn't allow user defined operator overloading, because if you allow programmer to do operator overloading, they will come up with multiple meanings for same operator, which will make the learning curve of any developer hard and things more confusing and messy. Its been observed that, there is increase in programming errors, when language supports operator overloading, which in turn increase e development and delivery time. Since Java and JVM has taken most of developers responsibility,  in memory management by providing garbage collector, it doesn't really make sense to left this feature to pollute the code, and as a loop hole for programming errors.


3) JVM Complexity
From JVM perspective, supporting operator overloading is more difficult, and if the same thing can be achieved, by using method overloading in more intuitive and clean way, it does make sense to not support operator overloading in Java. A complex JVM, may result in slower JVM, than a relatively simpler JVM ,and reduce the opportunity of optimization by taking out guaranteed behavior of operators in Java.

4) Easy Development of Tools
This is an additional benefit of not supporting operator overloading in Java. Omission of operator overloading has kept the language easier to handle and process, which in turn makes it easier to develop the tools, that process the language e.g. IDE or re-factoring tool. Re-factoring tools in Java are far better than C++.

Further Learning
Complete Java Masterclass
Java Fundamentals: The Java Language
Java In-Depth: Become a Complete Java Engineer!

In conclusion many things, which can be achieved by operator overloading, can also be achieved using method overloading using more intuitive and easy way and that might be the reason java designer thought that supporting operator overloading will not be a big benefit for language, but in fact only Java designer can answer real motivation of, why Java doesn't support operator overloading, like some other questions as Why Java doesn't support multiple inheritance or Why String is immutable in Java.

Saturday, August 26, 2017

5 example of sort command in UNIX or Linux >>>> Unix Tutorial

Sorting is one of the essential tasks we always need to perform and UNIX or Linux has great support for sorting by using sort command. No matter what kind of shell script you are writing or you are looking for some information or reports many times you need to sort the output of one command or a set of line, with a combination of the sort with find command and grep in UNIX you can handle support request and report quite easily. In this UNIX sort command tutorial, we will see how we can use sort command in UNIX to achieve our sorting goal. This tutorial contains some of the practical example of sort command for sorting data in UNIX. With the use of “unique” and “sort” command, you can remove duplicates and present a sorted data in UNIX.

2 Examples to Convert Byte[] Array to String in Java

Converting a byte array to String seems easy but what is difficult is, doing it correctly. Many programmers make mistake of ignoring character encoding whenever bytes are converted into a String or char or vice versa. As a programmer, we all know that computer's only understand binary data i.e. 0 and 1. All things we see and use e.g. images, text files, movies, or any other multi-media is stored in form of bytes, but what is more important is process of encoding or decoding bytes to character. Data conversion is an important topic on any programming interview, and because of trickiness of character encoding, this questions is one of the most popular String Interview question on Java Interviews. While reading a String from input source e.g. XML files, HTTP request, network port, or database, you must pay attention on which character encoding (e.g. UTF-8, UTF-16, and ISO 8859-1) they are encoded. If you will not use the same character encoding while converting bytes to String, you would end up with a corrupt String which may contain totally incorrect values. You might have seen ?, square brackets after converting byte[] to String, those are because of values your current character encoding is not supporting, and just showing some garbage values.

How to calculate Large Factorials using BigInteger in Java?

Factorial of numbers greater than or equal to 13 cannot be found using primitive int data type as shown in our earlier factorial solution due to overflow. These factorials are too large to fit in an int variable, whose maximum value is just 2147483647 (2^31 -1). Even if we use the long data type, factorials greater than or equal to 21 will generate an overflow. To find the factorial of anything above 21, you need to use the BigInteger class from java.math package. As the name suggests, BigInteger class is designed to hold really large integer value, something which is even bigger than the maximum value of long primitive e.g. 2^63 -1 or 9223372036854775807L. You also need to change the way we calculate factorial for a smaller number. You can not use recursion to calculate factorial of a larger number instead we need to use for loop for that.

Thursday, August 24, 2017

How to Delete Empty Files and Directories in Unix or Linux Server - find Command Example

Deleting empty file and directory in Unix
Many times we need to find and delete empty files or directories in UNIX/Linux. Since there is no single command in Unix/Linux which allows you to remove empty files or empty directories rather we need to rely on find command and xargs command. In this UNIX and linux example we will see How to delete empty files and directories. Before removing empty files and directories we need to find those files and there are lots of option available to search for empty directories like find, grep , awk etc. You just need to know correct option. Like in any other operating system empty files and directories in Unix are those whose size is zero. Empty files doesn't contains any content while empty directories does not contain anything at all e.g files or sub-directories. As discussed in previous post 10 frequently used  find command examples we can also use find command to search and delete empty files and directories as it provides searching files based on size as well.

Difference between HashMap, LinkedHashMap and TreeMap in Java

The java.util.Map is one of the most important interfaces from Java Collection Framework.  It provides hash table data structure functionality by its implementations like HashMap, Hashtable, LinkedHashMap and a little bit of sorting with the TreeMap. So if you are looking to store key-value pairs in Java program,  you have a wide range of choices available depending upon your requirement. The main difference between LinkedHashMap, TreeMap and HashMap comes in their internal implementation and specific features, which makes them useful in certain scenarios. For example, the HashMap is a general purpose Map (hash table data structure), which should be used whenever you need a hashing-based data structure for storing your mappings (key-value pairs).

Wednesday, August 23, 2017

How to Convert Collection to String in Java - Spring Framework Example

How to convert Collection to String in Java
Many times we need to convert any Collection like Set or List into String like comma separated or any other delimiter delimited String. Though this is quite a trivial job for a Java programmer as you just need to Iterate through the loop and create a big String where individual String are separated by a delimiter, you still need to handle cases like the last element should not have delimiter or at a bare minimum you need to test that code. I like Joshua Bloch advice on Effective Java to use libraries for those common tasks let it be an internal proprietary library or any open source library as used in previous examples of  Spring, Apache Commons or Google’s Guava but point is that you should avoid converting ArrayList to String like common task by yourself on application code.

Tuesday, August 22, 2017

3 CDN URL to load jQuery into Web Page from Google, Microsoft

jQuery is one of the most popular and powerful JavaScript libraries, but in order to use it, you need to load into your web page using standard HTML <script> tag. Based on whether your web page is public accessible or for an organization, you can either choose to load the jQuery library from local file system, bundled inside your web application or you can directly download using one of the content delivery network (CDN) e.g. Google or Microsoft CDN. Choosing CDN to download jQuery can offer a performance benefit because there servers are spread across the globe. This also offer an advantage that if visitor of your site has already downloaded a copy of jQuery from the same CDN, then it won't have to be re-downloaded.  By the way if you want to bundle jQuery into your web application or want to load it from local file system, you can always download latest version of jQuery from jQuery site at http://jquery.com. Installing jQuery required this library to be placed inside your web application and using the HTML <script> tag to include it into your pages e.g. <script type="text/JavaScript" src="scripts/jquery-1.10.2.js"></script>

Sunday, August 20, 2017

How to resolve java.lang.ClassNotFoundException in Java

What is ClassNotFoundException in Java
ClassNotFoundException is one of Java nightmare every Java developer face in there day to day life. java.lang.NoClassDefFoundError and java.lang.ClassNotFoundException are two errors  which occurs by and now and chew up of your precious time while finding and fixing root cause. From the name java.lang.ClassNotFoundException looks quite simple but underlying cause of it is always different and which classifies it as an environmental issue. In this java tutorial we will see what is ClassNotFoundException in java, what is real cause of it and how to fix it along with some more frequent and infamous examples of java.lang.ClassNotFoundException in Java or J2EE, Don’t mistake this exception with NoClassDefFoundError in Java which is also due to incorrect classpath in Java.  Though both of them are related to missing class file when Java tries to load class in Java they are completely different to each other.  Correct understanding of  When class is loaded in Java and How Classpath works  is must to troubleshoot and fix this error quickly.

5 Entertaining Posts from StackOverFlow - Must Read

StackOverFlow is great place to look for help, learn and participate, but it's also a great place to taste some real entertainment, contributed by programmers from all over the world. Though, due to strict policies of stackoverflow.com, most of entertaining post either are either gets closed or deleted, some of them remained to entertain programming community. Being a regular reader of StackOverFlow from long time, I have found couple of threads which are truly amazing, and has lot's of funny and entertaining content. Here I am going to share 5 of my favorite StackOverFlow posts, which I suggest you to read, if you get bored or you have some time to kill. By the way, don't forget to leave comments and let us know which is your favorite funny and entertaining threads in StackOverFlow.

Why use SLF4J over Log4J for logging in Java

Every Java programmers know that logging is critical for any Java application, especially server-side application, and many of them are already familiar with various logging libraries e.g. java.util.logging, Apache log4j, logback, but if you don't know about SLF4J, Simple logging facade for Java,  then it's time to learn and use SLF4J in your project. In this Java article, we will learn why using SLF4J is better than using log4j or java.util.logging. It’s been a long time, since I wrote 10 logging tips for Java programmer,I don’t remember anything I have writing about logging. Anyway, let’s get back to the topic, on contrary to all those logging libraries, there is a major difference between them and SLF4J. SLF4J or Simple logging Facade for Java is not really a logging implementation, instead, it's an abstraction layer, which allows you to use any logging library in the back-end. If you are writing API or utility library, which can be used internally or externally, then you really don't want that any client, which uses your library, should also stick with your choice of logging library. 

Saturday, August 19, 2017

10 Best Practices to Follow While Writing Code Comments

Comments are an important part of writing code not only in Java but whatever programming or scripting language you use. At the same time, this is one of the most abused things as well. Both writing no comment and writing too much comment is bad and this has been highlighted by many software gurus e.g. Robert C. Martin in his classic book Clean code. There is a whole chapter dedicated to How to write comments and finding pros and cons of comment. This article is my learning in the same direction, here I am going to share with you guys some 0f the rule and best practices I follow while writing comments. Before that let's first see what is the purpose of having a comment in the code? Why do we need comment, isn't writing code is enough. Some of the people I have met always argue that we are getting paid for writing code and not comment :).

15 Java NIO, Socket, and Networking Interview Questions Answers

Networking and Socket Programming is one of the important area of Java programming language, especially for those programmers, who are working in client server based applications. Knowledge of important protocols e.g. TCP and UDP in detail is very important, especially if you are in business of writing high frequency trading application, which communicate via FIX Protocol or native exchange protocol. In this article, we will some of the frequently asked questions on networking and socket programming, mostly based around TCP IP protocol. This article is kinda light on NIO though, as it doesn't include questions from multiplexing, selectors, ByteBuffer and FileChannel but it does include classical questions like difference between IO and NIO. Main focus of this post is to make Java developer familiar with low level parts e.g. how TCP and UDP protocol works, socket options and writing multi-threaded servers in Java. Questions discussed here is not really tied up with Java programming language, and can be used in any programming language, which allows programmers to write client-server applications. By the way, If you are going for interview on Investment banks for core Java developer role, you better prepare well on Java NIO, Socket Programming, TCP, UDP and Networking along with other popular topics e.g. multi-threadingCollections API and Garbage Collection tuning. You can also contribute any question, which is asked to you or related to socket programming and networking and can be useful for Java interviews.

What is polymorphism in Java? Method overloading or overriding?

What is Polymorphism in Java
Polymorphism is an important Object oriented concept and widely used in Java and other programming languages.  Polymorphism in java is supported along with other concepts like Abstraction, Encapsulation, and Inheritance. Few words on the historical side; Polymorphism word comes from ancient Greek where poly means much so polymorphic are something which can take many forms. In this Java Polymorphism tutorial we will see what is Polymorphism in Java , How Polymorphism has implemented in Java e.g method overloading and overriding, why should we use Polymorphism and how can we take advantage of polymorphism while writing code in Java. Along the way we will also see a real world example of using Polymorphism in Java

Friday, August 18, 2017

How to write parametrized Generic class and method in Java Example

Parameterized Generic class and method in Java
Writing Generic parametrized class and method in Java is easy and should be used as much as possible. Generic in Java was introduced in version 1.5  along with Autoboxing, Enum, varargs and static import. Most of the new code development in Java uses type-safe Generic collection i.e. HashSet in place of HashSet but still Generic is underused in terms of writing own parametrized classes and method. I agree that most Java programmers has started using Generic while working with the Java collection framework but they are still not sure how Generic can allow you to write Template kind of classes which can work with any Type just like the parametrized ArrayList in Java which can store any Type of element. In the last couple of article  about Generics we have seen How Generic works in Java and  explored wild cards of Generic in Java and In this part of Java Generic example we will see How to write parametrized Generic Class and method in Java.

How to Remove key value pairs or Entries from HashMap in Java 8

In the last article, I have shown how to remove key/value pairs from a map in Java based upon some conditions e.g. remove all entries where values are greater than 10$. I have told you that you must use the Iterator's remove() method for removing mapping while iteration to avoid ConcurrentModificationException, but that's not required anymore in Java 8. From JDK 8 onwards, you can selectively remove mapping without iterating over Map. The JDK 8 API has added several new methods to existing interfaces e.g. java.util.Collection, java.util.Map, Comparator etc because the interface can now contain concrete methods in form of static and default methods.

Wednesday, August 16, 2017

How to remove key value pair from Map during Iteration - Example tutorial

Suppose you have a Map e.g. HashMap or Hashtable, which contains key value pairs e.g. books and their prices, and you want to remove all books whose prices are greater than 40 USD, How do you that in Java? Many Java programmer, will say that they will iterate over Map and check each entry and then use remove(Object key) or remove(Object key, Object value) methods from java.util.Map to remove any mapping where the value is greater than 40 USD. Though the approach is right, the answer is wrong. Yes, we'll iterate over Map to check each value but we'll not use the two remove() methods from java.util.Map interface because they will throw ConcurrentModficationException, when you call them to remove mapping during iteration. Instead, we'll use the Iterator.remove() method to remove any key value pair, where the value is greater than 40 USD.

How to Sort List in reverse Order in Java Collection Framework with Example

Java Collection Framework provides a convenient reverse comparator, to sort List of objects in reverse order.  You can obtain reverse Comparator, by calling Collections.reverseOrder(), which by default sort List of Integer in reverse numeric order and List of String in reverse alphabetic order. It actually reverse natural ordering of objects imposed by Comparable interface. Apart from this method, Collections class also provides an overloaded method Collections.reverseOrder(Comparator cmp), which takes a Comparator, and sort List on reverse order of that Comparator. So next time if you need to sort your Collection in reverse order, you don’t need to write any extra comparator by yourself, you can directly leverage reverse comparator provided by java.util.Collections class. It is as simple as calling Collections.sort() method providing comparator wrapped into Collections.reverseOrder() method. By using these two methods, you can sort any List implementation e.g. ArrayList, LinkedList or Vector in Java.

Tuesday, August 15, 2017

10 tips to quickly become productive with new Project/Codebase

One of the main drawback of changing job or changing project it that you lost all subject matter expertise you have learned by working the last couple of years in that project or domain. It doesn't matter whether you are an expert in a programming language, once you change job, you lost your hard earned experience on projects or domain you are working on. When starting a new job or on to a new project you will rarely be working on a complete greenfield environment. Understanding and mastering an unfamiliar code is a difficult process and it can sometimes feel overwhelming due to the amount of new information you need to take on.

Monday, August 14, 2017

How to Find All Permutations of String in Java using Recursion

How to find all permutation of a String using recursion is one of the tricky coding questions from Programming job interviews. I have first seen this question in my college exam when we were asked to code the solution using C or C++ language. Since then I have seen this question many times at various written tests and Java interviews for a junior developer position. It does not only serve as a good question to check whether the candidate understands recursion but also its one of the better Java programming exercise for beginners. Typically, you will be asked to write a method, which accepts a String and print all permutations or may return all permutations in a List for a junior developer position. Depending upon the company you are going for an interview, they may ask you to code on IDE like Eclipse or NetBeans, or simply write code in plain paper, so be prepared for both.

Bubble Sort Algorithm in Java with Example

Bubble Sort is the first sorting algorithm I learned during my college day, and after so many years it's the one I remember by heart. It's kind of weird that one of the most popular sorting algorithm is also one of the worst performing sorting algorithm. Bubble sort's average case performance is in O(n^2), which means as the size array grows, the time it take to sort that array increases quadratic. Due to this reason, bubble sort is not used in production code, instead quick sort and merge sort are preferred over it. In fact, Java's own Arrays.sort() method, which is the easiest way to sort an array in Java also uses two pivot quicksort to sort primitive array and stable mergesort algorithm to sort object arrays.

How to fix java.net.SocketException: Too many files open java.io.IOException in Tomcat, Weblogic Server

Not many Java programmers knows that socket connections are treated like files and they use file descriptor, which is a limited resource. Different operating system has different limits on number of file handles they can manage. One of the common reason of java.net.SocketException: Too many files open in Tomcat, Weblogic or any Java application server is, too many clients connecting and disconnecting frequently at very short span of time. Since Socket connection internally use TCP protocol, which says that a socket can remain in TIME_WAIT state for some time, even after they are closed. One of the reason to keep closed socket in TIME_WAIT state is to ensure that delayed packets reached to the corresponding socket. Different operating system has different default time to keep sockets in TIME_WAIT state, in Linux it's 60 seconds, while in Windows is 4 minutes. Remember longer the timeout, longer your closed socket will keep file handle, which increase chances of java.net.SocketException: Too many files open exception

SQL Query to Find All Table Names on a Database With MySQL and SQL Server Examples

How do you find names of all tables in a database is a recent  SQL interview questions asked to one of my friend. There are many ways to find all table names form any database like MySQL and SQL Server. You can get table names either from INFORMATION_SCHEMA or sys.tables based upon whether you are using MySQL or Sql Server database. This is not a popular question like when to use truncate and delete or correlated vs noncorrelated subquery which you can expect almost all candidate prepare well but this is quite common if you are working on any database e.g. MySQL. In this SQL tutorial we will see examples of getting names of all tables from MySQL and SQL Server database. In MySQL there are two ways to find names of all tables, either by using "show" keyword or  by query INFORMATION_SCHEMA. In  case of SQL Server or MSSQL, You can either use sys.tables or INFORMATION_SCHEMA to get all table names for a database. By the way if you are new in MySQL server and exploring it , you may find this list of frequently used MySQL server commands handy.

Sunday, August 13, 2017

Java Enum Tutorial: 10 Examples of Enum in Java

What is Enum in Java
Enum in Java is a keyword, a feature which is used to represent fixed number of well-known values in Java, For example, Number of days in Week, Number of planets in Solar system etc. Enumeration (Enum) in Java was introduced in JDK 1.5 and it is one of my favorite features of J2SE 5 among Autoboxing and unboxing , Generics, varargs and static import. One of the common use of Enum which emerged in recent years is Using Enum to write Singleton in Java, which is by far easiest way to implement Singleton and handles several issues related to thread-safety and Serialization automatically. By the way, Java Enum as a type is more suitable to represent well known fixed set of things and state,  for example representing the state of Order as NEW, PARTIAL FILL, FILL or CLOSED.

Saturday, August 12, 2017

Swing is not Thread-safe in Java - What Does it Mean? Event Dispatcher, SwingWorker, Multithreading and Best Practices

Couple of my reader ask question, what does it mean by Swing is not thread-safe and How does it affect coding in Swing GUI application? This post is an effort to help those readers and several other programmers to understand Swing and thread-safety in a bit more detailed way. To keep it simple, let's revise what does it mean by being thread-safe? We say an object is thread-safe, if we can call it's method, which can change it's state, from multiple thread at same time. To give you an example, java.lang.String is a thread-safe class, which means you can call any method e.g. substring(), toUpperCase() or toLowerCase() from multiple threads. By the way, String is thread-safe because it's immutable. Let's come back to Swing now, Core part of Swing is made up of different GUI component e.g. JLable, JPanel, JCombobox etc. All these components are not thread-safe, which means you can not call methods of this components e.g. JLable.setText("new title") from any thread, other than Event Dispatcher Thread(EDT)

What is JSESSIONID in J2EE Web application - JSP Servlet?

What is JSESSIONID in JSP-Servlet
JSESSIONID is a cookie generated by Servlet containers like Tomcat or Jetty and used for session management in J2EE web application for HTTP protocol. Since HTTP is a stateless protocol there is no way for Web Server to relate two separate requests coming from the same client and Session management is the process to track user session using different session management techniques like Cookies and URL Rewriting. If a Web server is using a cookie for session management it creates and sends JSESSIONID cookie to the client and then the client sends it back to the server in subsequent HTTP requests. JSESSIONID and session management is a not only a popular Servlet interview question but also appear in various JSP interviews. Along with What is JSESSIONID interviewer are also interested in when and how JSESSIONID is created in Servlet and JSP which we will see in next section.

How to Find all Pairs in Array of Integers Whose sum is Equal to a Given Number - Java Solution

Practising coding problems are very important to do well in any programming interview. You should at your best on data-structures like an array, linked list, and string to clear any programming interview and believe me, you can not do this in one day or one week. It's rather a long process of learning through coding, and that's where these small coding problems help. Today, we are going to look at another interesting programming question from the array; write a program to find all pairs of integers whose sum is equal to a given number. For example if input integer array is {2, 6, 3, 9, 11} and given sum is 9, output should be {6,3}. Sounds simple? maybe, but this exact question has appeared in a technical interview at Amazon, Microsoft, Facebook and couple of another fortune five tech companies in past. Many of you might already heard about this question and some of you may already know the solution to this problem as well, but it's not enough to know just the answer. In a programming interview, many things matter apart from correct solution. For example, first thing Interviewer look is whether a candidate can ask right questions or not. So before jumping straight to coding, spare a second or two to think about the problem and clear any doubt you may have. For example, you can ask following questions based upon problem statement given above :

Java 8 - Journey of for loop in Java, for(index) to forEach()

for loop has come a long way in Java 8 with new forEach() method in java.util.stream.Stream class. In this article, we will take a look at the journey of for loop in different versions of Java programming language. for loop is there from the very beginning of Java i.e. JDK 1.0. Almost all Java programmers have used the classical for() loop, as it is also an essential programming construct, I guess just next to if-else, but when the foreach loop or as some people call it enhanced for loop was introduced in JDK 1.5, everything changed from looping over Collection and array perspective. Yesterday's popular looping construct become old and ugly and more elegant solution took over. It was shorter, cleaner and less error prone, what else you need at that time.

Friday, August 11, 2017

Top 5 Books to Learn Groovy for Java Developers - Best Of Lot, Must Read

Groovy is a programming language which is specially created for Java developers with a view to being a fast-paced, scripting companion to Java. It aims to increase the productivity of Java developer by simplifying Java code by removing unnecessary boilerplate. Groovy not only present a succinct and easy to read syntax but also provide a much more elegant and convenient API than Java for common stuff. For example, a Groovy file can do in 50 lines what a Java source code do in 500 lines. You can declare an array as [] and map as [: ] which really make code full of data without much syntax. Because of this property, Groovy is heavily used in unit testing of Java application using a framework like Spock is built on Groovy.

Writing JUnit Test Cases in Java? Follow These Best Practices to Create Better Tests

JUnit best practices in Java
No doubt writing good JUnit test cases is a rare skill just like writing good Code. A good, well thought and well-written JUnit test can prevent several production issues during initial development or later maintenance in Java application. Though one can only be perfect in writing JUnit test by practice and a level of business knowledge which is important to envision different scenarios on which a method gets called, some best practices or experience of another developer may help to guide other programs. In this Java article, I am sharing some JUnit tips and JUnit best practices which I have learned and follow while writing unit tests using JUnit for Java programs. One of the books which helped me a lot is Pragmatic Unit Testing in Java with JUnit by Andrew Hunt and Dave Thomas,  This book shares a lot of JUnit best practices which are worth reading and learning if you are serious about Unit testing using JUnit

Thursday, August 10, 2017

How to Parse String to Float in Java | Convert Float to String in Java - 3 Examples

float and double are two data type which is used to store floating point values in Java and we often need to convert String to float in Java and sometimes even a Float object or float primitive to String. One thing, which is worth remembering about floating point numbers in Java is that they are approximate values, a float value 100.1f may hold actual value as 100.099998, which will be clear when we have seen examples of converting float to String and vice-versa. By the way, It's easy to parse String to float and vice-versa, as rich Java API provides several ways of doing it. If you already familiar with converting String to int or may be String to double in Java, then you can extend same techniques and method to parse float String values. key methods like valueOf() and parseInt(), which is used to parse String to float are overloaded for most primitive data types. 

Wednesday, August 9, 2017

10 Differences between StringBuffer and StringBuilder in Java

StringBuffer and StringBuilder are two important classes in Java which represents mutable String i.e. the String object, whose value can be changed. Since String is Immutable in Java, any change or operation on String object e.g. converting it to upper or lower case, adding character, removing character or substring all result in a new String object. This can put a lot of pressure on Garbage collector if your application generates lots of throws away String instances, to avoid this issue, Java designer presented initially StringBuffer class and later StringBuilder. When StringBuffer was introduced it has its own problem e.g. it was synchronized and hence was a lot slower.

Tuesday, August 8, 2017

Difference Between ON HOLD and ON ICE Jobs in Autosys - Interview Question

Autosys is job management and scheduling tool and widely used in Investment banks on UNIX or Linux based environment. Autosys is used to start Java process, takes backup of log files, stop Java process, cleaning and purging database and will all sort of housekeeping jobs in Linux environment. Autosys system is made of Autosys server and Autosys clients, each server or box, which has services scheduled by autosys, requires autosys client to be install on that. One of the key advantages of Autosys is that one job can depend upon another job, and can execute, depending upon, success and failure of parent job. Though Java developers are not asked a lot of interview questions, you might expect few of them during your interview with Wall Street banks, Brokers or Financial Institution, which uses autosys.

Difference between getPath(), getCanonicalPath() and getAbsolutePath() of File in Java

File API is very important one in Java, it gives access of File system to Java programs. Though Java's file API is rich, there are lot of subtleties to know when you use them. One of the common query programmer's has about file path is difference between getPath(), getCanonicalPath() and getAbsolutePath() methods, why there are three methods to get file path and what happens if you call getPath() in place of getCanonicalPath(). By the way, before understanding difference between getPath(), getAbsolutePath() and getCanonicalPath() let's understand the concept behind this methods, i.e. difference between path, absolute path, and canonical path.

How to format String in Java – String format Example

String format and printf Example
How to format String in Java is most common problem developer encounter because of classic System.out.println() doesn’t support formatting of String while printing on console. For those who doesn’t  know What is formatted String? here is a simple definition,  Formatted String is a String which not only displays contents but also displays it in a format which is widely accepted like including comma while displaying large numbers e.g. 100,000,000 etc. Displaying formatted String is one of the needs for modern GUI application and thankfully Java has good support for formatting String and all other types like Integers, Double, and Date. How to format a String in Java is never as easy as it has been since Java 1.5 which along with front line features like Generics, Enum, Autoboxing and Varargs also introduce several utility methods to support rich formatting of String in Java

How to format/parse dates with LocalDateTime in Java 8 - Example Tutorial

One of the common tasks in Java project is formatting or parsing date to String and vice-versa. Parsing date means you have a String which represents a date e.g. "2017-08-3" and you want to convert it into an object which represents the date in Java e.g. java.util.Date in pre-Java 8 world and LocalDate or LocalDatetime in Java 8 world. Similarly, formatting a date means converting a date instance into String, for example, you have a Date object or LocalDatetime object and you want a String in dd-MM-yyyy format. Java 8 API provides a good support for formatting and parsing dates. For example, if you have a date as String e.g. "2017-08-3 12:30" and you want to convert it to a LocalDateTime instance, which is a new class from JDK 8 Date and Time API and contains both date and time part, how do you do that? Well, you can use the format() and parse() method from LocalDateTime class to achieve that, but you need one more thing, a date format.

Sunday, August 6, 2017

How to Convert String to Integer to String in Java with Example

Converting String to integer and Integer to String is one of the basic tasks of Java and most people learned about it when they learn Java programming. Even though String to integer and Integer to String conversion is basic stuff but same time its most useful also because of its frequent need given that String and Integer are two most widely used type in all sort of program and you often gets data between any of these formats. One of the common tasks of programming is converting one data type another e.g. Converting Enum to String or Converting Double to String, Which is similar to converting String to Integer. Some programmers asked a question that why not Autoboxing can be used to Convert String to int primitive or Integer Object? 

Difference between SubStr vs SubString method in JavaScript - Tutorial Example

JavaScript provides two similar looking String manipulation function, substr and substring, though both are used to get substring from an String, there is a subtle difference between substring and substr method in JavaScript. If you look at there signature, both substr(to, length) and substring(to, from) both takes two parameters, but substr takes length of substring to be returned, while substring takes end index (excluding) for substring.This main difference will be more clear when we will see couple of examples of using substr and substring in JavaScript code. By the way this is also a good JavaScript question and frequently asked to web developers during HTML, CSS and JavaScript interviews, along with how to prevent multiple submission of form data. Because of extensive uses of String, this knowledge is not only important from interview point of view but also from development point of view. It also helps to reduce subtle bugs in JavaScript code, which is introduce because of incorrect use of substr or substring method.

How to get Environment Variables in Java- Example Tutorial

Environment variables in Java
There are two ways to get environment variable in Java, by using System properties or by using System.getEnv(). System properties provides only limited set of predefined environment variables like java.classpath, for retrieving Java Classpath or java.username  to get User Id which is used to run Java program etc but a more robust and platform independent way of getting environment variable in Java program on the other hand System.getEnv() method provide access to all environment variables inside Java program but subject to introduce platform dependency if program relies on a particular environment variable. System.getEnv() is overloaded method in Java API and if invoked without parameter it returns an unmodifiable String map which contains all environment variables and there values available to this Java process while System.getEnv(String name) returns value of environment variable if exists or null. In our earlier posts we have seen How to get current directory in Java and  How to run shell command from Java program and in this Java tutorial we will see how to access environment variable in Java.

How to get environment variables in Java - Example

How to get value of environment variable in Java - example tutorialHere is a quick example on How to get environment variable in Java using System.getEnv() and System.getProperty(). Remember System.getEnv() return String map of all environment variables while System.getEnv(String name) only return value of named environment variable like JAVA_HOME will return PATH of your JDK installation directory.


/**
 * Java program to demonstrate How to get value of environment variables in Java.
 * Don't confuse between System property and Environment variable and there is separate
 * way to get value of System property than environment variable in Java, as shown in this
 * example.
 *
 * @author Javin Paul
 */


public class EnvironmentVariableDemo {  

    public static void main(String args[]){
   
      //getting username using System.getProperty in Java
       String user = System.getProperty("user.name") ;
       System.out.println("Username using system property: "  + user);
   
     //getting username as environment variable in java, only works in windows
       String userWindows = System.getenv("USERNAME");
       System.out.println("Username using environment variable in windows : "  + userWindows);
   
     
     //name and value of all environment variable in Java  program
      Map<String, String> env = System.getenv();
        for (String envName : env.keySet()) {
            System.out.format("%s=%s%n", envName, env.get(envName));
        }

    }
     
}

Output:
Username using system property: harry
Username using environment variable in windows : harry
USERPROFILE=C:\Documents and Settings\harry
JAVA_HOME=C:\Program Files\Java\jdk1.6.0_20\
TEMP=C:\DOCUME~1\harry\LOCALS~1\Temp


Getting environment variable in Java – Things to remember
Java is platform independent language but there are many things which can make a Java program platform dependent e.g. using a native library. Since environment variables also vary from one platform to another e.g. from windows to Unix you need to be bit careful while directly accessing environment variable inside Java program. Here are few points which is worth noting :

1) Use system properties if value of environment variable is available via system property e.g. Username which is available using "user.name" system property. If you access it using environment variable directly you may need to ask for different variable as it may be different in Windows  e.g. USERNAME and Unix as USER.

2) Environment variables are case sensitive in Unix while case insensitive in Windows so relying on that can again make your Java program platform dependent.

3) System.getEnv() was deprecated in release JDK 1.3 in support of using System.getProperty() but reinstated again in JDK 1.5.

That's all on how to get environment variable in Java. Though you have convenient method like System.getEnv() which can return value of environment variable, its better to use System.getProperty() to get that value in a platform independent way, if that environment variable is available as system property in Java.

Further Learning
Complete Java Masterclass
Java Fundamentals: The Java Language
Java In-Depth: Become a Complete Java Engineer!

Other How to tutorials from Javarevisited Blog