Monday, September 27, 2021

How to Clone a Collection in Java? Deep copy of ArrayList and HashSet Example

Programmers often mistook copy constructors provided by various collection classes, as a means to clone Collection like List, Set, ArrayList, HashSet, or any other implementation. What is worth remembering is that the copy constructor of Collection in Java only provides a shallow copy and not a deep copy, which means objects stored in both original Lists and cloned List will be the same and point to the same memory location in the Java heap. One thing, which adds to this misconception is a shallow copy of Collections with Immutable Objects. Since Immutable objects can't be changed, It's Ok even if two collections are pointing to the same object. This is exactly the case of String contained in the pool, update on one will not affect the other.

How to use Stream with List and Collection in Java 8? filter + map Example Tutorial

Finally, Java 8 is here, after more than 2 years of JDK 7, we have a much expected Java 8 with lots of interesting features. Though Lambda expression is the most talked-about item of the coming Java 8 release, it wouldn't have been this much popular, if Collections were not improved and Stream API was not introduced. Java 8 is bringing on new Streams API java.util.stream package, which allows you to process elements of Java Collections in parallel. Java is inheritably sequential and there are no direct means to introduce parallel processing at the library level, stream API is going to fill that gap. By using Stream API in Java, you can filter elements of collection on a given criterion. For example,  if you have a list of orders, you can filter buy orders with sell orders, filter orders based upon their quantity and price, and so on.

How to fix java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver [Solution]

This error comes when you try to connect to the Microsoft SQL Server database from the Java program but the required JDBC driver is not available in Classpath or driver is available in CLASSPATH but the class loader is not able to find it due to classpath intricacies. Depending upon your situation, a solution could be as simple as downloading any of sqljdbc.jar, sqljdbc4.jar, or sqljdbc41.jar, based upon the Java version you are using and adding them into CLASSPATH as set CLASSPATH = %CLASSPATH%; (path to Microsoft JDBC driver) in Windows. BTW, in most of the cases "java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver" comes because of classpath intricacies.

Saturday, September 25, 2021

How to Convert an Array to Comma Separated String in Java - Example Tutorial

The simplest way to convert an array to comma separated String is to create a StringBuilder, iterate through the array, and add each element of the array into StringBuilder after appending the comma. You just need Java 1.5 for that, even if you are not running on Java 5, you can use StringBuffer in place of StringBuilder. The joining of String has got even easier in JDK 8, where you have got the join() method right in the String class itself. The join() method takes a delimiter and a source, which can be an array or collection, and returns a String where each element is joined by a delimiter.

Thursday, September 23, 2021

Overriding equals() and hashCode() method in Java and Hibernate

Override equals and hashCode in Java
Equals and hashCode in Java are two fundamental methods that are declared in Object class and part of the core Java library. equals() method is used to compare Objects for equality while hashCode is used to generate an integer code corresponding to that object. equals and hashCode have been used extensively in Java core library like they are used while inserting and retrieving Object in HashMap, see how to get method of HashMap works in Java for the full story, equals method is also used to avoid duplicates on HashSet and other Set implementation and every other place where you need to compare Objects.

Wednesday, September 22, 2021

Difference between map() and flatMap() in Java 8 Stream - Example

The map() and flatmap() are two important operations in the new functional Java 8. Both represent functional operation and they are also methods in java.util.stream.Stream class but the map is used for transformation and flatmap is used for both transformation and flattening, that's why it's called the flatmap. The key difference between map() and flatmap() function is that when you use a map(), it applies a function on each element of the stream and stores the value returned by the function into a new Stream. This way one stream is transformed into another like a Stream of String is transformed into a Stream of Integer where each element is the length of the corresponding Stream.

Tuesday, September 21, 2021

10 Example of Lambda Expressions and Streams in Java 8

Java 8 release is just a couple of weeks away, scheduled on 18th March 2014, and there is a lot of buzz and excitement about this path-breaking release in the Java community. One feature, which is synonymous with this release is lambda expressions, which will provide the ability to pass behaviors to methods. Prior to Java 8, if you want to pass behavior to a method, then your only option was the Anonymous class, which will take 6 lines of code, and the most important line, which defines the behavior is lost in between. Lambda expression replaces anonymous classes and removes all boilerplate, enabling you to write code in a functional style, which is sometimes more readable and expression.

Monday, September 20, 2021

5 Difference between Constructor and Static Factory method Pattern in Java

