Thursday, November 14, 2024

How to Compare Two Strings Without Case Sensitivity in Java? Example

How to Compare Two Strings Without Case Sensitivity in Java

Java provides several ways to compare strings without taking case sensitivity into account. In this article, we'll explore different methods to perform case-insensitive string comparisons in Java.

Method Use Case Efficiency
equalsIgnoreCase() Checking equality High
compareToIgnoreCase() Ordering comparison High
String.CASE_INSENSITIVE_ORDER Sorting collections High
equals() + toUpperCase() Not recommended Low

1. Using equalsIgnoreCase()

The equalsIgnoreCase() method

This method is ideal for checking if two strings are equal without considering their case. It returns true if both strings contain the same characters, regardless of their case.

String str1 = "Hello";
String str2 = "hello";
boolean isEqual = str1.equalsIgnoreCase(str2); // Returns true

2. Using compareToIgnoreCase()

The compareToIgnoreCase() method

Use this method when you want to check which string is greater or smaller, or to find out their relative ordering in lexicographical or alphabetical order, without considering case.

String str1 = "Apple";
String str2 = "banana";
int result = str1.compareToIgnoreCase(str2); // Returns a negative value

3. Using String.CASE_INSENSITIVE_ORDER

The String.CASE_INSENSITIVE_ORDER comparator

This comparator is useful for sorting a list of strings in case-insensitive order.

List<String> fruits = Arrays.asList("Apple", "banana", "Cherry");
Collections.sort(fruits, String.CASE_INSENSITIVE_ORDER);
// Result: [Apple, banana, Cherry]

4. Using equals() + toUpperCase()

Combining equals() and toUpperCase()

This is a tricky way to compare two strings in Java in a case-insensitive manner. First, convert both strings to uppercase, then compare them using equals().

String str1 = "Hello";
String str2 = "hello";
boolean isEqual = str1.toUpperCase().equals(str2.toUpperCase()); // Returns true

Note: This method is not recommended as it creates new String objects, which can be inefficient for large-scale comparisons.

Conclusion

When comparing strings without case sensitivity in Java, it's generally best to use the built-in methods like equalsIgnoreCase() for equality checks and compareToIgnoreCase() for ordering comparisons. 

These methods are optimized and provide clear, readable code. For sorting collections of strings, the String.CASE_INSENSITIVE_ORDER comparator is an excellent choice.

Remember, all these methods compare strings in lexicographical order. Choose the method that best fits your specific use case to ensure efficient and accurate string comparisons in your Java applications.

Thursday, November 7, 2024

How to convert XML to JSON in Java? Example

Since XML and JSON are two popular data interchange formats, you will often need to convert one into other. For example, many SOAP web services returns XML response and if you are using Java and wants to convert that XML response to JSON, then you can use JSON library from https://json.org. It provides a class called XML.java, which provides static methods to convert an XML text into a JSONObject. It also support JSON to XML conversion, which will learn in second part of the article. In order to use this class, you can dowload JAR files from Maven Central repository, or you can add required dependency in your pom.xml file. 

Thursday, October 31, 2024

How to convert JSON String to Java HashMap? Example

Suppose you have a JSON String, may be a web-service response and you want to create a Map out of it, where key should be the fields and value should be values of those fields e.g. if given JSON String is following :

{

"zip": "90210",

"city": "Beverly Hills"

"state": "CA"

"timeZone": "P"

}


then your HashMap should contain 4 mappings where keys are zip, city, state and timeZone, all of String type and corresponding values. 

Thursday, October 24, 2024

What is Timer and TimerTask in Java – Tutorial Example

Timer in Java is a utility class that is used to schedule tasks for both one time and repeated execution. Timer is similar to the alarm facility many people use in mobile phones. Just like you can have one time alarm or repeated alarm, You can use java.util.Timer to schedule a time task or repeated task. In fact, we can implement a Reminder utility using Timer in Java and that's what we are going to see in this example of Timer in Java. Two classes java.util.Timer and java.util.TimerTask is used to schedule jobs in Java and forms Timer API. 

4 Reasons and Benefits of Using Multithreading in Java? Why Threads?

In one word, we use Threads to make Java applications faster by doing multiple things at the same time. In technical terms, Thread helps you to achieve parallelism in Java programs. Since CPU is very fast and nowadays it even contains multiple cores, just one thread is not able to take advantage of all the cores, which means your costly hardware will remain idle for most of the time. By using multiple threads, you can take full advantage of multiple cores by serving more clients and serving them faster. Since, in today's fast-paced world, response time matters a lot and that's why you have multi-core CPUs, but if your application doesn't make full use of all resources then there is no point adding them, multi-threading is one way to exploiting huge computing power of CPU in Java application.

4 examples to convert Date to LocalDate in Java 8?

One of the challenge you will face while using new Java 8 Date and time API, JSR-310 in existing Java application is the conversion between java.util.Date and java.time.LocalDate and other classes. Even though library has everything you would expect, it doesn't have a direct conversion method between old Date and new LocalDate. There is a reason for it, eventhough java.util.Date says its a date its not, becuase its just a millisecond value since midnight at the start of 1970 GMT. It's equivalent to Instant class in new Java Date API and that's why you have a direct conversion method between Date and Instant in Java 8. Anyway, its not hard to convert a java.util.Date to java.time.LocalDate in Java 8, in fact there are multiple ways which we will explore in this tutorial. 

