Tutorial Playlist

Java Tutorial for Beginners

Overview

10 Reasons That Explain Why You Need to Learn Java

Lesson - 1

What is Java: A Beginners Guide To Java

Lesson - 2

What Is JDK? Why Do We Need It?

Lesson - 3

One-Stop Solution for Java Installation in Windows

Lesson - 4

How to Get Started With Eclipse IDE?

Lesson - 5

What Are Java Strings And How to Implement Them?

Lesson - 6

Arrays In Java: Declare, Define, and Access Array

Lesson - 7

What Are Java Collections and How to Implement Them?

Lesson - 8

What Are Java Classes and Objects and How Do You Implement Them?

Lesson - 9

How to Implement the Revolutionary OOPs Concepts in Java

Lesson - 10

What is Encapsulation in Java and How to Implement It?

Lesson - 11

What is an Abstract Class in Java and How to Implement It?

Lesson - 12

What is Inheritance in Java and How to Implement It

Lesson - 13

What is Java Interface and Why it's Needed?

Lesson - 14

What is Polymorphism in Java and How to Implement It?

Lesson - 15

What is a Java Lambda Expression and How to Implement It?

Lesson - 16

Your One-Stop Solution for Multithreading in Java

Lesson - 17

The Differences Between C++ and Java That You Need To Know

Lesson - 18

Java vs. Python: Which is the Best Programming Language?

Lesson - 19

Java vs JavaScript: Know The 8 Major Differences

Lesson - 20

Top 25 Pattern Programs in Java For Printing Numbers

Lesson - 21

Java EE Tutorial: All You Need To Know About Java EE

Lesson - 22

What is Exception Handling in Java?

Lesson - 23

What Is Java JDBC? The Complete Reference

Lesson - 24

What is Java API and The Need for Java APIs?

Lesson - 25

Introduction To Java Servlets and Its Life-Cycle

Lesson - 26

10 Best Java Frameworks You Should Know in 2021

Lesson - 27

Top 10 Brilliant Java Project Ideas You Need to Know

Lesson - 28

Top 60 Java Interview Questions and Answers in 2021

Lesson - 29

Java Programming: The Complete Reference You Need

Lesson - 30

All You Need to Know to Implement JUnit Testing in Java

Lesson - 31

What Is Junit? a Look Into the Best Java Testing Framework

Lesson - 32

Ruby on rails

Lesson - 33
What Are Java Strings And How to Implement Them?

Java Strings are typically a data type but often treated as a data structure as it stores the elements of character type sequentially, just as an array does. In this article, we will learn anything and everything about Java Strings straightforwardly through the following docket.

What Are Java Strings?

We can define Java Strings as objects in Java dedicated to sequentially storing characters. 

For example:

char[] S ={'S', 'i', 'm', 'p', 'l', 'i', 'l', 'e', 'a', 'r', 'n'};  

String str=new String(S);

//or

String S = "Simplilearn";

Now that we have learned the definition of Java strings and their examples, let us move ahead and know how to create Java Strings in real-time.

How to Create Java Strings?

We can create Java Strings in two different ways. We will learn both of them along with examples for a more sound learning experience.

FREE Java Certification Training

Learn A-Z of Java like never beforeEnroll Now
FREE Java Certification Training

Method one - String Literal

Java Strings can be created by using the String Literals Method by following the syntax given below.

String str = "Hello World";

