Saturday, July 31, 2021

Parsing Large JSON Files using Jackson Streaming API Example

In the last couple of JSON tutorials for Java programmers, we have learned how to parse JSON using JSON-Simple library, parsing JSON array to Java array using GSon, and in this tutorial, we will learn how to parse a large JSON file in Java using Jackson's Streaming API. Jackson is one of the most popular JSON processing frameworks and provides three main models to parse and process JSON data including Streaming API, data binding, and tree model. Out of these three, Streaming works at the lowest level and can be used to parse huge JSON responses up to even gigabytes of size. If you are familiar with XML parsing, then you know that how difficult it is to parse huge XML files with DOM parser because it fully loads the file in memory before you can process it.

How to Solve UnrecognizedPropertyException: Unrecognized field, not marked as ignorable - JSON Parsing Error using Jackson

While parsing JSON string received from one of our RESTful web services, I was getting this error "Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "person" (class Hello$Person), not marked as ignorable". After some research, I found that this is one of the common errors while parsing JSON documents using Jackson open-source library in Java application. The error messages say that it is not able to find a suitable property name called "person" in our case, let's first take a look at the JSON we are trying to parse, the class we are using to represent the JSON document, and the error message itself.

How to parse JSON with date field in Java - Jackson @JsonDeserialize Annotation Example

I have read many articles on parsing JSON in Java and most of them give examples where properties are either String or int, there are very few examples, where you will see the JSON string contains a date field and that's one important thing to learn. It's easy to parse JSON in Java using Jackson or Gson with just integer and string field but you need to do a little more work if your JSON contains a date field because everything in JSON is String but Java is a type-based programming language, where Date is a type.

How to Ignore Unknown Properties While Parsing JSON in Java? Example

One of the common problems while parsing JSON in Java using Jackson API is that it fails when your JSON contains unknown properties i.e. your Java class doesn't have all the fields corresponding to all JSON properties. For example, if you are consuming JSON from a REST Web Service and tomorrow they added a new field into JSON then your code will break because Jackson will throw UnrecognizedPropertyException and stop parsing JSON. This is troublesome and can cause problems in production if you are not aware. I  have faced this issue when a developer shipped the code to consume data from REST API without properly handling unknown fields.

Why use SerialVersionUID inside Serializable class in Java? Example

Serialization and SerialVersionUID always remain a puzzle for many Java developers. I often see questions like what is this SerialVersionUID, or what will happen if I don't declare SerialVersionUID in my Serializable class? Apart from the complexity involved and rare use, one more reason for these questions is Eclipse IDE's warning against the absence of SerialVersionUID e.g. "The Serializable class Customer does not declare a static final SerialVersionUID field of type long". In this article, you will not only learn the basics of Java SerialVersionUID but also its effect during the serialization and de-serialization process. 

How to Find Prime Factors of Integer Numbers in Java - Factorization Algorithm Example

One of the common homework/tasks in programming courses is about Prime Factorization. You are asked to write a program to find prime factors of a given integer number. The prime factors of a number are all of the prime numbers that will exactly divide the given number. For example, prime factors of 35 are 7 and 5, both are prime in themselves and exactly divide 35. The last time I did this exercise was when I was in college, and it was something like, writing a program that asks the user for an integer input and then displays that number's prime factorization on the command line.  

java.lang.ClassNotFoundException: org.postgresql.Driver - Cause and Solution

java.lang.ClassNotFoundException: org.postgresql.Driver error comes when you are trying to connect to a PostgreSQL database from Java program but Java ClassLoader is not able to find the Driver class "org.postgresql.Driver" required to make the connection. Usually, this class is found in PostgreSQL JDBC driver jars like postgresql-9.4-1201.jdbc41.jar, which is required to connect the PostgreSQL server version greater than 9.3 from JDK 1.7 or JDK 1.8, the exact JAR depends upon your PostgreSQL server version, the Java version you are running, and JDBC version you are using.

Why multiple inheritances are not supported in Java

Why multiple inheritence is not supported implemented in javaRecently one of my friends appeared for an interview and after few so-called easy questions, he was asked "Why multiple inheritance is not supported in Java", though he has a brief idea that in Java we can support multiple inheritance in java via interface but the interviewer was kept pressing on why part, maybe he was just read any blog post about it :). So after the interview, my friend comes to me and in a usual talk, he told me about these questions and ask me the answer. 

How to create HTTP Server in Java - ServerSocket Example

Java has very good networking support, allows you to write client-server applications by using TCP Sockets. In this tutorial, we will learn how to create a simple HTTP Server in Java, which can listen to HTTP requests on a port let's say 80 and can send a response to the client. Being an HTTP Server, you can connect to it using your browser e.g. Chrome, Firefox, or Internet Explorer. Though HTTP is ubiquitous and present everywhere, Java doesn't have a dedicated API to create and parse HTTP requests, there is no in-built HTTP client library in JDK. 

Law of Demeter in Java - Principle of least Knowledge - Real life Example

The Law of Demeter also known as the principle of least knowledge is a coding principle, which says that a module should not know about the inner details of the objects it manipulates. If a code depends upon the internal details of a particular object, there is a good chance that it will break as soon as the internal of that object changes. Since Encapsulation is all about hiding internal details of an object and exposing only operations, it also asserts the Law of  Demeter. One mistake many Java programmer makes it exposing internal detail of object using getter methods and this is where the principle of least knowledge alerts you.

How to do GROUP BY in Java 8? Collectors.groupingBy() Example

Java 8 now directly allows you to do GROUP BY in Java by using Collectors.groupingBy() method. GROUP BY is a very useful aggregate operation from SQL. It allows you to group records on certain criteria. How do you group by in Java? For example, suppose you have a list of Persons, How do you group persons by their city. London, Paris, or Tokyo? Well, we can do that by using a for loop, checking each person, and putting them on a list of HashMap with the same city, but in Java 8, you don't need to hack your way like that, you have a much cleaner solution. You can use Stream and Collector which provides groupingBy() method to do this.

