Disclosure: This article may contain affiliate links. When you purchase, we may earn a small commission.
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 Java. In this post, we will revisit some of those techniques and explore Java 1.6 wildcard to add multiple JAR into the classpath.
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.
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.
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.
If you have worked in Spring MVC then you may be familiar with
java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener,
which is common problem during deployment. Spring MVC throws java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener ,
when its not able to find org.springframework.web.context.ContextLoaderListener class which is used to load spring MVC configuration files like application-context.xml and other Spring Framework configuration files defined in context-param element of web.xml in an Spring MVC web application as:
Hello guys, In this series of new features of Java 10 articles, today, I am going to talk about probably the most popular and most useful, the introduction of
var keyword (well, it's not really a keyword but I'll you later about it) in Java. If I am not wrong, this feature was supposed to come on
Java 9 but dropped later. Finally, Java also has a
var keyword to declare variables which allows you to declare a variable without their type e.g. instead of doing
String str = "Java" you can now just say
var str = "Java". This may not sound much gain when declaring
String or an
int variable but consider complex types with generics, this will surely save a lot of typing and also improves the readability of code.
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.
@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.
Until Java 8, there was no standard way to Base64 encode a String in Java or decode a base64 encoded String. Java Programmers either use Apache Commons library and its Base64 class to encode or decode binary data into base 64 encoding, as shown
here, or rely on internal Sun classes e.g.
sun.misc.BASE64Encoder and
sun.misc.BASE64Decoder(), which was not officially part of JDK and can be removed without notification. Java 8 solves this problem by providing standard support for base64 encoding and decoding by providing a
java.util.Base64 class.
One of the common questions from programming interviews is,
what is the difference between a Thread and a Process? Well, the main difference between them is that a Process is a program that is executing some code and a thread is an
independent path of execution in the process. A process can have more than one thread for doing independent tasks e.g. a thread for reading data from disk, a thread for processing that data, and another thread for sending that data over the network. This technique to improve throughput and better utilize CPU power is also known as
multi-threading.
Map and List are two common data structures available in Java and in this article, we will see how can we convert Map values or Map keys into List in Java. The primary difference between Map (HashMap, ConcurrentHashMap, or TreeMap) and List is that Map holds two objects key and value while List just holds one object which itself is a value. Key in hashmap is just an add-on to find values, so you can just pick the values from Map and create a List out of it. The map in Java allows duplicate values which is fine with List which also allows duplicates but Map doesn't allow duplicate keys.
One of the most essential parts of Spring MVC is the
@Transactional annotation, which provides broad support for transaction management and allows developers to concentrate on business logic rather than worrying about data integrity in the event of system failures.
Spring Framework provides declarative and programmatic transaction management, and developers can choose between convenience and control, depending on the requirement. Declarative transaction management is easier and suitable in most cases, but in some cases, you want fine-grain control, and you can use the declarative transaction. We'll see examples of both declarative and programmatic transaction management in this article.
Thread safe Singleton means a Singleton class that returns exactly the same instance even if exposed to multiple threads. Singleton in Java has been a classical design pattern like Factory method pattern, or Decorator design pattern and has been used a lot even inside JDK like java.lang.Runtime is an example of Singleton class. Singleton pattern ensures that exactly one instance of the class will remain in the Java program at any time. In our last post, 10 Interview questions on Singleton in Java we have discussed many different questions asked on Singleton pattern, One of them was writing Thread safe singleton in Java.
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.
Mapping network drive in Windows 10 or other versions of Windows operating system e.g. Windows 7 or Windows 8 is much easier and faster by using the command line than by doing it on Windows Explorer. If you have been working in a Windows environment with a bunch of Windows Server 2016 or 2012 servers and your job requires frequent access, copy or paste from the local machine to those remote machines then mapping them as a network drive is the best option.
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?
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.
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.
Sometimes we need to append text into File in Java instead of creating a new File. Thankfully Java File API is very rich and it provides several ways to
append text into File in Java. Previously we have seen how
to create files and directories in Java and how
to read and write to a text file in Java and in this Java IO tutorial we will
see how to append text into files in Java. We are going to use the standard FileWriter and BufferedWriter approach
to append text to File. One of the key points to remember while using FileWriter in Java is
to initialize FileWriter to append text i.e. writing bytes
at the end of the File rather than writing at the beginning of the File.
There are multiple ways to iterate, traverse or loop through Map, HashMap, or TreeMap in Java and we are all familiar with either all of those or some of those. But to my surprise, one of my friends was asked in his interview (he has more than 6 years of experience in Java programming) to write code for getting values from hashmap or TreeMap in Java in at least 4 ways. Just like me he was also surprised by this question but written it. I don't know why exactly someone asks this kind of java interview question to a relatively senior java programmer. Though my closest guess is to verify that whether he is still hands-on with coding in java.
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.
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.
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.
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.
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.
Class and Object are the two most important concepts of Object-oriented
programming language (OOPS) e.g. Java. The main difference between a Class and an Object in Java is that class
is a blueprint to create different objects of the same type. This may look
simple to many of you but if you are a beginner or just heard the term Object
Oriented Programming language might not be that simple. I have met many
students, beginners, and programmers who don’t know the difference between class and
object and often used them interchangeably.
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.
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.
Singleton class is quite common among Java developers, but it poses many challenges to junior developers. One of the key challenges they face is how to keep Singleton class as Singleton? i.e. how to prevent multiple instances of a Singleton due to whatever reasons.
Double-checked locking of Singleton is a way to ensure only one instance of Singleton class is created through an application life cycle. As the name suggests, in double-checked locking, code checks for an existing instance of
Singleton class twice with and without locking to double ensure that no more than one instance of singleton gets created.
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.
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.
How to check if a number is a palindrome or not is a variant of popular String
interview question how to check if a String is a palindrome or not. A number
is said to be a palindrome if the number itself is equal to the reverse of number e.g.
313 is a palindrome because the reverse of this number is also 313. On the other
hand, 123 is not a palindrome because the reverse of 123 is 321 which is not equal
to 123, i.e. original number. In order to check if a number is a palindrome or
not we can reuse the logic of How
to reverse a number in Java.
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.
Write a program to calculate the square root of a number in Java or C++ is one of the popular coding interview questions from Programming job interviews both on tech companies like Facebook, Amazon, and investment banks like Citibank and Bank Of America, etc. The problem may look easy because you might know how to find the square root of a number but it's not. In fact, it's one of the tricky questions you would encounter in
programming job interviews. The first hurdle is do you really remember how to calculate square root by hand? Many programmers don't. I know they have learned it past but when you ask them to calculate square root by hand, many won't remember the algorithm they have learned in school or college.
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.
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.
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.
Write a program to count the number of occurrences of a character in String is one of the common
programming interview questions not just in Java but also in other programming languages like C or C++.
As String is a very popular topic in programming interviews and there are a lot of good programming exercises on String like "count number of vowels or consonants in
String", "count number of characters in String",
How to reverse String in Java using recursion or without using
StringBuffer, etc, it becomes extremely important to have a solid knowledge of
String in Java or any other programming language. Though, this question is mostly used to test the candidate's coding ability i.e. whether he can convert logic to code or not.
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.
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 System.in 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:
How to convert a string to long in Java is one of those frequently asked questions by a beginner who has started learning Java programming language and is not aware of how to convert from one data type to another. Converting String to long is similar to converting String to Integer in Java, in-fact if you know how to convert String to Integer then you can convert String to Long by following the same procedure. Though you need to remember few things while dealing with long and String first of all long is the primitive type which is wrapped by the Long wrapper class and String is an Object in Java backed by character array.
There are lots of programming exercises in Java, which involve printing a particular pattern in the console, one of them is printing the Floyd triangle in the console. In the Floyd triangle, there are
n integers in the
nth row and a total of
(n(n+1))/2 integers in n rows. This is one of the most simple patterns to print but helpful in learning how to create other more complex patterns. The key to develop patterns is using
nested loops and methods like
System.out.print() and
println() appropriately. Actually, pattern-based programming tasks are originally designed to master loops in programming.
The main method in Java is the first programming method a Java programmer knows when he starts learning Java programming language. have you ever thought about why the main method in Java is public, static, and void, of-course Yes, since most of us first learn C and C++ than we move to Java in our programming path we familiar with the main method but in Java main method is slightly different it doesn't return any value like in C it returns an int, the main method is public static and void Why?
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.
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.
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?
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.
Does Java is pass by value or pass by reference is one of the tricky Java questions mostly asked on fresher level interviews. Before debating
whether Java is pass by value or pass by reference lets first clear what is
pass by value and what is pass by reference. This question has its origin in C
and C++ where you can pass function parameter either value or memory address,
where value is stored (pointer). As per Java specification everything in Java
is pass by value whether its primitive value or objects and it does make sense
because Java doesn't support pointers or pointer arithmetic, Similarly multiple inheritance and operator
overloading is also not supported in Java.
Google
Guava is an open-source library that provides lots of useful utility to Java
programmers, one of them is an easy way to find the intersection and union of two Sets in Java. You might have used Google
Guava for other functionality e.g. for overriding
toString in an easy way or Immutable Collection provided by Guava library.
Along with Apache commons and Spring, Google Guava is a library you definitely want
to include in your Project. Guava provides a couple of static
methods to operate on Set
in Java on package com.google.common.collect.Sets.
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.
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.
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.
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.
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.
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.
Can you write a
Java program to check if two rectangles are overlapping with each other or not? is one of the frequently asked coding questions on tech giants like Facebook, Amazon, Microsoft, and others. This is also a kind of problem where it's easy to find opposite or negative conditions like
when rectangles are not overlapping and then inverting the result to prove that rectangles are colliding with each other. I first heard about this problem from one of my friends who were in the
Android game development space. He was asked to write an algorithm to find if given rectangles are intersecting or not.
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.
Serialization is one of the important but confusing concepts in Java. Even experienced Java developers struggle to implement Serialization correctly. The Serialisation mechanism is provided by Java to save and restore the state of an object programmatically. Java provides two classes
Serializable and
Externalizable in
java.io package to facilitate this process, both are
marker interfaces i.e. an interface without any methods. Serializing an Object in Java means converting it into a wire format so that you can either persist its state in a file locally or transfer it to another client via the network, hence it becomes an extremely important concept in distributed applications running across several JVMs.
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.
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.
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.
The final keyword in Java is not as mysterious as volatile or transient, but still, it creates a lot of doubts in programmers' minds. I often receive questions like, When to make a method final in Java or When to make a method static in Java, later I answered in my earlier post. Questions like this are not trivial, knowing what a keyword does is just a small part of mastering that functionality. Similar to the real world, where knowing that a sword can cut a lot of things is not enough for a warrior to survive, you need to know how to use that and more importantly, use it effectively.
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.
Java has excellent support for reading from file and writing to file in Java. In the last post, we have seen how to create files and directories in Java and now we will see how to read content from files in java and how we will write text into file in Java. File provides a persistent solution to Java developers; in almost every Java application you need to store some of the data in persistent may be its user configuration, system configuration or related to state of the application but without persistence, no enterprise Java application can buildup.
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.
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.
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.
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.
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.
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.
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.
One of the most frequently asked questions on programming interviews are, write a program to find the missing number in an array in Java, C#, or any other language; depending upon which language you choose. This kind of
coding interview questions are not only asked in small start-ups but also on some of the biggest technology companies like Google, Amazon, Facebook, Microsoft, mostly when they visit the campus of reputed universities to hire graduates. The simplest version of this question is to
find missing elements in an area of 100 integers, which contains numbers between 1 and 100.
What is the difference between the final, finally, and finalize method is asked to my friend in a Java interview with one of the US-based Investment banks. Though it was just a telephonic round interview, he was asked a couple of good questions e.g. how to avoid deadlock in Java, How to get() method of HashMap works, and one of the puzzles which are based on recursion. In short final keyword can be used along with variable, method, and class and has a different meaning for all of them. finally is another Java keyword is used in Exception handling along with try, catch, throw, and throws. finalize() is a special method in Java that is called by Garbage Collector before reclaiming GC eligible objects.
In this article, we will take a look at the difference between the static and non-static methods in Java, one of the frequently asked doubts from Java beginners. In fact, understanding static keyword itself is one of the main programming fundamentals, thankfully it's well defined in the Java programming language. A static method in Java belongs to the class, which means you can call that method by using class name e.g. Arrays.equals(), you don't need to create an object to access this method, which is what you need to do to access non-static method of a class.
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 Java, Observer pattern, static 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.
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.
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.
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.
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.
TreeSet, LinkedHashSet, and HashSet all are
implementation of the Set interface and by virtue of that, they follow the contract of Set interface i.e. they do not allow duplicate elements.
Despite being from the same type of hierarchy, there are a lot of differences between them;
which is important to understand, so that you can choose the most appropriate Set implementation based upon
your requirement. By the way difference between TreeSet and HashSet or LinkedHashSet is also
one of the popular Java Collection interview questions, not as popular as Hashtable vs HashMap or ArrayList vs Vector but still
appears in various Java interviews.
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.
I was thinking to write on decorator design pattern in Java when I first wrote 10 interview questions on Singleton Pattern in Java. Since design pattern is quite important while building software and it’s equally important on any Core Java Interview, It’s always good to have a clear understanding of various design patterns in Java. In this article, we will explore and learn the Decorator Design pattern in Java which is a prominent core Java design pattern and you can see a lot of its examples in JDK itself. JDK use decorator pattern in IO package where it has decorated Reader and Writer Classes for the various scenario, for example, BufferedReader and BufferedWriter are examples of decorator design pattern in Java.
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.
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.
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.