Preparing for Java and Spring Boot Interview?

Join my Newsletter, its FREE

Tuesday, August 31, 2021

5 ways to add multiple JAR in to Classpath in Java - Examples

How to add the JAR file to Classpath in Java
Adding JAR into classpath is a common task for Java programmers and different programmers do it in different ways. Since Java allows multiple ways to include JAR files in the classpath, it becomes important to know the pros and cons of each approach and How exactly they work. There are 5 ways to add jars into classpath in Java some of them we have already seen in  How classpath works in Java and How to set Path in JavaIn this post, we will revisit some of those techniques and explore Java 1.6 wildcard to add multiple JAR into the classpath. 

How to implement Post Order Traversal of Binary Tree in Java - Recursion and Iteration Example

This is the third article on tree traversal. In the last couple of articles, I have shown you how to implement preorder and inorder traversal in Java, both recursively and iteratively and today, you will learn about the post-order traversal. Out of these three main tree traversal algorithms, the post-order traversal is most difficult to implement, especially the iterative version. In postorder traversal, you first visit left subtree, then right subtree and at last you print the value of root or not. So, the value of root is always printed at last in the post-order traversal.

Java Enum Tutorial: 10 Examples of Enum in Java

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

Top 10 Excuses Programmers Gives to Avoid Unit Testing

Though everyone loves unit tests and everyone agrees with the benefits they bring in, when the time comes to write them, you will see a lot of excuses, even from some of the more experienced and senior developers. At the heart of the problem of not writing unit tests or enough unit tests are two things, first is time pressure i.e. you don't have enough time to complete coding forget about writing unit tests. This problem comes due to erroneous estimation i.e. only estimating time for coding and not including unit testing as part of development.

Friday, August 27, 2021

How to Implement Binary Search Tree in Java? Example

A binary search tree or BST is a popular data structure that 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 the value of the right child is greater than or equal to the parent node. Since it's 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.

Thursday, August 26, 2021

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

@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.

Tuesday, August 24, 2021

How to Code in Dart Programing language? Dart Hello World Example Tutorial

Google Datt is a general-purpose programming language from Google and is used to build web applications, mobile applications, and the Internet of Things (IoT).  Its most popular application is in Flutter framework, which is Google's mobile app SDK for crafting high-quality native interfaces on iOS and Android in record time. If you haven't tried it yet then it's a good time to try it and see how much it offers to a programmer and whether it is a suitable language to replace JavaScript or not. 

Inner class and nested Static Class in Java with Example

Inner class and nested static class in Java both are classes declared inside another class, known as top level class in Java. In Java terminology, If you declare a nested class static, it will called nested static class in Java while non-static nested classes are simply referred as Inner Class. Inner classes are also a popular topic in Java interviews. One of the popular questions is the difference between inner class and nested static class , some time also referred to as a difference between static and non static nested class in Java. One of the most important questions related to nested classes are Where should you use nested class in Java?

How to Attach Source Code in Eclipse to JAR Files for Debugging and Navigation With JDK Example

Attaching the source of any Jar in Eclipse e.g. JDK or open-source libraries like Spring framework is a good idea because it helps during debugging and code development. As a Java programmer at least you should attach the source of JDK in Eclipse IDE to find out more about JDK classes. Though Eclipse IDE is pretty good on code assist, sometimes You want to know what's going inside a library or a JDK method, rather than just reading the documentation. Interview questions like How HashMap works in Java or How substring causes memory leak can only be answered if you are familiar with the source code of these classes.  

How to Compare Arrays in Java – Equals vs deepEquals Example

java.util.Arrays class provides equals() and deepEquals() method to compare two Arrays in Java. Both of these are overloaded methods to compare primitive arrays e.g. int, long, float, double, and Object arrays e.g. Arrays.equals(Object[], Object[]). Arrays.equals() returns true if both Arrays which it is comparing are null If both arrays pointing to the same Array Object or they must be of the same length and contains the same element in each index. In all other cases, it returns false. Arrays.equals() calls equals() method of each Object while comparing Object arrays.

Monday, August 23, 2021

How to add, subtract days, months, years, hours from Date and Time in Java - Example