10 Things Every Java Programmer Should Know about String

String in Java is a very special class and the most frequently used class as well. There are lot many more things to learn about String in Java than any other class, and having a good knowledge of different String functionalities makes you use it properly. Given the heavy use of Java String in almost any kind of project, it becomes even more important to know subtle detail about String. Though I have shared a lot of String related articles already here in Javarevisited, this is an effort to bring some of the String features together. 

How to Find If Linked List Contains Loop or Cycle in Java? Exapmle Solution

Write a Java program to check if a linked list is circular or cyclic,  and how do you find if a linked list contains loop or cycles in Java are some common linked list related data structure interview questions asked in various Java Interviews. This is sometimes asked as a follow-up question of basic linked list questions like inserting an element at the beginning, middle and end of a linked list or finding the length of linked list. In order to solve linked list related algorithmic questions in Java, you need to be familiar with the concept of singly linked list, doubly linked list, and circular linked list. Until stated specifically, most questions are based on a singly linked list. For those who are not familiar with the linked list data structure, its a collection of nodes.

10 Tips to Debug Java Program in Eclipse - Examples

How to debug a java program in Eclipse

Debugging is a must-have skill for any java developer. Having the ability to debug java program enables to find you any subtle bug which is not visible during code review or comes when a particular condition offer, This becomes even more important if you are working in high-frequency trading or electronic trading system project where time to fix a bug is very less and bug usually comes on the production environment and doesn't appear in your Windows XP machine. in my experience debugging the java applications also helps you understand the flow of the java programs.

How SSL, HTTPS and Certificates Works in Java web Applications

Basic knowledge of SSL, HTTPS, and Certificates is a must for any Java programmer, especially those who are working in financial and security-sensitive applications, which are accessed over the internet. In this article, I am giving you an overview of these three key concepts and How SSL, HTTPS, and certificates work together, to provide secure communication between client and server. Security is a major concern while developing web applications, which are accessible using the HTTP protocol. Since HTTP protocol transfers data in plain text format, it's not safe for transferring sensitive information like username, password, social security number (SSN), or credit card details for online shopping.

3 Ways to Convert an Array to ArrayList in Java? Example

How to convert an Array to ArrayList in Java
Have you encountered any situation where you quickly wanted to convert your array to ArrayList or ArrayList to array in Java? I have faced many such situations that motivate me to write these quick Java tips about converting an array to ArrayList and ArrayList to array in Java. Both array and ArrayList are quite common and every Java developer is familiar with this. Former is used to store objects and primitive types while later can only hold objects. The array is part of standard Java fundamental data structure while ArrayList is part of the collection framework in Java.

Difference between LEFT and RIGHT OUTER Joins in SQL - MySQL Join example

There are two kinds of OUTER joins in SQL, LEFT OUTER join and RIGHT OUTER join. The main difference between RIGHT OUTER joins and LEFT OUTER join, as their name suggests, is the inclusion of non-matched rows. Sine INNER join only include matching rows, where the value of the joining column is the same, in the final result set, but OUTER join extends that functionality and also include unmatched rows in the final result. LEFT outer join includes unmatched rows from the table written on the left of the join predicate. 

Difference Between Linked List and Array in Java? Example

Array and linked lists are two fundamental data structures in the programming world. Almost all programs use Array in some form or other, which makes it increasingly important to learn array and linked list. The difference between the linked list and array data structure is also a popular data structure question, frequently asked in the various programming job interviews. This makes it even more important to learn and understand the difference between an array and a linked list. Well, there are a lot of differences between these two starting from how they store data, to how you retrieve data from them.

When to Make a Method Static in Java? Example

Making a method static in Java is an important decision. Though, static keyword is one of the fundamental concepts, many times programmers get confused to make a particular method static or not. In Java programming, the main motivation for making a method static is convenience. You can call a static method without creating any object, just by using its class name. So if you need a method, which you want to call directly by class name, make that method static. Utility classes e.g. java.lang.Math or StringUtils are good examples of classes, which use static methods. Before making a method static, you should look into the limitations of static methods as well, as you can not override static methods in Java

Different Types of JDBC Drivers in Java - Quick Overview

How many types of JDBC drivers in Java is a classical JDBC interview question, though I have not seen this question recently it was very popular during the last decade and still asked mostly on Junior programmer level interviews. There are mainly 4 types of JDBC drivers in Java, those are referred to as type 1 to type 4 jdbc drivers. I agree it's easy to remember them by type rather than with their actual name, Which I have yet to get in-memory except for plain old JDBC-ODBC bridge driver.

Is it possible to have an abstract method in a final class? Example

This is one of the interesting core Java questions which was asked to one of my readers recently during a telephonic interview for a Java developer job interview. Even though he knows that you cannot make an abstract class final in Java, he got confused by the wording of the methods. The answer is simple, No, it's not possible to have an abstract method in a final class in Java. Why? because as soon as you declare an abstract method in a Java class, the class automatically becomes an abstract class and you cannot make an abstract class final in Java as discussed before, hence it's not possible to have an abstract method in a final class in Java.

Difference between ClassNotFoundException vs NoClassDefFoundError in Java

ClassNotFoundException vs NoClassDefFoundError
Though both of these errors are related to missing classes in the classpath, the main difference between them is their root cause. ClassNotFoundExcpetion comes when you try to load a class at runtime by using Class.forName() or loadClass() and requested class is not present in the classpath for example when you try to load MySQL or Oracle driver class and their JAR is not available, while in case of NoClassDefFoundError requested class was present at compile time but not available at runtime. Sometimes due to an exception during class initialization e.g. exception from static block causes NoClassDefFoundError when a failed-to-load class was later referenced by the runtime. 

Friday, July 30, 2021