In this method, using the double quotes (") is mandatory.

Whenever you pass a command to create a new string using the literal string method, the Java Virtual Machine(JVM) will search for the String in the String Pool. If the String exists, then JVM will return the reference to the String. 

If the required String is not existing in the string pool, then the JVM will create the new String as per the user's command.

Method two - New Keyword

In the second method, we use the keyword 'new' to create a new string. We will be following the syntax mentioned below to create a unique string.

String str = new String("Hello World")

Here the string str will be created using the heap memory. The literal "Hello World," however, is stored in the String Pool.

Now, we have understood Java Strings and how to create them using two different methods and their syntax. Next, moving ahead, we will understand the Java Strings Interfaces.

Java Strings Interfaces

Java Strings are from the java.lang.String class. Java Strings are capable of performing various string manipulation operations. To do so, the java.lang.String class implements three interfaces, as mentioned below.

  1. Serializable 
  2. Comparable 
  3. CharSequence

Java-strings-1

To create new strings, we need to String a StringBuilder and StringBuffer. The StringBuffer and StringBuilder implement the CharSequence to create new strings in Java.

Java-strings-2

Following the fundamentals of Java Strings, we will move ahead into the methods available with Java Strings.

Full Stack Java Developer Course

In Partnership with HIRIST and HackerEarthEXPLORE COURSE
Full Stack Java Developer Course

Methods in Java Strings

Following are the primary methods available in Java. 

String charAt()

The string charAt() method is dedicated to returning a char value of a selected index number in a whole string.

Syntax:

public char charAt(int index) 

Example:

package SimpliString;

public class string {

public static void main(String args[]) {

String name = "Simplilearn";

char ch = name.charAt(5);

System.out.println(ch);

}

}

Output:

i

String compareTo()

The Sting compareTo method is used to compare two strings lexicographically. 

If the comparison results are a positive number, then the given String is lexicographically greater than the current String.

If the comparison results are negative, then the given number is lexicographically lesser than the current String.

If the comparison is zero, then the given number is lexicographically equal to the current String.

Syntax:

public int compareTo(String anotherString)  

Example:

package SimpliString;

public class string {

public static void main(String args[]) {

String s1 = "Simple";

String s2 = "Simplilearn";

String s3 = "Simplilearn";

String s4 = "Learn";

String s5 = "E-Learning";

System.out.println(s1.compareTo(s2));

System.out.println(s2.compareTo(s3));

System.out.println(s1.compareTo(s4));

System.out.println(s1.compareTo(s5));

}

}

Output:

-4

0

7

14

String concat()

String concat() method is used to combine two different strings. Here, the second String gets connected to the end of the first String.

Syntax:

public String concat(String secondString)

Example:

package SimpliString;

public class string {

public static void main(String args[]) {

String s1 = "Simplilearn ";

s1.concat("Best in class");

System.out.println(s1);

s1 = s1.concat("Best in class E-Learning Platform");

System.out.println(s1);

}

}

Output:

Simplilearn 

Simplilearn Best in class E-Learning Platform

String contain()

The String contain() method is used to search a specific character or string segment in the given String. The method returns true if the search keyword is found and negative if it is not found.

Syntax:

public boolean contains(CharSequence search_keyword)  

Example:

package SimpliString;

public class string {

public static void main(String[] args) {

String str = "Simplilearn E-Learning Platform";

boolean isContains = str.contains("Simplilearn");

System.out.println(isContains);

System.out.println(str.contains("Simple"));

}

}

Output:

true

false

String endsWith()

The String endsWith() method is employed to check if the string ends with a particular character or a set of characters. If the current String ends with the given character/string, then the method returns true; else, the method will return false.

Syntax:

public boolean endsWith(String suffixString)

Example:

package SimpliString;

public class string {

public static void main(String args[]) {

String s1 = "Hello World. Welcome to Simplilearn'';

System.out.println(s1.endsWith("Simplilearn"));

}

}

Output:

true

String equals()

The String equals() method is used to compare the current String with the given String and check if they are equal. The method returns true if they both match and false if they do not match.

Syntax:

public boolean equals(Object givenObject)  

Example:

package SimpliString;

public class string {

public static void main(String args[]) {

String s1 = "HelloWorld";

String s2 = "HelloWorld";

String s3 = "Welcome to Simplilearn";

System.out.println(s1.equals(s2));

System.out.println(s1.equals(s3));

}

}

Output:

true

false

String format()

The String format() method is used to print the formatted version of the given String. The user needs to use the String.format() method or the Locale.getDefault() method will be called by default.

Syntax:

public static String format(String format, strings, args)

Example:

package SimpliString;

public class string {

public static void main(String args[]) {

String name = "simplilearn";

String sf1 = String.format("String is %s", name);

String sf2 = String.format("value is %f", 14.1234);

String sf3 = String.format("value is %14.12f", 14.1234);

System.out.println(sf1);

System.out.println(sf2);

System.out.println(sf3);

}

}

Output:

String is simplilearn

value is 14.123400

value is 14.123400000000

String equalsIgnoreCase()

The String equalsIgnoreCase() method also compares two different strings, just like the String equal() method. Still, the difference is that the case sensitivity is not considered as a parameter of comparison. 

Syntax:

public boolean equalsIgnoreCase(String s) 

Example:

package SimpliString;

public class string {

public static void main(String args[]) {

String s1 = "Simplilearn";

String s2 = "SIMPLILEARN";

System.out.println(s1.equalsIgnoreCase(s2));

}

}

Output:

true

String getBytes()

The String getBytes() method is used to get the byte array of the given String.

Syntax:

public byte[] getBytes(Charset charset)  

Example:

package SimpliString;

public class string {

public static void main(String args[]) {

String s1 = "SIMPLILEARN";

byte[] byteArray = s1.getBytes();

for (int i = 0; i < byteArray.length; i++) {

System.out.println(byteArray[i]);

}

}

}

Output:

83

73

77

80

76

73

76

69

65

82

78

String getChars()

The getChars() method copies the content of the given String into the current char array.

Syntax:

public void getChars(int sourceBeginInd, int sourceEndInd, char[] destination, int destBeginInd)  

Example:

package SimpliString;

public class string {

public static void main(String args[]) {

String str = new String("Welcome to Simplilearn");

char[] ch = new char[10];

try {

str.getChars(5, 11, ch, 0);

System.out.println(ch);

} catch (Exception ex) {

System.out.println(ex);

}

}

}

Output:

me to

String indexOf()

The String indexOf() method is used to return the selected character's index value in the given String. If the character is found, then the method returns the index value. Else it returns -1.

Syntax:

int index= s1.indexOf("str");

Example:

package SimpliString;

public class string {

public static void main(String args[]) {

String s1 = "Hello World, Welcome to Simplilearn";

int ind1 = s1.indexOf("World");

System.out.println(ind1);

int ind3 = s1.indexOf("to", 4);

System.out.println(ind3);

int index4 = s1.indexOf('S');

System.out.println(index4);

}

}

Output:

6

20

23

String intern()

The String inter() method is used to convert a given string into an interned string and return the string canonical form.

Syntax:

public String intern()  

Example:

package SimpliString;

public class string {

public static void main(String args[]) {

String s1 = new String("Simplilearn");

String s2 = "Simplilearn";

String s3 = s1.intern();

System.out.println(s1 == s2);

System.out.println(s2 == s3);

}

}

Output:

false

true

String isEmpty()

The String isEmpty() method is used to check if the given string is empty or not. If the string is found empty, then the method returns true. If not, then the method returns false.

Syntax:

public boolean isEmpty()  

Example:

package SimpliString;

public class string {

public static void main(String args[]) {

String s1 = "";

String s2 = "Simplilearn";

System.out.println(s1.isEmpty());

System.out.println(s2.isEmpty());

}

}

Output:

true

false

String join()

The String join() method is used to return the given String after joining it with a given delimiter.

Syntax:

public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)  

