Top 10 Java wait, notify, Locking and Synchronization Interview Questions Answers for Experienced

There has been a lot of articles and books written on how to use wait and notify in Java, how they work, when do you need synchronization, and how to write concurrent code in Java, but, unfortunately, I still see many Java programmer struggles to solve even the classic producer-consumer problem. I know, writing correct concurrent code is challenging and it takes a lot of practice, think through ability, and experience to get it right, but at the same time, every Java programmer should be familiar with the basics of inter-thread communication, synchronization, locking, and understand how all the things work together.

Top 5 Courses to learn Quarkus, MicroNaut, DropWizard, and Vert for Java Microservices in 2021 - Best

Hello guys, if you create Microservices in Java and want to explore frameworks like DropWizard, MicroNaut, and Quarkus, you have come to the right place. In the past, I have shared the best Microsercies courses with Spring Boot and Spring Cloud, and today, I will share the best online courses to learn Dropwizard and Micronauts. These are the best online courses and tutorials you can get to learn this useful technology. Unfortunately, not many online courses are available, but API docs and guides are also handy; along with these courses, you can read them.

How to delete a directory with files in Java - Example

Deleting an empty directory is easy in Java, just use the delete() method of java.io.File class, but deleting a directory with files is unfortunately not easy. You just can't delete a folder if it contains files or sub folders. Calling delete() method on a File instance representing a non-empty directory will just return false without removing the directory. In order to delete this folder, you need to delete all files and subdirectories inside this folder. This may seem cumbersome, but unfortunately, there is no method that can delete a directory with files in Java, not even on Java 7 Files and Paths class.

Top 15 SQL Server Management Studio Keyboard Shortcuts and Tips for Beginners

SQL Server Management Studio, also known as SSMS is an essential tool for Microsoft SQL Server developers as well as any full-stack Java developer whose application is using SQL Server database in the backend. It allows you to connect to the MSSQL database, execute SQL queries, check execution plan, see table and schema detail, writing and debugging stored procedures, and many more features. Imagining life without SSMS for SQL Server DBA and developer is impossible. 

How to Remove First and Last Character of String in Java - Example Tutorial

You can use the substring() method of java.lang.String class to remove the first or last character of String in Java. The substring() method is overloaded and provides a couple of versions that allows you to remove a character from any position in Java. Alternatively, you can convert String to StringBuffer or StringBuilder and then use its remove() method to remove the first or last character. Both StringBuffer and StringBuilder provides a convenient deleteCharAt(int index) method which removes a character from the corresponding index. You can use this method to remove both first and last characters from String in Java.

How to use Counting Semaphore in Concurrent Java Application? Example Tutorial

Counting Semaphore in Java is a synchronizer that allows imposing a bound on the resource is added in Java 5 along with other popular concurrent utilities like CountDownLatch, CyclicBarrier, and Exchanger, etc. Counting Semaphore in Java maintains a specified number of pass or permits, In order to access a shared resource, Current Thread must acquire a permit. If a permit is already exhausted by other threads than it can wait until a permit is available due to the release of permits from different threads. This concurrency utility can be very useful to implement a producer-consumer design pattern or implement bounded pool or resources like Thread Pool, DB Connection pool, etc.

Difference between Singleton Pattern vs Static Class in Java? Example

Singleton pattern  vs  Static Class (a class, having all static methods) is another interesting questions, which I missed while blogging about Interview questions on Singleton pattern in Java. Since both Singleton pattern and static class provides good accessibility, and they share some similarities e.g. both can be used without creating object and both provide only one instance, at very high level it looks that they both are intended for same task. Because of high level similarities, interviewer normally ask questions like, Why you use Singleton instead of Static Methods, or Can you replace Singleton with static class, and  what are differences between Singleton pattern and static in Java. I

What is GET and POST method in HTTP and HTTPS Protocol? Answer

GET and POST method in HTTP and HTTPS are two most popular methods used to transfer data from client to server using  HTTP(HyperText Transfer Protocol)  protocol. Both GET and POST can be used to send requests and receive response but there are significant differences between them. The difference between GET and POST in HTTP or HTTPS is also a popular interview question in JSP and any web programming interview. Since HTML is independent of any web server technology like Java, ASP or PHP and HTTP is core protocol in space of the internet, the importance of a clear understanding of GET and POST method can not be ignored.

Difference between Struts 1 and Struts 2 Web Development Framework

I had worked previously on Struts 1 but never touched Struts 2, especially since Spring MVC was there to take the leading role. Recently one of my friends ask me to help with Struts2, which leads me to look on the Struts2 framework from start. First thing I wanted to find out differences between Struts 1 and Struts 2 framework, because in my experience, if you have worked in the previous version looking differences between two versions of Struts can quickly help to find, what changes and What are the new features, concepts and improvement is offered by Struts 2. Also the difference between Struts 1 and Struts 2 is a good candidate to include in my list of Struts interview questions for quick revision.

Prefer TimeUnit Sleep over Thread.Sleep - Java Coding Tips Example

What is TimeUnit in Java
TimeUnit
in Java is a class on java.util.concurrent package, introduced in Java 5 along with CountDownLatch, CyclicBarrier, Semaphore, and several other concurrent utilities. TimeUnit provides a human-readable version of the Thread.sleep() method which can be used in place of the former. For a long time Thread's sleep() method is a standard way to pause a Thread in Java and almost every Java programmer is familiar with that. In fact, the sleep method itself is very popular and has appeared on many Java interviews. The difference between wait and sleep is one of the tough Java questions to answer. 

Why wait notify and notifyAll called from synchronized block or method in Java

Most of the Java developers know that wait(), notify(), and notifyAll() methods of object class must have to be called inside synchronized method or synchronized block in Java but how many times we thought why? Recently this question was asked to in Java interview to one of my friend, he pondered for a moment and replied that if we don't call wait() or notify() method from synchronized context we will receive IllegalMonitorStateException in Java. He was right in terms of the behavior of language but as per him, the interviewer was not completely satisfied with the answer and wanted to explain to him more about it.