Top 5 Courses to learn Groovy and Grails in 2021 - Best of Lot

Hello guys, If you want to learn Groovy or Grails in 2021 and looking for some awesome resources like books, courses, and tutorials, then you have come to the right place. In the past, I have shared the best Groovy books and best Gradle courses. Today, I will share some of the best online courses to learn both the Groovy programming language and Grails framework .you might have heard about Groovy, if not maybe heard about Grails, Akka, Play, and Gradle, the top 5 Groovy frameworks for Java developers. Instead of competing with Java, Groovy focuses on co-existing with Java and enhancing Java developer's capability on Java's traditional weak areas like scripting.

Why Enum Singleton are better in Java? Examples

Enum Singletons are new way to implement Singleton pattern in Java by using Enum with just one instance. Though Singleton pattern in Java exists from long time Enum Singletons are relatively new concept and in practice from Java 5 onwards after introduction of Enum as keyword and feature. This article is somewhat related to my earlier post on Singleton, 10 interview questions on Singleton pattern in Java where we have discussed common questions asked on interviews about Singleton pattern and 10 Java enum examples, where we have seen how versatile enum can be. This post is about why should we use Enum as Singleton in Java, What benefit it offers compared to conventional singleton methods etc.

HashSet in Java – 10 Examples Programs Tutorial

HashSet in Java is a collection that implements the Set interface and is backed by a HashMap. Since HashSet uses HashMap internally it provides constant-time performance for operations like add, remove, contains and size give HashMap has distributed elements properly among the buckets. Java HashSet does not guarantee any insertion orders of the set but it allows null elements. HashSet can be used in place of ArrayList to store the object if you require no duplicate and don't care about insertion order.

Builder Design pattern in Java - Example Tutorial

Builder design pattern in Java is a creational pattern i.e. used to create objects, similar to factory method design pattern which is also a creational design pattern. Before learning any design pattern I suggest find out the problem a particular design pattern solves. Its been well-said necessity is a mother of invention. learning design pattern without facing problems is not that effective, Instead, if you have already faced issues then it's much easier to understand design patterns and learn how they solve the issue

5 Coding Tips for Improving Performance of Java application

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

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

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

Difference between repaint and revalidate method in Java Swing

What is the difference between revalidate() and repaint() in Java Swing is one of the popular Swing Interview Questions especially on Investment banks? Though both methods sound similar, there is a subtle difference between them. the revalidate() method instructs LayoutManager to recalculate layout and often called once new components are added or removed from Container. The revalidate() can also trigger to call the repaint() method to repaint components that have changed i.e. width, height, or any other visible property, which can affect layout. On the other hand repaint() method puts a paint request in AWT thread, for the repainting of a component on which it has called.

How to Count number of Set bits or 1's of Integer in Java? Example

There are multiple ways to count the number of 1's or set bits in an integer number in Java. You can use a bitwise and bit shift operator on your own, or, you can use Java API to count the number of set bits. Java 1.5 added two utility methods called bitCount(int i) which returns a number of 1's in your integer number, java.lang.Long class has a similar bitCount(long number) for long primitives. As I have said earlier, Coding questions are an important part of any Java interview, and from that recursion and bitwise operations are most popular. 

When a class is loaded and initialized in JVM - Java Example

Understanding when a class is loaded and initialized in JVM is one of the fundamental concepts of Java programming language. Thanks to Java language specification we have everything clearly documented and explained, but many Java programmer still doesn't know when a class is loaded or when a class is initialized in Java. Classloading and initialization seems confusing and complex to many beginners and its true until having some experience in belt its not always easy to get into subtle details of How JVM works in Java. In this Java tutorial, we will see when class loading occurs in Java and when and how class and interface are initialized in Java.

How to Add Two Integer Numbers without using Plus + or ++ Arithmetic Operator in Java - Recursion example

In this article, we will take a look at another interview question about adding two numbers, but without using the + or ++ operator. The interview starts with a simple statement, Can you write a function to add two numbers (integers) without using + or plus arithmetic operator in Java? If you are good at maths, it wouldn’t take more than a second to say that, we can use subtraction or - operator to add two numbers because a-(-b)== a+b. Well, that’s correct, but the real question starts when the interviewer quickly points out that, you can not use any arithmetic operator including +,-,*,/++, or --

Java ArrayList and HashMap Performance Improvement in Java

For a long time, one reason for me to update to the newer Java version was always bug fix and performance improvement. Apart from major changes like Generics in Java 1.5 and Lambdas in Java 8, there are so many small improvements, performance optimization which just goes under the radar, one such change is creating empty ArrayList and HashMap with size zero in JDK 1.7.0_40 update. Many Java developer doesn't even know about these changes, part of the blame lies on Java developers like me, as I hardly read release notes of minor Java updates. 

Is Swing Thread Safe in Java? Answer

A couple of my readers ask questions, what does it mean by Swing is not thread-safe and How does it affect coding in Swing GUI application? This post is an effort to help those readers and several other programmers to understand Swing and thread safety in a bit more detailed way. To keep it simple, let's revise what does it mean by being thread-safe? We say an object is thread-safe if we can call its a method, which can change its states, from multiple threads at the same time. To give you an example, java.lang.String is a thread-safe class, which means you can call any method e.g. substring(), toUpperCase() or toLowerCase() from multiple threads.

Invalid initial and maximum heap size in JVM - How to Fix

I was getting "Invalid initial heap size: -Xms=1024M" while starting JVM and even after changing the maximum heap size from 1024 to 512M it keeps crashing by telling "Invalid initial heap size: -Xms=512m, Could not create the Java virtual machine". I check almost everything starting from checking how much physical memory my machine has to any typo in JVM parameters, only to find out that instead of M, I had put MB there. Java accepts both the small case and the capital case for Kilo, Mega, and Gigs. you can use m or M, g or G, etc but never used MB, GB, or KB.  A similar problem can occur with the maximum heap size specified by -Xmx. Also from Java 6 update 18, there is a change in default heap size in JVM.  