The common way to create objects in Java is by using public constructors. A class provides a public constructor like java.lang.String so anyone can create an instance of String class to use in their application, but, there is another technique that can be used to create objects in Java and every experienced Java programmer should know about it. A class can provide a public static factory method that can return an instance of the class e.g. HashMap.newInstance(). The factory method is a smart way to create objects in Java and provides several advantages over the traditional approach of creating objects using constructors in Java. It can also improve the quality of code by making the code more readable, less coupled, and improves performance by caching.

How to set Java Path and Classpath in Windows 7, 8 and Windows 10 - Tutorial

So, you just bought a new PC or Laptop with Windows 8 operating system, and wondering how to set PATH and Classpath on Windows 8; Or, you might have just upgraded your Windows 7 laptop to the professional edition of Windows 8 and looking to set JDK Path to compile Java programs. Not to worry, this is the second step for anyone who wants to learn Java programming. Of course, the first step is to install JDK.  In this Java tutorial, we will see step by step guide to set Java PATH and CLASSPATH in the Windows 8 operating system. By the way, if you are learning Java in Windows 10 operating system, You should still be able to set the Java path and classpath in Windows 10 by following the steps given here, because navigation steps for modifying environment variables on Windows 10 and Windows 8 are almost same.

Difference between @WebMvcTest and @DataJpaTest in Spring Boot? Example

Hello guys, testing the Spring Boot application is very important but not many developers pay attention to that. If you are learning how to test the Spring Boot application and wondering what is @WebMvcTest and @DataJpaTest and how to use them then you have come to the right place. Earlier, I have shared 20+ Spring Boot Testing interview questions and in this article, I will teach you how to use @DataJpaTest and @WebMvcTest annotation with real-world examples.  Spring Boot is an evolution of the Spring framework which helps to create both stand-alone and spring-based applications with minimal cost. 

Sunday, September 19, 2021

How to remove all special characters from String in Java? Example Tutorial

You can use a regular expression and replaceAll() method of java.lang.String class to remove all special characters from String. A special character is nothing but characters like - ! #, %, etc. Precisely, you need to define what is a special character for you. Once you define that you can use a regular expression to replace those characters with empty String, which is equivalent to removing all special characters from String. For example, suppose, your String contains some special characters e.g. "Awesome!!!" and you want to remove those !!! to reduce some excitement, you can use replaceAll("!", "") to get rid of all exclamation marks from String.

Difference between Comparison (QuickSort) and Non-Comparison (Counting Sort) based Sorting Algorithms? Example

For many of you, this might be a surprise that how you can sort or arrange items without comparing them with each other, but it's possible. There are some sorting algorithms that perform sorting without comparing the elements rather than making certain assumptions about the data they are going to sort. The process is known as non-comparison sorting and algorithms are known as the non-comparison-based sorting algorithms. Non-comparison sorting algorithms include Counting sort which sorts using key-value, Radix sort, which examines individual bits of keys, and Bucket Sort which examines bits of keys. These are also known as Liner sorting algorithms because they sort in O(n) time. They make certain assumptions about data hence they don't need to go through a comparison decision tree.

Why Static Code Analysis is Important? Pros and Cons

In the last few years, Software code quality and security have gone from being a “nice to have” to a necessity, and many organizations, including investment banks, are making it mandatory to pass static code analysis tests, penetration testing, and security testing before you deploy your code in production. Static analysis tools like findbugs and fortify are getting popular every passing day and more and more companies are making fortify scan mandatory for all new development.  For those unaware of what static code analysis is, static code analysis is about analyzing your source code without executing them to find potential vulnerabilities, bugs, and security threats.

Saturday, September 18, 2021

How to Read/Write from RandomAccessFile in Java - Example Tutorial

Random access file is a special kind of file in Java that allows non-sequential or random access to any location in the file. This means you don't need to start from 1st line if you want to read line number 10, you can directly go to line 10 and read. It's similar to the array data structure, Just like you can access any element in the array by index you can read any content from the file by using a file pointer. A random-access file actually behaves like a large array of bytes stored in the file system and that's why it's very useful for low latency applications which need some kind of persistence e.g. in front office trading application and FIX Engine, you can use random access file to store FIX sequence numbers or all open orders.

Friday, September 17, 2021

Difference between JAX-RS, Restlet, Jersey, RESTEasy, and Apache CXF Frameworks

