Tuesday, August 31, 2021

Java 8 Stream filter() + findFirst Example Tutorial

Suppose, you have a list of prime numbers and you need to find the first prime number which is greater than a given number? How do you find it? Don't tell that you will loop through the list and check each element and return the first element which is greater than the given number. Well, that's right but that's not what you should do in Java 8. That's good for Java 7 or earlier version but Java 8 offers you many better alternatives and one of them is Stream. You can use the Stream class along with filter() and findFirst() methods to find out an element based upon a Predicate, a functional interface for defining a condition which returns a boolean.

How to add and remove Elements from an Dynamic Array in Java? Example Tutorial

Java beginners often ask how to add new elements to an array in Java? or how to remove elements from an array in Java? is that possible in Java? Well, no, it's not possible in Java because arrays length cannot be changed once created. This means neither you can add new elements nor you can remove an old one from an array in Java. All you can do is reassign values to a different bucket. For example, if you have a string array of length 3 like {"java", "is", "great"} then you can just replace the individual index to make it like {"Python", "is", "great"} by replacing "java" with "Python" at first index, but you cannot add or remove elements.

Saturday, August 28, 2021

Top 20 Java EE Web Developer Interview Questions

Ever since J2EE become obsolete the enterprise Java has got confusing names e..g JEE or Java EE. I am still not sure what is called officially and popularly so I have included all of them i.e. J2EE, Java EE and JEE. In this article you will find questions about Java EE platform, architecture and technolgoies e.g. JSP, Servlet, EJB, JMS, JSF, JMX, JNDI and JDBC. It will also include questions from application servers like GlassFish, WebLogic and WebSphere and messaging technologies like MQ Series, TIBCO and others. 



Difference between Servlet and JSP?

Difference between Web and application Server?

What is EJB?

Difference between EJB 2.0 and EJB 3.0?

What is JMS?

What is difference between JMS and WebSphere MQ Series?

Some basic platform stuff:

List three Collections interfaces and the basic contract of each. List concrete implementations of each, how they differ, and performance characteristics in space and time.

Describe the contract of equals and hashCode. Why is it important that if you implement one, that you implement both?

What are generics? What is type erasure and what are the consequences? What are variance, covariance and contravariance? If blank stare: why can't you assign a collection with a generic type binding of a sub type to a reference to the same collection type binding of the super type? How do you specify the type binding of the super type to allow this? How do you specify the type binding to allow type-safe insertion?


Concurrency

Explain how notify and notifyAll work, and the difference between the two. Why prefer notifyAll to notify?

What is a deadlock and how do you avoid it?

What is a race condition and how do you avoid it?

What are some of the high-level concurrency classes provided by java.util.concurrent and how do they work?


Database

What are the different statement types and why would you use each?

How do you prevent SQL injection attacks?

What are transactions? What is ACID?


Hibernate

Give an overview of Hibernate and ORM. How do you load objects into the session? What does the session do with the objects while in the session? What is the difference between getting a persistent object from the session and querying for persistent objects?

When is it better to use plain SQL instead of ORM?


Java EE

How do you configure a DataSource in Weblogic to make it available using JNDI?

What are some ways for the client to obtain a reference to the DataSource from the app server? (Spring is not the answer I am looking for)


Spring

Give an overview of how Spring Dependency Injection container works. What is the purpose of DI? How to specify bean definitions? What are the different scopes? When do beans of each scope type get instantiated?


Web Services

What is the difference between SOAP-based web services and REST-based web services?

Describe SOAP and WSDL.

What exactly is REST? What is HATEOAS? What is the purpose of each of the HTTP verbs? What is idempotence? What is content-negotiation?


OOP

What is decoupling? Why are loose-coupling coupled classes desirable? What are some drawbacks?

What is cohesion? Why are highly cohesive classes desirable? What are some drawbacks?

Describe polymorphism. What is the importance of contracts between interfaces and concrete types? Why is polymorphic code desirable? What are some drawbacks?


REf : https://www.reddit.com/r/java/comments/2lo7it/conducted_an_interview_for_a_senior_java/


Friday, August 27, 2021

How to Remove Objects From ArrayList while Iterating in Java - Example Tutorial

One of the common problems many Java Programmers face is to remove elements while iterating over ArrayList in Java because the intuitive solution doesn't work like you just cannot go through an ArrayList using a for loop and remove an element depending upon some condition. Even though java.util.ArrayList provides the remove() methods, like remove (int index) and remove (Object element), you cannot use them to remove items while iterating over ArrayList in Java because they will throw ConcurrentModificationException if called during iteration. The right way to remove objects from ArrayList while iterating over it is by using the Iterator's remove() method.