Top 20 jQuery Interview Questions and Answers

Without a doubt, jQuery has given a much-needed boost to JavaScript, a language so useful but equally underrated at times. Before jQuery comes into the picture, we used to write lengthy JavaScript code not just for bigger but even for smaller functions. Those codes were at times both difficult to read and maintain. Having written JavaScript before using this excellent library, I realized the true power of jQuery, just after using it for a month. Given its huge popularity, jQuery interview questions are increasingly asked in any web developer interview, not just beginners but also experienced developers, including HTML and JavaScript.

How to Close Java Program or Swing Application with Example

In order to close the Java program, we need to consider which kind of Java application it is?, because termination of Java application varies between normal core java programs to swing GUI applications. In general, all Java program terminates automatically once all user threads created by program finishes its execution, including main thread. JVM doesn't wait for the daemon thread so as soon as the last user thread is finished, the Java program will terminate. If you want to close or terminate your java application before this your only option is to use System.exit(int status) or Runtime.getRuntime().exit().

How to Check if Integer Number is Power of Two in Java - 3 examples

How to check if an integer number is a power of 2 in Java is one of the popular programming interview questions and has been asked in many interviews. Surprisingly, this problem which looks simple enough to answer doesn't turn out that simple if for many developers. Many Java programmers, both freshers and less experienced,  struggle to write code for a function, which can check if the number is the power of 2 or not. 

InvokeLater and InvokeAndWait in Java Swing (an example tutorial)

Everyone who is doing programming in java swing has to come across invokeAndWait and invokeLater provided by SwingUtilites. In this java swing tutorial, we will learn about both invokeLater() and invokeAndwait() method. In the first part, we will mostly focus on invokeLater and will find answers to questions like What is invokeLater, how to use invokelater in java swing, an example of invokelater in swing, etc while in the second part of this invokeLater tutorial we will learn more about invokeAndWait method in java swing and will learn Why we need InvokeAndWait, how to use InvokeAndWait method in java Swing and differences between invokelater and invokeAndWait.

How to Use Break, Continue, and Label in Loop in Java? Example

break and continue in Java are two essential keyword beginners needs to familiar while using loops ( for loop, while loop and do while loop). break statement in java is used to break the loop and transfers control to the line immediately outside of the loop while continue is used to escape current execution and transfers control back to the start of the loop. Both break and continue allows programmers to create sophisticated algorithms and looping constructs.

How to get current URL, parameters and Hash tag using JQuery and JavaScript? Example

While dealing with the current URL, many times you want to know what is the current URL path, What are the parameters, and what is the hashtag on the URL. The hashtag is pretty important if you are implementing a tab structure using HTML and JQuery. To avoid confusion, let's take an example of a URL: http://javarevisited.blogspot.com/2013/01/top-5-java-programming-books-best-good.html#ixzz2PGmDFlPd, in this example ixzz2PGmDFlPd, is a hashtag. Now, both JavaScript and JQuery provide a convenient way to retrieve the current URL in the form of window.location object. You can use various properties of the window.location JavaScript object like the window.location.href to get complete URL, window.location.pathname to get the current path, and window.location.hash to get a hashtag from current URL.

10 Examples of HotSpot JVM Options in Java

There are hundreds of JVM parameters or JVM Options exists inside sun JDK and its virtually impossible to keep track of every single JVM option and based on my experience we don't even use most of JVM flags except a couple of important JVM option related to java heap size, java options for printing garbage collection details and most likely JVM switches for setting up remote debugging in Java. but there are many other useful categories of JVM parameters that you at least like to be familiar with even if not intending to use them more frequently.

Difference between Sun (Oracle) JVM and IBM JVM?

There are different JVM implementations available apart from popular Sun's (now Oracle) hotspot JVM like IBM's JVM. Now the question comes, what makes two JVM different from each other? Quite a lot of things can be different even if two JVMs are implemented by following Java virtual machine specifications. IBM has its own JVM implementation which is different than Oracle's JVM in many things like JIT(Just in Time) Compiler, the structure of Java heap, garbage collectors, and support for monitoring and management. Though I have mostly used Sun’s hotspot JVM recently got a chance to run some Java programs on IBM JVM on the AIX platform.

Top 30 JavaScript Interview Questions and Answers for 1 to 2 years Experienced Developers

Building a career as a developer in the IT industry can be challenging if you lack stream-specific preparation. For instance, if you want to be a JavaScipt developer, you have to dig deep into its concepts and learn every bit about JavaScript, but then also, I would say, you are 50% prepared for the Job. I'm not saying that you aren't capable enough to get that JavaScript developer's Job; instead, I mean to say that you aren't ready enough to face the recruiters.

How to Generate MD5 checksum for Files in Java? Example

MD5 checksums are good to verify the integrity of files and It's easy to generate MD5 checksum in Java. Java provides a couple of ways to generate the MD5 checksum for any file, you can either use java.security.MessageDigest or any open source library like Apache commons-codec or Spring. All 3 ways we have seen in our earlier article about generating the MD5 hash for String is also applicable to generate the MD5  checksum for any file. Since most of the md5() or md5Hex() method takes byte[], you can simply read bytes from InputStream or pass to these md5 methods. 

How to find CPU and Memory used by Java process in Solaris – prstat command example

We often need to find CPU and memory utilization of a particular Java process in order to get some performance stats, capacity planning or just to understand the current load on the system. Performance monitoring and testing is an integral part of any Java application development, especially if you are working in a high-frequency trading space. In order to fix a performance problem, you have to find them first and knowledge of the right tools and commands helps there. One of the primary causes of poor application performance is it Java or any other process is the exhaustion of important resources like CPU and memory.

10 XSLT or XML, XSL Transformation Interview Questions and Answers

