How to Remove all Spaces from a String in Java

The following Java program removes all space characters from the given string. Please note that this program doesn't work if you want to remove all whitespaces (not just spaces!) from a string.

// Java Example Program to remove all spaces from a String
public class RemoveSpacesExample {

    public static void main(String[] args) {
        String input = "hello world";
        String output = removeSpaces(input);
        System.out.println(input);
        System.out.println(output);
    }

    // Remove all space characters
    private static String removeSpaces(String input) {
        return input.replaceAll(" ", "");
    }
}

Following Java program removes all whitespaces from the given string. In Java, whitespace includes space, tab, line feed, form feed, etc. The full list of whitespace characters are listed here.

// Java example program to remove all whitespaces from a string
public class RemoveAllWhiteSpaces {

    public static void main(String[] args) {
        String input = "hello world\texample\rwith\twhitespaces";
        String output = removeWhiteSpaces(input);
        System.out.println(input);
        System.out.println(output);
    }

    // Remove all whitespace characters (space, tab, return etc.)
    private static String removeWhiteSpaces(String input) {
        return input.replaceAll("\\s+", "");
    }
}

Finally here is a Java implementation that doesn't use replaceAll method. In this example we extract all characters to an array and then create a new string from the array ignoring whitespace characters.

// This example Java program removes all whitespaces in a string
public class RemoveWhiteSpaceAlternate {
    public static void main(String[] args) {
        String input = "hello world\texample\rwith\twhitespaces";
        String output = removeWhiteSpaces(input);
        System.out.println(input);
        System.out.println(output);
    }

    // Remove all whitespace characters (space, tab, return etc.)
    private static String removeWhiteSpaces(String input) {
        char[] characters = input.toCharArray();
        StringBuffer buffer = new StringBuffer();
        for(char c:characters) {
            if(!Character.isWhitespace(c)) {
                buffer.append(c);
            }
        }
        return buffer.toString();
    }
}

How to Create Deadlock in Java

A deadlock can occur in Java multithreaded programs when one thread is waiting on another thread and vice versa. Since each thread is waiting, the program is deadlocked and cannot proceed.

A deadlock can be simulated in a multi-threaded program if there are two resources and two threads. Let us call them R1/R2 and T1/T2. T1 and T2 needs both R1 and R2. T1 acquires R1 and then tries to acquire R2. At the same time T2 acquires R2 and then tries to acquire R1. T1 has R1 but before it can get R2, T2 has acquired R2. Now T2 cannot get R1 since R1 is already with T1! Now we have a deadlock and the program is stuck forever.

The following program demonstrates deadlock in Java threads. We have used two strings for R1 and R2. Also note that we have added sufficient delay between acquisition of resources in a single thread so that deadlocks will happen all the time. If we remove the delay, deadlocks become unpredictable!

// Java example program on thread deadlock
public class DeadLockSample {

    // Simulates global resources shared by multiple threads
    String R1 = "R1";
    String R2 = "R2";

    Thread T1 = new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("Starting T1");

            // Acquired R1
            synchronized (R1) {
                try {
                    // Sleep is added to make deadlock predictable
                    // One second delay ensures that the other thread
                    // acquires lock on R2!
                    Thread.sleep(100);
                } catch (Exception ex) {
                }
                synchronized (R2) {
                    System.out.println("Acquired both!");
                }
            }

            // If we reach here, no deadlock!
            System.out.println("Completed T1");
        }
    });

    Thread T2 = new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("Starting T2");
            synchronized (R2) {
                try {
                    // Sleep is added to make deadlock predictable
                    // One second delay ensures that the other thread
                    // acquires lock on R1!
                    Thread.sleep(100);
                } catch (Exception ex) {
                }
                synchronized (R1) {
                    System.out.println("Acquired both!");
                }
            }
            // If we reach here, no deadlock!
            System.out.println("Completed T2");
        }
    });

    // Java example program on thread deadlock
    public static void main(String[] args) {
        DeadLockSample ds = new DeadLockSample();
        ds.T1.start();
        ds.T2.start();
    }
}

Unpredictable deadlocks can be a serious issue in applications running in the production environment. Hence it is very important to take a close look at the code if you are using multithreading in your programs.

Deadlocks in Java threads can be minimized by avoiding nested locks. Also lock only those resources that are used and shared across multiple threads.

Quick Microservice Prototyping With Spring Boot CLI

Spring boot command line interface (CLI) can be used to quickly create microservice backend prototypes. If you are not familiar with spring boot cli, see our earlier articles - introduction to spring boot cli and introduction to spring boot framework. In this article, I will show you how quickly you can create spring based microservice prototypes with spring boot cli. Spring boot cli is an essential tool for Java web application developer.

Http Microservice Endpoints With JSON Output

The following groovy controller shows how a JSON HTTP REST endpoint for customer data can be quickly prototyped using spring boot cli,

@RestController
class Customers {

    class Customer {
        String email;
        String name;
    }

    @RequestMapping("/customers")
    Map home() {
        Map customers = new HashMap();
        customers.put("customers",getCustomers());
        return customers;
    }

    List<Customer> getCustomers() {
        List<Customer> list = new ArrayList();
        def c = new Customer();
        c.name = "QPT";
        c.email = "qpt@quickprogrammingtips.com";
        list.add(c);

        c = new Customer();
        c.name = "QPT2";
        c.email = "qpt2@quickprogrammingtips.com";
        list.add(c);

        return list;
    }
}

Run the above controller using the following command,

spring run *.groovy

Use the URL http://localhost:8080/customers to access the microservice endpoint.

Sending And Receiving Messages Through JMS Queue

It is easy to prototype message queues using spring boot cli. The following groovy file creates an Artemis embedded message queue and sends a message.