Adding days, hours, month or years to dates is a common task in Java. java.util.Calendar can be used to perform Date and Time arithmetic in Java. Calendar class not only provides date manipulation but it also support time manipulation i.e. you can add, subtract hours, minutes and seconds from current time. Calendar class automatically handles date transition or month transition for example if you ask date after 30 days it will return you date based on whether current month is 30 or 31 days long. Same is true in case of adding and subtracting years, Calendar takes care whether current or following year is a leap year or not.

Sunday, August 22, 2021

Difference between equals method and "==" operator in Java - Interview Question

Both equals() and "==" operators in Java are used to compare objects to check equality but the main difference between the equals method and the == operator is that the former is a method and the latter is an operator. Since Java doesn’t support operator overloading, == behaves identical for every object but equals() is a method, which can be overridden in Java, and logic to compare objects can be changed based upon business rules. Another notable difference between the == and equals method is that the former is used to compare both primitive and objects while the latter is only used for objects comparison.

What is final in Java? Final variable , Method and Class Example

Final in Java is very important keyword and can be applied to class, method, and variables in Java. In this java final tutorial we will see what is a final keyword in Java, what does it mean by making final variable, final method and final class in java and what are primary benefits of using final keywords in Java and finally some examples of final in Java. Final is often used along with static keyword in Java to make static final constant and you will see how final in Java can increase the performance of Java application.

What is Type Casting in Java? Casting one Class to other class or interface Example

Type casting in Java is to cast one type, a class or interface, into another type i.e. another class or interface. Since Java is an Object-oriented programming language and supports both Inheritance and Polymorphism, It’s easy that Super class reference variable is pointing to SubClass objects but the catch here is that there is no way for Java compiler to know that a Superclass variable is pointing to SubClass object. This means you can not call a method that is declared in the subclass. In order to do that, you first need to cast the Object back into its original type. This is called type casting in Java. You can type cast both primitive and reference type in Java. The concept of casting will be clearer when you will see an example of type casting in the next section.

Saturday, August 21, 2021

Recursion in Java with Example – Programming Tutorial for Beginners

Recursion is one of the tough programming techniques to master. Many programmers working on both Java and other programming languages like C or C++ struggles to think recursively and figure out the recursive pattern in the problem statement, which makes it is one of the favorite topics of any programming interview. If you are new to Java or just started learning Java programming language and you are looking for some exercise to learn the concept of recursion then this tutorial is for you. 

Observer design Pattern in Java with Real world code Example

Observer design pattern in Java is a fundamental core Java pattern where Observe watches for any change in state or property of Subject. For Example, Company updates all its shareholders for any decision they make here Company is Subject and Shareholders are Observers, any change in the policy of company and the Company notifies all its Shareholders or Observer. This was a simple real-world explanation of the Observer pattern. 

How to get current date, month, year and day of week in Java program - Example tutorial

Here is a quick Java tip to get the current date, month, year, and day of the week from the Java program. Java provides a rich Date and Time API though having thread-safety issue but it's rich in function and if used locally can give you all the date and time information that you need for your enterprise Java application. In the last Java tutorial on Date and Time API we have seen how to get the current date and time from different timezone using DateFormat and SimpleDateFormat classes and in this post, we will get some more details like the current month, year, day of the week, etc by using java.util.Calendar class.  Just keep in mind that the Calendar instance should not be shared between multiple threads.

How to convert milliseconds to Date in Java - Tutorial example

Do you want to convert milliseconds to Date in Java? Actually java.util.Date is internally specified in milliseconds from epoch. So any date is the number of milliseconds passed since January 1, 1970, 00:00:00 GMT and Date provides constructor which can be used to create Date from milliseconds. Knowing the fact that Date is internally maintained in milliseconds allows you to store date in form of milliseconds in Server or in your Class because that can be effectively expressed with a long value.

3 Examples to Print Array Elements/Values in Java - toString and deepToString from Arrays

Printing array values in Java or values of an array element in Java would have been much easier if  arrays are allowed to directly prints its values whenever used inside System.out.println() or format and printf method, Similar to various classes in Java do this by overriding toString() method. Despite being an object, array in Java doesn't print any meaningful representation of its content when passed to System.out.println() or any other print methods. If you are using array in method argument or any other prominent place in code and actually interested in values of an array then you don't have much choice than for loop until Java 1.4.

Friday, August 20, 2021

How to check if String contains another SubString in Java? contains() and indexOf() example