Thursday, August 26, 2021

9 JSP Implicit Objects and When to Use Them

If you are new to JSP then your first question would be what are implicit objects in JSP? Well, implicit objects in JSP are Java object which is created by Servlet containers like the tomcat or Jetty during translation phase of JSP, when JSP is converted to Servlet. These objects are created as local variables inside the service() method generated by the container. The most important thing about the implicit objects is to remember that these objects are available to any JSP developer inside the JSP page and they can do a lot of things with implicit objects and expression language which was only possible with scriptlet earlier. That's why they are known as implicit objects. 

How to implement PreOrder traversal of Binary Tree in Java - Example Tutorial

The easiest way to implement the preOrder traversal of a binary tree in Java is by using recursion. The recursive solution is hardly 3 to 4 lines of code and exactly mimic the steps, but before that, let's revise some basics about a binary tree and preorder traversal. Unlike array and linked list which have just one way to traverse, I mean linearly, the binary tree has several ways to traverse all nodes because of its hierarchical nature like level order, preorder, postorder, and in order. Tree traversal algorithms are mainly divided into two categories, the depth-first algorithms, and breadth-first algorithms. In depth-first, you go deeper into a tree before visiting the sibling node, for example, you go deep following the left node before you come back and traverse the right node.

How to Enable GC Logging in Java HotSpot JVM

When we are diagnosing problems in a Java (EE or otherwise) application, is often a good idea to check how garbage collection is performing. One of the basic and most unobtrusive actions is to enable garbage collection logging.


As you may know, if we add the following arguments to the java start command…


-Xloggc:<file_name> –XX:+PrintGCDetails -XX:+PrintGCDateStamps


… the JVM will start writing garbage collection messages to the file we set with the parameter -Xlogcc. The messages should be something like:



2010-04-22T18:12:27.796+0200: 22.317: [GC 59030K->52906K(97244K), 0.0019061 secs]

2010-04-22T18:12:27.828+0200: 22.348: [GC 59114K->52749K(97244K), 0.0021595 secs]

2010-04-22T18:12:27.859+0200: 22.380: [GC 58957K->53335K(97244K), 0.0022615 secs]

2010-04-22T18:12:27.890+0200: 22.409: [GC 59543K->53385K(97244K), 0.0024157 secs]


The bold part is simply the date and time when reported garbage collection event starts.


Unfortunately -XX:+PrintGCDateStamps is available only for Java 6 Update 4 and later JVMs. So, if we are unlucky and our application is running on older JVMs we are forced to use…


-Xloggc:<file> –XX:+PrintGCDetails


… and the messages will be like:



22.317: [GC 59030K->52906K(97244K), 0.0019061 secs]

22.348: [GC 59114K->52749K(97244K), 0.0021595 secs]

22.380: [GC 58957K->53335K(97244K), 0.0022615 secs]

22.409: [GC 59543K->53385K(97244K), 0.0024157 secs]


Now, the bold numbers (also present in previous format) are the seconds elapsed from JVM start time



-XX:+PrintGCDateStamps -verbose:gc -XX:+PrintGCDetails -Xloggc:"<path to log>"

These options make Java to log garbage collector activities into specified file. All records will be prepended with human readable date and time. Meanwhile you should avoid using -XX:+PrintGCTimeStamps as it will prepend record with useless timestamp since Java application start.


Generate log can be later analysed with GCViewer.


-XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=10 -XX:GCLogFileSize=100M

GC log files rotation makes analysis of garbage collection problems easier, also it guaranties that disk is protected from space overconsumption


Reference

https://blog.sokolenko.me/2014/11/javavm-options-production.html

https://176.34.122.30/blog/2010/05/26/human-readable-jvm-gc-timestamps/


java gc log file


java gc log format


how to read java gc log

How to reverse a singly linked list in Java without recursion? Iterative Solution Example

Hello guys, reverse a linked list is a common coding problem from Programming Job interviews and I am sure you have seen this in your career, if you are not, maybe you are a fresher and you will going to find about this very soon in your next technical interview. In the last article, I have shown you how to use recursion to reverse a linked list, and today, I'll show you how to reverse a singly linked list in Java without recursion. A singly linked list, also known as just linked list is a collection of nodes that can only be traversed in one direction like in the forward direction from head to tail. Each node in the linked list contains two things, data and a pointer to the next node in the list.

Wednesday, August 25, 2021

Some JavaScript Tips

Javascript requires discipline. You can easily create a giant mess. The language allows it. That doesn't mean you should. I've seen and worked on modular, object-oriented driver software written in assembly language. If a clean project and codebase can be done in assembly language, it can be done in javascript.


Use a lint