@Grab("spring-boot-starter-artemis")
@Grab("artemis-jms-server")

@RestController
@EnableJms
class JMSSender {

    @Autowired
    JmsTemplate jmsTemplate

    @RequestMapping("/send")
    String home() {
        def messageCreator = {
            session ->
            session.createObjectMessage("Hello: Via Artemis")
        } as MessageCreator
        jmsTemplate.send("spring-boot", messageCreator)

        return "Message Sent";
    }
}

The following groovy file listens on the Artemis embedded message queue and whenever a message is received it will output the message on the spring boot cli console.

@Grab("spring-boot-starter-artemis")
@Grab("artemis-jms-server")

@RestController
@EnableJms
@Log
class JMSReceiver {

    @Autowired
    JmsTemplate jmsTemplate

    @JmsListener(destination = 'spring-boot')
    def receive(String message) {
        log.info "Received ${message}"
    }
}

Run both groovy controllers using the following command.

spring run jmssender.groovy jmsreceiver.groovy

Access the URL http://localhost:8080/send with the spring boot console visible. You should see the message being processed by the queue listener in the console.

Using MongoDB Database Backend with Microservice Endpoints

You can easily integrate the microservice prototype with an existing database. The following example groovy file (mongodemo.groovy) shows how to connect to a local MongoDB instance. This example assumes that a MongoDB instance is up and running on the local machine/default port with the "test" database and a table named "user" with attributes "name" and "email". Add a number of table entries before running the program below.

package com.quickprogrammingtips.demo

@Grab("spring-boot-starter-data-mongodb")
import org.springframework.data.mongodb.repository.MongoRepository
import org.springframework.data.annotation.Id;

@RestController
class MongoDemo {

    @Autowired
    UserRepository repo;

    @RequestMapping("/users")
    List home() {
        return repo.findAll();
    }
}

// By default maps to user table in Mongo
class User {
    @Id
    String id;
    String name;
    String email;
}
interface UserRepository extends MongoRepository<User, String> {
}

Note that the above groovy file uses a package (com.quickprogrammingtips.demo). This is required for auto scanning/auto creation of Mongo repository class (default package won't work). Also we cannot run the above application using spring run since scanning of repository classes cannot work with groovy scripts. The generated classes are required for auto scanning. Hence to run the above example, we need to create a jar and then execute the jar.

spring jar app.jar mongodemo.groovy

java -jar app.jar

Access the URL http://localhost:8080/users to get a list of users from the database table. Voila! Now you have a JSON based microservices endpoint with MongoDB connectivity!

References

How to Write a BMI Calculator in Java

BMI stands for Body Mass Index. It is a measure of body mass based on height and weight of an individual. Using the range of BMI, individuals are classified as underweight, normal or overweight. Its value is in a specific range for a healthy individual. The following table shows the main BMI categories.

Category BMI Range
Underweight < 18.5
Normal 18.5 - 25
Overweight 25 - 30
Obese > 30

Formula for Calculating BMI in Metric Units

BMI = Weight in Kg/(Height in Meters * Height in Meters)

Example calculation for weight = 90kg, height = 1.5m

BMI = 90/(1.5*1.5) = 40

The following example program in Java calculates BMI value based on inputs in metric units. Note that the program takes the height input in centimeters.

import java.util.Scanner;

// BMI Calculator in Java
// Uses metric units
public class BMICalculatorInMetric {

    public static void main(String[] args) throws Exception {
        calculateBMI();
    }

    private static void calculateBMI() throws Exception {
        System.out.print("Please enter your weight in kg: ");
        Scanner s = new Scanner(System.in);
        float weight = s.nextFloat();
        System.out.print("Please enter your height in cm: ");
        float height = s.nextFloat();
        
        // multiplication by 100*100 for cm to m conversion
        float bmi = (100*100*weight)/(height*height);
        
        System.out.println("Your BMI is: "+bmi);
        printBMICategory(bmi);
        
    }
    
    // Prints BMI category
    private static void printBMICategory(float bmi) {
        if(bmi < 18.5) {
            System.out.println("You are underweight");
        }else if (bmi < 25) {
            System.out.println("You are normal");
        }else if (bmi < 30) {
            System.out.println("You are overweight");
        }else {
            System.out.println("You are obese");
        }
    }
}

How to Zip a Folder in Java

Java has a good library of classes for handling zip files. These classes are available in the java.util.zip package. The following example program in Java shows how you can use java.util.zip classes to create a zip of an entire folder. We use the Files.walkFileTree to recursively navigate through the directory tree and then add each file into the newly created zip file. Please note that this example works only in Java 1.7 and above.

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

// Source code to create a zip file from a given folder
// This example program recursively adds all files in the folder
// Works only with Java 7 and above
public class ZipFolder {
    public static void main(String[] args) throws Exception {
        ZipFolder zf = new ZipFolder();
        
        // Use the following paths for windows
        //String folderToZip = "c:\\demo\\test";
        //String zipName = "c:\\demo\\test.zip";
        
        // Linux/mac paths
        String folderToZip = "/Users/jj/test";
        String zipName = "/Users/jj/test.zip";
        zf.zipFolder(Paths.get(folderToZip), Paths.get(zipName));
    }

    // Uses java.util.zip to create zip file
    private void zipFolder(Path sourceFolderPath, Path zipPath) throws Exception {
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipPath.toFile()));
        Files.walkFileTree(sourceFolderPath, new SimpleFileVisitor<Path>() {
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                zos.putNextEntry(new ZipEntry(sourceFolderPath.relativize(file).toString()));
                Files.copy(file, zos);
                zos.closeEntry();
                return FileVisitResult.CONTINUE;
            }
        });
        zos.close();
    }
}

In linux/mac, you can test the newly created zip file using the following command,

unzip -t test.zip