Saturday, September 30, 2017

How to String Split Example in Java - Tutorial

Java String Split Example
I don't know how many times I needed to Split a String in Java. Splitting a delimited String is a very common operation given various data sources e.g CSV file which contains input string in the form of large String separated by the comma. Splitting is necessary and Java API has great support for it. Java provides two convenience methods to split strings first within the java.lang.String class itself: split (regex) and other in java.util.StringTokenizer. Both are capable of splitting the string by any delimiter provided to them. Since String is final in Java every split-ed String is a new String in Java.

Difference between EnumMap and HashMap in Java

HashMap vs EnumMap in Java
What is the difference between EnumMap and HashMap in Java is the latest Java collection interview question which has been asked to a couple of my friends? This is one of the tricky Java questions, especially if you are not very much familiar with EnumMap in Java, which is not uncommon, given you can use it with only Enum keys. The main difference between EnumMap and HashMap is that EnumMap is a specialized Map implementation exclusively for Enum as key. Using Enum as key allows doing some implementation level optimization for high performance which is generally not possible with other objects as key. We have seen a lot of interview questions on HashMap in our article How HashMap works in Java but what we missed there is this question which is recently asked to some of my friends. Unlike HashMap, EnumMap is not applicable for every case but it's best suited when you have Enum as key. We have already covered basics of EnumMap and some EnumMap example in my last article What is EnumMap in Java and In this post, we will focus on key differences between HashMap and EnumMap in Java.

ORA-00904: invalid identifier Error in Oracle 11g database - Solved

If you have worked in Oracle database ever, you would definitely have seen ORA-00904: invalid identifier error. Doesn't matter which version you are working 10g, 11g or 12g, this is one of the most common error comes while doing CRUD (Create, Read, Update, and Delete) operations in Oracle. By the way, if you are beginner, SELECT, INSERT, UPDATE and DELETE are used to perform CRUD operation in Oracle database. What do you do if you get this error while running in SQL script? Like any error, you should first pay attention to error message, what is Oracle trying to say here. Invalid identifier means the column name entered is either missing or invalid, this is one of the most common cause of this error but not the only one. Some time it come if you use names, which happened to be reserved word in Oracle database. Now how do you resolve it?  We will learn in this article, by following series of examples which first reproduce this error and later suggest how to fix it.

How clone method works in Java?

The clone() is a tricky method from java.lang.Object class, which is used to create a copy of an Object in Java. The intention of the clone() method is simple, to provide a cloning mechanism, but somehow it's implementation became tricky and has been widely criticized from a long time. Anyway, we will not go to classic debate of clone in Java, at least for now; instead, we will try to learn how clone method works in Java. To be fair, understating cloning mechanism in Java is not easy and even experienced Java programmer fail to explain how cloning of mutable object works, or a difference between deep and shallow copy in Java.

Friday, September 29, 2017

Difference between trustStore and keyStore in Java - SSL

trustStore vs keyStore in Java
trustStore and keyStore are used in context of setting up SSL connection in Java application between client and server. TrustStore and keyStore are very much similar in terms of construct and structure as both are managed by keytoolcommand and represented by KeyStore programatically but they often confused Java programmer both beginners and intermediate alike. Only difference between trustStore and keyStore is what they store and there purpose. In SSL handshake purpose of trustStore is to verify credentials and purpose of keyStore is to provide credential. keyStore in Java stores private key and certificates corresponding to there public keys and require if you are SSL Server or SSL requires client authentication. TrustStore stores certificates from third party, your Java application communicate or certificates signed by CA(certificate authorities like Verisign, Thawte, Geotrust or GoDaddy) which can be used to identify third party. This is second article on setting up SSL on Java program, In last post we have seen How to import SSL certificates into trustStore and keyStore and In this Java article we will some differences between keystore and truststore in Java, which will help to understand this concept better.

How to remove all elements from ArrayList in Java - Clear vs RemoveAll

Many times we want to reset an ArrayList for the reusing purpose, by resetting we mean clearing it or removing all elements. There are two ways to reset an ArrayList in Java, by using clear() method or calling removeAll(). If your ArrayList is small enough e.g. contains only 10 or 100 elements then you can use any of these two methods without worrying too much, but, if you have a huge list of lots of objects e.g. an ArrayList containing 10M entries, then choice of clear() vs removeAll() can make a huge difference in performance of your Java application. Sometimes it's even better to create a new ArrayList instead of resetting the old one, especially if resetting takes a long time, but this also has a caveat, you need to make sure that old ArrayList is eligible for garbage collection, otherwise there is a huge risk of java.lang.OutOfMemoryError: Java Heap Space.