read other people's code, especially popular things like jquery, node, etc

Follow Crockford's advice about which features to use and which to avoid, e.g. always use === over ==. You almost never want what == does. Just don't use it at all. He has a lot of tips like that.


One good way to learn is to take somewhat complex functions/libraries and write them from scratch, and then compare your source code to the official source code. I did this with jQuery.Deferred, and it was really interesting to see how different my code was from the actual code.

4 Ways to Write String to File in Java

There are many ways to write String to File in Java and we will see four ways in this article. Simplest way to write text data into a File is by using FileWriter, it takes care of character encoding and provides simple methods to write String directly into file. Another way to write String is by using PrintWriter object. It provides convinient and much used to print() and println() method to write String to file in Java. Ofcourse you can alawys use FileOutputStream if you are getting String as bytes but its not as efficent as FileWriter. For those, who hates to deal with Java IO mainly to avoid closing files, stream and freeing up resource can use third party library like Apache Commons IO which provides very convinient methods to write String to file without worring about resource cleanup part. 


using FileWriter

using PrintWriter

using FileOutputStream

Apache Commons FileUtils


How to write string to text file in Java using FileOutputStream

how to write string to a file in Java using FileWriter

How to write String to File using PrintWriter in Java

Java 7 one liner to write String to file


Writing text into File using Apache Commons IO

FileUtils class from Apache Commons IO contains some convinient utility methods to write String to text file. 


main advantage of using a PrintWriter for writing String to file is that you can use its convinient print() and println() method to write lines. If you use println() then a line fee will always be inserted on contnet, effecitly writing content in new line. Don't forget to close stream, reader or file once you are done writing on it. This is one area where many developers make mistake, also you must know how to close stream in right way to avoid any issue. If you feel this is too much then you better stick with Apache Commons IO FileUtils class which will take care of closign file properly after writing.

How to use Expression language in JSP - Example

In order to use Expression language in JSP you need to include JSTL 1.1 Jar. It was introduced in JSP 2.0 version. Alogn with JSTL and custom tag library, JSP expression langauge are very important to minimize Java codes from JSP pages and by using thsi we can create more maintainable JSP pages. JSP Expression language or EL allows you to access attribute and properties of any object seemlessly without using scriptlet. You can use expression language as ${expr} and its processed at runtime by JSP engine. You can disable use of expression language in any JSP page by using taglib directive. 


Syntax of Expression language


Implicit objects for Expressionlangauge


Benefits of using expression language


Expression language example in JSP


That's all about how to use expression language in JSP. 


important points about expression langauge (EL)

1) Expression language provides a mechanism for enabling the presentation layer (JSP pages) to communicate with application logic (managed beans) without using Java code or scriptlet. 

https://docs.oracle.com/javaee/6/tutorial/doc/bnahu.html

2) EL is used by both Java server pages (JSP) and JavaServer Faces (JSF).


3) EL allows JSP developers or page authors to use simple expressions to dynamically access data from any collection or object. EL greatly improves readability of JSP pages.


4) EL can also be used with Java Enum


jQuery pseudo selector Example

Apart from Class and ID selector, jQuery also provides CSS like pseudo selectors to select elements like first, last, even or odd in list of elements. For example, if you have an unordered list, which contains 5 list items and you want to select the first list item, you can use pseudo selector like $("#course li:first"). Similarly you can also choose the last list item in the unordered list by using $("#course li:last). Ifyou want to select alternate elements, you have options of choosing even or odd elements by using $("course li:odd) and $("#course li:even"). Odd selector will select all elements whose index is odd number, remember indes starts at 0. So odd selector will choose 2st and 4rd element and even selector will choose first, 3rd and 5th element. 


here is an example :

jQuery DOM Traversal example

Apart from using descendant, child and pseudo selector to select descendant, childrens, first, and last elements, you can also use DOM traversing to find elements in jQuery. DOM traversing is a powerful technique which you can use in place of selector and it give better performance. jQuery provides methods to go up and down in DOM tree and also to select first, last, next, prev, parent and child like methods to move around efficiently. Here are examples of using different DOM traversal method in jQuery :


1) first

2) last

3) next

4) previous

5) parent

6) children

How to select and change multiple lines in SSMS (SQL Server Management Studio Tips)

Many times we copy Id, names and other attributes form Excle file, email or from other query result which doesn't have single quotes on it. In order ot add single quotes to make it Sring in SQL Server mangaement studio, you are left with no opiton but to manually add single quotes before and after stirng and comma between two values. This is ok if you have just couple of values but if you have 50 or 100 then you are screwed. Today I come to know about an excellent SSMS shortcut, which will let you change multiple lines at once, what this means is that you can add single quotes at front of those 50 values in one keystroke, provided they are in different lines. THis will save a lot of time while working wtih SQL Server, 


