Core Java

Java String trim() method with Example

In this post, we feature a comprehensive article about the Java String trim() method with Examples.

1. Introduction

The java.lang.String class represents character strings. It provides a trim() method since version 1.4 to return a new string object whose value is the copy of the original string without any leading or trailing white-space.

Note: a white-space is when the ASCII code of the character is less than or equal to the space character, which is \u0020.

Here is the method syntax:

public String trim()

In this example, I will demonstrate how to trim a string in three ways:

  • Create a Function to trim a string in JDK 8 or higher version
  • Invoke trim for a non-null String object
  • Invoke trim for an Optional String object

2. Technologies Used

The example code in this article was built and run using:

  • Java 1.8.101
  • Maven 3.3.9
  • Eclipse Oxygen
  • JUnit 4.12
  • H2
  • Spring

3. Maven Project

I will create a Maven project via the Spring starter tool. Enter the group and artifact values and click the Generate Project button. A maven project will be generated and downloaded to your workstation. Import it into your Eclipse work space.

3.1 Dependency

Add H2 dependency to pom.xml.

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>jcg.zheng.demo</groupId>
	<artifactId>spring-string-trim-demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>spring-jparepository-demo</name>
	<description>Demo Spring Data JPA Application</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.10.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>	
	</properties>

	<dependencies>		

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>

		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
			<scope>runtime</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>


	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

3.2 Spring Boot Application

I will save contacts into a H2 database table via Spring JpaRepositories. You just need to add @EnableJpaRepositories to the generated DemoApplication.java file.

DemoApplication.java

package jcg.zheng.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@SpringBootApplication
@EnableJpaRepositories(basePackages = "jcg.zheng.demo")
public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}

}

3.3 Application Properties

Spring boot will configure a H2 data source based on the values in application.properties.

application.properties

spring.datasource.url=jdbc:h2:file:~/main-source;AUTO_SERVER=TRUE
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver

4. Contact

In this step, I will create a contact class that maps to a database table. It has several data members: id, first name, last name, and a title (optional). The Contact(String, String) constructor uses setFirstName and setLastName to set the first name and last name with trimmed values.

Here are setters that trim a string in three ways:

  • setLastName – it first creates a Java 8 Function to trim a string with a method reference and then uses its apply method to set the last name value. Click my other article for details about Java 8 Function.
  • setFirstName – it calls the trim method on the first name.
  • setTitle – it invokes the trim method if a title exists.

Contact.java

package jcg.zheng.demo.entity;

import java.util.Optional;
import java.util.function.Function;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Transient;

import org.springframework.util.StringUtils;


@Entity
public class Contact {

    @Id
    @GeneratedValue
    private Long id;

    private String firstName;

    private String lastName;

    @Transient
    private Optional<String> title;

    public Contact(String firstName, String lastName) {
        if (StringUtils.isEmpty(firstName) || StringUtils.isEmpty(lastName)) {
            throw new IllegalArgumentException("Require both firstName and lastName");
        }
        setFirstName(firstName);
        setLastName(lastName);
    }

    public Long getId() {
        return id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName.trim();
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        Function<String, String> trimF = String::trim;
        this.lastName = trimF.apply(lastName);
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Optional<String> getTitle() {
        return title;
    }

    public void setTitle(Optional<String> title) {
        this.title = title;
        if (title.isPresent()) {
            this.title = Optional.ofNullable(title.get().trim());
        }
    }

}

4.1 ContactTest

I will create several unit tests to demonstrate that the contact’s getFirstName and getLastName methods return a name without any leading and trailing white-spaces.

  • contact_happypath – It constructs a contact object with the first name as " Mary Shan " and last name as " Zheng Jr ". Please note that both names have leading and trailing white-spaces. The last name also has white-spaces in the middle. With the help of the trim method, both leading and trailing white-spaces are removed and the white-spaces in the middle remains as expected.
  • contact_has_title – It sets contact’s title with ” Developer “. Please note that the leading and trailing white-spaces are removed when getTitle() returns.

ContactTest.java

package jcg.zheng.demo.entity;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import java.util.Optional;

import org.junit.Test;

public class ContactTest {

    @Test
    public void contact_happypath() {
        Contact contact = new Contact(" Mary shan ", " Zheng  Jr ");
        assertEquals("Mary shan", contact.getFirstName());
        assertEquals("Zheng  Jr", contact.getLastName());
    }

    @Test(expected = Exception.class)
    public void contact_miss_names() {
        Contact contact = new Contact(null, "");
    }

    @Test
    public void contact_has_no_title() {
        Contact contact = new Contact("Mary", "Zheng");
        contact.setTitle(Optional.ofNullable(null));
        assertFalse(contact.getTitle().isPresent());
    }