You can use contains(), indexOf() and lastIndexOf() method to check if one String contains another String in Java or not. If a String contains another String then it's known as a substring. The indexOf() method accepts a String and returns the starting position of the string if it exists, otherwise, it will return -1. For example "fastfood".indexOf("food") will return 4 but "fastfood".indexOf("Pizza") will return -1. This is the easiest way to test if one String contains another substring or not.

Thursday, August 19, 2021

Difference between mvn install, release and deploy commands in Maven - Examples

Even though there are a couple of powerful build and deployment tools that exist for Java applications like Gradle or ANT, It seems Maven is the king of them. I have used it in several Java projects over the years and it was initially ANT, but now they all use Maven with few Scala projects using Gradle. When you work with Maven you know that there are lots of commands to remember, especially if you are working on the command line. The thee Maven build commands which often confuses Java developers are mvn install, mvn release, and mvn deploy.

How to check if a String is numeric in Java? Use isNumeric() or isNumber() Example

In day-to-day programming, you often need to check if a given string is numeric or not. It's also a good interview question but that's a separate topic of discussion. Even though you can use Regular expression to check if the given String is empty or not, as shown here, they are not full proof to handle all kinds of scenarios, which common third-party libraries like Apache commons-lang will handle e.g. hexadecimal and octal String. Hence, In the Java application, the simplest way to determine if a String is a number or not is by using the Apache Commons lang's isNumber() method, which checks whether the String is a valid number in Java or not.

How to use instanceof operator in Java with example

The instanceof operator in Java is used to check if an object belongs to a particular type or not at runtime. It's also a built-in keyword in Java programming language and is mostly used to avoid ClassCastException in Java. It is used as a safety check before casting any object into a certain type. This operator has a form of object instanceof Type and returns true if the object satisfies IS-A relationship with the Type i.e. object is an instance of class Type or object is the instance of a class which extends Type or object is an instance of a class which implements interface Type.

How to remove duplicates elements from ArrayList in Java - Example

You can remove duplicates or repeated elements from ArrayList in Java by converting ArrayList into HashSet in Java. but before doing that just keep in mind that the set doesn't preserver insertion order which is guaranteed by List, in fact, that’s the main difference between List and Set in Java. So when you convert ArrayList to HashSet all duplicates elements will be removed but the insertion order will be lost. Let’s see this in action by writing a Java program to remove duplicates from ArrayList in Java.

How to read input from command line in Java using Scanner - Example

Java 5 introduced a nice utility called java.util.Scanner is capable of reading input from the command line in Java. Using Scanner is a nice and clean way of retrieving user input from the console or command line. The scanner can accept InputStream, Reader, or simply the path of the file from where to read input. In order to read from the command line, we can pass into Scanner's constructor as a source of input. The scanner offers several benefits over the classical BufferedReader approach, here are some of the benefits of using java.util.Scanner for reading input from the command line in Java:

Wednesday, August 18, 2021

Constructor Chaining in Java Example - Calling one constructor from another using this and super

Constructor Chaining in Java
In Java, you can call one constructor from another and it’s known as constructor chaining in Java. Don’t confuse between constructor overloading and constructor chaining, the former is just a way to declare more than one constructor in Java. this and the super keyword is used to call one constructor from other in Java. this() can be used to call another constructor of the same class while super() can be used to call a constructor from superclass in Java. Just keep in mind that this() in reality calls the no-argument constructor of the same class while this(2) calls another constructor of the same class which accepts one integer parameter.

Tuesday, August 17, 2021

How to Escape String Literal in Java Using Eclipse IDE? Example

Whenever you paste String in Eclipse which contains escape characters,  to store in a String variable or just as String literal it will ask to manually escape special characters like single quotes, double quotes, forward slash, etc. This problem is more prominent when you are pasting a large chunk of data which contains escape characters like a whole HTML or XML file,  which contains lots of single quotes e.g. ‘’ and double quotes “” along with forwarding slash on closing tags. It’s very hard to manually escape all those characters and it's pretty annoying as well.

9 Things about null keyword and reference in Java

Java and null are uniquely bonded. There is hardly a Java programmer, who is not troubled by the null pointer exception, it is the most infamous fact about. Even the inventor of the null concept has called it his billion-dollar mistake, then why Java kept it? Null was there from a long time and I believe the Java designer knows that null creates more problems than it solves, but still they went with it. It surprises me even more because Java's design philosophy was to simplify things, that's why they didn't bother with pointers, operator overloading, and multiple inheritance of implementation, they why null? 

