Tuesday, October 31, 2017

How to Convert Double to String to Double in Java Program with Example

Many scenarios come in day to day Java programming when we need to convert a Double value to String or vice versa. In my earlier article we have seen how to convert String to Integer and in this article, we will first see how to convert double to String and the later opposite of  that from String to double. One important thing to note is Autoboxing which automatically converts primitive type to Object type and only available from Java 5 onwards. This conversion example assumes the code is running above Java 5 version and actually tested in JDK 1.6, which makes it unable to pass Double object when the method is expecting double primitive value e.g. String.valueOf(double d) which expect a double value.

Monday, October 30, 2017

How to Stop Thread in Java Code Example

The thread is one of important Class in Java and multithreading is most widely used a feature,but there is no clear way to stop Thread in Java. Earlier there was a stop method exists in Thread Class but Java deprecated that method citing some safety reason. By default, a Thread stops when execution of run() method finish either normally or due to any Exception.In this article, we will How to Stop Thread in Java by using a boolean State variable or flag. Using a flag to stop Thread is a very popular way  of stopping the thread and it's also safe because it doesn't do anything special rather than helping run() method to finish itself.

Sunday, October 29, 2017

What is static import in Java 5 with Example

Static import in Java allows to import static members of class and use them, as they are declared in the same class. Static import is introduced in Java 5 along with other features like Generics, Enum, Autoboxing and Unboxing and variable argument methods. Many programmer think that using static import can reduce code size and allow you to freely use static field of external class without prefixing class name on that. For example without static import you will access static constant MAX_VALUE of Integer class as Integer.MAX_VALUE but by using static import you can import Integer.MAX_VALUE and refer it as MAX_VALUE. Similar to regular import statements, static import also allows wildcard * to import all static members of a class. In next section we will see Java program to demonstrate How to use static import statements to import static fields.

Saturday, October 28, 2017

How to use multiple JQuery UI Date Picker or Datepicker in HTML or JSP page

We often needs to use multiple JQuery date picker in one HTML or JSP page, classical example is online flight booking for return trips, where you need to pick departure date and arrival date from two separate datepickers. While designing HTML forms either statically or dynamically using JSP, you may want to associate date picker with multiple input text field, paragraph or any other HTML elements. By using JQuery UI and some help from CSS ID and class selector, we can easily use multiple datepicker in one HTML page. All you need to do is, declare a CSS class say .datepicker and apply that class to all HTML elements which needs date picker, for example we have associated date picker with 4 input text fields, which has .datepicker class. By using a class, it becomes extremely easy to select all those element using JQuery class selector, and once you got all those element, you can just call datepicker() methods. This method does all the hard-work and associate a date picker object with selected items, that's it. Now you are ready to use multiple date picker in your HTML or JSP page, let's see the complete code. By the way if you are just starting with jQuery than I highly recommend Head First Query, it’s easy to read  and contain some non trivial example to learn jQuery quickly.

Friday, October 27, 2017

What is difference between java.sql.Time, java.sql.Timestamp and java.sql.Date - JDBC interview Question

Difference between java.sql.Time, java.sql.Timestamp and java.sql.Date  is most common JDBC question appearing on many core Java interviews. As JDBC provides three classes java.sql.Date, java.sql.Time and java.sql.Timestamp to represent date and time and you already have java.util.Date which can represent both date and time, this question poses lot of confusion among Java programmer and that’s why this is one of those tricky Java questions which is tough to answer. It becomes really tough if differences between them is not understood correctly. We have already seen some frequently asked or common JDBC questions like why JDBC has java.sql.Date despite java.util.Date and Why use PreparedStatement in Java in our last tutorials and we will see difference between java.sql.Date, java.sql.Time and java.sql.Timestamp in this article. By the way apart from these JDBC interview questions, if you are looking to get most from JDBC you can also see 4 JDBC performance tips and 10 JDBC best practices to follow. Those article not only help you to understand and use JDBC better but also help on interviews. Let’s come back to difference sql time, timestamp and sql date.

Thursday, October 26, 2017

JSTL foreach tag example in JSP - looping ArrayList

JSTL  foreach loop in JSP
JSTL  foreach tag is pretty useful while writing Java free JSP code.  JSTL foreach tag allows you to iterate or loop Array List, HashSet or any other collection without using Java code. After introduction of JSTL and expression language(EL) it is possible to write dynamic JSP code without using scriptlet which clutters jsp pages. JSTL foreach tag is a replacement of for loop and behaves similarly like foreach loop of Java 5 but still has some elements and attribute which makes it hard for first-timers to grasp it. JSTL foreach loop can iterate over arrays, collections like List, Set and print values just like for loop. In this JSP tutorial we will see couple of example of foreach loop which makes it easy for new guys to understand and use foreach loop in JSP. By the way this is our second JSP tutorial on JSTL core library, in last tutorial we have seen How to use core <c:set> tag in JSP page.

How to replace NULL with Empty String in SQL Server? ISNULL() vs COALESCE() Examples