    @Test
    public void contact_has_title() {
        Contact contact = new Contact("Mary ", "Zheng");
        contact.setTitle(Optional.ofNullable(" Developer "));
        assertTrue(contact.getTitle().isPresent());
        assertEquals("Developer", contact.getTitle().get());
    }

}

4.2 Demo

Execute mvn test -Dtest=ContactTest. All tests should pass. Capture the output here.

Test results

C:\JCG\spring-string-trim-demo>mvn test -Dtest=ContactTest
[INFO] Scanning for projects...
[INFO]
[INFO] ---------------< jcg.zheng.demo:spring-string-trim-demo >---------------
[INFO] Building spring-jparepository-demo 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ spring-string-trim-demo ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ spring-string-trim-demo ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ spring-string-trim-demo ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory C:\JCG\spring-string-trim-demo\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ spring-string-trim-demo ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.18.1:test (default-test) @ spring-string-trim-demo ---
[INFO] Surefire report directory: C:\JCG\spring-string-trim-demo\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running jcg.zheng.demo.entity.ContactTest
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.242 sec - in jcg.zheng.demo.entity.ContactTest

Results :

Tests run: 4, Failures: 0, Errors: 0, Skipped: 0

5. ContactRepository

I will create a ContactRepository class to save contacts into a database without any leading and trailing white-spaces. Click here for my other article Spring JPARepository.

CommonRepository.java

package jcg.zheng.demo.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import jcg.zheng.demo.entity.Contact;

@Repository
@Transactional
public interface ContactRepository extends JpaRepository<Contact, Long> {

    @Query("SELECT con FROM Contact con  WHERE con.lastName= (:lName)")
    List<Contact> findByLastName(@Param("lName") String lName);

}

5.1 ContactRepositoryTest

We have a contact class whose constructor accepts first name and last name and three setter methods trim a string. In this step, I will create test cases with three steps:

  • Construct a contact with both leading and trailing white-spaces names.
  • Save the contact into a H2 database table.
  • Find the saved contact and check the saved values have no any leading and trailing white-spaces.

CommonRepositoryTest.java

package jcg.zheng.demo.repository;

import static org.junit.Assert.assertEquals;

import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit4.SpringRunner;

import jcg.zheng.demo.entity.Contact;

@RunWith(SpringRunner.class)
@DataJpaTest
public class ContactRepositoryTest {

    @Autowired
    private ContactRepository contactRepo;

    @Test
    public void it_can_find_the_contact_after_save_it() {
        Contact contact = new Contact(" Mary ", " Zheng");

        contactRepo.save(contact);

        List contacts = contactRepo.findAll();

        assertEquals(1, contacts.size());
        assertEquals("Mary", contacts.get(0).getFirstName());
        assertEquals("Zheng", contacts.get(0).getLastName());
    }