I used to make a cab in excel, then open in notepad, and copy+paste. This will save so much more time.


here is this tip in action :

https://www.reddit.com/r/SQL/comments/39lfaf/i_just_learned_about_altshift_in_ssms/


I knew about ALT to select a column of text but I didn't know you could snap like that with shift. It also works in Visual Studio and Notepad++

It is indeed real, and other good text editors supports this action as well. I use it everyday in Visual Studio for example.


Neat trick, but it only works if all the items in your list are the same size like the GUIDs in your example, hat's a bummer. At least it'll always work on the left side.


You can also alt-mouse move for box selecttions.


It also works in conjunction with ctrl and the arrow keys and pageup/down and home/end.

Exception in thread thread_name: java.lang.OutOfMemoryError: Requested array size exceeds VM limit

Cause: The detail message "Requested array size exceeds VM limit" indicates that the application (or APIs used by that application) attempted to allocate an array that is larger than the heap size. For example, if an application attempts to allocate an array of 512 MB but the maximum heap size is 256 MB then OutOfMemoryError will be thrown with the reason Requested array size exceeds VM limit.


Action: Usually the problem is either a configuration issue (heap size too small), or a bug that results in an application attempting to create a huge array (for example, when the number of elements in the array is computed using an algorithm that computes an incorrect size).

Tuesday, August 24, 2021

How to use Randam vs ThreadLocalRandom vs SecureRandom in Java? Example Tutorial

Hello guys, one of the common tasks for Java developers is to generate an array of random numbers, particularly in game development. For example, if you are coding for dice-based games like Ludo or Snake and Lader then you need to generate a random number from 1 to 6 to simulate dice behavior. The same goes for other dice-based games. There are many cases where you need to generate random numbers and an array of random numbers. In some cases, duplicates may be allowed while other duplicates are not permitted.  

How to Convert String to LocalDateTime in Java 8 - Example Tutorial

Hello guys, today, I will talk about a common problem while working in a Java application, yes you guessed it right, I am talking about String to Date conversion in Java. I had discussed this before (see the Date to String) when Java 8 was not out, but with Java 8, I don't see any reason to use old date and time API, and hence I am writing this post to teach you how to convert String to Date in Java 8 or beyond. Suppose you have a date-time String "2016-03-04: 11:01:20" and you want to convert this into a LocalDateTime object of Java 8 new date and time API, how do you do that? Well, if you have worked previously with String and Date then you know that you can parse String to Date in Java.

How to use Stream.filter method in Java 8? Example Tutorial

In the last couple of Java 8 tutorials, you have learned how to use map(), flatMap(), and other stream methods to get an understanding of how Java 8 Stream and Lambda expressions make it easy to perform the bulk data operation on Collection classes like List or Set. In this Java 8 tutorial, I am going to share how to use the filter() method in Java 8, another key method of the Stream class.  This is the one method you will always be used because it forms the key part of the Stream pipeline. If you have seen some Java 8 code, you would have already seen this method a couple of times.

Monday, August 23, 2021

10 Examples of Stream API in Java 8 - count + filter + map + distinct + collect() Examples

The Java 8 release of Java Programming language was a game-changer version. It not only provided some useful methods but totally changed the way you write programs in Java. The most significant change it brings in the mindset of Java developers was to think functional and supported that by providing critical features like lambda expression and Stream API, which takes advantage of parallel processing and functional operations like filter, map, flatMap, etc. Since then, a lot of Java developers are trying their hands to learn those significant changes like lambda expression, method reference, new Date and Time classes, and, more importantly, Stream API for bulk data operations.

Sunday, August 22, 2021

How to debug Java 8 Stream Pipeline - peek() method Example Tutorial

Hello guys, I have been writing about some important methods from Java SE 8  like map(), flatMap(), collect(), etc for quite some time, and today I'll share my experience with another useful method peek() from java.utill.stream.Stream class. The peek() method of the Stream class can be very useful to debug and understand streams in Java 8. You can use the peek() method to see the elements as they flow from one step to another like when you use the filter() method for filtering, you can actually see how filtering is working like lazy evaluation as well as which elements are filtered.

How to Calculate Next Date and Year in Java? LocalDate and MonthDay Example Tutorial

Hello guys, if you are wondering how to calculate the next premium date, next birthday, or exact date for the next Christmas holiday in Java then you have come to the right place. Earlier, I have shared 20+ examples of Date and Time in Java, and in this article, I will show you how you can use the LocalDate and MonthDay class from the new Java 8 Date and Time package to calculate the next or previous date in Java. This new API is very well structured and you have classes to represent different Date concepts, for example, you can use LocalDate to represent a Date without time components like the next premium date or employee joining date or birth date. 