XSLT stands for XML style sheet transformation and it as XML technology used to transform one XML into another XML or HTML format.  XML and XSLT interview questions are commonly asked Java developers, who happen to use XML in their projects and mentioned XSLT as a key skill in their resumes. Given XML’s popularity as a data transfer protocol, many systems in the middle and back-office space use XML messages to transfer trade details, for example, Bookings, Settlement, and Confirmation systems use it as data exchange protocol. Since each of these systems performs some normalization, enrichment, and transformation on incoming trade messages, they use XSLT for that transformation.

How ClassLoader Works in Java? Example

Java class loaders are used to load classes at runtime. ClassLoader in Java works on three principles: delegation, visibility, and uniqueness. Delegation principle forward request of class loading to parent class loader and only loads the class if the parent is not able to find or load the class. The visibility principle allows the child class loader to see all the classes loaded by the parent ClassLoader, but the parent class loader can not see classes loaded by a child. The uniqueness principle allows one to load a class exactly once, which is basically achieved by delegation and ensures that child ClassLoader doesn't reload the class already loaded by a parent. Correct understanding of class loader is a must to resolve issues like NoClassDefFoundError in Java and java.lang.ClassNotFoundException, which is related to class loading.

3 ways to solve java.lang.NoClassDefFoundError in Java J2EE

I know how frustrating is to see Exception in thread "main" java.lang.NoClassDefFoundError,  which is a manifestation of NoClassDefFoundError in Java. I have seen it a couple of times and spent quite a lot of time initially to figure out what is wrong, which class is missing etc. The first mistake I did was mingling java.lang.ClassNotfoundException and NoClassDefFoundError, in reality, are totally different, and my second mistake was using the trial and error method to solve this java.lang.NoClassDefFoundError instead of understanding why NoClassDefFoundError is coming, what is the real reason behind NoClassDefFoundError and how to resolve this.

jQuery Tutorial - How to modify multiple HTML elements in one line? Example

jQuery allows you to modify multiples elements in one go, you can modify attributes, text, or color of multiple HTML elements by executing just one line of jQuery code. In this jQuery tutorial, I will show you how to modify multiple <li> elements in one go. In our example, we have a couple of <li> tags to display sub-headings, now we will change them in one go using jQuery. If you look at our HTML, we have an ordered list <ol> to display the top 10 programming languages, each of them is an <li> item. We also have one button, "Click Me", which will when clicked, change all <li> item's text to "jQuery is the new Boss". Here is the jQuery code, which does that.

20 Design Patterns and Software Design Interview Questions for Programmers

Design patterns and software design questions are an essential part of any programming interview, no matter whether you are going for a Java interview or a C#  interview. In fact, programming and design skills complement each other quite well, people who are good programmers are often good designers as well as they know how to break a problem in to piece of code or software design but these skills just don’t come. You need to keep designing, programming both small-scale and large-scale systems, and keep learning from mistakes. 

Thursday, July 29, 2021

How to use Comparator and Comparable in Java? With example

Comparator and Comparable in Java Examples
The difference between Comparator and Comparable in Java is very popular Java interview question mostly asked in the telephonic rounds and writing code to sort objects using Comparable or Comparator is popular on the written test round of interviews. The question was this “How you will sort Employee object based on his EmployeeID and his name” and this involves the use of both Comparable as well as Comparator interface in Java. This post is my revision on Java fundamentals similar to what I did about the equals method in Java and some tips to override hashCode in Java. 

10 Interview Questions on Java Generics for Programmer and Developers

Generic interview questions in Java interviews are getting more and more common with Java 5 around there for a considerable time and many applications either moving to Java 5 and almost all new Java development happening on Tiger(code name of Java 5).  The importance of Generics and Java 5 features like Enum,  Autoboxing, varargs, and Collection utilities like CountDownLatch, CyclicBarrier, and BlockingQueue is getting more and more popular on Java interviews. Generic interview questions can get really tricky if you are not familiar with bounded and unbounded generic wildcards, How generics works internally, type erasure and familiarity with writing parametrized generics classes and methods in Java.

What is -XX:+UseCompressedOops in 64 bit JVM? Example

-XX:+UseCompressedOops JVM command-line option is one of the most talked-about options of 64 bit JVM. Though 64 bit JVM allows you to specify larger Java heap sizes it comes with a performance penalty by using 64 bit OOPS. Ordinary object pointers also are known as OOPS which is used to represent Java objects in Virtual Machine have an increased width of 64 bit than smaller 32 bit from earlier 32 bit JVM. because of the increased size of OOPS, fewer OOPS can be stored in CPU cache registers which effectively reduced CPU cache efficiency. -XX:+UseCompressedOops enables the use of compressed 32 bit OOPS in 64 bit JVM which effectively compensates the performance penalty imposed by 64 bit JVM without scarifying heap size advantage offered by them.

Top 10 Garbage Collection Interview Questions and Answers for Java Programmers

GC Interview Questions Answer in Java
Garbage collection interview questions are very popular in both core Java and advanced Java Interviews. Apart from  Java Collection and Thread many tricky Java questions stem Garbage collections which are tough to answer. In this Java Interview article, I will share some questions from GC which is asked in various core Java interviews. These questions are based upon the concept of How Garbage collection works, Different kinds of Garbage collectors, and JVM parameters used for garbage collection monitoring and tuning. As I said GC is an important part of any Java interview so make sure you have good command in GC. One more thing which is getting very important is the ability to comprehend and understand Garbage collection Output, more and more interviewer are checking whether the candidate can understand GC output or not.

How to Copy File in Java Program - Example Tutorial

How to copy files in Java from one directory to another is a common requirement, given that there is no direct method in File API for copying files from one location to another. A painful way of copying files is reading from FileInputStream and writing the same data to FileOutputStream to another directory. Though this process works it's pretty raw to work with and the best approach is for anyone to create a library for common File operations like cut, copy, paste, etc. 