    @Test
    public void it_can_find_contacts_by_name() {

        contactRepo.save(new Contact(" Mary", " Zheng "));
        contactRepo.save(new Contact("Tom", "Smith"));
        contactRepo.save(new Contact("John", "Joe"));
        contactRepo.save(new Contact("Cindy ", "Zheng"));

        List contactsWithZheng = contactRepo.findByLastName("Zheng");
        assertEquals(2, contactsWithZheng.size());

        Contact foundMary = contactsWithZheng.stream()
                .filter(con -> con.getFirstName().equalsIgnoreCase("Mary"))
                .findFirst().get();
        assertEquals("Mary", foundMary.getFirstName());

        Contact foundCindy = contactsWithZheng.stream()
                .filter(con -> con.getFirstName().equalsIgnoreCase("Cindy"))
                .findAny().get();
        assertEquals("Cindy", foundCindy.getFirstName());

        contactsWithZheng = contactRepo.findByLastName(" Zheng ");
        assertEquals(0, contactsWithZheng.size());
    }

}

5.2 Demo

Execute mvn test -Dtest=ContactRepositoryTest. All tests should pass. Capture the output as the following.

Test Results

2019-02-16 11:53:20.518  INFO 17644 --- [           main] j.z.d.repository.ContactRepositoryTest   : Starting ContactRepositoryTest on S443831 with PID 17644 (started by aa00765 in C:\JCG\spring-string-trim-demo)
2019-02-16 11:53:20.519  INFO 17644 --- [           main] j.z.d.repository.ContactRepositoryTest   : No active profile set, falling back to default profiles: default
2019-02-16 11:53:20.549  INFO 17644 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@12aba8be: startup date [Sat Feb 16 11:53:20 CST 2019]; root of context hierarchy
2019-02-16 11:53:21.505  INFO 17644 --- [           main] beddedDataSourceBeanFactoryPostProcessor : Replacing 'dataSource' DataSource bean with embedded version
2019-02-16 11:53:21.507  INFO 17644 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'dataSource' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Tomcat; factoryMethodName=dataSource; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]] with [Root bean: class [org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration$EmbeddedDataSourceFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null]
2019-02-16 11:53:22.090  INFO 17644 --- [           main] o.s.j.d.e.EmbeddedDatabaseFactory        : Starting embedded database: url='jdbc:h2:mem:f15dc85a-1020-4cbb-8e97-688f3367bc69;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false', username='sa'
2019-02-16 11:53:22.930  INFO 17644 --- [           main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2019-02-16 11:53:22.978  INFO 17644 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
        name: default
        ...]
2019-02-16 11:53:23.162  INFO 17644 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.0.12.Final}
2019-02-16 11:53:23.167  INFO 17644 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2019-02-16 11:53:23.171  INFO 17644 --- [           main] org.hibernate.cfg.Environment            : HHH000021: Bytecode provider name : javassist
2019-02-16 11:53:23.317  INFO 17644 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2019-02-16 11:53:23.711  INFO 17644 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2019-02-16 11:53:24.499  INFO 17644 --- [           main] org.hibernate.tuple.PojoInstantiator     : HHH000182: No default (no-argument) constructor for class: jcg.zheng.demo.entity.Contact (class must be instantiated by Interceptor)
2019-02-16 11:53:24.703  INFO 17644 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000227: Running hbm2ddl schema export
Hibernate: drop table contact if exists
Hibernate: create table contact (id bigint generated by default as identity, first_name varchar(255), last_name varchar(255), primary key (id))
2019-02-16 11:53:24.732  INFO 17644 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000230: Schema export complete
2019-02-16 11:53:24.844  INFO 17644 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-02-16 11:53:25.279  INFO 17644 --- [           main] o.h.h.i.QueryTranslatorFactoryInitiator  : HHH000397: Using ASTQueryTranslatorFactory
2019-02-16 11:53:25.773  INFO 17644 --- [           main] j.z.d.repository.ContactRepositoryTest   : Started ContactRepositoryTest in 6.167 seconds (JVM running for 11.505)
2019-02-16 11:53:25.976  INFO 17644 --- [           main] o.s.t.c.transaction.TransactionContext   : Began transaction (1) for test context [DefaultTestContext@7c469c48 testClass = ContactRepositoryTest, testInstance = jcg.zheng.demo.repository.ContactRepositoryTest@4313f5bc, testMethod = it_can_find_contacts_by_name@ContactRepositoryTest, testException = [null], mergedContextConfiguration = [MergedContextConfiguration@12e61fe6 testClass = ContactRepositoryTest, locations = '{}', classes = '{class jcg.zheng.demo.DemoApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[[ImportsContextCustomizer@7ee955a8 key = [org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration, org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration, org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration, org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManagerAutoConfiguration]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@467aecef, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@2173f6d9, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.OverrideAutoConfigurationContextCustomizerFactory$DisableAutoConfigurationContextCustomizer@5bb21b69, org.springframework.boot.test.autoconfigure.filter.TypeExcludeFiltersContextCustomizer@351584c0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@c763d37b, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@5ed828d], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]]; transaction manager [org.springframework.orm.jpa.JpaTransactionManager@68ee3b6d]; rollback [true]
Hibernate: insert into contact (id, first_name, last_name) values (null, ?, ?)
Hibernate: insert into contact (id, first_name, last_name) values (null, ?, ?)
Hibernate: insert into contact (id, first_name, last_name) values (null, ?, ?)
Hibernate: insert into contact (id, first_name, last_name) values (null, ?, ?)
Hibernate: select contact0_.id as id1_0_, contact0_.first_name as first_na2_0_, contact0_.last_name as last_nam3_0_ from contact contact0_ where contact0_.last_name=?
Hibernate: select contact0_.id as id1_0_, contact0_.first_name as first_na2_0_, contact0_.last_name as last_nam3_0_ from contact contact0_ where contact0_.last_name=?
2019-02-16 11:53:26.246  INFO 17644 --- [           main] o.s.t.c.transaction.TransactionContext   : Rolled back transaction for test context [DefaultTestContext@7c469c48 testClass = ContactRepositoryTest, testInstance = jcg.zheng.demo.repository.ContactRepositoryTest@4313f5bc, testMethod = it_can_find_contacts_by_name@ContactRepositoryTest, testException = [null], mergedContextConfiguration = [MergedContextConfiguration@12e61fe6 testClass = ContactRepositoryTest, locations = '{}', classes = '{class jcg.zheng.demo.DemoApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[[ImportsContextCustomizer@7ee955a8 key = [org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration, org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration, org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration, org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManagerAutoConfiguration]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@467aecef, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@2173f6d9, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.OverrideAutoConfigurationContextCustomizerFactory$DisableAutoConfigurationContextCustomizer@5bb21b69, org.springframework.boot.test.autoconfigure.filter.TypeExcludeFiltersContextCustomizer@351584c0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@c763d37b, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@5ed828d], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]].
2019-02-16 11:53:26.262  INFO 17644 --- [           main] o.s.t.c.transaction.TransactionContext   : Began transaction (1) for test context [DefaultTestContext@7c469c48 testClass = ContactRepositoryTest, testInstance = jcg.zheng.demo.repository.ContactRepositoryTest@949c598, testMethod = it_can_find_the_contact_after_save_it@ContactRepositoryTest, testException = [null], mergedContextConfiguration = [MergedContextConfiguration@12e61fe6 testClass = ContactRepositoryTest, locations = '{}', classes = '{class jcg.zheng.demo.DemoApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[[ImportsContextCustomizer@7ee955a8 key = [org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration, org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration, org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration, org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManagerAutoConfiguration]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@467aecef, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@2173f6d9, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.OverrideAutoConfigurationContextCustomizerFactory$DisableAutoConfigurationContextCustomizer@5bb21b69, org.springframework.boot.test.autoconfigure.filter.TypeExcludeFiltersContextCustomizer@351584c0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@c763d37b, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@5ed828d], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]]; transaction manager [org.springframework.orm.jpa.JpaTransactionManager@68ee3b6d]; rollback [true]
Hibernate: insert into contact (id, first_name, last_name) values (null, ?, ?)
Hibernate: select contact0_.id as id1_0_, contact0_.first_name as first_na2_0_, contact0_.last_name as last_nam3_0_ from contact contact0_
2019-02-16 11:53:26.375  INFO 17644 --- [           main] o.s.t.c.transaction.TransactionContext   : Rolled back transaction for test context [DefaultTestContext@7c469c48 testClass = ContactRepositoryTest, testInstance = jcg.zheng.demo.repository.ContactRepositoryTest@949c598, testMethod = it_can_find_the_contact_after_save_it@ContactRepositoryTest, testException = [null], mergedContextConfiguration = [MergedContextConfiguration@12e61fe6 testClass = ContactRepositoryTest, locations = '{}', classes = '{class jcg.zheng.demo.DemoApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[[ImportsContextCustomizer@7ee955a8 key = [org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration, org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration, org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration, org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManagerAutoConfiguration]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@467aecef, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@2173f6d9, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.OverrideAutoConfigurationContextCustomizerFactory$DisableAutoConfigurationContextCustomizer@5bb21b69, org.springframework.boot.test.autoconfigure.filter.TypeExcludeFiltersContextCustomizer@351584c0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@c763d37b, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@5ed828d], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]].
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 7.687 sec - in jcg.zheng.demo.repository.ContactRepositoryTest
2019-02-16 11:53:26.392  INFO 17644 --- [       Thread-3] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@12aba8be: startup date [Sat Feb 16 11:53:20 CST 2019]; root of context hierarchy
2019-02-16 11:53:26.399  INFO 17644 --- [       Thread-3] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2019-02-16 11:53:26.400  INFO 17644 --- [       Thread-3] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000227: Running hbm2ddl schema export
Hibernate: drop table contact if exists
2019-02-16 11:53:26.415  INFO 17644 --- [       Thread-3] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000230: Schema export complete

Results :

Tests run: 2, Failures: 0, Errors: 0, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  28.066 s
[INFO] Finished at: 2019-02-16T11:53:26-06:00
[INFO] ------------------------------------------------------------------------

C:\JCG\spring-string-trim-demo>

6. Java String trim() method – Summary

In this example, I demonstrated how to trim a string value in three ways:

  • Create a Function to trim a string in JDK8+
  • Invoke trim for a non-null String object
  • Invoke trim for an Optional String object

7. Download the Source Code

This example consists of a Maven project which trims a string before saving it into a database table.

Download
You can download the full source code of this example here: Java String trim() method with Example

Last updated on May 7th, 2020

Mary Zheng

Mary has graduated from Mechanical Engineering department at ShangHai JiaoTong University. She also holds a Master degree in Computer Science from Webster University. During her studies she has been involved with a large number of projects ranging from programming and software engineering. She works as a senior Software Engineer in the telecommunications sector where she acts as a leader and works with others to design, implement, and monitor the software solution.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button