$show=/label

Java Strings - Common Working Examples and Interview Programs

SHARE:

A quick guide to Java String Recipes that most used in real projects. Practical and working examples on commonly used real-time use cases.

1. Introduction


In this tutorial, We'll learn more about Java Strings. without String usage, there is no application in the java world. Java Strings are very crucial in defining the properties in the model classes. Java String is part of java.lang package. String class is getting added with new methods in java 8, 11, 12 versions. String API has a lot of utility methods.

In this article, we will be exploring different scenarios where String is being used always.



Java Strings - Common Working Examples and Interview Programs



2. Obtaining s Sub Section from a String


We may need to take or retrieve the portion of a String in java in sometimes. String API has a method to get the exact portion of a string that method is substring() method.

This substring() method is overloaded in varients.

public String substring​(int beginIndex)
public String substring​(int beginIndex, int endIndex)

Use the substring() method to obtain a portion of the string between two different positions or one position that is from the given index to till the end.

String substring Example:



package com.javaprogramto.w3schools.engineering.string;
/**
 *
 * Getting a substring or part of a String.
 *
 * @version javaprogramto.com
 */
public class StringSubString {

    public static void main(String[] args) {
        String value = "Welcome to JavaProgramTo.com";
        System.out.println("Original String : " + value);
        
        String substring1 = value.substring(0, 7);
        System.out.println("Substring one : "+substring1);
        
        String substring2 = value.substring(7, value.length());
        System.out.println("Substring Two : "+substring2);
        
        String substring3 = value.substring(10);
        System.out.println("Substring Three : "+substring3);
    }

}

Output:

Original String : Welcome to JavaProgramTo.com
Substring one : Welcome
Substring Two :  to JavaProgramTo.com
Substring Three :  JavaProgramTo.com

3. Comparing Strings (Two Strings)


Comparing two string is the most common asked in the java interview. String has a method equals() and equalsIgnoreCase() methods to compare the strings.
Along with that "==" double equal operator also can be used to compare. The interview will ask the differences between == and equals method.

Read more on:


"String equals() method in java with example - Internal Implementation"

"Difference between String.equals() and String.contentEquals() method?"

"Java Compare Two Strings Lexicographically and how compareTo() method works internally"

Example on "==" and equals():



  • "==" compares the memory address of the string or any object always.
  • equals(Object o) method compares the contents of two string and passed objects mostly will be a string in all cases. But, we can pass any object to it. It internally checks if the passed object is an instance of String or not. If the object does not string then it returns false immediately without checking its contents.



package com.javaprogramto.w3schools.engineering.string;

/**
 *
 * Comparing two strings with == and equals() method.
 *
 * @version javaprogramto.com
 */
public class StringCompare {

    public static void main(String[] args) {
        String s1 = "hello";
        String s2 = "world";
        String s3 = "hello";
        String s4 = new String("hello");
        String s5 = new String("hello");
        String s6 = new String("world");

        System.out.println("s1 == s2 : " + s1 == s2);
        System.out.println("s1 == s3 : " + s1 == s3);
        System.out.println("s1 == s4 : " + s1 == s4);
        System.out.println("s3 == s4 : " + s3 == s4);

        System.out.println("s1.equals(s2) : " + s1.equals(s2));
        System.out.println("s1.equals(s3) : " + s1.equals(s3));
        System.out.println("s1.equals(s4) : " + s1.equals(s4));
        System.out.println("s4.equals(s5) : " + s4.equals(s5));
        System.out.println("s4.equals(s6) : " + s4.equals(s6));
        
        StringBuffer buffer = new StringBuffer("hello");
        System.out.println("s1.equals(buffer) : " + s1.equals(buffer));
    }

}

Output:

false
false
false
false
s1.equals(s2) : false
s1.equals(s3) : true
s1.equals(s4) : true
s4.equals(s5) : true
s4.equals(s6) : false
s1.equals(buffer) : false