How to configure Log4j in Java program without XML or Properties File - Example

Sometimes configuring Log4j using XML or properties file looks annoying, especially if your program is not able to find them because of some classpath issues, wouldn't it be nice if you can configure and use Log4j without using any configuration file e.g. XML or properties. Well, Log4j people have thought about it and they provide a BasicConfigurator class to configure log4j programmatically, though this is not as rich as their XML and properties file version is, but it's really handy for quickly incorporating Log4j in your Java program.

What is Constructor in Java with Example – Constructor Chaining and Overloading

What is constructor in Java
Constructor in Java is a block of code which is executed at the time of Object creation. But other than getting called, Constructor is entirely different than methods and has some specific properties like name of the constructor must be same as name of Class. Constructor also can not have any return type, constructor’s are automatically chained by using this keyword and super. Since Constructor is used to create object, object initialization code is normally hosted in Constructor. Similar to the method you can also overload the constructor in Java

How to sort HashMap by key and value in Java - Hashtable, Map Example Tutorial

Sorting HashMap in Java is not as easy as it sounds because unfortunately, Java API doesn't provide any utility method to sort HashMap based on keys and values. Sorting HashMap is not like sorting ArrayList or sorting Arrays in Java. If you are wondering why we can not use Collections.sort() method than for your information it only accepts List<E>, which leaves us to write our own utility methods to sort Map in Java. This is true for all types of Maps like Hashtable, HashMap, and LinkedHashMap. TreeMap is already a sorted Map so we don't need to sort it again. 

How to comment uncomment single line and block of code in Java - Eclipse Tips Tricks Example