Saturday, August 21, 2021

How to Reverse an Array in place in Java? Example Solution

It's relatively easy to reverse an array if you have the luxury to use another array, but how would you reverse an array if a temporary buffer is not allowed? This is one of the testing array interview questions, which often proved tricky for Java and other beginner Programmers. But, don't worry, I'll tell you how you can solve this problem without losing your cool. Well, you can also reverse an array in place without using an additional buffer. If you know how to access array elements and how to loop over an array in Java using traditional for loop, you can easily solve this problem without using additional space or in-place as described in many Algorithms books and courses, and on Coding interviews.

3 ways to ignore null fields while converting Java object to JSON using Jackson? Example

Ignoring null fields or attribute is a one of the common requirement while marshaling Java object to JSON string because Jackson just prints null when a reference filed is null, which you may not want. For example, if you have a Java object which has a String field whose value is null when you convert this object to Json, you will see null in front of that. In order to better control JSON output, you can ignore null fields, and Jackson provides a couple of options to do that. You can ignore null fields at the class level by using @JsonInclude(Include.NON_NULL) to only include non-null fields, thus excluding any attribute whose value is null.

Friday, August 20, 2021

5 Differences between an array and linked list in Java

The difference between an array and a linked list is one of the frequently asked data structure and algorithm interview questions and you might have seen it before on your telephonic or face-to-face interview. It is also a very popular question during practical exams in Computer Science degree courses like B.E. and B.Tech. It's very simple and easy to answer but you just can't afford to miss this question in an interview. Both array and linked list are two of the most popular and fundamental data structures in Computer Science and Programming, and Java supports both of them.

What is difference between final vs finally and finalize in Java?

Hello guys, final, finally, and finalize are three confusing keywords, modifiers, and methods in Java. They sound similar, but they are for different purposes. For example, the final keyword is a modifier in Java. When you use the final keyword with a class, it becomes a final class, and no one can extend this like String is final in Java. When you use the final modifier with a method, then it cannot be overridden in a subclass, and when you use the final keyword with a variable, it becomes a constant, i.e. its value cannot be changed once assigned.

Thursday, August 19, 2021

How to convert ArrayList to HashMap and LinkedHashMap in Java 8 - Example Tutorial

One of the common tasks in Java is to convert a List of objects, like a List<T> into a Map, I mean Map<K, V>, where K is some property of the object and V is the actual object. For example, suppose you have a List<Order>, and you want to convert it into a Map, e.g. Map<OrderId, Order>, how do you that? Well, the simplest way to achieve this is iterating over List and add each element to the Map by extracting keys and using the actual element as an object. This is exactly what many of us do in the pre-Java 8 world, but JDK 8 has made it even simpler.

How to code Binary Search Algorithm using Recursion in Java? Example

Hello guys, In the last article, we have seen the iterative implementation of binary search in Java, and in this article, you will learn how to implement binary search using recursion. Recursion is an important topic for coding interviews but many programmers struggle to code recursive solutions. I will try to give you some tips to come up with recursive algorithms in this tutorial. In order to implement a recursive solution, you need to break the problem into sub-problems until you reach a base case where you know how to solve the problem like sorting an array with one element. Without a base case, your program will never terminate and it will eventually die by throwing the StackOverFlowError.

Post Order Binary Tree Traversal in Java Without Recursion - Example Tutorial

In the last article, I have shown you how to implement post-order traversal in a binary tree using recursion, and today I am going to teach you about post order traversal without recursion. To be honest, the iterative algorithm of post-order traversal is the toughest among the iterative pre-order and in-order traversal algorithm. The process of post-order traversal remains the same but the algorithm to achieve that effect is different. Since post-order traversal is a depth-first algorithm, you have to go deep before you go wide. I mean, the left subtree is visited first, followed by the right subtree, and finally, the value of a node is printed.

Wednesday, August 18, 2021

7 Examples to Sort One and Two Dimensional String and Integer Array in Java | Ascending, Descending and Reverse Order

Sorting array is a day-to-day programming task for any software developer.  If you have come from a Computer Science background then you have definitely learned fundamental sorting algorithms like the bubble sort, insertion sort, and quicksort but you don't really need to code those algorithms to sort an array in Java because Java has good support for sorting different types of array. You can use Arrays.sort() method to sort both primitive and object array in Java. But, before using this method, let's learn how the Arrays.sort() method works in Java. This will not only help you to get familiar with the API but also its inner workings.  This method sorts the given array into ascending order, which is the numeric order for primitives and defined by compareTo() or compare() method for objects.