The JAX-RS is a Java specification request (JSR 311 & JSR 339) that standardizes the development and deployment of RESTful web services using Java and JEE technologies. It provides API in Java Programming language to create web services according to the REST (Representational State Transfer) architectural pattern. Both Restlet and Jersey are two of the most popular implementation of JAX-RS used for developing RESTful web services in Java ecosystem but there is a couple of other implementation also exist like Apache Wink, Apache CXF, and JBoss RESTEasy, along with omnipresent and the most popular option of creating REST web services with Spring Framework, Spring Boot, and Spring MVC

Thursday, September 16, 2021

How to compare objects on natural order in Java? Comparable + compareTo Example

Java allows you to sort your object in natural order by implementing a Comparable interface. It's one of the fundamental interfaces of Java API and is defined in java.lang package, which means you don't need to implement this unlike its counterpart Comparator, which is defined in java.util package.  Comparable is used to provide natural order of sorting to objects e.g. numeric order is a natural order for numbers, alphabetic order is a natural order for String and chronological order is natural for dates. Similarly when you define your own objects like Person, Book, or Employee, sorting them by name sounds natural. Similarly, for teams, ranking seems their natural order. It all depends on how the object is looked into in its domain.

Difference between Association, Composition and Aggregation in Java, UML and Object Oriented Programming

In Object-oriented programming, one object is related to another to use functionality and service provided by that object. This relationship between two objects is known as the association in object-oriented general software design and is depicted by an arrow in Unified Modelling Language or UML. Both Composition and Aggregation are the forms of association between two objects, but there is a subtle difference between composition and aggregation, which is also reflected by their UML notation. We refer to the association between two objects as Composition when one class owns other classes and other classes can not meaningfully exist, when the owner is destroyed.

How to Filter Stream and Collections in Java 8? Example Tutorial

Java 8 provides excellent features to support the filtering of elements in Java Collections. Prior to Java 8, the only better way to filter elements is by using a foreach loop or iterating over Collection using the Iterator and selecting the required object, leaving out rest. Though that approach work, it was very difficult to run them in parallel and take advantage of multiple CPUs available in modern-day servers. Java 8 provides Streams, which not only makes it easy to run any operation parallel but also supports lazy loading and lazy evaluation, which means as soon as the filtering condition is satisfied, it stooped doing work, doesn't matter how many objects the collection contains.

Wednesday, September 15, 2021

StringTokenizer Example in Java with Multiple Delimiters - Example Tutorial

StringTokenizer is a legacy class for splitting strings into tokens. In order to break String into tokens, you need to create a StringTokenizer object and provide a delimiter for splitting strings into tokens. You can pass multiple delimiters e.g. you can break String into tokens by, and: at the same time. If you don't provide any delimiter then by default it will use white-space. It's inferior to split() as it doesn't support regular expression, also it is not very efficient. Since it’s an obsolete class, don't expect any performance improvement either. On the hand split() has gone some major performance boost on Java 7, see here to learn more about splitting String with regular expression.

Tuesday, September 14, 2021

5 ways to check if String is empty in Java - examples

String in Java is considered empty if it's not null and its length is zero. By the way, before checking length you should verify that String is not null because calling length() method on null String will result in java.lang.NullPointerException. Empty String is represented by String literal “”. The definition of empty String may be extended to those String as well which only contains white space but it's a specific requirement and in general String with white space is not considered as empty String in Java. Since String is one of the most frequently used classes and commonly used in method arguments, we often need to check if String is empty or not. Thankfully there are multiple ways to find if String is empty in Java or not.

Monday, September 13, 2021

Difference between for loop and Enhanced for loop in Java? Example Tutorial

Though you can use both for loop and enhanced for loop to iterate over arrays and collections like a list, set, or map. There are some key differences between them. In general, enhanced for loop is much easier to use and less error-prone than for loop, where you need to manage the steps manually. At the same time, for loop is much more powerful because you get the opportunity to control the looping process. All the differences, you will learn in this article, stems from the very fact that traditional for loop gives more control than enhanced for loop but on the other hand enhanced or advanced for loop gives more convenience.

What is difference between Maven, ANT, Jenkins and Hudson?

In short, though Maven and ANT are build tools the main difference is that maven also provides dependency management, standard project layout, and project management. On the difference between Maven, ANT, and Jenkins, later is a continuous integration tool which is much more than a build tool. You can set up your CI environment using Jenkins or Hudson and automatically build, test, and deploy your Java project. Now last, the main difference between Jenkins and Hudson, both originate from the same source code but one is a closed source while the other is open source. You can read the details in this article.