Thursday, September 28, 2017

Clean Architecture by Uncle Bob Martin - Book Review - Must read for Programmers

Hello Guys, today, I am very excited to talk about a new book (Clean Architecture: A Craftsman's Guide to Software Structure and Design) from one of my favorite author of programming books, you guessed it right, Uncle Bob. The same Uncle Bob (aka Robert Martin) who brought you the Clean Code and Clean Coder has been at it again. It's been a long time since I last read an Uncle Bob and somehow I wasn't aware of this book. It comes to me as a surprise yesterday when one of the colleagues mentioned it and I didn't take time to realize that I need to buy and read this book. I just cursed myself that why I didn't know about this book before, it is still new but given I love to read his books, it's just a miss for me.

Wednesday, September 27, 2017

Top 4 Books to learn Oracle PL/SQL Programming - Best, Must Read

In last summer, I had worked on a Java project which was using Oracle database at their backend. The project was a mix of Java code with Oracle PL/SQL stored procedures, where Stored procedures were quite big and complex to read. I had not worked on Oracle for a couple of years and almost forget whatever I knew before. So, to revise, update and re-learn and I looked over some of the books I remember would help me. In the search, I also find lots of their used books on Oracle PL/SQL which are both interesting to read as well as provide a great wealth of information to any programmer. These books are from application developer's perspective and not for DBAs.

Monday, September 25, 2017

Java 8 forEach() Loop Example

Java 8 has introduced a new way to loop over a List or Collection, by using the forEach() method of the new Stream class. You can iterate over any Collection e.g. List, Set or Map by converting them into a java.util.sttream.Stream instance and then calling forEach() method. This method performs given operation on every element of Stream, which can be either simply printing it or doing something else. Since stream can be sequential or parallel, the behavior of if this method is not deterministic if used with a parallel stream. One more thing to remember about the forEach() method is that it's a terminal operation, which means you cannot reuse the Stream after calling this method. It will throw IllegalStateException if you try to call another method on this Stream.

Sunday, September 24, 2017

Code Review Checklist and Best practices in Java

What to review while doing Code review
Code Review and Unit testing is one of best development practice I always recommend, strive for and enforce as much as possible. Even just by doing code review and Junit test case always offer positive result it can be improved a lot by constantly learning with our mistakes , others mistakes and by observing how others are doing it. I always try to get my code review by some one with more experience so that I can capture any domain specific scenario which has been missed during think through process and some with less experience so that he can improve his code readability, have a four eye check and most importantly I found that when i explain my code to some one as part of code review I myself discover many things which can be improved or left out.Overall it always add something and improve code quality and reduce bug.

How to convert String to Date in Java - SimpleDateFormat Example

SimpleDateFormat in Java can be used to convert String to Date in Java. java.text.SimpleDateFormat is an implementation of DateFormat which defines a date pattern and can convert a particular String which follows that pattern into Date in Java.This is the second part of the article on java.util.Date and String in Java. In the first part, we have seen How to convert Date to String in Java. SimpleDateFormat accepts a String in any date format e.g. yyyyMMdd is a date pattern and  20110924 is a String in that format. Now you want to create a java.util.Date object from this String. In this Java tutorial, we will see list steps to convert String to Date in Java and then we will see different examples of SimpleDateFormat with different date patterns e.g. ddMMyy or dd-MM-yyyy. Though converting String to Date is quite easy using SimpleDateFormat, but you need to remember that SimpleDateFormat is not thread-safe, which means you can not share the same instance of SimpleDateFormat between multiple threads. 

JSTL forTokens Tag Example - Split String in JSP

JSTL forTokens tag is another tag in core JSTL library to support Iteration or looping. It effectively complements, more useful <c:forEach> tag, by allowing you to iterate over comma separated or any delimited String. You can use this tag to split string in JSP and can operate on them individually. forTokens tag has similar attribute like forEach JSTL tag except one more attribute called delims, which specifies delimiter. For example to iterate over colon separated String "abc:cde:fgh:ijk", delims=":". By the way, forTokens tag also accept multiple delimiter, which means, you can split a big string into token based upon multiple delimiter e.g. colon(:) and pipe (|), This will be more clear, when we will see examples of JSTL forTokens tag in JSP. Rest of attribute e.g. items, var, varStatus, begin, end and step are same, as they are in case of <c:forEach> tag. For quick review, items specify String which needs to be split-ed in token and var hold current String.

Saturday, September 23, 2017

How to write Production quality code?

We often here the term "production quality code" , some times in interview where interviewee asked to write production quality code for a particular function,sometimes discussion between developers and programmers and sometimes during code review. I know most of you familiar with the term but for those who wonder what is production quality code in simple terms its code which can bear the test of time in a production environment.

We all develop code in development, then test in QA and finally it gets released in production. But there are a lot of difference between test and prod and if you have not coded taking prod environment in mind most likely code will fail in prod or result in exceptions.So what makes production environment different than development environment? Here are few things which I noted:

Variable argument or Varargs methods from Java 5 with Example - Programming Tutorial

Variable argument or varargs in Java allows you to write more flexible methods which can accept as many argument as you need. variable arguments or varargs were added in Java 1.5 along with great language features like Java Enum, Generics, auto boxing and various others. Variable arguments a relatively small feature but useful for a developer who has been well aware about method and array. Some time we have a scenario that one method can take variable number of argument  and now with varargs from language makes it much easier. In this Java tutorial we will see How variable arguments makes it easy to write convenient method which can accept any number of arguments,  perfect candidates are sum() and average() kind of methods.

This article is in continuation of exploring features of Java programming language. I have already covered fork-join framework from Java 7 and automatic resource management or ARM blocks, if you haven't read them already you may find them useful.

Friday, September 22, 2017

10 Tips to override toString() method in Java - ToStringBuilder Netbeans Eclipse

Java toString method
toString method in Java is used to provide clear and concise information about Object in human readable format. A correctly overridden toString method can help in logging and debugging of Java program by providing valuable and meaningful information. Since toString() is defined in java.lang.Object class and its default implementation don't provide much information, it's always a best practice to override the toString method in sub class. In fact, if you are creating value class or domain class e.g. Order, Trade or Employee,  always override equals,hashCode, compareTo and toString method in Java.  By default toString implementation produces output in the form package.class@hashCode e.g. for our toString() example, Country class’ toString() method will print test.Country@18e2b22 where 18e2b22 is hashCode of an object in hex format, if you call hashCode method it will return 26094370, which is decimal equivalent of 18e2b22. This information is not very useful while troubleshooting any problem. 

DispatcherServlet of Spring MVC - 10 things Java Developer should know

If you have worked with Spring MVC then you should know what is a DispatcherServlet? It's actually the heart of Spring MVC, precisely the C of MVC design pattern or Controller. Every single web request which is supposed to be processed by Spring MVC goes through DispatcherServlet. In general, its an implementation of Front Controller Pattern which provides a single point of entry in your application. It handles all incoming requests. It is also the bridge between Java and Spring and DispatcherServlet like any other Servlet is declared in the web.xml with a URL pattern enough to map every single web request to DispathcherServlert.

How to read File into String in Java 7, 8 with Example

Many times you want to read contents of a file into String, but, unfortunately, it was not a trivial job in Java, at least not until JDK 1.7. In Java 8, you can read a file into String in just one line of code. Prior to the release of new File IO API, you have to write a lot of boilerplate code e.g. open an input stream, convert that input stream into a Reader, and then wrap that into a BufferedReader and so on. Of course, JDK 1.5's Scanner class did provide some breathing space but it was still not as simple as it should be, like in Python or Ruby. By using Java 7 new File API and Java 8's new features like lambda expression and stream API, Java is now close to Python or other utility languages, when it comes to reading the file into String.

Common Multi-threading Mistakes in Java - Calling run() instead of start()

Writing multi-threaded and concurrent programs is not easy, not even in Java.  Even senior developers, including myself, make mistakes while writing concurrent Java applications. This is also one of the trickiest area of Java programming language, where misconceptions outnumbers concepts. Considering amount of misconception an average Java programmers has about multi-threading and concurrency, I thought to start a new series about common multi-threading mistakes done by Java programmers; what is better way to learn from common real word mistakes. Learning from mistakes has another name Experience, but if you only learn from your mistakes then there is only limited things you can learn, but if you learn from other peoples mistake, you can learn much more in short span of time. Have you ever thought, Why writing multi-threaded code is difficult? IMHO, primarily reason for this is that it multi-threading makes it hard for a code to speak for itself. Programmer read code sequentially to understand how it's executed, but it is only correct if one and only one thread is executing it. That's why Single threaded code are easy to read and debug. As soon as two threads comes into picture, It become very difficult to make prediction about how your code behave, especially in the absent of any synchronization rules e.g. rules enforced by Java Memory Model. Without JMM you can not make correct prediction about your code in a multi-threaded environment, because it's possible for one thread to stop at arbitrary point and another thread at different point. Situation becomes even more tricky if those threads are sharing data between them e.g. in form of objects, a poorly written multi-threaded program can cause deadlock, race condition and responsiveness issues, which will prevent a Java application to fulfil it's promise. I hope, in this series we can learn from each other's mistake and take a step forward on writing correct multi-threaded application in Java.

Thursday, September 21, 2017

How to determine Type of object at runtime in Java - Runtime Type Identification

Runtime Type identification in Java
Determining Type of object at runtime in Java means finding what kind of object it is. For those who are not familiar with What is a Type in Java,  Type is the name of class e..g for “abc” which is a String object, Type is String. Finding Type of any object at runtime is  also known as Runtime Type Identification in Java. Determining Type becomes increasingly important for a method which accepts parameter of type java.lang.An object like compareTo method of the Comparable class. Since two objects of different type can not be equal to each other if we know how to determine the type of Object from the object itself then we can, not only avoid ClassCastExcpetion but also optimized the equals method. Java provides three different ways to find the type of object at runtime e.g. instanceof keyword, getClass() and isInstance() method of java.lang.Class. Out of all three only getClass() is the one which exactly find Type of object while others also return true if Type of object is the super type. 

10 examples of displaytag in JSP, Struts and Spring

Display tag is one of the best free open source libraries for showing data in tabular format in a J2EE application using jsp, struts or spring. it is shipped as tag library so you can just include this  in your jsp and add corresponding jar and there dependency in class-path and you are ready to use it. Display tag is my favorite solution for displaying any tabular data because of its inherent capability on paging and sorting. It provides great support for pagination on its own but it also allows you to implement your own pagination solution. On Sorting front you can sort your data based on any column, implement default sorting etc.

Wednesday, September 20, 2017

Difference between HashMap and HashSet in Java

HashMap vs HashSet is the most frequently asked question during any core java interview and interview is not said completed until they will not cover the Collection Framework and multi-threading interview and collections are uncompleted without Covering Hash Set and HashMap.
Both HashMap and HashSet are part of collection framework which allows us to work with a collection of objects. Collection Framework has their own interfaces and implementation classes. Basically, a collection is divided as Set Interface, List, and Queue Interfaces. All these interfaces have their own property also apart from they get from a collection like Set allows Collection of objects but forbids duplicate value, List allows duplicate along with indexing.Queue works on FCFS algorithm.

Tuesday, September 19, 2017

How to Create Complex directory Tree Using mkdir -p Command in UNIX

One of the most common task in any Linux is creating directories, and most of us spend a lot of time creating complex directory structure in UNIX.  I am sure you know about mkdir command, we have been using this command in almost every operating system e..g DOS, Windows, Linux, OS/2, Solaris or many other *NIX operating system. It is one of the basic command but as important as find, grep or chmod.  mkdir stands for "make directory" and this command is literally used to create directories. Suppose, you need to create a directory tree like /opt/software/java/app/config, how are you going to create these directories? One by one right? Well, yes you can use mkdir and command to create these directories one by one as shown in below example :

Monday, September 18, 2017

Eclipse - java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet in Tomcat

Problem : You are getting java.lang.ClassNotFoundException exception complaining that Spring's DispatcherServlet class is not available in the classpath. This error is coming while running a Spring MVC based Java application from Eclipse and Tomcat as Server (running inside Eclipse IDE itself). You have either included spring framework JAR files manually by yourself or you are using Maven to download and manage dependent JAR files. Here is the stack trace of this error :

java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1678)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1523)
    at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:525)
    at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:507)
    at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:126)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1099)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1043)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4957