Knowing Eclipse shortcut to comment and uncomment single line or block of code can save you a lot of time while working in Eclipse. In fact I highly recommend every Java programmer to go through these top 30 Eclipse shortcut and  10 java debugging tips in Eclipse for improved productivity.  If you are Java programmer, coding in Eclipse and want to comment and uncomment single line or block of code quickly you can either use ctrl + / to comment a single line and subsequently uncomment a commented line. If you want to comment a block of code or a complete method, you have two options you can either line comment (//) all those selected lines or block comment (/* */) those lines.

Java TreeMap Tutorial: 15 Example of TreeMap in Java

TreeMap in Java is a SortedMap and it maintains Sorting order when you insert an object on it. You can specify Sorting order while Creating TreeMap by providing an explicit Comparator to TreeMap. Basically, you can create TreeMap in Java in different ways, a TreeMap with natural sorting order, and TreeMap with custom Sorting Order by providing Comparator, Copying Sorting order from other SortedMap, etc. TreeMap has a specific constructor for these conditions. We will see these in the section on creating instances of TreeMap in Java. 

Monday, August 16, 2021

How to parse String to Enum in Java | Convert Enum to String with Example

Converting Enum into String and parsing String to Enum in Java is becoming a common task with the growing use of Enum. Enum is very versatile in Java and preferred the choice to represent bounded data and since is almost used everywhere to carry literal value it's important to know how to convert Enum to String in Java. In this article, we will see both first converting Strings to Enum in Java and then Change an Enum to String in Java with Example. I thought about this Enum tutorial when I wrote 10 Examples of Enum in Java. I missed String to Enum conversion and one of the readers pointed out that. So here we have now.

Sunday, August 15, 2021

How to split String in Java by WhiteSpace or tabs? Example Tutorial

You can split a String by whitespaces or tabs in Java by using the split() method of java.lang.String class. This method accepts a regular expression and you can pass a regex matching with whitespace to split the String where words are separated by spaces. Though this is not as straightforward as it seems, especially if you are not coding in Java regularly. Input String may contain leading and trailing spaces, it may contain multiple white spaces between words and words may also be separated by tabs. Your solution needs to take care of all these conditions if you just want words and no empty String.

3 ways to get number of months and year between two dates in Java? Examples

Earlier I have talked about how to calculate the number of days between two dates in Java (see here), and now you will learn how to get the number of months and years between dates. Though it may look easy, it's not that easy to calculate months and years between dates, unless you take care of all kinds of nuisances like Daylight saving time and when daylight change occurs, leap seconds, and an extra day added in a leap year. Unfortunately, JDK doesn't have a standard method like the Period.between() methods of Java 8 before solving this problem.

Saturday, August 14, 2021

Iterative QuickSort Example in Java - without Recursion

The quicksort algorithm is one of the important sorting algorithms. Similar to merge sort, quicksort also uses divide-and-conquer hence it's easy to implement a quicksort algorithm using recursion in Java, but it's slightly more difficult to write an iterative version of quicksort. That's why Interviewers are now asking to implement QuickSort without using recursion. The interview will start with something like writing a program to sort an array using a quicksort algorithm in Java and most likely you will come up with a recursive implementation of quicksort as shown here. As a  follow-up, the Interviewer will now ask you to code the same algorithm using Iteration.

Friday, August 13, 2021

How to do static import in Eclipse - Java Example Tutorial

Do you know what is a shortcut to doing static import in Eclipse? Well, I didn't know before, but today I come to know that shortcut Ctrl+Shift+M (Source > Add Import) can not only be used to add missing imports but can also help with static import in the Java program.  Suppose you are using lots of static variables from a utility class e.g. TimeUnit by referring them with the class name, just like we refer to static variables. In Eclipse IDE, you can select the whole reference variable and press Ctrl+Shift+M and it will automatically import that static element using static import in Java.

What is Object in Java and Object Oriented Programming? Example Tutorial

Object in Java
Object in Java programming language or any other Object-oriented programming language like C++ is the core of the OOPS concept and that's why the name. Class and Object along with Inheritance, Polymorphism, Abstraction and Encapsulation form the basis of any Object-oriented programming language e.g. Java. Objects are instances of Class, Class defines blueprints and Objects are things that are created based upon that blueprint. Object is also known as instances in Java, e.g. When we say an instance of String class, we actually mean an Object of String class. The object has state and behavior in Java. 

Where is Java used in Real World?

If you are a beginner and just started learning Java, you might be thinking about where correctly Java is used? You don't see many games written in Java except Minecraft, desktop tools like Adobe Acrobat, Microsoft Office are not written in Java, neither are your operating systems like Linux or Windows, so where exactly do people use Java? Does it have any real-world application or not? Well, you are not alone, many programmers ask this question before starting with Java, or after picking Java as one of the programming languages of choice at the graduate level.

Why getter and setter are better than public fields in Java? Example

public modifier vs getter and setter method in Java
Providing getter and setter method for accessing any field of class in Java may look unnecessary and trivial in the first place, simply because you can make field public and it’s accessible from everywhere in Java program. In fact, many programmers do this in their early days but once you start thinking in terms of enterprise application or production code, you will start seeing how much trouble it can create in terms of maintenance

How to use BlockingQueue in Java? ArrayBlockingQueue and LinkedBlockingQueue Example Tutorial

Hello Java Programmers, if you have ever implemented a classical producer-consumer problem in Java then there is a great chance that you may have heard about BlockingQueue class from the Java concurrency package. It's a very useful class to implement inter-thread communication in Java without you having to write low-level wait and notify code.  BlockingQueue in Java is added in Java 1.5 along with various other concurrent Utility classes like ConcurrentHashMap, Counting Semaphore, CopyOnWriteArrrayList etc.

Top 10 JDBC Interview questions answers for Java programmer

JDBC Interview Question and Answer
JDBC Questions are an integral part of any Java interview,  I have not seen any Java Interview which is completed without asking the single JDBC Interview question, there is always at least one or two questions from JDBC API. Some of the popular questions like Why you should use PreparedStatement in Java,  Difference between PreparedStatement and CallableStatement in Java and few questions are related to improving the performance of the JDBC layer by applying some JDBC performance tips.

Thursday, August 12, 2021

Top 20 Core Java Interview Questions and Answers from Investment Banks

Core Java Interview Question Answer
This is a new series of sharing core Java interview questions and answer on the Finance domain and mostly on big Investment banks. Many of these Java interview questions are asked on JP Morgan, Morgan Stanley, Barclays, or Goldman Sachs. Banks mostly asked core Java interview questions from multi-threading, collection, serialization, coding and OOPS design principles. Anybody who is preparing for any Java developer Interview on any Investment bank can be benefited from this set of core Java Interview questions and answers. I have collected these Java questions from my friends and I thought to share them with you all. 

What is Factory method Design Pattern in Java with Example - Tutorial

Factory design pattern in Java one of the core design pattern which is used heavily not only in JDK but also in various Open Source framework such as Spring, Struts and Apache along with decorator design pattern in Java. Factory Design pattern is based on Encapsulation object oriented concept. Factory method is used to create different object from factory often refereed as Item and it encapsulate the creation code. So instead of having object creation code on client side we encapsulate inside Factory method in Java. One of the best examples of factory pattern in Java is BorderFactory Class of Swing API.

Top 10 Struts Framework Interview Questions and Answers

This time it's Struts interview questions, After writing Spring interview questions a few weeks back I was thinking about what to pick for my interview series and then I thought about any web framework, and on that struts is my favorite. Struts are open-source frameworks used for web applications. These Struts interview questions are based on my experience as well as collected by friends and colleague and they are not only good for interview practice but also shows a new direction of learning for anyone who is not very familiar with struts. The best way to use these interview questions does revise before going for any Struts interview or any Java or J2EE interview.

Wednesday, August 11, 2021

How to Create File and Directory in Java Example - Java IO Tutorial

How to create a File and directory in Java is probably the first thing that come to mind when we are exposed to the file system from Java. Java provides rich IO API to access contents of File and Directory in Java and also provides lots of utility methods to create a file, delete a file, read from a file, and write to file or directory. Anybody who wants to develop an application in Java should have a solid understanding of IO and Networking package. 

Open Closed Design Principle in Java - Benefits and Example

Great Example of Open Closed Design Principle
I am a big fan of design pattern articles and love to read articles on design patterns and recently wrote about decorator design pattern in JavaObserver patternstatic factory pattern and Singleton pattern. Today I come across this good article on open closed design patterns, what I like most is there example and clear way of explanation, first example is true value and it will help you understand open closed principle very quickly and second example is also not bad.

How to Create and Run a batch file in Windows - .bat File Example

batch files and shell scripts are developers best friend, they help to improve productivity a lot. They not only help you to automate boring, time consuming task but also saves lot of time doing and doing them again. Batch file also reduce chances of error, once tested and encourage re-usability by sharing them across team or people with similar needs. Though not every programmer, developer or computer user has mindset to use batch file, something it's too difficult to write, some just not able to fight with initial resistance and many of them are not even aware of batch file.

4 Ways to Search Java Array to Find an Element or Object - Tutorial Example

Searching in Java Array sounds familiar? should be,  because it's one of the frequently used operations in Java programming. The array is an index-based data structure that is used to store elements but unlike Collection classes like ArrayList or HashSet which has contains() method, the array in Java doesn't have any method to check whether an element is inside an array or not. Java programming language provides several ways to search any element in the Java array

How to setup Java Environment and run Java Program from command prompt - Helloworld Example

This article contains HelloWorld Example in Java and step by step guide to run a Java program from the command prompt. Beginners who just started to learn Java or using Java often struggled and don't know how to run a Java program from the command prompt. Running a Java program is simple but setting up a Java environment is rather cumbersome especially if you are new in the Programming world and not very familiar with words like PATH, CLASSPATH, or even command prompt.

Tuesday, August 10, 2021

Java String Replace Example Tutorial

This String replace example in Java will show you how to replace String in Java both at the character level and by using regular expression. Since String is final in Java every time you replace String you will get a new String object only if your actually replace anything on original String otherwise replace methods of String return same String object. String Class in Java provides 4 methods to replace String in Java. Those methods allow you to replace character from String, replace CharacterSequence from String, replace all occurrence of pattern in String or just first occurrence of any pattern in Java.

Top 25 Java Collection Framework Interview Questions Answers for Freshers and Experienced Programmers

Interview questions from the Collection package or framework are most common in any Core Java Interview yet a tricky one. Together Collection and multithreading make any Java interview tough to crack and having a good understanding of Collection and threads will help you to excel in Java interviews. I thought about writing interview questions on the Java collection framework and important classes like ArrayList, HashMap, Hashtable, and newly added concurrent collections e.g. ConcurrentHashMap when I first wrote 10 multi-threading Interview questions but somehow this article got delayed. Though I have shared several questions individually in between.

What is Static Variable Class method and keyword in Java - Example Tutorial

What is Static in Java
Static in Java is an important keyword and used to create static method, static class and static variable in Java. Correct understanding of static keyword is required to understand and write sophisticated Java programs. Java 5 also introduced static imports along with Autoboxing, Generics, Enum and varargs method, which allows to import static members of one class or package into another using import keyword and then using them like they are member of that class. In this Java tutorial we will learn about What is is static in Java, What does it mean to be a static field, static class or method in Java and various points and issues involved around How to use static members in Java.

What is static import in Java with Example

Static import in Java allows importing static members of the 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 programmers 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 is MAX_VALUE.

How to use Class in Java Programming - 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.

How to use Iterator and ListIterator in Java? Example Tutorial

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-loopwhile-loopdo-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 objects, we have Enumeration, Iterator, and ListIterator in Java which we will in this Java Iterator tutorial.

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

Substring method from the String class is one of the most used methods in Java, and it's also part of an interesting String interview question e.g. How substring works in Java or sometimes asked as to how does substring creates memory leak in Java. In order to answer these questions, your knowledge of implementation details is required. Recently one of my friends was drilled on the substring method in Java during a Java interview, he was using the substring() method for a long time, and of course, all of us has used this, but what surprises him was the interviewer's obsession on Java substring, and deep-dive till the implementation level.

How to build Java Projects using Apache ANT ? Beginner Tutorial with Example

Apache Ant tutorials for beginners

Hi Guys, today I would like to share some of my experience while working with the ant build tool in form of short ant tutorials, ANT is one tool that has gained its place almost everywhere, it’s an integral part of any project’s build system and provides the foundation for a complex, extensible build environment. I have been using ANT since my early programming days and I have seen some of the best-designed build environments around ANT. 

Eclipse shortcut to Type System.out.println in Java - Example Tips

Eclipse IDE provides quick shortcut keys to print System.out.println statement in Java but unfortunately not every Java programmers are familiar with that.  Even programmers with 3 to 4 years of experience sometimes don't know this useful Eclipse shortcut to generate System.out.println messages.  This Eclipse tip is to help those guys. Let me ask you one question, How many times do you type System.out.println in your Java program?  I guess multiple times 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 require setups like configuring Log4J or java.util.Logger .

What is Dart Programming language? how to use Dart? Example

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 the 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.

Top 10 Java Serialization Interview Questions and Answers

What is Serialization in Java
Java Serialization is one of the important concepts but it’s been rarely used as a persistence solution and developers mostly overlooked Java serialization API. As per my experience, Java Serialization is quite an important topic in any core Java interview, In almost all the interviews I have faced there are one or two Java serialization questions and I have seen an interview where after a few questions on serialization candidate start feeling uncomfortable because of lack of experience in this area. 

How to override compareTo method in Java - Example Tutorial

compareTo in Java is in the same league of equals() and hashcode() and used to implement natural order of object, compareTo is slightly different to compare() method of Comparator interface which is used to implement custom sorting order. I have seen during java interviews that many Java programmers not able to correctly write or implement equals(), hashCode() and compareTo() method for common business objects like Order or Employee. Simple reason behind this is that they either not understand the concept well enough or doesn't write this stuff at all.

Monday, August 9, 2021

How to check if a String is Number in Java - Regular Expression Example

Regular Expression to check numeric String
In order to build a regular expression to check if String is a 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 a great tool in a developer's 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 a regular expression in Java. Java supports regex from JDK 1.4, which means well before Generics, Enum, or Autoboxing.

How to Convert 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 is 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 likeString.valueOf(double d) which expect a double value.

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

This article is a simple Java program that converts the decimal number to binary, octal, and hexadecimal format. When it first came into my mind I thought I would probably need to write whole code to convert decimal to various other radix or base numbers but when I looked at Integer class and saw these two ways 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.

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

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 concepts but in a clear and concise manner and puts weight on fundamentals. I try to adopt the same theory while writing my blog post while writing my experience coupled with the concept which is important for a software developer's point of view. Here I am answering some of the basic questions related to installing the ANT tool, running ANT build, creating a build.XML file, debugging build.xml in the case of any issue.

How to Set Path for Java Unix Linux and Windows

PATH is one of the fundamental Environment variables on shell or DOS but it’s commonly associated with Java mainly because if we try to run a java program that 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 programs they are completely different from each other.

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

PriorityQueue is an unbounded Queue implementation in Java, which is based on a priority heap. PriorityQueue allows you to keep elements in a particular order, according to their natural order or custom order defined by the Comparator interface in Java. Head of priority queue data structure will always contain the least element with respect to specified ordering. For example, in this post, we will create a PriorityQueue of Items, which are ordered based upon their price, this will allow us to process Items, starting from the lowest price. A priority queue is also very useful in implementing the Dijkstra algorithm in Java. You can use to PriorityQueue to keep unsettled nodes for processing.

What is Inheritance in Java and OOP 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.

Sunday, August 8, 2021

How to use ARM- Automatic resource management in Java - Try with Resource Example

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 resources and make programmers 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.

Variable argument and Varargs methods in Java with Example - Programming Tutorial

Variable argument or varargs in Java allows you to write more flexible methods which can accept as many arguments as you need. variable arguments or varargs were added in Java 1.5 along with great language features like Java Enum, Generics, autoboxing and various others. Variable arguments a relatively small feature but useful for a developer who has been well aware of method and array. Some time we have a scenario that one method can take a 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.

How to loop over two dimensional array in Java? Example

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 dimensions and 2D arrays is what you will see in most of the places. It's one of the most useful data structures 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 that is populated using tiles.

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 a 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.

How to use String in switch case in Java with Example

Have you ever feel that String should be used in switch cases like int and char? JDK 7 has made an important enhancement in their support of String, now you can use String in switch and case statements, No doubt String is the most widely used type in Java, and in my opinion, they should have made this enhancement long back when they provided support for enum in java and allowed enum to be used in a switch statement. 

Saturday, August 7, 2021

How to override hashcode in Java example - Tutorial

Equals and hashcode methods are two primaries but yet one of the most important methods for java developers to be aware of. Java intends to provide equals and hashcode for every class to test equality and to provide a hash or digest based on the content of the class. The 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 a collision.

Code Review Checklist and Best practices in Java

What to review while doing Code review
Code Review and Unit testing are some of the best development practices I always recommend, strive for, and enforce as much as possible. Even just by doing code review and Junit test case always offer positive results it can be improved a lot by constantly learning from our mistakes, others mistakes and by observing how others are doing it. I always try to get my code review done by someone with more technical and domain experience so that I can capture any domain-specific scenarios which have been missed during think through the process.

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 Objects in a human-readable format. A correctly overridden toString method can help in logging and debugging Java programs 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 a subclass. In fact, if you are creating value class or domain class e.g. Order, Trade or Employee,  always override equalshashCode, compareTo, and toString method in Java.

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 the 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.

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.

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

Converting a byte array to String seems easy but what is difficult is, doing it correctly. Many programmers make the mistake of ignoring character encoding whenever bytes are converted into a String or char or vice versa. As a programmer, we all know that computer's only understand binary data i.e. 0 and 1. All things we see and use like images, text files, movies, or any other multi-media are stored in form of bytes, but what is more important is the process of encoding or decoding bytes to a character. Data conversion is an important topic in any programming interview, and because of the trickiness of character encoding, this question is one of the most popular String Interview questions on Java Interviews.

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

We often need 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 date pickers. While designing HTML forms either statically or dynamically using JSP, you may want to associate date picker with multiple input text field, paragraphs or any other HTML elements. By using JQuery UI and some help from CSS ID and class selector, we can easily use multiple date pickers in one HTML page. All you need to do is, declare a CSS class says .datepicker and apply that class to all HTML elements which need date picker, for example, we have an associated date picker with 4 input text fields, which has .datepicker class.

2 Ways to Parse CSV Files in Java - BufferedReader vs Apache Commons CSV Example

In last tutorial, you have learned how to parse Excel file in Java and in this Java tutorial, you will learn how to parse CSV file in Java. You can directly parse CSV file in Java without using any third party library, because ultimately its a text file and you can use BufferedReader to read it, but you can also take advantage of good open source library like Apache commons CSV to parse comma separated values. These library makes developer's life easy and provides rich functionality to parse various CSV formats. In real programming world, CSV or comma separated files are used for variety of purpose, including for transporting data from one system to another e.g. FX rates, importing and exporting records from database etc.