What is Class File and Byte Code in Java? Example

.class file in Java is the core of achieving platform independence which is a key feature of Java. class files are compiled form of any Java program written in byte codes. Since the Java program executes inside JVM, these instructions are read by JVM and then translated into machine code for the underlying platform. effectively you can run the class file on any platform if you have a corresponding JVM supported for that platform. Java compilers are responsible for generating .class files and they follow the class file format specified by Sun and it's different based on different Java versions.

6 Best Free SQL Courses for Beginners to Learn in 2021 - Best of Lot

Hello guys, we are already in the second week of New year, and everyone is talking about their goals to improve them as a better person, a better programmer, or better health. If you have also made your goal, and one of them is to improve your SQL skill, you have come to the right place because I will share some of the free online courses to learn and master SQL this year. The list includes a free course from Udemy, a popular online portal to learn Oracle, PostgreSQL, and Microsoft SQL Server. Yes, I have tried hard to include free courses on different databases to choose the course you want. 

Top 10 Java Swing Interview Questions Answers asked in Investment banks

The Swing  API and toolkit are heavily used in developing trading application front end in Java on both large Investment banks and small broker firms. Doesn’t matter whether it's a front office or middle office application, you will find Java Swing GUI everywhere. The Swing-based GUI is used to develop an Order entry system, Order monitoring GUI, and other tools that trader or operations can use on different trade life cycles in the front office. middle office and back-office space. Due to its heavy usage, there are a lot of requirements of Java Swing developers in investment banks like Barclays, Citibank, Deutsche Bank, Nomura, JP Morgan, Morgan Stanley, and Goldman Sachs, etc.

How to compare two lists of values in Microsoft Excel? Example

If you are working in the real-world application then you may frequently face scenarios where you have to compare data e.g. you get two lists of values and you want to know which values are common between two lists, which values only exists in the first list, and which values only exist in the second list. If the list contains just 5 to 10 values you can do it easily with your eyes but what is fun if a programmer doing the task manually. You should be able to leverage all the tools available to you to do this comparison reliably. 

Difference between JVM, JIR, JRE, and JDK in Java? [Answered]

JRE, JVM, and JDK are three terms you often heard in conjunction with Java programming language, and most people either confuse them or think they all are the same. In this Java article, you will learn what is Java Run-time (JRE), what is Java Virtual Machine (JVM) and what is Java Development Kit (JDK) along with the Just in Time compiler or JIT. Once you know what JRE, JVM or JDK means you can differentiate them easily by yourself.  This article is in continuation of the Essential JVM options which every Java programmer should know. If you haven't read those articles, you can also read them as well. 

How to reload/refresh a page using JavaScript and jQuery? Example

JavaScript provides several ways to reload or refresh an HTML page but the standard way to do this job is by using window.location object. This object provides a reload() method which instructs the browser to reload the page. The browser can do it from its cache or from the server, which depends upon optional parameter i.e. reload(true) will reload the page from the server but reload(false) will only reload the page from the browser's cache, which may or may not represent the current version at the server.

How to increase Heap memory of Apache Tomcat Server? Example

Increasing Heap size of Tomcat
You can increase the heap size of Tomcat by setting JAVA_OPTS or CATALINA_OPTS at the top of the catalina.sh, file if you are running Tomcat in Linux and by putting JAVA_OPTS or CATALINA_OPTS into the catalina.bat file if you are running Tomcat in Windows. This approach will work irrespective of the tomcat version i.e. you can increase the heap memory of tomcat 5.5, tomcat 6, tomcat 7, and even tomcat 8 by using this technique. You can find the catalina.sh and catalina.bat file in the bin directory of tomcat installation folder e.g. in my machine catalina.sh and the catalina.bat file is located under C:\Program Files\Apache Software Foundation\Apache Tomcat 7.0.41\bin directory. 

How many characters allowed on VARCHAR(n) columns in SQL Server? How much memory VARCHAR variable takes in disk?

One of the frequently asked SQL questions in any programming interview is what is the difference between VARCHAR and CHAR data type in SQL? particularly when your project is using Microsoft SQL Server. You might have seen this couple of times, but given its popularity, nowadays people are asking this question differently e.g. they will ask you how much space a column of VARCHAR(2) data type will take? How many characters can it take? How do you minimize space? Is it better to use a CHAR variable instead of VARCHAR(2) and why? These are some of the really interesting questions and more meaningful than classical SQL questions like the difference between char vs varchar data type questions.

Wednesday, July 28, 2021

What is bounded and unbounded wildcards in Generics Java? Example

Bounded and unbounded wildcards in Generics are two types of wildcards available on Java. Any Type can be bounded either upper or lower of the class hierarchy in Generics by using bounded wildcards. In short <? extends T> and <? super T> represent bounded wildcards while <?> represent an unbounded wildcard in generics. In our last article How Generics works in Java, we have seen some basic details about bounded and unbounded wildcards in generics and In this Java tutorial, we will see bounded and unbounded generics wildcards in detail.

How to Split String based on delimiter in Java? Example Tutorial

You can use the split() method of String class from JDK to split a String based on a delimiter e.g. splitting a comma-separated String on a comma, breaking a pipe-delimited String on a pipe, or splitting a pipe-delimited String on a pipe. It's very similar to earlier examples where you have learned how to split String in Java. The only point which is important to remember is little bit of knowledge of regular expression, especially when the delimiter is also a special character in regular expression e.g. pipe (|) or dot (.), as seen in how to split String by dot in Java. In those cases, you need to escape these characters e.g. instead of |, you need to pass \\| to the split method.

Difference between Right shift and Unsigned right shift in Java ( >> and >>> ) Example