Sunday, September 12, 2021

Difference between OCPJP 8 Upgrade Exams 1Z0-813 and 1Z0-810? Which one to take?

Many Java developers who hold a Java certification either from Sun or Oracle and who are looking to upgrade to the latest Java version i.e. Java SE 8 certification have a common doubt, should they go for 1Z0-810 or 1Z0-813 upgrade exams? What are the differences between these two exams? Well, even though they are both upgrades to Java SE 8 exams, they are separate exams and have a different exam code, the difference is also obvious when you look at their title. The 1Z0-810 exam is known as "Upgrade Java SE 7 to Java SE 8 OCP Programme" while the 1Z0-813 exam is known as "Upgrade to Java SE 8 OCP ( Java SE 6 and all prior versions)".

5 Free OCEJWCD 6 Mock Exam 1Z0-899 Practice Test

The OCEJWCD is Oracle's version of the SCWCD (Sun Certified Web Component Developer) exam, which tests the candidate's knowledge of Servlet, JSP, and other web technology. The OCEJWCD stands for Oracle Certified Enterprise Java Web Component Developer. Like other Java certifications like the OCAJP or OCPJP, the key to success is selecting a good book, practicing code daily, and then solving as many mock questions as possible.

How to create LocalDateTime in Java 8 - Example Tutorial

The LocalDateTime is a new class introduced in Java 8 new Date and Time API. This class is in java.time package and it represents both date and time information without timezone. In this example, you will learn different ways to create an instance of LocalDateTime class in Java 8 like by using the static factory method, or by combining LocalDate and LocalTime instances together, which are subsequently used to denote date without time and time without the date in Java 8. As their name suggests they are local, so they don't contain timezone information.

Saturday, September 11, 2021

3 ways to loop over Set or HashSet in Java? Examples

Since Set interface or HashSet class doesn't provide a get() method to retrieve elements, the only way to take out elements from a Set is to iterate over it by using the Iterator, or loop over Set using advanced for loop of Java 5. You can get the iterator by calling the iterator() method of the Set interface. This method returns an iterator over the elements in the sets but they are returned in no particular order, as Set doesn't guarantee any order. Though individual Set implementations e.g. LinkedHashSet or TreeSet can impose ordering and in such iterator will return elements on that order.

Friday, September 10, 2021

Java Comparator Example for Custom Sorting Employee by Name, Age and Salary

In this tutorial, we will see the Java Comparator example to sort an Employee object by name, age, and salary. In order to sort Employee object on different criteria, we need to create multiple comparators e.g. NameComparator, AgeComparator, and SalaryComparator, this is known as custom sorting in Java. This is different from the natural ordering of objects, provided by the compareTo() method of java.lang.Comparable interface. Though both compare() and compareTo() method looks similar they are different in the sense that, former accepts one parameter, while later accepts two-parameter. Former compare passed object to the current object, on the other hand, compare() method compares two different objects passed to it.

How to use Lambda Expression in Place of Anonymous Class in Java 8 - Example Tutorial

Before Java 8, the Anonymous class was the only way you can implement functional idioms in Java. Since prior to Java 8 you cannot pass a function to another function, you would have to wrap it into an object, as seen in Strategy Pattern. Those are also known as function objects in Java. Anonymous class was also handy to create a throw-away implementation of SAM (Single Abstract Methods) interfaces like RunnableCallable,  CommandListener, or ActionListener. Despite all these goodies and flexibility, the Anonymous class adds too much boilerplate code, making it hard to read and understand.

Reading/Writing to/from Files using FileChannel and ByteBuffer in Java - Example Tutorial

In the past, I have talked about RandomAccessFile and how it can be used for doing faster IO in Java, and in this Java NIO tutorial, we are going to see how to use read/write data from using FileChannel and ByteBuffer. Channel provides an alternate way to read data from a file, it provides better performance than InputStream or OutputStream. It can also be opened in blocking and non-blocking mode. Though FileChannles are read/write channels and they are always blocking, they cannot be put into non-blocking mode.

Wednesday, September 8, 2021

Top 5 Blogs Java EE developers should follow

One reason for Java's great success as a programming language is that it has dominated the Enterprise space. Earlier J2EE used to be the popular platform, but now we have a more modern and improved Java EE platform, with the latest release of Java EE 7. Java Platform, Enterprise Edition 7 provides new features that include enhanced HTML5 support, increases developer productivity, and further improves how enterprise demands can be met. One of the biggest advantages of Java EE 7 is the reduction of boilerplate code.

