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:
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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 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.
Iterator in Java is nothing but a traversing object, made specifically for Collection objects like List and Set. we have already aware about different kind of traversing methods like for-loop, while-loop, do-while, for each lop, etc, they all are index-based traversing but as we know Java is purely object-oriented language there is always possible ways of doing things using objects so Iterator is a way to traverse as well as access the data from the collection. Even with traversing with objects, we have Enumeration, Iterator, and ListIterator in Java which we will in this Java Iterator tutorial.
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.
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 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 .
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.
Calculate the area of Triangle in Java
Write a Java program to calculate
Area of Triangle, accept input from User, and display output in Console is
one of the frequently asked homework questions. This is not a tough
programming exercise but a good exercise for beginners and anyone who has
started working in Java. For calculating the area of a triangle using the formula 1/2(base*height), you need
to use arithmetic operators. By doing this kind of exercise you will understand
how arithmetic operators work in Java, subtle details which affect calculation
like precedence and associativity of the operator, etc.
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.
The thread is one of the important Classes in Java and multithreading is the most widely used feature, but there is no clear way to stop Thread in Java. Earlier there was a stop method that exists in Thread Class but Java deprecated that method citing some safety reasons. By default, a Thread stops when the execution of run() method finishes either normally or due to any Exception. In this article, we will How to Stop Thread in Java by using a boolean State variable or flag.
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.
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 get input from users in Java from the command line or console is one of the common thing, everyone started learning Java looks for. It’s the second most popular way of
starting programming after HelloWorld
in Java. There are so many ways to get input from Users in Java including
command line and Graphical user interface. For beginners simpler the example,
better it is. first and foremost way of getting input from user is String[]
passed to main
method in Java but that only work for one time requirement and its not
interactive. Another way of getting input from User is involving IO classes
like InputStream
to read from console or command line which can be little complicated for true
beginner.
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.
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.
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.
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.
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.
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.
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.