How to prepare Oracle Certified Master Java EE Enterprise Architect (1z0-807, 1Z0-865, 1Z0-866) - OCMJEA6 Exam

The OCMJEA 6 certification is one of the most difficult, time-consuming, and tiresome Java certifications. Still, it was also the one that made me learn and grow professionally. This certification consists of 5 phases:

Phase 1: Compulsory Course

At this point, the candidate is required to take at least one official Oracle course from Java at any partner company. You can complete this course during certification - before, during, or after.

If you already have experience in Java and architecture, leave to take the course at the end. If not, use the classes to gain knowledge for the test by doing them before. There is a complete grid of Java courses for the candidate to acquire the necessary know-how for this certification.

How to use Record in Java? Example

A Java record is a special kind of java class that is used as a 'data carrier' class without the traditional 'Java ceremony' (boilerplate). This represents an immutable state that is passing immutable data between objects. The Java Record was introduced with Java 14, and it is a preview feature because it must be enabled before it can be used. Records received via a database query, records returned from a remote service call, records read from a CSV file, and other use cases can all benefit from Java Record instances.

Monday, August 16, 2021

Top 5 Free Apache Maven eBooks for Java Developers

If you are working in Java for a couple of years, you surely know about Maven, the most popular tool to build Java applications. Recently I had shared 10 things about Maven Java developers should know, (if you have read it yet, you can read it here) and I receive a lot of good feedback about how useful those plugins and Maven, in general, are for Java developers. This motivated me to write more stuff about Apache Maven, and then I thought about sharing some of the free Maven courses and ebooks Java developers can use to learn Maven. 

Top 4 Free Microsoft SQL Server Books - PDF Download or Online Read

Hello Guys, if you want to learn SQL Server and looking for free resources then you have come to the right place. Earlier, I have shared free SQL and database courses and today, I am going to share some of the excellent database and SQL server books that are freely available on the internet for reading online or download as PDF. If you have been reading this blog then you know that I love books, I love to read books, and I love to collect books, that's why I have a significant online and offline library. Many people question me, do I really find to read all the books which I share? Well, I don't read all books page by page, unless and until it's something like Effective Java or Clean Code

4 Best Books to Learn Web Service in Java - SOAP and RESTful

If you are a Java developer and want to learn how to develop Web Services in Java, both SOAP and RESTful, but confused about where to start, then you have come to the right place. In this article, I am going to share some of the best books to learn about both SOAP and RESTful web services in Java. If you are not familiar with Web Services, it's a way to expose the services provided by your application to other developers and applications. For example, if your system offers weather information, then the user can go and check whether manually by looking at the Web GUI built using HTML, CSS, and JavaScript. Still, by exposing the same information using Web services, you allow a programmer to display as they want.

Sunday, August 15, 2021

What is the cost of Oracle Java Certifications - OCAJP, OCPJP, OCEWCD, OCPJD?

One of the frequently asked questions about Oracle Java certifications, formerly known as Sun Certified Java programmer like OCAJP, OCPJP, OCEWCD, OCMEJA, etc. is about the cost of certification. Many of my readers often ask what the cost of OCAJP  like OCAJP 8 or OCAJP 11 and  OCPJP like OCPJP 8 and OCPJP 11 is? Is there any discount available? What are the fees of Java 8 certifications? How much Java architect exam cost? Etc. I have answered many of them one to one via Facebook and Email in the past, but after so many such requests, I decided to write a blog post about it.

Saturday, August 14, 2021

Top 3 Free Struts Books for Java EE developers - Learn Online, PDF download

Jakarta Struts is one of the most popular MVC frameworks to create a Java web application. Struts 1.0 had ruled the world in the early 2000 era before Spring MVC took over. Still, there are lots of projects written in Struts that need active maintenance, and that's why Struts developers are still in demand. It has not become anything like COBOL, but the latest version of Struts 2.0 is a capable web MVC framework with dependency injection and has a sizable community behind it. It has close competition with Spring MVC, but given the demand for Struts developers, it's still a good technology to learn if you are looking for a job in a Java web development position.

Thursday, August 12, 2021

Insertion Sort Algorithm in Java with Example

Insertion sort is another simple sorting algorithm like Bubble Sort. You may not have realized but you must have used Insertion sort in a lot of places in your life. One of the best examples of Insertion sort in the real-world is, how you sort your hand in playing cards. You pick one card from the deck, you assume it's sorted, and then we insert subsequent cards in their proper position. For example, if your first card is Jack, and the next card is Queen then you put the queen after Jack. Now if the next card is King, we put it after the queen, and if we get 9, we put it before jack.