Difference between start and run method in Thread? Example

Why to do one call start method of the thread if start() calls run() in turn" or "What is the difference by calling start() over run() method in java thread" are two widely popular beginner level multi-threading interview question. When a Java programmer start learning Thread, the first thing he learns is to implement thread either overriding run() method of Thread class or implementing Runnable interface and then calling start() method on the thread, but with some experience, he finds that start() method calls run() method internally either by looking API documentation or just poking around, but many of us just don’t care at that time until it been asked in Java Interview.

Top 5 Courses to learn Bootstrap CSS Framework for Beginners in 2021 - Best of Lot

Hello guys, If you are doing web design and want to learn Bootstrap to become a better web designer, you have come to the right place. In the past, I have shared the best courses to learn HTML, CSS, JavaScript, and Web Development, and today, I'll share the best online courses to learn BootStrap in 2021. Bootstrap is one of the most popular CSS Frameworks in the world. Is it meant for developing responsive and mobile-first websites? This is the reason why in the last couple of years, it has grown a lot in popularity, and it’s one of the essential tools for both web designers and front-end developers. In fact, full-stack Developers can also learn Bootstrap to get a feeling for design and become truly full-stack developers.

What is CountDownLatch in Java - Concurrency Example Tutorial

What is CountDownLatch in Java
CountDownLatch in Java is a kind of synchronizer which allows one Thread to wait for one or more Threads before starts processing. This is a very crucial requirement and often needed in server-side core Java applications and having this functionality built-in as CountDownLatch greatly simplifies the development. CountDownLatch in Java is introduced on Java 5 along with other concurrent utilities like CyclicBarrier, Semaphore, ConcurrentHashMap, and BlockingQueue in java.util.concurrent package. 

Difference between transient and volatile keyword in Java? example

Surprisingly "Difference between transient and volatile keyword in Java" has asked many times on various java interviews. volatile and transient are two completely different keywords from different areas of Java programming language. the transient keyword is used during serialization of Java object while volatile is related to the visibility of variables modified by multiple threads during concurrent programming. The only similarity between volatile and transient is that they are less used or uncommon keywords and not as popular as public, static, or final.

Difference between Wait and Sleep, Yield in Java? Example

The difference between wait and sleep or the difference between sleep and yield in Java is one of the popular core Java interview questions and asked on multi-threading interviews. Out of three methods that can be used to pause a thread in Java, sleep() and yield() methods are defined in thread class while wait() is defined in the Object class, which is another interview question. The key difference between wait() and sleep() is that the former is used for inter-thread communication while later is used to introduced to pause the current thread for a short duration.

What is Abstraction in Java? Abstract Class and Interface Example

What is abstraction?
Abstraction in Java or Object-oriented programming is a way to segregate implementation from an interface and one of the five fundamentals along with Encapsulation, Inheritance, Polymorphism, Class, and Object.  Abstraction in Java is achieved by using the interface and abstract class in Java. An interface or abstract class is something that is not concrete, something which is incomplete. In order to use interface or abstract class, we need to extend and implement an abstract method with concrete behavior.

Why String is Immutable or Final in Java? Example

The string is Immutable in Java because String objects are cached in the String pool. Since cached String literals are shared between multiple clients there is always a risk, where one client's action would affect all another client. For example, if one client changes the value of the String "Test" to "TEST", all other clients will also see that value as explained in the first example. Since caching of String objects was important from performance reason this risk was avoided by making String class Immutable. At the same time, String was made final so that no one can compromise invariant of String class like Immutability, Caching, hashcode calculation, etc by extending and overriding behaviors. Another reason why String class is immutable could die due to HashMap.

How to find Largest Prime Factor of a Number in Java? Example

One of the common programming kata to learn coding is to write a program to find the largest prime factor of a number. Like any other programming problem, you need to build the logic to solve this problem. Before solving the problem, let's revise the concept of number theory. Prime factors of a positive integer are the prime numbers that divide the number exactly i.e. without any remainder, and prime factorization is the process of finding all prime numbers when multiplied together to make the original number.

Avoid Mixing static and non static synchronized method - Java mistake 2 Example

Using a static and non-static synchronized method for protecting shared resources is another Java mistake we are going to discuss in this part of our series “learning from mistakes in Java”. In the last article, we have seen why double and float should not be used for monetary calculation, In this tutorial, we will find out why using static and non-static synchronized methods together for protecting the same shared resource is not advisable.  I have seen some times Java programmers mix static synchronized method and instance synchronized method to protect the same shared resource.

Top 10 Coursera Courses & Certifications to Learn Computer Science in 2021 - Best of Lot

Hello folks, if you are looking for the best Coursera courses for Software Development and Computer Science, then you have come to the right place. Earlier, I have shared the best Data Science courses and the best Python Courses from Coursera. In this article, I will share the best courses to learn Software Development, Programming, and Computer Science for Beginners and experienced alike. 
Software development and programming are estimated to grow about 13% by 2026, which means that there is no better time to enter this field and learn new skills in software development and programming, whether web development, mobile apps, or the internet of things, so you need to do the impossible to stay above your competitor.  

Why use Spaces over Tabs for Indentation in Code Editors - Eclipse

When I started coding in Eclipse, I was not aware that by default Eclipse uses tabs for indentation and tabs can have varied with e.g. 1 tab can be equal to 2 spaces or 4 spaces or even 8 spaces. Sometimes, It's all up to you how you configure tabs in your code editor, and other times just at the mercy of the tool you don't know how to configure like VIM in UNIX. I only realize the problem when I found too many differences in a file while check-in in into SVN. Apparently, other people were using different indentations (spaces) and that's why the file was showing so many differences when I reformatted them in Eclipse. 

