Preparing for Java and Spring Boot Interview?

Join my Newsletter, its FREE

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.

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

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.

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

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.

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.

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.

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.  

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().

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.

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.

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

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.

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.

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.

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.

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 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, 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 and catalina.bat file in the bin directory of tomcat installation folder e.g. in my machine 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.

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.

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.

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;

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.

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 Compare Two Enum in Java? Equals vs == vs CompareTo Example

How do I compare two enum in Java? Should I use == operator or equals() method? What is difference between comparing enum with == and equals() method are some of the tricky Java questions. Until you have solid knowledge of Enum in Java, It can be difficult to answer these question with confidence. By the way unlike comparing String in Java, you can use both == and equals() method to compare Enum, they will produce same result because equals() method of Java.lang.Enum internally uses == to compare enum in Java. Since every Enum in Java implicitly extends java.lang.Enum ,and since equals() method is declared final, there is no chance of overriding equals method in user defined enum. If you are not just checking whether two enums are equal or not, and rather interested in the order of different instances of Enum, then you can use compareTo() method of enum to compare two enums. 

How to disable JUnit Test - @Ignore annotation Example

If you are using JUnit 4, then you can use @Ignore annotation to disable a test case; what this means is that any method which is annotated by @Ignore, will not be executed by JUnit. Why would you want to disable a test? Well, It may be because that particular test is for functionality that is not yet implemented fully, and because of that your build is failing. Like that there could be some other scenarios where you would like to temporarily disable a test or a group of tests. From JUnit 4 onward test methods are annotated with @Test, so if they are also annotated with @Ignore will not be executed as tests.

The Ultimate Guide of Generics in Java - Examples

Java Generics Tutorial
Generics in Java is one of the important features added in Java 5 along with Enum, autoboxing, and varargs, to provide compile-time type-safety. Generics are also considered to be one of the tough concepts to understand in Java and somewhat it’s true as well. I have read many articles on generics in Java, some of them are quite good and detailed but I still felt that those are either too technical or exhaustively detailed, so I thought to write a simple yet informative article on Java generics to give a head start to beginners without bothering their head too much. 

Difference between trunk, tags and branches in SVN? Answer

SVN or Subversion is one of the popular source control systems used in the Java world for source code management. There are a lot of source control systems available e.g. Git, Perforce, CVS, ClearCase, VSS, but SVN has its own place among Java developer and open source communities. Knowledge of source control systems is a must for any professional programmer. New users of subversion are often confused between three things trunk, tags, and branches. Questions like, what is the difference between a tag and a branch in subversion is frequently asked in various Java forums and chat rooms.

How to Convert InputStream to Byte Array in Java - 2 Examples

Sometimes we need to convert InputStream to byte array in Java, or you can say reading InputStream as a byte array, In order to pass output to a method that accepts byte array rather than InputStream. One popular example of this, I have seen is an older version of Apache commons-codec, while converting byte array to the hex string. Though, a later version of the same library does provide an overloaded method, to accept InputStream. Java File API provides excellent support to read files like image, text as InputStream in Java program, but as I said, sometimes you need String or byte array, instead of InputStream .

How to convert double to int in Java? Example

Suppose you have a double primitive variable 4.444 and you want to convert it to the integer value 4, how do you that in Java? Since double is bigger data type than int, you can simply downcast double to int in Java. double is 64-bit primitive value and when you cast it to a 32-bit integer, anything after the decimal point is lost. Btw, typecasting doesn't do any rounding or flooring, which means if you have 9.999999 and while casting to int you are expecting 10 then you would be disappointed, casting will give you just 9. If you need 10 then you need to use Math.round() method to first round the double value to the nearest integer and then truncate decimals.

Does making all fields Final makes the class Immutable in Java? Example

One of the common misconceptions among many Java Programmers is that a class with all final fields automatically becomes Immutable. This is not correct, you can easily break the immutability of a certain class if the final field it contains is a mutable one, as we'll see in this article. One of the most common examples of this is a java.util.Date fields e.g. birthDay, expirtyDate, or joiningDate sort of fields. You have to be extra cautious to keep your class' immutability intact with mutable fields. The most common mistake in this regard happens when a Java programmer returns a reference of the original object when a client asks like getBirthDay() returns the date object pointed by birthDay field.

Top 10 Tips on Logging in Java - Tutorial

Java logging or logging in java is as much an art as science. knowing to write tools and API for java logging is definitely the science part but choosing the format of java logs, the format of messages, what to log in to java, which logging level to use for which kind of messages are purely experienced-based things, and sort of art which you learn by applying logging in java. Since its proven fact that java logging severely affects performance and I have seen latency of online stock trading application goes multiple times if they run in DEBUG mode than in WARN or higher level mode.

Tuesday, July 27, 2021

How to Setup Java Remote Debugging in Eclipse - Step by Step Guide

