Java Strings – Stuff You Must Know!

Java String Manipulation: Functions and Methods with EXAMPLE

 

What are Strings?

A string in literal terms is a series of characters. Hey, did you say characters, isn’t it a primitive data type in Java. Yes, so in technical terms, the basic Java String is basically an array of characters.

So my above string of “ROSE” can be represented as the following –

Java String Tutorial

Why use Strings?

One of the primary functions of modern computer science, is processing human language.

Similarly to how numbers are important to math, language symbols are important to meaning and decision making. Although it may not be visible to computer users, computers process language in the background as precisely and accurately as a calculator. Help dialogs provide instructions. Menus provide choices. And data displays show statuses, errors, and real-time changes to the language.

As a Java programmer, one of your main tools for storing and processing language is going to be the String class.

String Syntax Examples

Now, let’s get to some syntax,after all, we need to write this in Java code isn’t it.

String is an array of characters, represented as:

The String Class Java extends the Object class.

String Concatenation:

Concatenation is joining of two or more strings.

Have a look at the below picture-

Java String Tutorial

We have two strings str1 = “Rock” and str2 = “Star”

If we add up these two strings, we should have a result as str3= “RockStar”.

Check the below code snippet,and it explains the two methods to perform string concatenation.

First is using “concat” method of String class and second is using arithmetic “+” operator. Both results in the same output

Important Java string methods :

Java String Tutorial

Let’s ask the Java String class a few questions and see if it can answer them 😉

 

 

String “Length” Method

How will you determine the length of given String? I have provided a method called as “length”. Use it against the String you need to find the length.

String “charAt” Method

 

Similar to the above question, given the index, how do I know the character at that location?

Simple one again!! Use the “charAt” method and provide the index whose character you need to find.

Returns true if the character sequence represented by the argument is a suffix of the character sequence represented by this object.

String Java “tolowercase” & Java “touppercase” Method

 

I want my entire String to be shown in lower case or Uppercase?

Just use the “toLowercase()” or “ToUpperCase()” methods against the Strings that need to be converted.

String S1 =”The number is: “+ “123”+”456″;

System.out.println(S1);

then it will print: The number is: 123456

If the initialization is like this:

String S1 = “The number is: “+(123+456);

System.out.println(S1);

then it will print: The number is:579 That’s all to Strings!

top
X
Glad to have you at Our Website
Welcome to WPBot
wpChatIcon