How to Iterate through ConcurrentHashMap and print all keys and values in Java? Example

Suppose you have a ConcurrentHashMap of String and Integer and you want to print all keys and values, how do you do that? This is a common, day-to-day programming task for Java programmers and there are many ways to do it. The Map interface provides several view methods e.g. keySet(), values(), and entrySet() to retrieve all keys, values, and all key and value pairs as entries. You can use respective methods to print all keys, all values, or all key values pairs. For printing, you also have multiple choices like you can either use enhanced for loop or Iterator, though later also provide you the facility to remove key-value pairs while printing if needed.

10 Examples to read a text file in Java [UPDATED]

The Java IO API provides two kinds of interfaces for reading files, streams and readers. The streams are used to read binary data and readers to read character data. Since a text file is full of characters, you should be using a Reader implementations to read it. There are several ways to read a plain text file in Java e.g. you can use FileReader, BufferedReader or Scanner to read a text file. Every utility provides something special e.g. BufferedReader provides buffering of data for fast reading, and Scanner provides parsing ability. 

Why Timestamp cannot be used in place of Date in Java? Example

One of the tricky questions from the Java Interview is, "Can we pass a Timestamp instance to a method expecting java.util.Date?", it's a tricky question because the answer is both Yes and No. You can, of course, pass a Timestamp object to a method with the argument as Date because first, Timestamp is a subclass of java.util.Date and second it contains both date and time values which are missing in either java.sql.Date and java.sql.Time. So there is more reason to pass a Timestamp value to Date but you should not be doing that. Why? because Timestamp is not exactly Date.

Why JPA Entity or Hibernate Persistence Class Should Not be Final? Answer

One of the interesting hibernate interview questions is, why you should not make a Hibernate persistent class final? I'll try to answer this question in this short blog post. The use of proxies is the core feature of Hibernate (one of the most popular ORM frameworks for Java Projects) for implementing key performance features e.g. lazy loading and lazy associations fetching. In order to use a proxy in place of a real class, your hibernate persistence class must be either non-final or the implementation of an interface that declares all of the public methods. 

Adapter Design Pattern in Java with Example

The adapter design pattern in Java, also known as the Wrapper pattern is another very useful GOF pattern, which helps to bridge the gap between two classes in Java. As per the list of Gang of Four patterns, the Adapter is a structural pattern, much like Proxy, Flyweight, Facade, and Decorator patterns in Java. As the name suggests, the Adapter allows two classes of a different interface to work together, without changing any code on either side. You can view the Adapter pattern as a central piece of the puzzle, which joins two pieces, which can not be directly joined because of different interfaces.

InOrder traversal of Binary tree in Java using Recursion and Iteration - Example Tutorial

This is the second article about tree traversal algorithms using Java. In the first part, we have seen the pre-order algorithm for visiting all nodes of the binary tree and today we'll learn about the InOrder traversal. As I told you before, unlike array and linked list, the binary tree has several ways of traversal. The traversal algorithms are broadly divided into depth-first and breadth-first traversal algorithms depending upon how the algorithm actually works. As the name suggests, depth-first explores binary tree towards depth before visiting sibling, while breath first visits all nodes in the same level before going to next level, hence it is also known as level order traversal. 

Eclipse - How to add/remove external JAR into Java Project's Classpath? Example

There are multiple ways you can add an external JAR into the classpath of a Java project in Eclipse, but all goes via adding them into the build path. Many beginners struggle to add JARs into classpath and we will try to address that problem in this tutorial. You will learn step by step tutorial to add an internal or third-party JAR in your application's CLASSPATH in Eclipse Indigo. Since this feature has hardly changed in any Eclipse version, you can follow some steps in Eclipse Kepler, Indigo, and Juno versions to add JARs into the classpath.

2 Books to Prepare Java EE 6 Web Component Developer Certified Expert 1Z0-899 Exam (OCEJWCD)

Oracle launched "Java EE 6 Web Component Developer Certified Expert 1Z0-899 Exam" in 2011 to replace "Java Platform, Enterprise Edition 6 Java Server Pages and Servlet Developer Certified Expert Exam" and the "Oracle Certified Expert, Java Platform, Enterprise Edition 6 Java Server Pages and Servlet Developer" certification. They are the equivalent to the plain old SCWCD exam of the Sun Microsystems era. Frankly speaking, I always found sun naming less confusing and clearer than Oracle's e.g. SCJP was much better than OCAJP and OCPJP

Java Comparable Interface and compareTo() Example

Hello, guys, today I am going to talk about one of the fundamental concepts in Java, defining the natural ordering of the objects e.g. lexicographical order for String and numerical order for Number classes e.g. Integer, Double, Float, etc. The compareTo() method is defined in the java.lang.Comparable interface. It is used to define the natural ordering of an object e.g. String class override compareTo() to define the lexicographical order for String objects. Integer class override compareTo() to define the numeric ordering of integer objects.

How to Fix java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/test [Solved]

The error "java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/test" occurs when you try to connect MySQL database running on your localhost, listening on port 3306 port from Java program but either you don't have MySQL JDBC driver in your classpath or driver is not registered before calling the getConnection() method. Since JDBC API is part of JDK itself, when you write a Java program to connect any database like MySQL, SQL Server, or Oracle, everything compiles fine, as you only use classes from JDK but at runtime, when the JDBC driver which is required to connect to the database is not available, JDBC API either throws this error or "java.lang.ClassNotFoundException: com.mysql.jdbc.Driver".

10 points on finalize method in Java – Tutorial Example

finalize method in java is a special method much like the main method in java. finalize() is called before the Garbage collector reclaims the Object, its last chance for any object to perform cleanup activity i.e. releasing any system resources held, closing the connection if open etc. The main issue with finalize() method in Java is it's not guaranteed by JLS that it will be called by Garbage collector or exactly when it will be called, for example, an object may wait indefinitely after becoming eligible for garbage collection and before its finalize() method gets called. similarly even after finalize gets called it's not guaranteed it will be immediately collected.