10 Difference between Primitive and Reference variable in Java - Example Tutorial

There are two types of variables in Java, primitive and reference type. All the basic types e.g. int, boolean, char, short, float, long and double are known as primitive types. JVM treats them differently than reference types, which is used to point objects e.g. String, Thread, File, and others. Reference variables are not pointers but a handle to the object which is created in heap memory. The main difference between primitive and reference type is that primitive type always has a value, it can never be null but reference type can be null, which denotes the absence of value. So if you create a primitive variable of type int and forget to initialize it then it's value would be 0, the default value of integral type in Java, but a reference variable by default has a null value, which means no reference is assigned to it.

Tuesday, September 7, 2021

Adapter vs Decorator vs Facade vs Proxy Design Pattern in Java

There is some striking similarity between Adapter, Decorator, Facade, and Proxy design patterns, in the sense that they all use Composition and delegation to solve the problem. The adapter pattern wraps an interface, and delegates call to it. The decorator wraps an object and implements behavior on top of that, Facade wraps one or more interfaces to provide a central interface, which is easy to use and Proxy Pattern also wraps Subject and delegates calls to it. Then questions come, why are different patterns? What is the difference between Adapter, Decorator, Facade, or Proxy pattern, if their structure is the same. The answer is Intent. Yes, all of these Java design patterns have similar structure and class diagrams but their intents are totally different from each other.

Difference between extends and implements keywords in Java? Example Tutorial

Though both extends and implements keyword in Java is used to implement Inheritance concept of Object-Oriented programming, there is a subtle difference between them. The extends keyword is mainly used to extend a class i.e. to create a subclass in Java, while the implements keyword is used to implement an interface in Java. The extends keyword can also be used by an interface for extending another interface. In order to better understand the difference between extends and implements, you also need to learn and understand the difference between class and interface in Java.

Why Default or No Argument Constructor is Important in Java Class? Answer

Almost all Java developers know that compiler adds a default constructor or better known as a no-argument constructor in every Java class, but many of them forget that it only does when you don't provide any other constructor. This means it becomes the developers' responsibility to add a no-argument constructor if he is adding an explicit constructor. Now, Why it's important to provide a default constructor in Java, What happens if your class doesn't have a no-argument constructor? Well, this is how it's asked in many Java interviews, most commonly as part of Spring and Hibernate interviews.

3 Ways to Convert Java 8 Stream to an Array - Lambda Expression and Constructor Reference Example

One of the frequently asked Java 8 interview questions is, how you do convert a Java 8 Stream to an array? For example, you have a Stream of Strings and you want an array of String so that you can pass this to a legacy method that expects an array, how do you do that? Well, the obvious place to search is the Javadoc of java.util.stream.Stream class and there you will find a toArray() method. Though this method will convert the Stream to an array it has a problem, it returns an Object array. What will you do, if you need a String array? Well, you can use the overloaded version of the toArray(IntFunction generator), which expects a generator function to create an array of the specified type.

Monday, September 6, 2021

2 solution of java.lang.OutOfMemoryError in Java

Everyone in java development faces java.lang.OutOfMemoryError now and then, OutOfMemoryError in Java is one problem which is more due to the system's limitation (memory) rather than due to programming mistakes in most cases though in certain cases you could have a memory leak which causing OutOfMemoryError. I have found that even though java.lang.OutOfMemoryError is quite common basic knowledge of its cause and the solution is largely unknown among junior developers. Beginners books like Head First Java don't teach you much about how to deal with this kind of error. You need real experience dealing with production systems, handling a large number of user sessions to troubleshoot and fix performance issues like running out of memory.

How to enable SSL debugging in Java JVM? Example

Dealing with SSL issues in Java web applications is no fun, especially when you have no debug or troubleshooting logs and all you see is an ugly ‘Page Cannot be displayed error message in your browser. Thankfully you can easily enable SSL to debug on your Application to start seeing verbose logs that will clearly show what happens during the SSL handshake process.

Top 5 Java 8 Practice Test and Exam Simulators (OCAJP and OCPJP) - Best of lot