We often need to replace NULL values with empty String or blank in SQL e.g. while concatenating String. In SQL Server, when you concatenate a NULL String with another non-null String the result is NULL, which means you lose the information you already have. To prevent this, you can replace NULL with empty String while concatenating. There are two ways to replace NULL with blank values in SQL Server, function ISNULL() and COALESCE(). Both functions replace the value you provide when the argument is NULL e.g. ISNULL(column, '') will return empty String if the column value is NULL. Similarly, COALESCE(column, '') will also return blank if the column is NULL.

Wednesday, October 25, 2017

Eclipse shortcut to System.out.println in Java program - Tips

Eclipse IDE provides quick shortcut keys to print System.out.println statement in Java but unfortunately not every Java programmers are familiar of that.  Even programmers with 3 to 4 year of experience sometimes doesn't know this useful Eclipse shortcut to generate System.out.println messages.  This Eclipse tips is to help those guys. Let me ask you one question, How many times you type System.out.println in your Java program?  I guess multiple time,  while doing programming, debugging and testing small stuff.  System.out.println is the most preferred way to print something on console because it doesn’t required setup like configuring Log4J or java.util.Logger . Though I recommend using logging for better information display in production code, nobody can undermine importance of System.out.println statement in Java. On the quest of learning Eclipse shortcut, some of them which I have discussed in my list of Top 30 Eclipse shortcut for Java programmers,  I found a very useful Eclipse shortcut for generating code for System.out.println statement in Java source file. 

Java program to calculate area of Triangle - Homework, programming exercise example

Calculate area of Triangle in Java
Write a Java program to calculate Area of Triangle, accept input from User and display output in Console is one of the frequently asked homework question. This is not a tough programming exercise but a good exercise for beginners and anyone who has started working in Java. For calculating area of triangle using formula 1/2(base*height), you need to use arithmetic operator. By doing this kind of exercise you will understand how arithmetic operators works in Java, subtle details which affect calculation like precedence and associativity of operator etc. Fortunately this question is not very popular on Java interview like other exercise we have seen e.g. Java program to print Fibonacci series and Java program to check for palindrome. Nevertheless its a good Java homework.

Monday, October 23, 2017

How to Implement Binary Search Tree in Java? Example

A binary search tree or BST is a popular data structure which is used to keep elements in order. A binary search tree is a binary tree where the value of a left child is less than or equal to the parent node and value of the right child is greater than or equal to the parent node. Since its a binary tree, it can only have 0, 1 or two children. What makes a binary search tree special is its ability to reduce the time complexity of fundamental operations like add, remove and search, also known as insert, delete and find. In a BST, all these operations (insert, remove and find) can be performed in O(log(n)) time. The reason for this improvement in speed is because of the unique property of binary search tree, where for each node, the data in the left child is less than (or equal) and the data in the right child is greater than (or equal) to the data in said node.

Sunday, October 22, 2017

Tibco tutorial : Certified Messagging

This is in continuation of my previous tibco tutorial. tibco rv is most widely used middleware in enterprise world heavily used in banking and many global investment bank rely on tibco rv for there high speed messaging requirement. its used by many trading application to receive high speed data e.g. Market data. in reliable mode tibco provide reliable delivery of data but not guaranteed means if sender sends data to receiver via tibco multicast network , tibco tries best to deliver that data to receiver but there is no guarantee, data could be lost if receiver is too busy to receive it , if receiver is not running or receiver is hang. In some cases its possible to recover lost data by sending "Resend Request".

Friday, October 20, 2017

5 ways to add multiple JAR in to Classpath in Java

How to add JAR file to Classpath in Java
Adding JAR into classpath is a common task for Java programmer and different programmer do it on different way. Since Java allows multiple ways to include JAR file in classpath, it becomes important to know pros and cons of each approach and How exactly they work. There are 5 ways to add  jars on into classpath in Java some of them we have already seen in  How classpath works in Java and How to set Path in Java. In this post we will revisit some of those techniques and explore Java 1.6 wildcard to add multiple JAR into classpath. By the way here is 5 ways to add JAR file into classpath. In short knowledge of Path, Classpath and Classloaders are must for any Java programmer, not only from knowledge point of view but also to successfully debug and resolve issues related to Classpath e.g. NoClassDefFoundError and java.lang.ClassNotFoundException  in Java.

What is Iterator and ListIterator in Java Program with Example - Tutorial Code Sample

Iterator in Java is nothing but a traversing object, made specifically for Collection objects like List and Set. we have already aware about different kind of traversing methods like for-loop ,while loop,do-while,for each lop etc,they all are  index based traversing but as we know Java is purely object oriented language there is always possible ways of doing things using objects so Iterator is a way to traverse as well as access the data from the collection. Even with traversing with object we have Enumeration, Iterator and ListIterator in Java which we will in this Java Iterator tutorial.

Thursday, October 19, 2017

Regular Expression in Java to check numbers in String - Example