Difference in String pool between Java 6 and 7? Answer

String pool in Java is a pool of String literals and interned Strings in JVM for efficient use of String objects. Since String is immutable in Java, it makes sense to cache and shares them in JVM. The String pool has gone through an important change in Java 7 release when it was relocated from PermGen space to heap space. Till Java 1.6, interned String and literals are stored in the PermGen space of JVM memory, which was a fixed size area for storing class metadata. The biggest issue of having a String pool in PermGen is the small and fixed size of PermGen space.

How to read a text file using Scanner in Java? Example Tutorial

As I told you before that there are multiple ways to read a file in Java e.g. FileReader, BufferedReader, and FileInputStream. You chose the Reader or InputStream depending upon whether you are reading text data or binary data, for example, the BufferedReader class is mostly used to read a text file in Java. The Scanner class is also another way to read a text file in java. Even though Scanner is more popular as a utility to read user input from the command prompt, you will be glad to know that you can also read a file using Scanner. 

How to Print all Leaf Nodes of Binary tree in Java - Recursion and Stack Examples

Binary tree based questions is very common in Java or any other programming job interviews. One of the frequently asked binary tree questions is "write a program to print all leaf nodes of a binary tree". In order to solve this problem, you must know what is a leaf node? A leaf node in a binary tree is a node whose left and right child is null. They are actually the last nodes of any binary tree. In a typical programming interview, you would be given a binary tree and asked to write a program to print all leaf nodes. Usually, all binary tree related questions can be solved easily using recursion because a tree is a recursive data structure, but you should also know how to solve them without recursion.

What is Encapsulation in Java and OOP with Example

Encapsulation in Java or object-oriented programming language is a concept that enforces protecting variables, functions from outside of class, in order to better manage that piece of code and having the least impact or no impact on other parts of a program due to change in protected code. Encapsulation in Java is visible at different places and the Java language itself provides many constructs to encapsulate members. You can completely encapsulate a member be it a variable or method in Java by using private keyword and you can even achieve a lesser degree of encapsulation in Java by using other access modifiers like protected or the public.

2 Reasons of org.springframework.beans.factory.BeanCreationException: Error creating bean with name [Solution]

The Spring framework is one of the most popular frameworks for developing Java applications. Apart from many goodies, it also provides a DI and IOC container that initializes objects and their dependencies and assembles them together. The Java classes created and maintained by Spring are called Spring bean. At the startup, when the Spring framework initializes the system by creating objects and their dependencies depending upon @Autowired annotation or spring configuration XML file, it throws "org.springframework.beans.factory.BeanCreationException: Error creating a bean with name X" error if it is not able to instantiate a particular Spring bean.

How to calculate GCF and LCM of two numbers in Java? Example

This week's programming exercise is to write a Java program to calculate GCF and LCM of two numbers. The GCF stands for a Greatest common factor and LCM stands for Lowest common multiplier, both are popular mathematical operations and related to each other. The GCF is the largest number which divides both the number without leaving any remainder e.g. if two numbers are 24 and 40 then their GCF is 8 because 8 is the largest number which divides both 24 and 40 perfectly, without leaving any remainder. 

What is Static and Dynamic binding in Java with Example

Static and dynamic binding in Java is two important concepts that Java programmer should be aware of. this is directly related to the execution of code. If you have more than one method of the same name (method overriding) or two variables of the same name in the same class hierarchy it gets tricky to find out which one is used during runtime as a result of their reference in code. This problem is resolved using static and dynamic binding in Java. For those who are not familiar with the binding operation, its process is used to a link which method or variable to be called as a result of their reference in code.

Top 5 Course to Crack Google Cloud Professional Data Engineer Certification in 2021 - Best of Lot

Hello guys, If you are looking for a Cloud certification, then let me tell you that the Google Cloud Professional Data Engineers are currently in demand for their ability to maintain the process of accumulating, converting, and publishing data with a certain level of expertise on Google Cloud Platform. When I published my list of 10 Cloud Certifications for 2021, I have included a couple of Google Cloud certifications because there are not many Google Cloud certified compared to certified AWS and Azure Professionals. They are mostly known for putting machine learning models into operation, creating and structuring data processing systems to work accurately, and ensuring that the data is secure and scalable.

How to Remove CTRL-M characters From a File in UNIX and Linux? Example

I wanted to transfer some files from Windows to Unix using FileZilla, but the problem arises when these files are transferred (Ascii or Binary mode both) and opened using VI we get ^M characters, also known as CTRL-M characters. I searched about this but the solutions were to remove these ^M characters when files are transferred using utilities. Is there any way that these ^M characters do not appear in the first place? Well, my search continues but I will share the solution which worked for me for removing control M characters i.e. CTRL-M or ^M characters.

Top 21 Java Final Modifier (Keyword) Interview Questions and Answers

The final modifier is one of the important keywords in Java. You can use this with a class, method, and variable as well. Good knowledge of the final keyword is not only essential for writing good, performant, and secure Java programs but also to clear any  Java interview. The interviewer pays special attention to the final keyword and expects candidates to know how and when to use the final modifier with variables, methods, and classes. In this article, I have collected Java interview questions that are based upon the concept of the final modifier. You might have seen many of these questions on both telephonic and face-to-face rounds. 

4 Free OCAJP 7 and OCPJP7 Mock Exams - Online Practice Test (1Z0-803 and 1Z0-804)

Hello guys, today I am going to share a list of free OCAJP7 and OCPJP7 mock exams and online practice tests. If you are preparing for Java SE 7 Programmer 1 or 2 certification or upgrading your existing OCJP 6 exam then this will help you to gauge your progress. As per my experience, the three keys to success in any Java certification is a selection of good books, writing small Java programs to understand concepts, and practicing mock exams. You can see that mock exams are very important to do well on the real exam. They give you much-needed practice as well as some idea about what kind of questions you can expect on real exams.