Sunday, September 17, 2017

10 Interview Questions Every Programmer Should Know

Conducting Interview is not cheap and costs both time and money to a company. It take a lot of time to find the right candidate for a job from 100s resume you receive from consultants and agents. They will always tell you that this guy is a Java Guru, this one is SQL Expert and next one is the full stack developer you are looking for. If you have trust them blindly and invite all of them for face-to-face interview, you are going to be disappointed. One of the first thing you should do is to filter candidates who claims to have certain skills e.g. SQL but doesn't have them, the faster you can weed out those candidates the cheaper will be the hiring process. A phone screening interview is just for that purpose, it doesn't cost you much and also suitable for candidate, as they don't have to take off and come down to your office. It's flexible for both the parties.

Saturday, September 16, 2017

How to Convert Date to String in Java with Example

Some times we need to convert java.util.Date to string in java  may for displaying purpose I need it that while working on displaytag then I thought about this article  to list down various way of converting this in various ways, after some reading I found that SimpleDateFormat makes this quite easy. To get the feel of Date API in java and to familiarize ourselves with these classes we will see different examples of converting date to String in our application. Both DateFormat and SimpleDateFormat class belongs java.text package and they are very powerful and you can use them for conversion. it also good for parsing string into date and can be used to show in various locale also.

Difference between SendRedirect() and Forward() in JSP Servlet