Regular Expression to check numeric String
In order to build a regular expression to check if String is number or not or if String contains any non digit character or not you need to learn about character set in Java regular expression, Which we are going to see in this Java regular expression example. No doubt Regular Expression is great tool in developer arsenal and familiarity or some expertise with regular expression can help you a lot. Java supports regular expression using java.util.regex.Pattern and java.util.regex.Matchter class, you can see a dedicated package java.util.regex for regular expression in Java. Java supports regex from JDK 1.4, means well before Generics, Enum or Autoboxing. If you are writing server side code in Java programming language than you may be familiar with importance of regular expression which is key in parsing certain kind of messages e.g. FIX Messages used in Electronic trading. In order to parse Repeating groups in FIX protocol you really needs understanding of regular expression in Java. Any way In order to learn validating numbers using regular expression we will start with simple example

Difference between private, protected, public and package modifier or keyword in Java

private vs public vs protected vs package in Java
Java has four access modifier namely private, protected and public. package level access is default access level provided by Java  if no access modifier is specified. These access modifiers are used to restrict accessibility of a class, method or variable on which it applies. We will start from private access modifier which is most restrictive access modifier and then go towards public which is least restrictive access modifier, along the way we will see some best practices while using access modifier in Java and some examples of using private and protected keywords.

Difference between Truncate and Delete command in SQL - Interview Questions with Example

Truncate and delete in SQL are two commands which are used to remove or delete data from a table. Though quite basic in nature both SQL commands can create a lot of trouble until you are familiar with details before using it. The difference between Truncate and delete are not just important to understand perspective but also a very popular SQL interview topic which in my opinion a definite worthy topic. What makes them tricky is the amount of data. Since most of Electronic trading system stores large amount of transactional data and some even maintain historical data, a good understanding of delete and the truncate command is required to effectively work in that environment.I have still seen people firing delete command just to empty a table with millions of records which eventually lock the whole table for doing anything and take ages to complete or Simply blew log segment or hang the machine.

Monday, October 16, 2017

10 Garbage Collection Interview Questions and Answers in Java Programming

GC Interview Questions Answer in Java
Garbage collection interview questions are very popular in both core Java and advanced Java Interviews. Apart from  Java Collection and Thread  many tricky Java questions stems Garbage collections which are tough to answer. In this Java Interview article I will share some questions from GC which is asked in various core Java interviews.These questions are based upon concept of How Garbage collection works, Different kinds of Garbage collector and JVM parameters used for garbage collection monitoring and tuning. As I said GC is an important part of any Java interview so make sure you have good command in GC. One more thing which is getting very important is ability to comprehend and understand Garbage collection Output, more and more interviewer are checking whether candidate can understand GC output or not. During Java interview they may provide a snippet of GC output and ask various questions based on that e.g. Which Garbage collector is used, whether output is from major collection or minor collection, How much memory is free from GC, What is size of new generation and old generation after GC etc. I have included few Garbage collection interview questions and answers from GC output to help with that. It’s recommended to prepare questions from Java collection,  multithreading and programming along with Garbage collection to do well in Java interviews at any stage.

Sunday, October 15, 2017

How to convert decimal to binary, octal and hex String in Java Program

This article is a simple Java program which converts the decimal number to binary, octal and hexadecimal format. When it first came into my mind I though I would probably need to write whole code to convert decimal to various other radix or base numbers but when I looked Integer class and saw these two way of converting decimal to binary etc I was simply amazed. It’s indeed extremely easy to do this in java and you can also write this program or use it is.

FIX Log Viewer - Tool to view FIX messages in Readable format

It's been a long time, I wrote anything related to FIX protocol, my last article was about FIX protocol dictionaries, also known as Fixionnary, one of the most important tools of the trade for Java developers and support personnel working in FIX. Today, I am going to share another useful tool called FIX Log Viewer, which allows you to view FIX engine logs in a much more readable format.

Saturday, October 14, 2017

10 Example Queries of SQL Select Command

The Select command in SQL is one of the most powerful and heavily used commands. This is I guess the first command anyone learn in SQL even before CREATE which is used to create a table in SQL. SELECT is used in SQL to fetch records from database tables and you can do a lot many things using Select. For example, you can select all records, you can select few records based on the condition specified in WHERE clause, select all columns using the wild card (*) or only selecting a few columns by explicitly declaring them in a query.

How to Use Locks in Multi-threaded Java Program

Many Java programmers confused themselves like hell while writing multi-threaded Java programs e.g. where to synchronized? Which Lock to use? What Lock to use etc. I often receive request to explain about how to use Locks in Java, so I thought to write a simple Java program, which is multi-threaded and uses rather new Lock interface. Remember Lock is your tool to guard shared resource which can be anything e.g. database, File system, a Prime number Generator or a Message processor. Before using Locks in Java program, it’s also better to learn some basics. Lock is an interface from java.util.concurrent package. It was introduced in JDK 1.5 release as an alternative of synchronized keyword. If you have never written any multi-threading program, then I suggest first start with synchronized keyword because it’s easier to use them. Once you are familiar with working of multi-threading program e.g. How threads share data, how inter thread communication works, you can start with Lock facility. As I told you Lock is an interface, so we cannot use it directly, instead we need to use its implementation class. Thankfully Java comes with two implementation of java.util.concurrent.locks.Lock interface, ReentrantLock and ReentrantReadWriteLock, later provides two more inner implementation known as ReentrantReadWriteLock.ReadLock and ReentrantReadWriteLock.WriteLock. For our simple multi-threaded Java program's purpose ReentrantLock is enough.