3 Maven Eclipse Tips for Java Developers

If you are using Maven inside Eclipse IDE via M2Eclipse plugin then the following tips can help you a lot.

1. Setup Dependency as Java Project in Eclipse

If your POM dependencies are another project in Eclipse then your project will automatically get updated whenever you build the dependent project. For example, let's say you have a project, ABC, which is dependent on two core modules e.g. framework.jar and persistence.jar, if you have checked out these project and has set up them as Maven Eclipse project, M2Eclipse can directly add them as a dependency, instead of loading their JAR files from the repository, be it local or remote.

10 Differences between Java and Groovy Programming - Examples

If you are working in Java, you might have heard about Scala, Groovy, and Closure. Out of these three Groovy seems to be gaining a place in Java projects more rapidly than others. Groovy is a Scripting language but runs on Java virtual machine. Every Java program can run on the Groovy platform. As per the official Groovy website, "Apache Groovy is a powerful, optionally typed and dynamic language, with static typing and static compilation capabilities, for the Java platform aimed at improving developer productivity thanks to a concise, familiar and easy to learn syntax". I think they have highlighted the key capabilities of Groovy very well in that sentence.

Top 10 Maven Plugins Every Java Developer Should Know

In the last couple of years, Maven has become the de-facto build tool for Java applications. Though there are challenges that exist from tools like Gradle, I think the dominance of Maven will help it to win the final battle. When I started with Maven, I was happy with just dependency management but then I come to know about maven plugins which let you customize your build-up to the level you can do with ANT. These plugins provide true power to Maven to automate most of the build-related tasks like compilation, testing, packaging, deployment, and even committing the source code into the remote source repository.

Top 10 EJB Interview Question and Answer asked in Java J2EE Interviews

10 EJB Interview Questions and Answer from my collection of interview questions. I have been sharing interview questions on various topics like Singleton interview questions, serialization interview questions, and most recently Spring interview questions. No doubt these questions are very important for performing better in J2EE and EJB interviews but also they open a new path for learning as you may find some concepts new even while revising your knowledge in EJB. EJB interviews have always been tough because its difficult to find people who have hands-on experience on Enterprise Java Beans (EJB) and most of the guys either have worked only on sample projects and are not aware of critical functionalities like distributed transaction management, container-managed persistence, and various other services which EJB provides.

How to read Properties File in Java – XML and Text Example Tutorial

Reading and writing properties file in Java is a little different than reading or writing text file in Java or reading xml files in Java using xml parsers like DOM because Java provides the special provision to the properties file. For those who are not familiar with Properties files in java, It is used to represent configuration values like JDBC connectivity parameter or user preference settings and has been a primary source of injecting configuration on Java applications.  Properties file in Java is a text file that stores data in the form of key and value, key being known as property. Java allows you to read the value of the property by providing its name which makes it easy to access configuration settings.

How to add or list certificates from keystore or trustStore in Java - Keytool Example

How to add certificates on keystore in Java is the primary question when you start working on SSL connection and a simple answer is keytool utility in Java is used to add or list Certificates into keystore. SSL is the industry standard for secure communication between two parties e.g. client and server. SSL offers two benefits, it encrypts data transferred between client and server to make it hard for someone to access and understand in between and SSL also verifies the identity of two parties in communication, and certificates are used for that purpose. SSL Setup in Java comes during various processes e.g. Setting up SSL on tomcat, configuring messaging over SSL, or JDBC over SSL are some examples of tasks where you need to deal with keyStore, certificates, and trust stores.

Top 10 Coursera Courses & Certification for Business Strategy, Finance & Entrepreneurship in 2021 - Best of Lot

Hello folks, If you are keen to start your career in Business and Finance and looking for the best Coursera certifications, courses, specializations, and projects, then you have come to the right place. Earlier, I have shared the best Coursera courses and certifications to learn Python, Artificial IntelligenceSoftware Development, and Web Development, and, in this article, I am going to share the best Coursera courses, projects, certifications, and specializations for Business and Finance from reputed universities like Rice University, London University, and the University of Pennsylvania. 

Top 5 Courses to learn Scala Programming Online in 2021 - Best of Lot

Hello guys, if you want to learn Scala Programming language and looking for the best online courses to start your journey, then you have come to the right place. In the past, I have shared the best Scala books and free Scala courses for Java developers, and today, I am going to share the best Scala courses for Programmers and Java developers. These are the truly best Scala courses and created by experts like Martin Oderskey, the creator of Scala himself; you will get a chance to learn Scala from the creator himself. They are also very affordable as Coursera courses are free for learning, and Udemy courses can be bought for just $10 on Udemy sales.

What is the use of java.lang.Class in Java? Example

java.lang.Class is one of the most important classes in java but mostly overlooked by Java developers. It is very useful in the sense that it provides several utility methods like getClass(), forName() which is used to find and load a class, you might have used to load Oracle or MySQL drivers. It also provides methods like Class.newInstance() which is the backbone of reflection and allows you to create an instance of a class without using a new() operator.  The class has no public constructor and its instance is created by JVM when a class is loaded.

Why Avoid Comparing Integers in Java using == Operator? Example

Java 5 introduced auto-boxing which automatically converts int to Integer and because of that many Java developers started writing code for comparing int variable to Integer object and Integer to Integer using == operator. You should avoid that because it can create subtle bugs in your program because it only works for a particular range of integers and not for all. There is another problem as well when you compare the int variable to the Integer object using == operator, the Integer object is converted to a primitive value. This can throw a null pointer exception if the Integer object is null, which can crash your program.

Top 5 HTML 5 and CSS 3 Courses to Learn Online in 2021 - Best of Lot