Example:

package SimpliString;

public class string {

public static void main(String args[]) {

String joinString1 = String.join("-", "Welcome", "to", "Simplilearn");

System.out.println(joinString1);

}

}

Output:

Welcome-to-Simplilearn

String lastIndexOf()

The string lastIndexOf() method is designed to return the given character string's last index value. If it is not found, then the method returns -1. 

Syntax:

package SimpliString;

public class string {

public static void main(String args[]) {

String s1 = "Hello World. Welcome to Simplilearn";

int indexV = s1.lastIndexOf('S');

System.out.println(indexV);

}

}

Output:

24

String length()

The String length() method is used to find out the size of the given String. It counts the number of characters available in the given String.

Syntax:

public int length()  

Example:

package SimpliString;

public class string {

public static void main(String args[]) {

String s1 = "Simplilearn";

System.out.println("The length of the string is: " + s1.length());

}

}

Output:

The length of the String is: 11

String replace()

The String replace() method is implemented to replace the set of old CharSequence with new CharSequence.

Syntax:

public String replace(char oldCharSeq, char newCharSeq)

Example:

package SimpliString;

public class string {

public static void main(String args[]) {

String s1 = "Hello World, Welcome to Java";

String replaceString = s1.replace('W', 'H');

System.out.println(replaceString);

}

}