Difference between SendRedirect and forward is one of classical interview questions asked during java web developer interview. This is not just applicable for servlet but also for JSP in which we can use forward action or call sendRedirect() method from scriptlet. Before examining difference on forward and SendRedirect let’s see what send Redirect method and forward method does.

SendRedirect ():  

This method is declared in HttpServletResponse Interface.

Signature: void sendRedirect(String url)

Difference between Primitive and Reference variable in Java

There are two types of variables in Java, primitive and reference type. All the basic types e.g. int, boolean, char, short, float, long and double are known as primitive types. JVM treats them differently than reference types, which is used to point objects e.g. String, Thread, File and others. Reference variables are not pointers but a handle to the object which is created in heap memory. The main difference between primitive and reference type is that primitive type always has a value, it can never be null but reference type can be null, which denotes the absence of value. So if you create a primitive variable of type int and forget to initialize it then it's value would be 0, the default value of integral type in Java, but a reference variable by default has a null value, which means no reference is assigned to it.

What is EnumMap in Java – Example Tutorial

What is EnumMap in Java
EnumMap in Java is added on JDK  5 release along with other important features like  Autoboxing, varargs and Generics. EnumMap is specialized Map implementation designed and optimized for using Java Enum as key. Since enum can represent a type (like class or interface)  in Java and it can also override equals() and hashCode() , It can be used inside HashMap or any other collection but using  EnumMap brings implementation specific benefits which are done for enum keys, In short EnumMap is optimized Map implementation exclusively for enum keys . As per Javadoc Enum is implemented using Arrays and common operations result in constant time. So if you are thinking of an high-performance Map, EnumMap could be a decent choice for enumeration data. We have already seen many examples of Java enum in our article 10 Examples of enum in Java  and using Enum as thread-safe Singleton. In this Java tutorial, we will see simple examples of using EnumMap in Java. 