There are two types of right shift operator in Java >> and >>>,  former is known as right shift and later is known as right shift with zero fill or simply unsigned right shift operator in Java.  Though both of them are known as bit shift operators and moves bits patterns towards right hand side of a bit sequence, there is a subtle difference between them. When we use right shift operator i.e. ">>" it keeps the sign bit intact i.e. if the original number is negative then it will remain negative even after right shift i.e. first or most significant bit never lost, doesn't matter how many times you shift.

What is the maximum Heap Size of 32 bit or 64-bit JVM in Windows and Linux?

Maximum heap size  for 32 bit or 64 bit JVM looks easy to determine by looking at addressable memory space like 2^32 (4GB) for 32 bit JVM and 2^64 for 64 bit JVM. The confusion starts here because you can not really set 4GB as the maximum heap size for 32 bit JVM using -Xmx JVM heap options. You will get could not create the Java virtual machine Invalid maximum heap size: -Xmx  error. There could be much different reasons why maximum heap space for JVM is less than its theoretical limit and varies from one operating system to other e.g. different in Windows, Linux, and Solaris.

How to Replace Line Breaks , New Lines From String in Java - Windows, Mac or Linux Example

We often need to replace line terminator characters, also known as line breaks e.g. new line \n and carriage return \r with different characters. One of the common case is to replace all line breaks with empty space in order to concatenate multiple lines into one long line of String. In order to replace line breaks, you must know line terminator or new line characters for that platform. For example, In Windows operating system e.g. Windows 7 and 8, lines are terminated by \n\r  also known as CR+LF, while in Unix environment e.g. Linux or Solaris line terminator is \n, known as line feed LF. You can also get line terminator pragmatically by using Java system property line.terminator.

How to Convert Byte Array to InputStream and OutputStream in Java? Example

Are you stuck with your coding because you have a byte array and the next method in the chain needs an InputStream? don't worry Java has a solution for that, You can use ByteArrayInputStream to convert byte array to InputStream in Java. This class takes a byte array as the source and since it's a subclass of InputStream, you can easily pass this to any method, which accepts InputStream as a parameter. Though most of the API like JDBC and File API allows you to read directly from InputStream because this allows you to process an arbitrary content with limited heap space. You should take advantage of this and directly read from InputStream instead of getting byte array and then converting them back to InputStream.

How to Create JUnit Tests in Eclipse and NetBeans IDE? Java Example

Writing JUnit tests for Java classes in Eclipse and Netbeans IDE is super easy, and I will show you that later in this JUnit tutorial. Before that, let’s revise what is a unit test and why should you write them. A unit test is to test a smaller unit of code, e.g. methods.  Writing a unit test to test the individual unit of code is one of the best development practices and helps to find bug earlier in the development cycle. Though there is another unit testing framework available in Java e.g. TestNG, JUnit has its own place among Java developers. IMHO code review and unit testing are two most important practices for improving code quality and should always be followed during software development.

10 Articles Every Programmer Must Read

Being a Java programmer and Software developer, I have learned a lot from articles titled What Every Programmer Should Know about ....., they tend to give a lot of useful and in-depth information about a particular topic, which otherwise is very hard to discover. In my quest for learning, I have come across some very useful articles, which I have bookmarked for reference and multiple readings. I personally think that all programmers can benefit by reading these articles, which makes me write this post and share all of these "What Every Programmer Should Know" articles with you guys. These are from my personal bookmarks.

What is java.library.path? How to set in Eclipse IDE? Example

java.library.path is a System property, which is used by Java programming language, mostly JVM, to search native libraries, required by a project. Similar to PATH and Classpath environment variable, java.library.path also includes a list of directory. When Java code loads a native library (a library or executable written in a language like C, C++, or native code) using System.loadLibrary("name of library") method, java.library.path is scanned for specified library. If JVM doesn't found the requested native library, then it throws java.lang.UnsatisfiedLinkError: no native library in java.library.path.

How to add and substract days in current date in Java? Example Tutorial

While working on Java projects, we often need to increment or decrement date e.g. adding one day to the current date to get tomorrow's date, subtracting one day to get yesterday's date, etc. Since date in Java is maintained as long millisecond value, Sometimes, programmers tend to add 24 hours as one day, which could be wrong if day falls on a daylight saving time zone, where a day could be either 23 or 25 hour long. When you add or subtract days from date, other components' of date e.g. month and year must roll. In this Java date tutorial, we will see two ways to increment and decrement date in Java

10 JDK 7 Features to Revisit, Before You Welcome Java 8 - Examples

It's been almost a month since Java 8 is released and I am sure all of you are exploring new features of JDK 8. But, before you completely delve into Java 8, it’s time to revisit some of the cool features introduced on Java 7. If you remember, Java 6 was nothing on the feature, it was all about JVM changes and performance, but JDK 7 did introduce some cool features which improved the developer's day to day task. Why I am writing this post now? Why I am talking about Java 1. 7, when everybody is talking about Java 8? Well I think, not all Java developers are familiar with changes introduced in JDK 7, and what time can be better to revisit an earlier version than before welcoming a new version.

Java Program to find factorial of number in Java - Example Tutorial

How to find the factorial of a number in Java in both recursive and iterative ways is a common Java interview question mostly asked at the fresher level. It’s not just popular in Java interviews but also in other programming languages like C or C++. It's also famous  In our last article we have seen how to check if a number is prime or not and in this Java programming tutorial, we will see a simple Java program to find the factorial of a number in Java by using recursion and iteration. The same program can also be used to print factorial of any number or print a range of factorial as well.

Top 50 Programmer Phone Interview Questions with Answers

For the last few years, phone interviews also known as the telephonic round is the single most popular way to screen candidates in a programming job interview. It's easy for both parties to gauge each other, the candidate doesn't need to travel to the prospective Employer's premises and the Interviewer also doesn't need to make any necessary arrangements. This is the second part of my article on programming interview questions, in the first part, I got feedback that it is a little bit heavy on coding-based questions and many programmers asked me to share a similar list for the telephonic round of programming Interviews. In order to clear the telephonic round and proceed to the next round, you must be good enough to answer all the questions related to your Job description.