Hello guys, if you are learning Web Development or thinking about becoming a Web Developer, then you have come to the right place. Earlier, I have shared the 2021 Web Developer RoadMap, and today, I'll talk about HTML and CSS and share some useful resources to learn them in depth. There are three pillars of Web Development, HTML, CSS, and JavaScript. HTML provides structure, CSS provides the style and JavaScript provides interactiveness. The HTML stands for HyperText Markup Langauge, and it's one of the oldest technology I know. I first come to know about HTML in my college day, good 20 years back, when we are happy to see a list of heading in different colors.

State Design Pattern Example in Java - Vending Machine

The state design pattern is a behavioral pattern, first introduced by GOF in their class is book design patterns. State pattern looks similar to Strategy pattern but it helps in managing object state and thus enabling them to behave differently in a different state. In this example, we will take a famous object-oriented design interview question, implementing Vending Machine in Java. In the past, we have solved this problem without using any design pattern, but here we will use state design patterns to create a vending machine with different states. 

Top 5 Online Courses to Learn Kubernetes for Beginners in 2021 - Best of Lot

Hello guys, Kubernetes has become a very popular tool and skill today in the container management community, and it's one of the most in-demand skills and a must-learn tool for both DevOps engineers and Developers. It is a tool written in Golang and it is created by Google. There are many things you need to take care of when working in production environments with microservice patterns and containers. These include version control, health check, rollback mechanism, and scaling. Kubernetes provides the management and orchestration capabilities to deploy containers in accordance with all the necessary mentioned things.

Top 5 Courses to Learn Servlet and JSP for Java Web Developers in 2021 - Best of Lot

Hello guys, if you want to learn Servlet and JSP and look for the best Servlet courses, you have come to the right place. In the past, I have shared the best Servlet and JSP books and free Servlet and JSP courses and today, I will share the best Sevelt and JSP online courses from websites like Udemy Coursera and Pluralsight. These courses have been created by experts and trusted by thousands of developers to learn Servlet and JSP. You can also join them to learn these key technologies online from your home or office. Servlet and JSP are two of the most important web technologies for Java developers. In the framework age, you may not directly work with Servlet and JSP but knowing fundamentals like this always helps. 

How to Fix Failed to connect to queue manager - WebSphere MQ Error in Java? Example

"Failed to connect to queue manager" error comes in WebSphere MQ if any Client like a Java program is not able to connect to the MQ server due to any reason. The reason is actually identified by reason code in error message e.g. code 2397 comes when SSL is enabled between client and server and Java client is not able to connect to the server due to unknown or expired SSL certificates. If you are working in a Java application that is using WebSphere MQ for messaging over SSL then you are bound to face some setup, certificate, and keystore vs truststore related error. 

java.lang.UnsatisfiedLinkError: no dll in java.library.path - Cause and Solution

"Exception in thread "main" java.lang.UnsatisfiedLinkError: no dll in java.library.path" is one of the frustrating errors you will get if your application is using native libraries like the DLL in Windows or .SO files in Linux. Java loads native libraries at runtime from either PATH environment variable or location specified by java.library.path system property depending upon whether your Java program is using System.load() or java.lang.System.loadLibarray() method to load native libraries. If Java doesn't find them due to any reason it throws "java.lang.UnsatisfiedLinkError: no dll in java.library.path"

How to fix java.net.SocketException: Too many files open java.io.IOException in Tomcat, Weblogic Server

Not many Java programmers know that socket connections are treated like files and they use file descriptors, which is a limited resource. The different operating system has different limits on the number of file handles they can manage. One of the common reasons for java.net.SocketException: Too many files open in Tomcat, Weblogic, or any Java application server is, too many clients connecting and disconnecting frequently a very short span of time. Since Socket connection internally uses TCP protocol, which says that a socket can remain in TIME_WAIT state for some time, even after they are closed. One of the reasons to keep the closed socket in the TIME_WAIT state is to ensure that delayed packets reached the corresponding socket.

How to Get & Print current Thread stack trace in Java - Debugging Tutorial Example

The stack trace is very useful while debugging or troubleshooting any issue in Java. Thankfully Java provides a couple of ways to get a current stack trace of a Thread in Java, which can be really handy in debugging. When I was new to Java programming and didn’t know how to remote debug a Java application, I used to put debug code as patch release, which uses classpath to pick debug code for printing stack trace and shows how a particular method is get called and that sometimes provide a vital clue on missing or incorrect argument.

How to avoid of fix ConcurrentModificationException in Java? Example

One of the common problems while removing elements from an ArrayList in Java is the ConcurrentModificationException. If you use classical for loop with the index or enhanced for loop and try to remove an element from the ArrayList using remove() method, you will get the ConcurrentModificationException but if you use Iterator's remove method or ListIterator's remove() method, then you won't get this error and be able to remove the element. It's an unwritten rule in Java that while looping through the list, you should not add() or remove() elements until the collection supports fail-safe Iterator e.g. CopyOnWriteArrayList, which operate on a copy of list rather than the original list.

java.lang.numberformatexception for input string null - Cause and Solution

The java.lang.NumberFormatException comes when you try to parse a non-numeric String to a Number like Short, Integer, Float, Double etc. For example, if you try to convert . "null" to an integer then you will get NumberFormatException. The error "Exception in thread "main" java.lang.NumberFormatException: For input string: "null" is specifically saying that the String you receive for parsing is not numeric and it's true, "null" is not numeric. Many Java methods which convert String to numeric type like Integer.parseInt() which convert String to int, Double.parseDoble() which convert String to double, and Long.parseLong() which convert String to long throws NumberFormatException to inform that the input String is not numeric.

Top 5 Courses to Crack Docker Certified Associate Certification Exam in 2021 - Best of Lot