Friday, September 15, 2017

6 Books to Learn and Master Programming and Coding - Must Read

Coding is an integral part of programming and we all somehow learn to code by following examples here and there. What is more difficult is to write good code. You can easily find programmers in Java, C++, Ruby or Python, but finding programmers, who are also a good coder is very difficult. Some universities have a good curriculum and practical classes to teach coding better than others, but most of these great codes are self-taught. The point is self-learning is VERY important in the field of Programming and Coding, you just cannot rely on your college and university to make you an expert programmer, you have to make that extra effort to distinguish yourself from the group. What could be best by learning coding and wisdom of programming from those who have gone through the same path?

How to use Fork Join in Java 1.7 - Tutorial with Example

What is fork Join framework in Java: Already popular project coin of JDK7 release has presented a lot of good feature e.g automatic resource management, string in switch case, better exception handling in JDK7 etc. On of another important feature to note is fork-join as name implies it divide one task into several small task as a new fork means child and join all the fork when all the sub-tasks complete. Fork/join tasks is “pure” in-memory algorithms in which no I/O operations come into picture.it is based on a work-stealing algorithm. Concept of fork join would be much clear by following diagram.

Thursday, September 14, 2017

Difference between save vs persist and saveOrUpdate in Hibernate

Save vs saveOrUpdate vs persist in Hibernate
What is difference between save and saveOrUpdate or Difference between save and persist are common interview question in any Hibernate interview, much like Difference between get and load method in Hibernate. Hibernate Session class provides couple of ways to save object into database by methods like save, saveOrUpdate and persist.  You can use either save(),  saveOrUpdate() or persist() based upon your requirement for persisting object into Database. Along with Spring framework Interview questions, Hibernate questions are also quite popular on J2EE interviews because of its status as leading ORM. It’s good to prepare some questions from Hibernate before appearing in any J2EE interviews. One of them is Difference between save , saveOrUpdate and persist, which we will see in this Hibernate article.