Friday, October 13, 2017

Java Program to get input from User from Console or command line- Example Tutorial Code

How to get input from user in Java from command line or console is one of the common thing ,every one started learning Java looks for. It’s second most popular way of starting programming after HelloWorld in Java. There are so many ways to get input from User in Java including command line and Graphical user interface. For beginner simpler the example, better it is. first and foremost way of getting input from user is String[] passed to main method in Java but that only work for one time requirement and its not interactive. Another way of getting input from User is involving IO classes like InputStream to read from console or command line which can be little complicated for true beginner. Thanks to Java 5 which added a nice utility class called Scanner, has made task of getting input from user very easy. Scanner is powerful and allows you to get any kind of input from User e.g. String, int, float etc.

Thursday, October 12, 2017

What is Double Brace Initialization in Java? Anti Pattern Example

Double brace initialization is a Java idiom to initialize a Collection like a list, set and map at the time of declaration. At times, you need a list of fixed elements e.g. supported products, supported currencies or some other config, and on the spot initialization reduces line of code and improves readability. Double brace initialization idiom becomes popular because there is no standard way to create and initialize Collection at the same time in Java. Unfortunately, unlike another language, Java doesn't support collection literals yet. Due to this limitation, creating an unmodifiable List with small numbers of elements requires many lines of code involving creating list, repeatedly calling add() method to add those elements and then finally wrapping it into unmodifiable list as shown below :

What is Class in Java Programming with General Example

When I first about Class in Java I just thought what is this Class in Java and from that date to now Whenever we talk about java its really incomplete without classes, every one who are little bit familiar with java knows it’s purely object oriented language means every thing we discuss in java as object .so its very important for learner or anyone who is keen to know about java should know about java class then only they can move forward on java world.
In this article we will see what Java Class, Example of Class in Java is and what makes a Java Class including members, field and method.If you have just started programming in Java or learning Please check my article How to Set Path for Java and How to set ClassPath for Java covering two important concept PATH and CLASSPATH.

Class in Java Programming Example

What is Java Class?

Java class is nothing but a template for object you are going to create or it’s a blue print by using this we create an object. In simple word we can say it’s a specification or a pattern which we define and every object we define will follow that pattern.

What does Java Class Consist

§          When we create class in java the first step is keyword class and then name of the class or identifier we can say.
§          Next is class body which starts with curly braces {} and between this all things related with that class means their property and method will come here.

Template is:

Class (name of the class) {

(Here define member of class)


Access level of class:

Java class has mainly two type of access level:

Default: class objects are accessible only inside the package.

Public: class objects are accessible in code in any package.

What are members of Class?

When we create a class its totally incomplete without defining any member of this class same like we can understand one family is incomplete if they have no members.
What is Class in Java Program with Example
Field: field is nothing but the property of the class or object which we are going to create .for example if we are creating a class called computer then they have property like model, mem_size, hd_size, os_type etc

Method: method is nothing but the operation that an object can perform it define the behavior of object how an object can interact with outside world .startMethod (), shutdownMethod ().

Access Level of members: Access level is nothing but where we can use that members of the class.
Each field and method has an access level:
  • private: accessible only in this class
  • package or default: accessible only in this package
  • protected: accessible only in this package and in all subclasses of this class
  • public: accessible everywhere this class is available

Real world example of Class in Java Programming:

In real world if we want to understand about the class everything of same quality  can be visualize as a class e.g. men,women,birds ,bicycles ,cars or  we can say vehicle .
The entire vehicle will make one class they have the property like no_of_wheels, color, model, brand etc.now we can think changeGear () and speedOfvehicle (), applyBreak () etc as a method on that class. Similarly all human being also can be one class now their member will be a men ,women ,child.,isAlive() ,isDeath() can be their method or behavior of that class .again we can make Men or women a separate class and define their property and method accordingly,
In short in java every problem we get solution can be think in terms of class and object.

One Java class example:

Class Stock {
Public commodity;
Public price;
Public void buy (int no_of commodity) {}
Public boolean sale () {}

In this example Stock is called Class and commodity, price are field and buy() and sale() are two methods defined inside class. To access elements of Class you need to create an instance of class Stock. You can create instance of Class using keyword new as shown below

Stock highBetaStock = new Stock();

For calling method of Stock just call by using instance.


Further Learning
SOLID Principles of Object Oriented Design
Absolute Introduction to Object Oriented Programming in Java
Java - Object Oriented Programming [For Absolute Beginners]

In short in java everything must be thinking in terms of java class its nothing but a template they have their own members and methods for accessing those members. The entire member has their own visibility which is decided by the developer where they want to use those objects.

Related Java Tutorials

Wednesday, October 11, 2017

Google Dart: New Programming language to replace JavaScript

Google Dart: Structured Web Programming language 

Google has launched its much awaited mysterious DART web programming language. Ahh another programming language…, why does google launched a new language Google DART? What I read from the web is that google is trying to replace JavaScript as main web scripting language. Over the years from Netscape Era JavaScript has evolved, formed a large based of Developers and has existing codes, framework, and utilities, so I am not sure how far Google DART can go but this is a serious attempt to replace JavaScript much in the line of Chrome which was launched to replace Internet Explorer and What we see now is they are living happily with their own market share though Chrome is growing and snatching market share from other browsers.

Tuesday, October 10, 2017

Effective Java, 3rd Edition Now Available - Covers JDK 7, 8, and 9 -Must Read Book for Java Programmers in 2019

Hello guys, I have an interesting news to share with you today. After a long wait of almost 10 years, Effective Java 3rd edition is finally coming this year, hopefully, December 2017. The Effective Java 2nd Edition was released in May 2008 and updated for Java SE 6, but it been, good 10 years now and there is a lot of interest from Java developers around the world for Effective Java 3rd edition after Java SE 8 release and I am very happy to inform you guys that, finally, all our wishes are granted and Effective Java 3rd edition is set to arrive this year. It will not only cover Java 9 release but also all the changes from Java 7 and Java 8.

Monday, October 9, 2017

How to write build.xml and run build in Apache ANT

This is the second article on Apache ANT tutorials for beginners series As I have always said that I like the short , clear and concise tutorial which tells about few concept but in a clear and concise manner and put weight on fundamentals . I try to adopt same theory while writing my blog post while writing my experience coupled with the concept which is important for a software developer point of view.

SQL Server JDBC Error: The TCP/IP connection to the host Failed

I had installed SQL SERVER 2014 Express edition and I was trying to connect to SQL SERVER from Java program using JDBC, but I was repeatedly getting following error:

com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host localhost, port 1433 has failed. Error: "connect timed out. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.".Error while closing connection !!null

Top 10 JSP Interview Questions Answers for Java Programmer

This JSP interview questions and answers are asked in the various J2EE interview and focus on view part of MVC framework. JSP or Java Server Pages is a Java technology used to render a dynamic view. Whenever you go for any Java web developer interview there is always some interview questions on JSP. This article is a collection of some JSP interview questions which has asked in the various interview to my friends and colleagues. You can easily find answers to these JSP interview question by google but I have included my version for quick reference. I would love to hear back from you and please share some JSP interview questions asked to you guys on the interview; I can include those in the main post for everybody’s benefit.

Right way to Close InputStream and OutputStream in Java

For some unknown reasons many Java programmers are not very comfortable with IO package. I don't know why, but I have found them much more comfortable with java.lang and java.util than java.io. One possible reason of this could be that, writing IO code require a bit of C++ like programming, which involves doing clean-up, releasing resources once done etc. Since Java made coding a lot easier by taking care of memory management, unknowingly it also introduced bad practice of not releasing resource after use e.g. database connections, socket connection, files, directory, printers, scanners or any other scarce resource.

Sunday, October 8, 2017

How SubString method works in Java - Memory Leak Fixed in JDK 1.7

Substring method from String class is one of most used method in Java, and it's also part of an interesting String interview question  e.g. How substring works in Java or sometime asked as how does substring creates memory leak in Java. In order to answer these questions, you knowledge of  implementation details is required. Recently one of my friend was drilled on substring method in Java during a Java interview, he was using substring() method from long time, and of course all of us has used this, but what surprises him was interviewer's obsession on Java substring, and deep dive till the implementation level. Though String is a special class in Java, and subject of many interview questions e.g. Why char array is better than String for storing password . In this case it was, substring method, which took center stage. Most of us rather just use substring(..), and than forgot. Not every Java programmer go into code, and see how exactly it's working. To get a feel of how his interview was let's start .

How to build project using Apache ANT ? ANT Build Tutorials for Beginners

Apache Ant tutorials for beginners

Hi Guys, today I would like to share some of my experience while working with ant build tool in form of short ant tutorials, ant is one tool which has gained its place in almost everywhere, it’s integral part of any project’s build system and provide foundation for complex, extensible build environment. I have been using ANT from my early programming days and I have seen some of the best designed build environments around ANT. In these ant tutorials for beginners we will see what is ant build tool? How to use ANT for building project? Fundamentals of ANT build tool, setting up ant build environment etc. I have created a series of ant tutorials and you can check next part of ant tutorials by following links ant tutorial part 2 and ant tutorial part 3

Saturday, October 7, 2017

20 Questions You can ask to Interviewer in Programming Job Interviews?

From the first round to HR round, from telephonic to face-to-face, in almost all kind of programming interviews, there will be a time when Interviewer will give you a chance to ask questions. Many programmers are too concern about asking questions, and they politely decline ; Well it's your chance to learn about the Job you are going to do, and you shouldn't let this opportunity goes away. The interviewer, also judges you by your questions; a good, thoughtful, positive question can create the great impression on Interviewer's mind. It also shows that  the interest of a candidate for a Job.

10 Programming Best Practices to Name Variables, Methods, Classes and Packages

What's in a name? "A rose by any other name would smell as sweet" is a famous quote from William Shakespeare's classic Romeo and Juliet, but sorry to say, name matter a lot in programming and coding.  It's also said that code is the best document for any software because any other document or comments can become outdated quickly, but code will always tell you the truth. And, If code is the best document than names are the most critical element of it. Every effort, small or big, invested while naming variables or methods, pays in both short term and long term. In fact, if you ask me just one coding practice to follow, It would definitely recommend giving meaningful names to your variables and methods.

Top 10 Java String interview Question answers - Advanced

10 Java String interviews Question answers
String interview questions in Java is one of Integral part of any Core Java or J2EE interviews. No one can deny the importance of String and how much it is used in any Java application irrespective of whether its core Java desktop application, web application, Enterprise application or Mobile application. The string is one of the fundamental of Java programming language and correct understanding of String class is a must for every Java programmer. What makes String interview questions in Java even more interesting is the special status of String in terms of features and privileges it has, like the + operator is kind of overloaded to perform String concatenation despite the fact that Java does not support operator overloading. There is a separate String pool to store String literal etc.

Friday, October 6, 2017

How to Set Path for Java Unix Linux and Windows

PATH is one of fundamental Environment variable on shell or DOS but it’s commonly associated with Java mainly because if we try to run a java program which doesn't include Java executable in PATH then we say PATH is not set for Java and we need to set the path for Java. I have also seen the developer getting confused over path and classpath in java. Though both path and classpath provide run-time settings for any java environment which is required to compile and executes Java program they are completely different to each other. Classpath is usually used to find out classes and mostly associated with lib part while PATH is used to find the executable or command to be executed. In order to compile and run a java program from command line, your PATH environment variable must have "javac" and "java" on it. In this Java PATH tutorial, we will see what is PATH for Java, How to Set Path for Java and how to troubleshoot PATH related issues.

What is Inheritance in Java and OOPS Tutorial - Example

Inheritance in Java is an Object oriented or  OOPS concepts, which allows to emulate real world Inheritance behavior, Inheritance allows code reuse in Object oriented programming language e.g. Java. Along with Abstraction, Polymorphism and Encapsulation, Inheritance forms basis of Object oriented programming. Inheritance is implemented using extends keyword in Java and When one Class extends another Class it inherit all non private members including fields and methods. Inheritance in Java can be best understand in terms of Parent and Child class, also known as Super class and Sub class in Java programming language. The class which extends another class becomes Child of the class it extends and inherit all its functionality which is not private or package-private given where Child class is created. Inheritance is the most easy way to reuse already written and tested code but not always best way to do so, which we will see in this article. There are lot of example of Inheritance in Object oriented world e.g. Child inherit properties from parent, Dog inherit properties of Animal etc. In this Java and OOPS tutorial we will learn What is Inheritance in Java, How to use Inheritance in Java, Simple Example of Java Inheritance and some important points about Inheritance in Java.

Wednesday, October 4, 2017

Improving Performance of java application

This is a big topic to discuss as there are many approaches which involve analyzing performance of an application starting from profiling application to finding the bottleneck.

here I am putting some of the basic tricks for improving performance which I learned in my early days in java , I will keep posted some approach , experience on performance improvement as and when time allows.

for now here are naive's tips for making your program run faster.

Database Website to Run and Practice SQL Query Online for FREE - SQLFiddle

Other day, I was looking for a website to execute SQL query online, since I have uninstalled Microsoft SQL Server because of memory and CPU constraint and I don't want to install it again, just for executing another query. Also, installing database is pain, it takes time and eats up lots of resources e.g. RAM memory, CPU etc; Given so many database to work with e.g. Oracle, MySQL, Sybase, PostgreSQL and SQLLite, it's not really possible to have all of them in your poor laptop. Fortunately my search leads be to this wonderful site called SQLFiddle, this is what exactly I wanted. This site offers support for lot of popular databases, allows you to build your database schema online and execute SQL query on the fly. I couldn't have asked more, It's a great resource to learn and practice SQL queries online. Apart from many sweet feature, it also allows you to share your problem with community. If you are writing a complex query and stuck in middle, looking for help, you can create your schema on SQLFiddle and can share with your query to any forum or question answer website like StackOverFlow or any forum. 

Monday, October 2, 2017

How to convert java.util.Date to java.sql.Date - JDBC Example

You often need to convert java.util.Date to java.sql.Date if you are storing dates in database e.g. SQL SERVER or MySQL. Since JDBC has their own data types for date and time e.g. java.sql.Date, java.sql.Time and java.sql.TimeStamp to match with database date, time and date-time types, you cannot pass a java.util.Date directly. All methods which are suppose to store dates e.g. setDate(paramName, paramValue) expects java.sql.Date, so it becomes essential to know how to convert java.util.Date to java.sql.Date in JDBC. You would be surprised to know that java.sql.Date is a subclass of java.util.Date and all it does is suppress or remove time-related fields from java.util.Date.

What is PriorityQueue or priority queue data structure in Java with Example - Tutorial

PriorityQueue is an unbounded Queue implementation in Java, which is based on priority heap. PriorityQueue allows you to keep elements in a particular order, according to there natural order or custom order defined by Comparator interface in Java. Head of priority queue data structure will always contain least element with respect to specified ordering. For example, in this post, we will create a PriorityQueue of Items, which are ordered based upon there price, this will allow us to process Items, starting from lowest price. Priority queue is also very useful in implementing Dijkstra algorithm in Java. You can use to PriorityQueue to keep unsettled nodes for processing. One of the key thing to remember about PriorityQueue in Java is that it's Iterator doesn't guarantee any order, if you want to traverse in ordered fashion, better use Arrays.sort(pq.toArray()) method. PriorityQueue is also not synchronized, which means can not be shared safely between multiple threads, instead it's concurrent counterpart PriorityBlockingQueue is thread-safe and should be used in multithreaded environment. Priority queue provides O(log(n)) time performance for common enqueing and dequeing methods e.g. offer(), poll() and add(), but constant time for retrieval methods e.g. peek() and element().

5 Articles to Learn about Shellshock Bash Bug

The year of 2014 is looking like a year of biggest software bug and vulnerabilities. Earlier this year, internet was bleeding by Heartbleed vulnerability and now it's shocked by ShellShock bug. To me it looks like even bigger than Heartbleed, just because it's a bug in Bash Shell, our own bash shell, most popular among all UNIX shells like C and K. Given most of the servers in Investment banks, Insurance companies, Clouds and e-commerce domain are Linux Servers with bash being most used shell, impact is quite large. I am sure people with Microsoft stack is smiling somewhere :), but wait, read the full article. First details of Shellshock bug emerged Wednesday last week, since then it has gone viral, both online and offline. People are busy talking about it and engineers are busy patching Servers, computers, routers, firewalls and other computing resources using vulnerable versions of bash. It has triggered patching almost everywhere. I am sure many of my readers are still puzzling with what is this ShellShock bug? For those, It's an example of an arbitrary code execution (ACE) vulnerability, which means attacker can execute their code on your vulnerable server. What this mean to you? Well if they can execute their own command they can do anything to your server and business. To start-with they can stop your servers, delete files, stole passwords and can take complete control for the machine, operating them remotely. Typically, arbitrary code execution vulnerability attacks are very sophisticated and require expert understanding of the internals of code execution, memory layout, and assembly language, which makes them very hard. Thanks to Bash ShellShock bug, now even a naive programmer can launch such kind of powerful attack to take control of vulnerable server. To give you an example, due to ShellShock vulnerability, anyone can take control of your web server by simply sending an HTTP request. This is massive, but fortunately impact is only limited to servers, where server side program pass user supplied information to Bash Shell, if your Java server doesn't do that, you are probably safe from that path of attack.

Sunday, October 1, 2017

How to override hashcode in Java example - Tutorial

Equals and hashcode methods are two primary but yet one of most important methods for java developers to be aware of. Java intends to provide equals and hashcode for every class to test the equality and to provide a hash or digest based on content of class. Importance of hashcode increases when we use the object in different collection classes which works on hashing principle e.g. hashtable and hashmap. A well written hashcode method can improve performance drastically by distributing objects uniformly and avoiding collision. In this article we will see how to correctly override hashcode() method in java with a simple example. We will also examine important aspect of hashcode contracts in java. This is in continuation of my earlier post on overriding equals method in Java, if you haven’t read already I would suggest go through it.

General Contracts for hashCode() in Java

1) If two objects are equal by equals() method then there hashcode returned by hashCode() method must be same.