Hello guys, if you are thinking about the Docker Associate exam or want to become a Certified Docker associate and looking for the best online courses to start your preparation then you have come to the right place. In the past, I have shared the best courses to learn Docker and Kubernetes and today, I am going to share the best online courses to crack the Docker Certified Associate Exam in 2021. These are the best Docker courses from Udemy, Coursera, Pluralsight, and Whizlabs and are very useful for this Docker certification. They are created by experts like Nigel Poulton who is Docker Captain himself and they have also trusted ty thousands of Docker developers around the world.

How to convert java.util.Date to java.time.LocalDate in Java 8 - Example

The easiest way to convert a java.util.Date to java.time.LocalDate is via Instant, which is the equivalent class of java.util.Date in JDK 8. You can first convert util Date to Instant and then create a LocalDateTime object from that instant at your default timezone. Once you have an instant of LocalDateTime, you can easily convert that to LocalDate or LocalTime in Java. If you are not living under the rock in the last two years that its 2016 and Java 8 has been around for more than 2 years, 18th March 2014 Java SE 8 GA happened.

How to fix java.net.SocketException: Software caused connection abort: recv failed

Out of many client servers related socket errors here is one more interesting socket related error from the Java program, "java.net.SocketException: Software caused connection abort: recv failed". The key point in this error message is "abort" and "recv", which means is someone (client or server) is trying to read from a closed connection. This error usually comes at the client socket end, when the server closed the connection before the client has read the response, but, in general, it can come to an end of the TCP socket, so you must check the log files for both clients and server to find out who is complaining. If the Server is complaining then it's fine and the client has closed the TCP connection may be due to timeout or any RuntimeException at the client end.

Java Tips and Best practices to avoid NullPointerException in Java Applications

A NullPointerException in Java application is the best way to solve it and that is also key to write robust programs that can work smoothly. As it said “prevention is better than cure”, same is true with nasty NullPointerException. Thankfully by applying some defensive coding techniques and the following contracts between multiple parts of an application, you can avoid NullPointerException in Java to a good extent. By the way, this is the second post on NullPointerException in Javarevisited, In the last post, we have discussed the common causes of NullPointerException in Java and in this tutorial,  we will learn some Java coding techniques and best practices, which can be used to avoid NullPointerException in Java.

Java Mistake 1 - Using float and double for monetary or financial calculation Example

Java is considered a very safe programming language compared to C and C++ as it doesn't have free() and malloc() to directly do memory allocation and deallocation, You don't need to worry about array overrun in Java as they are bounded and there is pointer arithmetic in Java. Still, there are some sharp edges in the Java programming language that you need to be aware of while writing enterprise applications. Many of us make a subtle mistake in Java which looks correct in the first place but turns out to be buggy when looked at carefully. In this series of java articles, I will be sharing some common Java mistakes programmers make while programming applications in Java.

10 Exception handling Best Practices in Java Programming

Exception handling is an important part of writing robust Java applications. It’s a non-functional requirement for any application, to gracefully handle any erroneous condition like resource not available, invalid input, null input, and so on. Java provides several exception handling features, in built-in the language itself in form of try, catch, and finally keywordJava programming language also allows you to create new exceptions and throw them using  throw and throws keyword. In reality, Exception handling is more than knowing the syntax. Writing a robust code is an art more than science, and here we will discuss few Java best practices related to Exception handling.

Dealing with Password in Java Application? 5 Best Practices You Should Follow

While working in core Java applications or enterprise web applications there is always a need of working with passwords in order to authenticate users. Passwords are very sensitive information like Social Security Number(SSN) and if you are working with real human data like in an online banking portal or online health portal it's important to follow best practices to deal with passwords or Social security numbers. here I will list down some of the points I learned and take care of while doing authentication and authorization or working with passwords. I recommend reading more on this topic and have a checklist of things based on your application requirement. Anyway here are few points which make sense to me:

How to create Immutable Class and Object in Java - Tutorial Example

Writing or creating immutable classes in Java is becoming popular day by day, because of the concurrency and multithreading advantage provided by immutable objects. Immutable objects offer several benefits over a conventional mutable object, especially while creating concurrent Java applications. Immutable object not only guarantees safe publication of object’s state but also can be shared among other threads without any external synchronization. In fact, JDK itself contains several immutable classes like String, Integer, and other wrapper classes. For those, who don’t know what is immutable class or object is, Immutable objects are those, whose state can not be changed once created like java.lang.String, once created can not be modified like trim, uppercase, lowercase.

Why use PreparedStatement in Java JDBC – Example Tutorial

PreparedStatement in Java is one of several ways to execute SQL queries using JDBC API. Java provides Statement,
PreparedStatement and CallableStatement for executing queries. Out of these three, Statement is used for general-purpose queries, PreparedStatement is used for executing a parametric query, and CallableStatement is used for executing Stored Procedures. PreparedStatement is also a popular topic in java interviews. Questions like Difference between Statement and PreparedStatement in Java and How to prevent SQL Injection attacks in Java are popular java interview questions.

10 Tips to Create Maintainable Java Applications

Hello all, today is 31st December, the last day of 2016 and this is probably the last post on Javarevisited for this year and I want to make it special. That's why I am going to share you some tips on creating maintainable Java applications which will help you not just in the new year, but also in all the coming years in your software development career.  One aspect of development, which is often overlooked by developers is to create applications that are both easy to maintain and support. Since software spends 90% of its lifetime in maintenance mode, it's very important that your application is easy to configure, support, and maintain. 

10 Best Free Educative Courses to learn Java, Python, and JavaScript in 2021

Hello guys, if you are looking for text-based, interactive free courses to learn in-demand skills like Python, Java, C++, and JavaScript, then you have come to the right place. Earlier, I have shared the best courses to learn Python, Java, C++, and JavaScript, and today, I am going to share some awesome, free, online text-based interactive courses to learn Java, Python, C, C++, JavaScript, R, Scala, and Web Development from Educative. If you don't know, Educative is a new platform for learning online. Unlike traditional video course platforms like Udemy or Pluralsight, they provide Interactive Courses for Software Developers.