InvokeLater and InvokeAndWait in Java Swing (an example tutorial)

Everyone who is doing programming in java swing has to come across invokeAndWait and invokeLater provided by SwingUtilites. In this java swing tutorial we will learn about both invokeLater() and invokeAndwait() method. In first part we will mostly focus on invokeLater and will find answers to questions like What is invokeLater, how to use invokelater in java swing, example of invokelater in swing etc while in second part of this invokeLater tutorial we will learn more about invokeAndWait method in java swing and will learn Why we need InvokeAndWait, how to use InvokeAndWait method in java Swing and differences between invokelater and invokeAndWait.

Finally, we will see a code example of both invokeLater and invokeAndWait in Swing and will be able to decide when to use invokeLater and when to use invokeAndWait while doing Swing programming.  We will also see famous Swing interview questions "difference between invokeLater and invokeAndWait" at the end of the article.

Monday, September 11, 2017

3 Examples of Parsing HTML File in Java using Jsoup

HTML is core of web, all the page you see in internet are HTML, whether they are dynamically generated by JavaScript, JSP, PHP, ASP or any other web technology. Your browser actually parse HTML and render it for you. But what would you do,  if you need to parse an HTML document and find some elements,  tags, attributes or check if a particular element exists or not from Java program. If you have been in Java programming for some years, I am sure you have done some XML parsing work using parsers like DOM and SAX, but there is also good chance that you have not done any HTML parsing work. Ironically, there are few instances when you need to parse HTML document from core Java application, which doesn't include Servlet and other Java web technologies. To make the matter worse, there is no HTTP or HTML library in core JDK as well; or at least I am not aware of that. That's why when it comes to parse a HTML file, many Java programmers had to look at Google to find out how to get value of an HTML tag in Java. When I needed that I was sure that there would be an open source library which will does it for me, but didn't know that it was as wonderful and feature rich as JSoup. It not only provides support to read and parse HTML document but also allows you to extract any element form HTML file, their attribute, their CSS class in JQuery style and also allows you to modify them. You can probably do anything with HTML document using Jsoup. In this article, we will parse and HTML file and find out value of title and heading tags. We will also see example of downloading and parsing HTML from file as well as any URL or internet by parsing Google's home page in Java.

How to find IP Address from hostname in Windows Linux and Unix

IP Address from hostname in Windows and Linux
How many times in a day you have a hostname and you want to know the IP address? Host name to IP address and IP address to hostname conversion is one of frequent thing which we need to do for many things when dealing with networking command in Unix. For one command we need an IP address for other we need hostname even from bash script sometimes we require hostname and sometimes we look for IP address. networking commands are not as popular as find command or grep command but they are equally important and if you working in Windows or UNIX environment you must learn them and they should also be included in any list of Unix commands for beginners. By the way, In this hostname to IP address tutorial, I will show you how to get IP address from hostname or computer name in Unix or Linux and how to get hostname if you have IP address. If you are looking a way to do it via Java program then you can also see my post how to find IP address of localhost in Java.

How to convert float to long or int in Java?

Yesterday one of the junior from my team came to me asking about how do you I convert a float variable into long or int? He was storing some values coming from another system in the database and only wanted to store value before the decimal point e.g. he was getting "3.144" and he want to convert it to "3" to store into database. Good thing was that API was returning a float primitive value and you don't need to convert a String to float etc. There are 3 ways to convert a float value into long or int in Java, but we will only focus on long part. You can write the Java program by following tips to convert float to an int by replacing long method to their int counterpart. The first way is to auto-box float primitive into Float object and call the longVale() method and another way is simply cast a float to long or int to get rid of decimal points.

Sunday, September 10, 2017

Java 8 - Sorting HashMap by values in ascending and descending order