Difference between VARCHAR and NVARCHAR in SQL Server

Hello guys, if you are confused between VARCHAR and NVARCHAR data types of SQL Server and wondering what is the difference between VARCHAR and NVARCHAR, or you have been asked this question on technical Interviews and you couldn't answer then you have come to the right place. There is a subtle difference between these two character data types in SQL Server, while both supports variable length, the VARCHAR data type is used to store non-Unicode characters while NVARCHAR is used to store Unicode characters. It also takes more space than VARCHAR. 

Wednesday, August 11, 2021

How to Rotate an Array to Left or Right in Java? Solution Example

Hello guys, welcome to another post with another array-based coding problem. In the last article, we've learned about finding missing numbers in the array with duplicates, and today we'll solve the problem of rotating an array by left or right by a given number. For example, suppose an integer array {1, 2, 3} is given and it was asked to rate this array to the left by 3 then the result array will look like {2, 3, 1} because it was rotated twice on left. Similarly, if you are asked to rotate the same array twice by right then you'll get {1, 2, 3}, the same array is back. 

How to implement Comparator and Comparable in Java with Lambda Expression & method reference? Example

Hello guys, After Java 8 it has become a lot easier to work with Comparator and Comparable classes in Java. You can implement a Comparator using lambda expression because it is a SAM type interface. It has just one abstract method compare() which means you can pass a lambda expression where a Comparator is expected. Many Java programmers often ask me, what is the best way to learn lambda expression of Java 8?  And, my answer is, of course by using it on your day to the day programming task. Since implementing equals(), hashcode(), compareTo(), and compare() methods are some of the most common tasks of a Java developer, it makes sense to learn how to use the lambda expression to implement Comparable and Comparator in Java.

Difference between List <?> and List<Object> in Java Generics - Example

There is No doubt that Generics is one of the most confusing topics in Java, and you can easily forget concepts and rules, especially if you don't code Java every day. For example, both List<?> and List<Object> looks similar there is a subtle difference between them, the List<?> is basically a list of any type, you can assign a list of String like List<String> or list of Integer i.e. List<Integer> to it. You see the point; it uses the unbounded wildcard <?>, which means any type. It provides it the much needed Polymorphism requires while writing Generic methods. 

Tuesday, August 10, 2021

Java - Difference between getClass() and instanceof in equals() method?

You might have seen both getClass(), and instanceof operator in Java can be used in the equals() method to verify the type of the object you are checking for equality. Do you know what the difference is between using getClass() vs instanceof operator in Java? What would be the consequence of using one over the other in the equals() method? This is one of the tricky Java interview questions, which some of you might have encountered. There is a very subtle difference between getClass() and instanceof operator, which can cause potential issues with respect to the equals() method. 

Monday, August 9, 2021

How to Read or Parse CSV files with Header in Java using Jackson - Example Tutorial

Hello guys, today I am going to show you how to read a CSV file in Java with a simple example of Jackson API. For a long time, I only knew that Jackson can be used to parse JSON but later realized that you can also use it to parse or read CSV files in Java. The Jackson DataFormat CSV library allows you to read a CSV file in just a couple of lines and it's really powerful and feature-rich. For example, you can read a CSV file with a header or without a header. You can even read a tab-delimited text file like CSV. It's also highly configurable and allows you to define a columns separator to read a text file with any delimiter. You can even use it to directly convert the CSV data into Java objects, just like we do while reading JSON String in Java.

Saturday, August 7, 2021

Can You Run Java Program Without a Main Method? [Interview Question Answer]

Hello guys, the first thing Java programmers learn is that they need a main method to run, but when they go to any Interview or college viva and ask can run a Java program without a main method, they are surprised like hell. Well, there are actually different types of execution models available in Java; for example, Applets, which run on the browser don't have the main method. Instead, they have life-cycle methods like init(), start() and stop(), which controls their execution. Since Applet is a Java program, you can answer this question is Yes. Similarly, we have Servlet, which runs in a Servlet container, comes as bundled in a web server like Tomcat, or Jetty.

Friday, August 6, 2021

How to Remove an Element from Array in Java with Example

There is no direct way to remove elements from an Array in Java. Though Array in Java objects, it doesn't provide any methods to add(), remove(), or search an element in Array. This is the reason Collection classes like ArrayList and HashSet are very popular. Thanks to Apache Commons Utils, You can use their ArrayUtils class to remove an element from the array more easily than by doing it yourself. One thing to remember is that Arrays are fixed size in Java, once you create an array you can not change their size, which means removing or deleting an item doesn't reduce the size of the array. This is, in fact, the main difference between Array and ArrayList in Java.