2) Whenever hashCode() mehtod is invoked on the same object more than once within single execution of application, hashCode() must return same integer provided no information or fields used in equals and hashcode is modified. This integer is not required to be same during multiple execution of application though.

3) If two objects are not equals by equals() method it is not require that there hashcode must be different. Though it’s always good practice to return different hashCode for unequal object. Different hashCode for distinct object can improve performance of hashmap or hashtable by reducing collision.

To better understand concept of equals and hashcode and what happens if you don’t override them properly I would recommend understanding of How HashMap works in Java

Overriding hashCode method in Java

Override java hashcode exampleWe will follow step by step approach for overriding hashCode method. This will enable us to understand the concept and process better.

1) Take a prime hash e.g. 5, 7, 17 or 31 (prime number as hash, results in distinct hashcode for distinct object)
2) Take another prime as multiplier different than hash is good.
3) Compute hashcode for each member and add them into final hash. Repeat this for all members which participated in equals.
4) Return hash

  Here is an example of hashCode() method

    public int hashCode() {
        int hash = 5;
        hash = 89  hash + (this.name != null ? this.name.hashCode() : 0);
        hash = 89  hash + (int) (this.id ^ (this.id >>> 32));
        hash = 89  hash + this.age;
        return hash;

It’s always good to check null before calling hashCode() method on members or fields to avoid NullPointerException, if member is null than return zero. Different data types has different way to compute hashCode.Integer members are simplest we just add there value into hash, for other numeric data-type are converted into int and then added into hash. Joshua bloach has full tables on this. I mostly relied on IDE for this.

Better way to override equals and hashCode

hashcode in Java exampleIn my opinion better way to override both equals and hashcode method should be left to IDE. I have seen Netbeans and Eclipse and found that both has excellent support of generating code for equals and hashcode and there implementations seems to follow all best practice and requirement e.g. null check , instanceof check etc and also frees you to remember how to compute hashcode for different data-types.

Let’s see how we can override hashcode method in Netbeans and Eclipse.

In Netbeans
1) Write your Class.
2) Right click + insert code + Generate equals() and hashCode().