In the last article, I have shown you how to sort a Map in Java 8 by keys and today, I'll teach you how to sort a Map by values using Java 8 features e.g. lambda expression, method reference, streams, and new methods added into the java.util.Comparator and Map.Entry classes. In order to sort any Map e.g. HashMap, Hashtable, LinkedHashMap, TreemMap, or even ConcurrentHashMap, you can first get set of entries by using the entrySet() method and then you can get the stream by calling the stream() method. The entrySet()  method returns a Set which inherit the stream() method from the java.util.Collection class. Once you got the stream, you can just call the sorted() method which can sort all Map.Entry objects available in Stream using a Comparator.

Saturday, September 9, 2017

How to work with transient variable in java (an example tutorial)

Transient keyword in java is comparatively less common than any other keyword like volatile.since transient is less common it becomes even more important to understand the correct usage of it. In One-word transient keyword is used in serialization process to prevent any variable from being serialized, so if you have any field which is not making sense to serialize, you can simply declare that as transient and it won't be serialized.In this article we will revise some basics like What is transient variable in java, why do we need transient variable and most importantly where should we use transient variable or which fields need to be declared as transient with example.

Maven JAR Artifiact Dependency Search Not Working in Eclipse - Solved

Recently I face an strange issue while using Maven in Eclipse via M2Eclipse plugin. I have created a Maven Java project in Eclipse and subsequently tried to add Spring framework as dependency, to my surprise, nothing was happening. Eclipse was not able to search dependency in Maven central repository. I was surprised because I have never faced this issue while I was using M2Eclipse plugin from long time. After some trial and error, I realized that this is my brand new workspace and I am running with Eclipse Luna, newest version of Eclipse which I had just downloaded couple days of back. My first hunch was that Eclipse might not able to connect to Internet, and to verify that I tried connecting Eclipse market place, and boom it was working fine. Then I quickly checked Maven settings in Eclipse and found that the option which is required to download and build the index was not turned on. The check box was unchecked there. To give you some background about how Eclipse search dependency on Maven remote repository, be it default Maven central or internal Nexus repository. Eclipse search artifact dependency on repository's index file. If that file is not download or not exist due to any reason, Maven's dependency search will not work in Eclipse. That's why you need to check the option "Download repository Index updates on startup". If this option is enabled then Eclipse will download repository index from configured location e.g. Maven central or Nexus and every time Eclipse will start it will just do update. You should also check the option "Do not automatically update dependencies from remote repositories", because that will download latest build every time they were pushed into Maven central repository. By the way, this error has nothing to do with Eclipse Luna. I received emails from my readers that some of them not able to add dependency in Maven project even in older versions of Eclipse e.g. Kepler and Indigo version. It is totally due to absent of artifact index file. One you enable "Download repository Index updates on startup" option and restart Eclipse, you will see that Eclipse is updating index at the bottom right corner, once this update this finish, you would be able to add dependency using Eclipse Maven GUI. In worst case, if your problem doesn't resolve even after enabling and restarting Eclipse, try re-building Index from Maven repository view in Eclipse, as shown in images attached here.

Friday, September 8, 2017

What is @SuppressWarnings annotation in Java? Unchecked, RawTypes, Serial

@SuppressWarnings annotation is one of the three built-in annotations available in JDK and added alongside @Override and @Deprecated in Java 1.5. @SuppressWarnings instruct the compiler to ignore or suppress, specified compiler warning in annotated element and all program elements inside that element. For example, if a class is annotated to suppress a particular warning, then a warning generated in a method inside that class will also be separated. You might have seen @SuppressWarnings("unchecked") and @SuppressWarnings("serial"), two of most popular examples of @SuppressWarnings annotation. Former is used to suppress warning generated due to unchecked casting while the later warning is used to remind about adding SerialVersionUID in a Serializable class.

ARM- Automatic resource management in Java7 an example tutorial

ARM automatic resource management is  another attractive features of Java 7 and project coin. As name itself implies that now JVM is going to be handling all the external resource and make programmer free to bother about resource management.  If my java programmers use any external resources like file, printer or any devices to close after my program execution complete. Normally we close the resources which we have open in beginning of our program or we decide that if program finish normally how to manage the resource or if our program finish abnormally how to close the resource.

Wednesday, September 6, 2017

Difference between ArrayList and Vector in Java