How to remote debug Java program in Eclipse
Remote debugging is not a new concept and many of you are aware of this just for those who doesn’t know what is remote debugging? It’s a way of debugging any process that could be Java or C++ running on some other location on your development machine.  Since debugging Java applications is an essential part of Java development and ability to debug your application not only saves time but also increases productivity. Local debugging is the best way to debug Java programs in my opinion and should always be preferred over remote debugging as discussed in my post How to debug Java program in Eclipse, but if local debugging is not possible and there is no way to debug your process then remote debugging Java application is the solution.  

Difference Between java and javaw Commands from JDK

The difference between java.exe and javaw.exe commands was the recent java question asked to one of my friends. while running a java program on windows you might have noticed that they will appear in the task manager as either java.exe or javaw.exe,  also in JAVA_HOME/bin we see these two java commands java.exe and javaw.exe, do you know the difference between java.exe and javaw.exe? surprisingly not many java programmers know the answer to this java interview question, maybe because java developers have not paid enough attention to these commands. anyway here we will see few differences between java and java commands:

Java Program to connect Oracle Database with Example - JDBC Tutorial Sample Code

How to connect to Oracle database from Java Program using JDBC API is common to need for many Java programmer, though there is a lot of framework available which has simplified JDBC development e.g Hibernate, Spring JdbcTempate and many more, creating Java program to connect to oracle database from plain old Java is still the easiest and quickest method for testing and debugging database connectivity. The database connection program is also a common Java programming exercise in many Java programming courses in schools, colleges, and various training institutes.

Difference between ValidatorForm vs ValidatorActionForm in Struts Framework? Example

Struts provide two classes ValidatorForm and ValidatorActionForm for validating form fields. Instead of doing basic validation by using the validate() method in Action class, these classes allows you to leverage rich feature of validation framework provided by Jakarta Struts framework. You can do declarative validation by defining rules in XML config files like validation-rule.xml or validations.xml as well. Since Struts is one of the popular Web MVC frameworks, you can also use its validation framework on any Java web application implemented using Struts. Now, coming back to the question, what is the actual difference between ValidatorForm and ValidatorActionForm in Struts? They both look quite similar, right?

10 points about Java Heap Space or Java Heap Memory

10 Points about Java heap memory
When I started Java programming I didn't know what is java heap or heap space in Java, I was even not aware of where does object in Java gets created, it’s when I started doing professional programming I came across error java.lang.OutOfMemoryError in Tomcat then I realized What is Heap in Java or Java Heap Space. It happens with most of the programmer because learning language is easy but learning basics are difficult since there is no formal process which can teach you every basic of programming its experience and work which reveals the secret of programming.

What is interface in Java with Example - Tutorial

What is an interface in Java?
Interface in java is a core part of the Java programming language and one of the ways to achieve abstraction in Java along with the abstract class. Even though the interface is a fundamental object-oriented concept; Many Java programmers think of Interface in Java as an advanced concept and refrain from using the interface from early in a programming career. At a very basic level interface in java is a keyword but same time it is an object-oriented term to define contracts and abstraction, This contract is followed by any implementation of Interface in Java. Since multiple inheritances are not allowed in Java, the interface is the only way to implement multiple inheritances at the Type level.

String replaceAll() example - How to replace all characters and substring from String

You can replace all occurrence of a single character, or a substring of a given String in Java using the replaceAll() method of java.lang.String class. This method also allows you to specify the target substring using the regular expression, which means you can use this to remove all white space from String. The replaceAll() function is a very useful, versatile, and powerful method and as a Java developer, you must know about it. Even though Java provides separate methods for replacing characters and replacing substring, you can do all that just by using this single method.

How to Measure Elapsed Execution Time in Java - Spring Framework's StopWatch Example

There are two ways to measure elapsed execution time in Java either by using System.currentTimeinMillis()or by using  System.nanoTime(). These two methods can be used to measure elapsed or execution time between two method calls or events in Java. Calculating elapsed time is one of the first things Java programmer do to find out how many seconds or millisecond a method is taking to execute or how much time a particular code block is taking. Most Java programmers are familiar with System.currentTimeInMillis()which is there from the beginning while a new version of more precise time measurement utility System.nanoTime is introduced in Java 1.5, along with several new features in a language like Generics, Enum types, autoboxing and variable arguments or varargs.

How to Invoke Method by Name in Java Dynamically Using Reflection? Example

In Java you can invoke any method by its string name dynamically using reflection API. java.lang.reflect API provides powerful reflection mechanism which can load classes by its name even if classes are not available at compile time, Can get all methods including private and public from class and allow you to invoke any method dynamically using reflection. For those who are new to Java this sound pretty strange that at runtime you provide a method name using string and Java can run that method without any code for calling the method during compilation, but Reflection is such a powerful mechanism it allows to do a lot of stuff dynamically and if you been using IDE like Netbeans or Eclipse, a J2EE framework like Spring and Struts, these all used reflection to provide powerful configuration module and several other useful features like code assist etc.

Difference Between java.util.Date and java.sql.Date in Java - JDBC Interview Question