Apart from books, exam simulators are another essential tool to prepare for Java certifications. They not only give you the opportunity to test your knowledge topic-wise but also provide a helpful explanation to clear your doubt and misconception, which means you can learn on the fly. Actually, when I prepared for my SCJP exam, I learned a lot of new concepts by just giving mock exams and solving practice questions. Since most of the Java certification aspirants are Java developers with some experience i.e., they have done a good amount of coding, they can easily understand the code, but they might not be familiar with the exam format.

How to convert java.util.Date to java.sql.Timestamp? Example Tutorial

You can convert a java.util.Date to java.sql.Timestamp value by using the getTime() method of Date class. This method returns the long millisecond value from Epoch (1st January 1970 midnight) which you can pass to java.sql.Timestamp to create a new instance of Timestamp object in JDBC. Remember, java.sql.TimeStamp class is a wrapper around java.util.Date to allow JDBC to view it as SQL TIMESTAMP value. The only way to create a Timestamp instance is by passing the long time value because the second constructor of the Timestamp class, which accepts individual fields like a year, month, date, hour, minute, second, and nano is deprecated. Timestamp class can also hold up to nanosecond value.

Sunday, September 5, 2021

How to get the last modified date and time of a File or Directory in Java? Example Tutorial

Sometimes before processing a file, you want to check its last modified date to avoid processing an old file. Though some programmers prefer to attach the date in the file name itself, I don't find it a cleaner approach. For example, suppose you are downloading closing prices of stocks and processing them at the start of the day, and loading them into the database. In order to accidentally process an old file, you can check the last modified date before processing and if it's in the acceptable range, you can process the file. You can get the last modified date of a file in Java by using java.io.File class. 

How to create RESTful Web Services using Restlet Framework in Java - Example Tutorial

Hello Java developer, if you are looking for an example of how to create RESTful web services using Restlet Framework in Java and Eclipse then you have come to the right place. Earlier, I have shared the best REST API Courses and in this tutorial, I will show you how to use Restlet for creating REST APIs in Java. The Restlet is one of the first open-source frameworks to create and deploy RESTful web services in Java. After the release of JAX-RS (Java API for RESTful Web Services) JSR - 317, Restlet also supports JAX-RS annotation and provides a consistent way to create both RESTful Server and Client. HelloWorld program is the traditional way to start with new technology and continuing to the tradition, we'll write our first Restlet program as HelloWorld. 

Difference between GETDATE() vs SYSDATETIME() vs GETUTCDATE() in SQL Server - Examples

One of the common questions on the Microsoft SQL Server interview is, what is the difference between GETDATE(), SYSDATETIME(), and GETUTCDATE(). Even though all three SQL Server function returns the current date-time in SQL Server, there are some subtle differences between them. The main difference between GETDATE() and SYSDATETIME() is that GETDATE returns the current date and time as DATETIME but SYSDATETIME returns a DATETIME2 value, which is more precise.

Friday, September 3, 2021

Difference between PUT and POST in REST Web Services in Java - Example

If you remember REST WebServices uses HTTP methods to map CRUD (create, retrieve, update, delete) operations to HTTP requests. Even though both PUT and POST methods can be used to perform create and update operations in REST WebServices, Idempotency is the main difference between PUT and POST. Similar to the GET request, the PUT request is also idempotent in HTTP, which means it will produce the same results if executed once more multiple times. Another practical difference between PUT and POST methods in the context of REST WebService is that POST is often used to create a new entity, and PUT is often used to update an existing entity.

Wednesday, September 1, 2021

How to replace a substring in Java? String replace() method Example Tutorial

You can replace a substring using replace() method in Java. The String class provides the overloaded version of the replace() method, but you need to use the replace(CharSequence target, CharSequence replacement). This version of the replace() method replaces each substring of this string (on which you call the replace() method) that matches the literal target sequence with the specified literal replacement sequence. For example, if you call "Effective Java".replace("Effective", "Head First") then it will replace "Effective" with "Head First" in the String "Effective Java". Since String is Immutable in Java, this call will produce a new String "Head First Java".

How to check if ResultSet is empty in JDBC Java - Example Tutorial

The JDBC ResultSet doesn't provide any isEmpty(), length() or size() method to check if its empty or not. Hence, when a Java programmer needs to determine if ResultSet is empty or not, it just calls the next() method and if next() returns false it means ResultSet is empty. This is correct but the main problem with this approach is if the ResultSet is not empty then you may miss the first row if you follow the standard idiom to iterate over ResultSet and get the rows that involve calling the next() method of ResultSet in a while loop.