ArrayList and Vector are two of most used class on java collection package and difference between Vector and ArrayList is one of the most frequently asked java interview question on first round or phone interview. Though it’s quite a simple question in my opinion but knowledge of when to use Vector over ArrayList or does matter if you are working on a project. In this article we will some point based difference between Vector and ArrayList in Java and trying to understand the concept behind those differences. Ultimate goal is to familiarize yourself with distinguish property of ArrayList and Vector. By the way Java 5 adds another implementation of List interface which is similar to Vector and ArrayList but provides better concurrency access than Vector, its called CopyOnWriteArrayList. By the way this is the third article on discussing about Collection interview question,  Difference between LinkedList and ArrayList  and   List vs Set are other popular interview questions based upon collection framework in Java.

Monday, September 4, 2017

How to loop over two dimensional array in Java?

You can loop over a two-dimensional array in Java by using two for loops, also known as nested loop. Similarly to loop an n-dimensional array you need n loops nested into each other. Though it's not common to see an array of more than 3 dimension and 2D arrays is what you will see most of the places. It's one of the most useful data structure in the programming world. You can use a two-dimensional array to make finite state machine (FSM) solve state based problems, you can use a 2D array to create board games like Chess, Sudoku and Tic-Tac-To and you can even use a two-dimensional array to create 2D arcade games e.g. Tetris, Super Mario Bros and so on. Whatever you see on your screen is nothing but a 2D array which is populated using tiles.

Saturday, September 2, 2017

2 solution of java.lang.OutOfMemoryError in Java

Everyone in java development faces java.lang.OutOfMemoryError now and then, OutOfMemoryError in Java is one problem which is more due to system's limitation (memory) rather than due to programming mistakes in most cases though in certain cases you could have a memory leak which causing OutOfMemoryError. I have found that even though java.lang.OutOfMemoryError is quite common basic knowledge of its cause and solution is largely unknown among junior developers. Beginners books like Head First Java doesn't teach you much about how to deal with this kind of error. You need real experience dealing with production systems, handling a large number of user sessions to troubleshoot and fix performance issues like running out of memory.

Why you should control Visibility of Class and Interface in Java

One of the important aspect of software development is maintenance, and  it's proven by experience that a software which keeps visibility of its component low is more maintainable than the one who exposes its component more. You won't realize it upfront, but you will miss it badly, while redesigning your application. Since maintaining backward compatibility is must have requirement for many app, you end up patching and repeating same mistakes. You can not do much because lots of other applications are tightly integrated with your class and interfaces. Java has always put encapsulation on priority, provided support of access modifiers from very beginning. It provides three ways to control visibility of any Type e.g. class or interface, by making them public, package-private or private. What happened to protected, can't we use protected with class or interface. No you can't, you can only use two access modifier with types, protected is not a legal modifier for class and interface.

Friday, September 1, 2017

How to replace escape XML special characters in Java String

How to replace XML special Characters in Java String
There are two approaches to replace XML or HTML special characters from Java String, First,  Write your own function to replace XML special characters or use any open source library which has already implemented it. Luckily there is one very common open source library which provides a function to replace special characters from XML String is Apache commons lang’s StringEscapeUtils class which provide escaping for several  languages like XML, SQL, and HTML. you can use StringEscapeUtils to convert XML special character in String to their escaped equivalent. I personally like to use open source code instead of reinventing the wheel to avoid any testing efforts. Even Joshua Bloch as advocated use of Open source library to leverage the experience and work of other programmers. If you are reading from XML file and after doing some transformation writing to another XML file , you need to take care of XML special characters present in the source file. If you don’t escape XML special characters while creating XML document than various XML parsers like DOM and SAX parser will consider those XML meta consider them as XML tag in case of < or >. 

Java program to find IP Address of localhost - Example Tutorial

How to find IP address of local host from Java program
Java networking API provides method to find IP address of localhost from Java program by using java.net. InetAddress class. It’s rare when you need IP address for localhost in Java program. Mostly I used Unix command to find IP address of localhost. For all practical purpose where program doesn’t need IP address but you need to troubleshoot any networking issues, Use DOS or windows command or Use Linux commands. Recently one of my friend faced this question in a core Java interview, where they are expecting Java developer with some socket programming experience, But until you know or you have done it before its hard to answer this fact based question, which motivates me to write this post. In this Java tutorial we will see How to find IP address of localhost from Java program. By the way it’s also good to remember list of Unix networking commands to troubleshoot any networking issues related to Java application in Unix environment.