Java Tutorial-Java Strings

Java Strings

It is used to store the text. A String variable contains a collection of characters surrounded by double quotes.

Example

Create a variable of type String and assign it to a value:

String value = "Hello World";

String Methods

A string in Java is actually an object, which contains methods that can perform certain operations on strings.

 

Example

The length of the String can be found using the length() method.


String text = "Hello World";
System.out.println("The length of the string is : " +text.length());
System.out.println("Uppercase : " +text.toUpperCase() );
System.out.println("Lowercase : " +text.toLowerCase());

Output

The length of the string is : 11
Uppercase : HELLO WORLD
Lowercase : hello world

Finding a String in a String


The indexOf() method returns the index of the first occurrence of a specified text in a string (including whitespaces)

Example

String txt = "Please say 'hello' to everyone";
System.out.println(txt.indexOf("hello"));

Output

12

String Concatenation


The + operator can be used between the strings to concatenate together to make a new String.


Example

String firstName = "Hello";
String lastName = "World!";
System.out.println(firstName+ " "+lastName);

Output

Hello World!


Special Characters


String must be written inside the quotes, the special characters inside the strings will be misunderstood and generate an error.


The following String will throw an error:

String txt = "Please say "hello" to everyone";

The above problem can be solved using the backlash escape character.


Escape Character

Result

Description

\’

Single quote

\”

Double quote

\\

\

Backslash

 

The sequence \” inserts a double quote in a String. The solution for the above error is

String txt = "Please say \"hello\" to everyone";

Example

String text = "It\'s alright";

Output

It’s alright

Escape sequences in Strings


The valid escape sequences in Java are:



Adding Numbers and Strings


Java uses + operator for both addition and concatenation. Numbers are added and Strings are concatenated.

 

Example (Adding Numbers)


If you add two numbers, the result will also be a number

int a = 10;
int b = 6;
int c = a + b; // c will be 16 (which is an integer/number)

Example (Adding Strings)


If you add two strings, the result will also be a string

String a = "10";
String b = "6";
String c = a + b; // c will be 106 (which is a string)

Example (Adding a String and a Number)


String a = "10";
int b = 6;
String c = a + b; // c will be 106 (which is a string)

Code

Result

\n

New Line

\r

Carriage Return

\t

Tab

\b

Backspace

\f

Form Feed