Difference between java.util.Date and java.sql.Date in Java or why does Java have java.sql.Date if there is already a Date class in java util package is a common java interview question. There is always confusion among many Java developers familiar with both java.util.Date and java.sql.Date. Though many of them already using java.sql.Date to interface with DATE type of any relational database like MySQL, Oracle, or any other database. In this Java tutorial, we will see some differences between java.sql.Date and java.util.Date will help to understand both of them better.

How to Convert Local Time to GMT in Java - Example Tutorial

Converting local time into GMT or any other timezone in Java is easy as Java has support for time zones. JDK has a class called java.util.Timezone which represents timezone and Java also has classes like SimpleDateFormat which can use Time zone while parsing or formatting dates. By using java.uti.TimeZone and java.text.SimpleDateFormat we can write a simple Java program to convert local time to GMT or any other time zone in Java. We have already seen examples of How to get current date and time in GMT and this Java program is an extension of that in order to convert time form one timezone to other timezones.

What is rt.jar in Java/JDK/JRE? Why it’s Important?

rt.jar stands for runtime JAR and contains the bootstrap classes, I mean all the classes from Core Java API. I have found that many Java programmer doesn't know what is rt.jar? and often confused with the role of rt.jar file or why we use of rt.jar file in Java? No surprise, the name is a little bit cryptic.  This file always resides inside the lib directory of JRE, at least in Windows and Linux. In MacOSX it resides at a different location and also has a different name i.e. classes.jar, but that is only prior to JDK 1.7. From Java 7 release Apple has stopped distributing Java and if you separately install, it will have the same name as rt.jar.

Difference between ConcurrentHashMap, Hashtable and Synchronized Map in Java

ConcurrentHashMap vs Hashtable vs Synchronized Map
Though all three collection classes are thread-safe and can be used in multi-threaded, concurrent Java application, there is a significant difference between them, which arise from the fact that how they achieve their thread-safety. Hashtable is a legacy class from JDK 1.1 itself, which uses synchronized methods to achieve thread safety. All methods of Hashtable are synchronized which makes them quite slow due to contention if a number of thread increases. Synchronized Map is also not very different than Hashtable and provides similar performance in concurrent Java programs. The only difference between Hashtable and Synchronized Map is that later is not a legacy and you can wrap any Map to create it's synchronized version by using Collections.synchronizedMap() method.

Java PropertyUtils Example - getting and setting properties by name

PropertyUtils class of Apache commons beanutils library is very useful and provides you the ability to modify properties of Java object at runtime. PropertyUtils enables you to write highly configurable code where you can provide the name of bean properties and their values from configuration rather than coding in Java program and Apache PropertyUtils can set those properties on Java object at runtime. One popular example of how powerful PropertyUtils can be is display tag which provides a rich tabular display for JSP pages, it uses PropertyUtils class to get values of an object at runtime and then display it.

What is Effectively Final variable of Java 8? Example

Apart from the big three, Lambda expression, Stream API, and new Date and Time API, Java 8 has also introduced a new concept called the "effectively final" variable. A non-final local variable or method parameter whose value is never changed after initialization is known as effectively final. It's very useful in the context of the lambda expression. If you remember, prior to Java 8, we cannot use a non-final local variable in an anonymous class. If you have to access a local variable ( a method parameter or a variable decreed in the method itself) in the Anonymous class, you have to make it final. This restriction is relaxed a bit with lambda coming up. Java designers have taken the need to make local variable final if it's not changed once initialized.

Top 10 JSP Interview Questions Answers for Java Programmer

These JSP interview questions and answers are asked in the various J2EE interview and focus on the view part of the MVC framework. JSP or Java Server Pages is a Java technology used to render a dynamic view. Whenever you go for any Java web developer interview there are always some interview questions on JSP. This article is a collection of some JSP interview questions which has asked in the various interview to my friends and colleagues. You can easily find answers to these JSP interview questions by google but I have included my version for quick reference.

How to use EnumSet in Java with Example

EnumSet is one of the specialized implementations of the Set interface for an enumeration type, introduced in Java 1.5 along with the enumeration type itself. Programmer often stores Enum into common collection classes e.g. HashSet or ArrayList, mostly because they are unaware of this little gem. Even I wasn't aware of this class a few years ago until I come across one of the finest books for Java programmers, Effective Java. It has an Item on EnumSet, which highlights some typical use-cases for this collection class instead of using int variable and bitwise operator. Since Enum constants are unique and have pre-defined lengths, as you can not define a new enum constant at runtime; it allows Java API designers to highly optimize EnumSet.

How to Reverse Array in Place in Java? Solution With Explanation

Reversing an array sounds pretty easy, isn't it? It does sound like that, because all you need to do is create an array of the same size, iterate through the original array from end to start, and populate your new array. Boom!!, you have got an array that has elements in reverse order of the original array, but the problem is you have used an additional array here, which makes space complexity of your solution O(n). You cannot use this solution if the array is big e.g. an array of 10 million orders and you don't have enough heap space available.