SimpleDateFormat in Java is not Thread-Safe Use Carefully

SimpleDateFormat in Java very common and used to format Date to String and parse String into Date in Java but it can cause very subtle and hard to debug issues if not used carefully because DateFormat and SimpleDateFormat both are not thread-safe and buggy. call to format() and parse() method mutate the state of DateFormat class and should be synchronized externally in order to avoid any issue. here are a few points which you should take care while using SimpleDateFormat in Java:

How to Fix Exception in thread "main" java.lang.ExceptionInInitializerError in Java Program? Example

JVM throws java.lang.ExceptionInInitializerError, when there is an Exception inside static initializer block. If you know about static variables in Java, then you may know that they are initialized at the time of class loading. If there is an Exception during that initialization of static variables, you will see ExceptionInInitializerError in Java. This could be any exception e.g. java.lang.ArrayIndexOutOfBound or java.lang.NullPointerException. Java developers are often confused with this error because they think that they have not defined any static initializer block, then how come they are getting ExceptionInInitializerError; well, by default Java combines all static variable initialization inside a static initializer block and initialize them in the order they are declared in the source file.

How to deal with Java.rmi.MarshalException: CORBA MARSHAL in Java? Solution

Java has some mysterious RMI exceptions one of them is java.rmi.MarshalException: CORBA MARSHAL, which was bothering me for the last couple of days while working. I thought to put this solution post similar to my earlier post How to solve OutofMEmroyError in Java and Fixing ClassNotFoundException in Java. RMI is still used in many places and many times it creates too many problems and chew-up your a lot of time to find the exact cause and solution.

java.lang.NullPointerException - Common Cause of NullPointerException in Java Example

The java.lang.NullPointerException or NullPointerException in Java is probably the first Exception you will face in Java. It is true nightmare for beginners in Java but pretty easy to solve once you get familiar with Exception handling in Java. What makes NullPointerException a little tricky is its name which has a pointer in itself and Java does not support pointers like multiple inheritances in Java. In this article, we will see What is NullPointerException in Java, How to solve Exceptions in thread "main" java.lang.NullPointerException, finding the possible cause of Java NullPointerException and how to troubleshoot NPE in Java.

What is difference between Enumeration and Iterator in Java? Answer

Though both Iterator and Enumeration allows you to traverse over elements of Collections in Java, there is some significant difference between them e.g. Iterator also allows you to remove elements from the collection during traversal but Enumeration doesn't allow that, it doesn't get remove() method. Enumeration is also a legacy class and not all Collection supports it e.g. Vector supports Enumeration but ArrayList doesn't. On the other hand, Iterator is the standard class for iteration and traversal. By the way,  what is the difference between Enumeration and Iterator in Java? 

How to fix java.io.IOException: Map failed and java.lang.OutOfMemoryError: Map failed? Example

While working with memory mapped file, you may get java.io.IOException: Map failed error, which is mainly caused by Caused by: java.lang.OutOfMemoryError: Map failed error as shown below. This error usually comes while mapping a big file in memory e.g. trying to map a file greater than 1 or 2GB

java.io.IOException: Map failed
 at sun.nio.ch.FileChannelImpl.map(FileChannelImpl.java:888)
Caused by: java.lang.OutOfMemoryError: Map failed
 at sun.nio.ch.FileChannelImpl.map0(Native Method)
 at sun.nio.ch.FileChannelImpl.map(FileChannelImpl.java:885)
 ... 6 more

Why Singleton is Anti Pattern in Java? Example

There was a time when the Singleton pattern was the darling pattern of many developers. It's a unique feature to keep certain services available globally, makes it very useful in all kinds of applications. It was also one of the most used design patterns among Java developers. I think the main reason for the Singleton pattern's popularity of designing the application is that there is always one instance of the most important service like Manager and Data Access classes. Still, with the adoption of Dependency injection, Singleton slowly faded away, and now it's considered an anti-pattern in Java applications. 

How to fix 'javac' is not recognized as an internal or external command? Example

So you are trying to compile your Java source file and getting "'javac' is not recognized as an internal or external command". If this is your first Java program or HelloWorld then I suggest going through How to compile and run HelloWorld in Java because that explains what do you need before you compile and run any Java program. If you have crossed that level and knows about How to set PATH in Java then there is something wrong while setting PATH in Java. Anyway let's see when do you get this error and from where does 'javac' is not recognized as an internal or external command comes.

How to fix VirtualBox - /sbin/mount.vboxsf: mounting failed with the error: Protocol error [Solution]

I use Oracle's virtual machine, Virtualbox to run the Linux operating system from my Windows machine. It's the most simple way to have two operating systems on your laptop or PC. Since I run most of the Java programs in Linux, VirtualBox gives me a nice interface to run UNIX commands right from the Windows box. This blog post is about the mounting of a shared folder failed error in Oracle's Virtualbox VM. It was working fine the day before yesterday and now, after I restarted my virtual box and tried to mount my shared folder, I was greeted by this error: "/sbin/mount.vboxsf: mounting failed with the error: Protocol error". I was using the following command to mount my shared folder on VirtualBox:
$ mount -t vboxsf mountfolder /home/devInHost/mountfolder

I was running Oracle's VirtualBox 4.1 version with the guest operating system as RedHat Linux and host OS like Windows 10.

What is Race Condition in Java Multithreading? Examples

Race condition in Java is a type of concurrency bug or issue that is introduced in your program because of parallel execution of your program by multiple threads at the same time, Since Java is a multi-threaded programming language hence the risk of Race condition is higher in Java which demands a clear understanding of what causes a race condition and how to avoid that. Anyway, Race conditions are just one of the hazards or risks presented by the use of multi-threading in Java just like deadlock in Java. Race conditions occur when two threads operate on the same object without proper synchronization and their operation interleaves on each other.