Thursday, August 5, 2021

What is double colon (::) operator in Java 8 - Example

Hello guys, if you are new to the Java 8 style of coding and wondering what is those double colon(::) in the code then you have come to the right place. In this article, I will explain to you the double colon operator and what it does in Java 8. The double colon (::) operator is known as the method reference in Java 8. Method references are expressions that have the same treatment as a lambda expression, but instead of providing a lambda body, they refer to an existing method by name. This can make your code more readable and concise.

How to copy Array in Java? Arrays copyOf and copyOfRange Example

There are multiple ways to copy elements from one array in Java, like you can manually copy elements by using a loop, create a clone of the array, use Arrays.copyOf() method or System.arrayCopy() to start copying elements from one array to another in Java. Even though both allow you to copy elements from source to destination array, the Arrays.copyOf() is much easier to use as it takes the just original array and the length of the new array. But, this means you cannot copy subarray using this method because you are not specifying to and from an index, but don't worry there is another method in the java.util.Arrays class to copy elements from one index to other in Java, the Arrays.copyOfRange() method. Both methods are overloaded to copy different types of arrays.

Tuesday, August 3, 2021

Java 8 Stream map() function Example with Explanation

The map is a well-known functional programming concept that is incorporated into Java 8. Map is a function defined in java.util.stream.Streams class, which is used to transform each element of the stream by applying a function to each element. Because of this property, you can use a map() in Java 8 to transform a Collection, List, Set, or Map. For example, if you have a list of String and you want to convert all of them into upper case, how will you do this? Prior to Java 8, there is no function to do this. You had to iterate through List using a for loop or foreach loop and transform each element. In Java 8, you get the stream, which allows you to apply many functional programming operators like the map, reduce, and filter.

Monday, August 2, 2021

How to implement linked list data structure in Java using Generics? Example

The linked list is a popular data structure for writing programs and lots of questions from a linked list are asked in various Programming Job interviews. Though Java API or JDK provides a sound implementation of the linked list data structure as java.util.LinkedList, a doubly-linked list, you don't really need to implement a linked list of your own for writing production code, but all these interview questions require you to code a linked list in Java for solving coding problems. If you are not comfortable creating your own a linked list, it would be really difficult to solve questions like reversing a linked list or finding the middle element of a linked list in one pass.

4 Examples to Round Floating-Point Numbers in Java up to 2 Decimal Places

Rounding numbers up to 2 or 3 decimal places id a common requirement for Java programmers. Thankfully, Java API provides a couple of ways to round numbers in Java. You can round any floating-point numbers in Java unto n places By using either Math.round(), BigDecimal, or DecimalFormat. I personally prefer to use BigDecimal to round any number in Java because of it's convenient API and support of multiple Rounding modes. Also, if you are working in the financial industry, it's best to do a monetary calculation in BigDecimal rather than double as I have discussed in my earlier post about common Java mistakes

How to Attach Apache Tomcat Server in Eclipse for Running and Debugging Java Web Application - Steps

Hello Java programmers, If you are doing Java Web development in Eclipse, then you definitely would like to run and debug your Java application right from Eclipse. To do so, you need to add Apache Tomcat in the Eclipse version you are using, like Eclipse Kepler, Oxygen, Photon, or Luna. Eclipse comes in multiple flavors, like Eclipse IDE for Java Developers, which is suitable for developers doing core Java work, and Eclipse IDE for Java EE developers, which is for people doing enterprise Java work, like developing Servlet, JSP, and EJB based applications in Eclipse. In fact, the Java EE version of Eclipse is also one of the most downloaded software built with Java, so far, more than 1 million programmers have downloaded it.

Sunday, August 1, 2021

How to find difference between two dates in Java 8? Example Tutorial

One of the most common programming task while working with date and time objects are calculating the difference between dates and finding a number of days, months, or years between two dates. You can use the Calendar class in Java to get days, months between two dates. The easiest way to calculate the difference between two dates is by calculating milliseconds between them by converting java.util.Date to milliseconds using the getTime() method. The catch is converting those milliseconds into Days, Months and Year is not tricky due to leap years, the different number of days in months, and daylight saving times.

Top 5 Java 8 Default Methods Interview Questions and Answers

Hello guys, If you are preparing for Java interviews and want to learn about default methods in Java then you have come to the right place. In the last couple of articles, I have to talk about default methods introduced in JDK 8. First, we have learned what is the default method and why it is introduced in Java. Then we have seen the example of how you can use default methods to evolve your interface. After that we have analyzed does Java really supports multiple inheritances now in JDK 8 (see here) and how Java handles the diamond problem that will arise due to default methods.