4. Trimming the white or blank spaces


If there are blank spaces or white space characters at the beginning or end of the string, then we can remove them using a string class trim() method.

public String trim()

Returns a string whose value is this string, with all leading and trailing space removed, where space is defined as any character whose code point is less than or equal to 'U+0020' (the space character).

String trim() Example:


package com.javaprogramto.w3schools.engineering.string;

/**
 *
 * Trimming the white spaces.
 *
 * @author javaprogramto.com
 */
public class StringTrim {

    public static void main(String[] args) {
        String value = "   Welcome to JavaProgramTo.com  ";
        System.out.println("Original String length : " + value.length());

        String trimmedStr = value.trim();
        System.out.println("Length after trimming : " + trimmedStr.length());

    }
}

Output:

Original String length : 33
Length after trimming : 28

See the difference between the original and trimmed string lengths. Trimmed one has no white space characters now.

5. Changing the cases of String


If the string is having the case sensitive values in your application then we need to convert them into either upper case or lowercase before processing to avoid any case sensitive issues.

String classs has toUpperCase() and toLowerCase() methods to work with case conversions.

Case conversion example:


package com.javaprogramto.w3schools.engineering.string;

/**
 *
 * Trimming the white spaces.
 *
 * @author javaprogramto.com
 */

public class StringCaseConversions {

    public static void main(String[] args) {
        String in = "India";
        String usa = "Usa";

        System.out.println("Converting upper case : " + in.toUpperCase());
        System.out.println("Converting upper case : " + usa.toUpperCase());

        System.out.println("Converting lower case : " + in.toLowerCase());
        System.out.println("Converting lower case : " + usa.toLowerCase());

    }

}

Output:

Converting upper case : INDIA
Converting upper case : USA
Converting lower case : india
Converting lower case : usa

Conversions with Locale:


System.out.println(in.toUpperCase(Locale.CHINA));
System.out.println(in.toUpperCase(new Locale("it","US")));
System.out.println(in.toLowerCase(new Locale("fr", "CA")));

Output:

INDIA
INDIA
india

6. Conclusion


In this article, We have seen some of the common use cases for String api methods as retrieving a portion of a string, comparison, removing white spaces and case conversions.

We will be exploring some of the things such as how to concatenate strings, a string to numbers, replacing patterns, file name ends with a specific format.. etc..

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,16,Arrays,7,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,5,Collections,22,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,81,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,4,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,9,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,29,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,Java 8,66,Java 8 Difference,2,Java 8 Stream Conversions,2,java 8 Stream Examples,3,Java 9,1,Java Conversions,11,Java Design Patterns,1,Java Files,1,Java Program,2,Java Programs,65,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Conversions,3,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Logging,1,Mac OS,2,Math,1,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,1,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,21,String,58,String Programs,9,String Revese,1,Swing,1,System,1,Tags,1,Threads,10,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java Strings - Common Working Examples and Interview Programs
Java Strings - Common Working Examples and Interview Programs
A quick guide to Java String Recipes that most used in real projects. Practical and working examples on commonly used real-time use cases.
https://1.bp.blogspot.com/-9EnyKeo3wH8/XmE1vxOTX2I/AAAAAAAACSo/wBH3lckR9f0qzYudxlgwWxVrHh4YG9L4gCLcBGAsYHQ/s640/Java%2BStrings%2B-%2BCommon%2BWorking%2BExamples%2Band%2BInterview%2BPrograms.png
https://1.bp.blogspot.com/-9EnyKeo3wH8/XmE1vxOTX2I/AAAAAAAACSo/wBH3lckR9f0qzYudxlgwWxVrHh4YG9L4gCLcBGAsYHQ/s72-c/Java%2BStrings%2B-%2BCommon%2BWorking%2BExamples%2Band%2BInterview%2BPrograms.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/03/java-strings.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/03/java-strings.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content