Wednesday, October 23, 2024

Difference between ExecutorService.submit() and Executor.execute() methods in Java?

What is the difference between Executor.submit() and Executor.execute() method in Java? This is one of the good multi-threading questions for experienced Java programmers, mostly asked in Investment Banks like Barclays, Deutsche Bank, or Citibank. A main difference between the submit() and execute() method is that ExecuterService.submit()can return the result of computation because it has a return type of Future, but the execute() method cannot return anything because return type is void. The core interface in Java 1.5's Executor framework is the Executor interface which defines the execute(Runnable task) method, whose primary purpose is to separate the task from its execution.

Difference between Process and Thread in Java - Example

One of the common questions from programming interviews is, what is the difference between a Thread and a Process? Well, the main difference between them is that a Process is a program that is executing some code and a thread is an independent path of execution in the process. A process can have more than one thread for doing independent tasks e.g. a thread for reading data from disk, a thread for processing that data, and another thread for sending that data over the network. This technique to improve throughput and better utilize CPU power is also known as multi-threading.

How to use Exchanger for Inter thread communication in Java? Example Tutorial

Hello guys, if you are working in a concurrent Java application then you might have heard about the Exchanger class of java.util.concurrent package. The Exchanger in Java is another concurrency or synchronization utility introduced in Java 1.5 along with CountDownLatch, CyclicBarrier, and Semaphores. As the name suggests, the Exchanger allows two Threads to meet and exchange data at the rendezvous or meeting point. This means you can use Exchanger to share objects between threads and for inter-thread communication. The java.util.Exchanger is a parametric class, which defines and holds the type of object to be exchanged. It has an overloaded method called the exchange(), which is used to exchange objects between threads.

What happens when you call Thread.run() instead of Thread.start() in Java? Trick Interview Question

Hello guys, writing multi-threaded and concurrent programs is not easy, not even in Java.  Even senior developers, including myself, make mistakes while writing concurrent Java applications. This is also one of the trickiest areas of Java programming language, where misconceptions outnumber concepts. Considering the amount of misconception an average Java programmer has about multi-threading and concurrency, I thought to start a new series about common multi-threading mistakes done by Java programmers; what is a better way to learn from common real word mistakes.

How to Implement Thread in Java with Example

How to implement Thread in Java
In my opinion, Thread is one of the most important features of the Java programming language which helped it to become the most popular programming language. I remember, when I first started learning Java in one of the programming classes in India how important Thread was a portrait and how much emphasis is given on a clear understanding of multi-threading. It’s still popular and one of most sought after skills in Java programmer because writing concurrent and multi-threaded applications in Java is challenging, despite Java providing excellent support at language level using synchronized and volatile keyword.

Educative Review - Is Grokking Modern System Design for Software Engineers and Managers worth it?

Hello guys, System Design Interview is one of the hardest part of any coding or programming job interview and it requires a lot of preparation and knowledge to crack system design interview. You need to know a lot of System design concepts like API Gateway, Load Balancer, Microservices vs Monolithic architecture, SQL vs NoSQL, Horizontal vs Vertical scalability and much. If you are preparing for System design interview then you may have come across that Educative.io has one of best System design courses like this one and Grokking the System Design Interview.  Before I give you my verdict on whether you need to choose Educative's Grokking Modern System Design For Software Engineers And Managers course, let me tell you a little bit about what system design really is.

Udemy vs Educative Review? Which is better Website for Beginners?

Hello guys, if you are wondering the difference between Udemy and Educative and whether you should take Udemy courses or join the Educative platform to learn new tech skills, you have come to the right place. Earlier, I have shared a comparison between Pluralsight and Udemy as well as CodeCademy vs Pluralsight in this article, I will compare Udemy with Educative, a new text-based, interactive learning platform. While I have often said that Udemy is my favorite platform because you can get high-quality and comprehensive courses from top instructors for just $9.9, which is phenomenal. 

Can You Learn Coding and Web Development in your 40s and 50s?

Yesterday, I was speaking to one of my friends who were not from a programming background but working as a teacher in a college of Engineering and Technology in the countryside of India. He just turned 40, and he is also the father of two wonderful kids. He has been teaching Maths to B.Tech students in a private engineer college for the last 15 years. He is earning Ok, but he always wanted to explore the world, and he now realizes that a Programming job can provide him that opportunity, so he contacted me to find out whether it's too late for a Programming career.

Monday, October 21, 2024

Review - Is Grokking the Machine Learning Interview on Educative Worth it in 2025?

Hello friends, we are here again today for another exciting topic to discuss. But, today we are not gonna discuss something which is related to Java or any other language or spring boot. Today we are gonna discuss something which is immensely practical and has the potential to land you very high-paying data science jobs.  Today we are gonna review a course that focuses on Machine Learning! Machine Learning is very important when we are considering data science interviews! So what's the wait? Let's start! On Educative.io, there is a great course called Grokking the Machine Learning Interview. It couldn't have come at a better moment, with machine learning expected to be a $3.6 billion business by 2025.