Output:

Hello Horld, Helcome to Java

String replaceAll()

The string replaceAll() method is designed to return a string after replacing its current sequence of characters with the matching regex and replacement string.

Syntax:

public String replaceAll(String regex, String newString)  

Example:

package SimpliString;

public class string {

public static void main(String args[]) {

String s1 = "Hello World Welcome to Simplilearn";

String replaceString = s1.replaceAll("l", "a");

System.out.println(replaceString);

}

}

Output:

Heaao Worad Weacome to Simpaiaearn

String split()

The string split() method is employed to split the current String with a given regular expression and then return a new char array.

Syntax:

public String split(String regex, int limit)  

Example:

package SimpliString;

public class string {

public static void main(String args[]) {

String s1 = "Hello World Welcome to Simplilearn";

String[] words = s1.split("\\s");

for (String w : words) {

System.out.println(w);

}

}

}

Output:

Hello

World

Welcome

to

Simplilearn

String startsWith()

The string startsWith() method is used to check if the current String starts with a given prefix or not. If the current String begins with a given prefix, then the method returns true; the method returns false.

Syntax:

public boolean startsWith(String prefixString)

Example:

package SimpliString;

public class string {

public static void main(String args[]) {

String s1 = "Hello World";

System.out.println(s1.startsWith("Hell"));

System.out.println(s1.startsWith("Java"));

}

}

Output:

true

false

String toCharArray()

The String toCharArray() method is used to convert a string into a character array. The index values of the new character array will be the same as that of the older String.

Syntax:

public char[] toCharArray()  

Example:

package SimpliString;

public class string {

public static void main(String args[]) {

String s1 = "Simplilearn";

char[] ch = s1.toCharArray();

for (int i = 0; i < ch.length; i++) {

System.out.print(ch[i]);

}

}

}

Output:

Simplilearn

String toUpperCase()

The String toUpperCase() method is employed to convert the String in the lower case to the upper case.

Syntax:

public String toUpperCase()  

Example:

package SimpliString;

public class string {

public static void main(String args[]) {

String s1 = "Simplilearn";

String s1upper = s1.toUpperCase();

System.out.println(s1upper);

}

}

Output:

SIMPLILEARN

String toLowerCase()

The String toLowerCase() method is used to convert the upper case string to lowercase.

Syntax:

public String toLowerCase()  

Example:

package SimpliString;

public class string {

public static void main(String args[]) {

String s1 = "SIMPLIlearn";

String s1lower = s1.toLowerCase();

System.out.println(s1lower);

}

}

Output:

simplilearn

String trim()

The String trim() method is implemented to remove the unwanted leading and trailing spaces in the given String.

Syntax:

public String trim()  

Example:

package SimpliString;

public class string {

public static void main(String args[]) {

String s1 = " Hello World ";

System.out.println(s1.trim() + " Welcome to Simplilearn");

}

}

Output:

Hello World Welcome to Simplilearn

String valueOf()

The String valueOf() method converts the different numerical or any data type values or elements into strings.

Syntax:

public static String valueOf(int i)  

Example:

package SimpliString;

public class string {

public static void main(String args[]) {

int value = 100;

String s1 = String.valueOf(value);

System.out.println(s1 + 299);

}

}

Output:

100299

With this, we have come to the end of this Java Strings article. Moving ahead, we will look into the next crucial steps that you could pursue to master Java.

Get a firm foundation in Java, the most commonly used programming language in software development with the Java Certification Training Course.

Next Steps

Java Collections can be your next stop as they are essential to go through before you start coding. It helps you master how to use the data types and data collection frameworks in real-time java.

The link to your next step is here: What Are Java Collections and How to Implement Them?

If you're looking for more in-depth knowledge about the Java programming language and information on how to get certified as a professional developer, explore our Java training and certification programs, which Simplilearn's experienced industry experts offer in real-time. In particular, check out our Full Stack Java Developer Master's Program today!

If you have any questions about this "Java Strings" article, please leave them in the comments section, and our experts will answer them for you at the earliest!

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.