How to override java hashcode
In Eclipse
1) Write your Class.
2) Go to Source Menu + Generate hashCode() and equals()

Things to remember while overriding hashcode in Java

1. Whenever you override equals method, hashcode should be overridden to be in compliant of equals hashcode contract.
2. hashCode() is declared in Object class and return type of hashcode method is int and not long.
3. For immutable object you can cache the hashcode once generated for improved performance.
4. Test your hashcode method for equals hashcode compliance.
5. If you don't override hashCode() method properly your Object may not function correctly on hash based collection e.g. HashMap, Hashtable or HashSet.

Complete example of equals and hashCode

public class Stock {
       private String symbol;
       private String exchange;
       private long lotSize;
       private int tickSize;
       private boolean isRestricted;
       private Date settlementDate;
       private BigDecimal price;
       public int hashCode() {
              final int prime = 31;
              int result = 1;
              result = prime * result
                           + ((exchange == null) ? 0 : exchange.hashCode());
              result = prime * result + (isRestricted ? 1231 : 1237);
              result = prime * result + (int) (lotSize ^ (lotSize >>> 32));
              result = prime * result + ((price == null) ? 0 : price.hashCode());
              result = prime * result
                           + ((settlementDate == null) ? 0 : settlementDate.hashCode());
              result = prime * result + ((symbol == null) ? 0 : symbol.hashCode());
              result = prime * result + tickSize;
              return result;
       public boolean equals(Object obj) {
              if (this == obj) return true;
              if (obj == null || this.getClass() != obj.getClass()){
                     return false;
              Stock other = (Stock) obj;
this.tickSize == other.tickSize && this.lotSize == other.lotSize && 
this.isRestricted == other.isRestricted &&
(this.symbol == other.symbol|| (this.symbol != null && this.symbol.equals(other.symbol)))&& 
(this.exchange == other.exchange|| (this.exchange != null && this.exchange.equals(other.exchange))) &&
(this.settlementDate == other.settlementDate|| (this.settlementDate != null && this.settlementDate.equals(other.settlementDate))) &&
(this.price == other.price|| (this.price != null && this.price.equals(other.price)));


Writing equals and hashcode using Apache Commons EqualsBuilder and HashCodeBuilder

EqualsBuilder and HashCodeBuilder from Apache commons are much better way to override equals and hashcode method, at least much better than ugly equals, hashcode generated by Eclipse. I have written same example by using HashCodebuilder and EqualsBuilder and now you can see how clear and concise they are.

    public boolean equals(Object obj){
        if (obj instanceof Stock) {
            Stock other = (Stock) obj;
            EqualsBuilder builder = new EqualsBuilder();
            builder.append(this.symbol, other.symbol);
            builder.append(this.exchange, other.exchange);
            builder.append(this.lotSize, other.lotSize);
            builder.append(this.tickSize, other.tickSize);
            builder.append(this.isRestricted, other.isRestricted);
            builder.append(this.settlementDate, other.settlementDate);
            builder.append(this.price, other.price);
            return builder.isEquals();
        return false;
    public int hashCode(){
        HashCodeBuilder builder = new HashCodeBuilder();
        return builder.toHashCode();
    public static void main(String args[]){
        Stock sony = new Stock("6758.T", "Tkyo Stock Exchange", 1000, 10, false, new Date(), BigDecimal.valueOf(2200));
        Stock sony2 = new Stock("6758.T", "Tokyo Stock Exchange", 1000, 10, false, new Date(), BigDecimal.valueOf(2200));

        System.out.println("Equals result: " + sony.equals(sony2));
        System.out.println("HashCode result: " + (sony.hashCode()== sony2.hashCode()));

Only thing to concern is that it adds dependency on apache commons jar, most people use it but if you are not using than you need to include it for writing equals and hashcode method.

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

Related Java tutorials