7 Examples to Read File into a Byte Array in Java

Hello guys, Java programmers often face scenarios in real-world programming, where they need to load data from a file into a byte array, it could be text or binary file. One example is to convert the contents of a file into String for display. Unfortunately, Java's File class, which is used to represent both files and directories, doesn't have a method say toByteArray(). It only holds path and allows you to perform certain operations like opening and closing file, but doesn't allow you to directly convert File to a byte array. Anyway, no need to worry as there are several other ways to read File into a byte array and you will learn those in this Java file tutorial.

Difference between Connected vs Disconnected RowSet in Java JDBC | RowSetProvider, RowSetFactory Example

RowSet interface is another key interface from JDBC API, which extends the ResultSet interface to provide support for the JavaBean component model. Along with convenient methods to set connection parameters like the setUrl(), setUsername(), setPassword() and setCommand(), it also defines getters and setters for different data types e.g. getLong() and setLong(). Another feature of RowSet is that it supports event listeners. You can attach listeners to RowSet object to listen for events, much like Observer design pattern. RowSet acts as Subject and notifies Observer on events like change in cursor location, change in a row, or change in the entire RowSet. There are two types of RowSet available in JDBC 4.1 API, connected and disconnected.

Difference between Stub and Mock object in Java Unit testing - JUnit

JUnit is the most popular framework for unit testing Java code. Unit testing is used to test a single programming unit e.g. a class or a method, in-fact many Java developers write unit tests on a per-method basis. Stub and Mock objects are two concepts that help during unit testing, they are not real objects but act like real objects for unit testing purposes. By the way, If you are absolutely a beginner in Java Unit testing then you can see this post to learn how to create the JUnit test in Eclipse. Coming back to Stubs and Mocks, One reason for using Stub and Mock object is the dependency of one unit into another. Since in real-world, the most unit doesn't work in isolation, they use dependent class and object to complete there task.

How to Add Leading Zeros to Integers in Java ? String Left Padding Example Program

Hello guys, you may know that from Java 5 onwards it's easy to left pad Integers with leading zeros when printing number as String. In fact, You can use the same technique to left and right pad Java String with any characters including zeros, space. Java 5 provides String format methods to display String in various formats. By using the format() method we can add leading zeros to an Integer or String number. By the way, this is also known as left padding Integers with zero in Java. For those who are not familiar with the left and right padding of String, here is a quick recap;

How to Implement Linked List in Java with JUnit Test Example

In this article, we will learn two things, how to implement a linked list from scratch in Java and how to write a unit test using JUnit framework. Though Java has LinkedList class, which is an implementation of the doubly linked list, its good to know how to implement singly linked list in Java, mostly to practice coding interview questions. Coming to back to writing a unit test, from time to time, I have said that a Java programmer must write unit tests. IMHO, unit testing is the best development practice to improve code quality. Fortunately, Java ecosystem has the luxury of great unit testing frameworks in form of JUnit and TestNG, and every Java developer should take advantage of this.

Difference between FileInputStream and FileReader in Java | InputStream vs Reader Example

Before going to explain specific difference between FileInputStream and FileReader in Java, I would like to state fundamental difference between an InputStream and a Reader in Java, and when to use InputStream and when to go for Reader. Actually, Both InputStream and Reader are abstractions to read data from source, which can be either file or socket, but main difference between them is, InputStream is used to read binary data, while Reader is used to read text data, precisely Unicode characters. So what is difference between binary and text data? well everything you read is essentially bytes, but to convert a byte to text, you need a character encoding scheme. Reader classes uses character encoding to decode bytes and return characters to caller.

Top 20 Amazon and Google Programming Interview Questions

Hello, In this article I am going to sharing some frequently asked programming job interviews from technical giants and startups. If you are going for a programming job interview with Microsoft, Google, or Amazon, you better be prepared for all kinds of questions. These companies are known to ask tough questions, tricky puzzles, and lots of data structure and algorithm questions. Since it's hard to prepare all these in a short time, it makes sense to at least have a good idea of frequently asked programming questions in Microsoft, Google, or Amazon.

Top 10 Puzzles, Riddles, Logical, and Lateral Thinking Questions Asked in Programming Job Interviews

Puzzles, riddles, logical questions, and lateral thinking questions are an integral part of any programming job interviews. I missed to include some puzzles when I shared my list of top 30 programming interview questions earlier, and a couple of my friends requested to share some puzzles as well. These puzzles and lateral thinking questions are mostly collected from various Java programming interviews on Investment banks, but they are equally useful for any programming job interviews. I have seen more puzzles and logical questions at the junior level i.e. 2 to 4 years.

Difference between UTF-8, UTF-16 and UTF-32 Character Encoding? Example

The main difference between UTF-8, UTF-16, and UTF-32 character encoding is how many bytes it requires to represent a character in memory. UTF-8 uses a minimum of one byte, while UTF-16 uses a minimum of 2 bytes. BTW, if the character's code point is greater than 127, the maximum value of byte then UTF-8 may take 2, 3 o 4 bytes but UTF-16 will only take either two or four bytes. On the other hand, UTF-32 is a fixed-width encoding scheme and always uses 4 bytes to encode a Unicode code point. Now, let's start with what is character encoding and why it's important? Well, character encoding is an important concept in the process of converting byte streams into characters, which can be displayed.

How to Remove Given Character From String in Java - Recursion Example

Write a program to remove a given character from String in Java. Your program must remove all occurrences of a given character. For example, if given String is "aaaaa" and String to remove is "a" then the output should be an empty String. Similarly, if input String is "abc" and character to remove is "b" then your program must return "ac" as output. You are not allowed to use any JDK method or third party method which solves this method directly, but you can use basic String manipulation method like indexOf(), toChar() or substring() from java.lang.String class.