Java – Strings


Strings

What is a String ?

A String is considered as the sequence of characters combined to form a String.

It may be numerals, letters, symbols.

What is a String in Java ?

Like the same way Strings are considered as sequence of characters combined together.

But in Java Strings are considered as Java pre-defined in-built object as it comes from java.lang.String .

public class Stringchar{
        public static void main(String args[])
        {
        char [] letters = {'H','e','l','l','o','W','o','r','l','d'};
        String a = new String(letters);
        System.out.println(a);
        }
}

Output :

HelloWorld

As discussed earlier, 

String is a Java Literal which should be enclosed within double quotes.

String country = "India";

Same like char literals java supports the same escape sequences for String literals too.

Escape sequences already explained in previous tutorial.

How can we create Strings ?

There are two ways to create a String object.


1. By Literal base

String can be created as per literal protocol (ie) enclosed within double quotes.

String Country  = "India";

Why are we creating String Literals ?

When we create a String as literal its value is directly stored in Java Memory.

String length can be calculated by StringName.length().

Once a String variable is created, Its size will not be changed and its stored directly in Memory.

Suppose we have created a String,

String country = "India";

JVM first checks in the constants pool whether any String present with the same name “country” or not.

If the String name already exists in the pool, JVM will return the reference of the already pooled constant while compiling the code.

So we cannot use the same String variable name again in Java.

public class StringEg{
  public static void main(String args[])
{
String country = "India";
String country = "India";
System.out.println(country);
}
}

Above case is not possible as JVM throws error.

StringEg.java:6: error: variable country is already defined in method main(String[])

String country = “India”;       

^1 error

String variable names should be different irrespective of its values.

Possible case :

public class StringEg{
  public static void main(String args[])
{
String country = "India";
String location = "India";
System.out.println(country);
System.out.println(location);
}
}

Output :

India

India

String variable name different but the values are same, JVM checks for the variable name and not its values in Java.

If String is declared as Java Literal, Its values are directly stored in Memory location. 

2. By Object base

String can be created with “new” keyword as object.

String Name = new String(“Mr.X”);

public class StringEg{
  
public static void main(String args[])
{
String country = "India";
System.out.println(country);
String Name = new String("Mr.X");
System.out.println(Name);
}
}

Output :

India

Mr.X

In this case, JVM will create a space for “new” String Object in Heap Memory, and the actual value “Mr.X” will be stored in Memory with reference to the object.

And in the program if the object is no longer used, it will be automatically cleaned by Garbage Collector.

String Concatenations

What is String concatenation ?

Its addition of two separated strings and stored in newly formed String.

String concatenation is done by two ways 

1. by .concat(); method

public class StringConcat{
public static void main(String args[])
{
String firstName = "Abdul";
String middleName = "Kalam";
String fullName = firstName.concat(middleName);
System.out.println(fullName);
}
}

Output :

AbdulKalam

2. by including “+” symbol

public class StringConcat{
public static void main(String args[])
{
String firstName = "Abdul";
String middleName = "Kalam";
String fullName1 = firstName + middleName;
System.out.println(fullName1);
}
}

Output :

AbdulKalam

Methods in String :

1 . “Length” Method

Length of the String value can be found by String Length method.

public class StringLen{
public static void main(String args[])
{
String countryViews = "India is my country";
System.out.println(countryViews.length());
}
}

Output :

19

2 . “indexOf” Method

Index of the String character is found by indexOf method.

indexOf method is case-sensitive, It checks for case of the value.

public class StringIndexOf{
public static void main(String args[])
{
        String Sample = "India is my country";
        System.out.println(Sample.indexOf("m"));
}
}

Output :

9

If in case if we search for indexOf wrong value it throws output as -1 .

3 . “charAt” Method

charAt method is used to find which character present in the index we mention.

public class StringCharAt{
        public static void main(String args[])
        {
        String Name = "AbdulKalam";
        System.out.println(Name.charAt(5));
        }
}

Output :

k

4. “CompareTo” Method


CompareTo method is used to compare the String values with the String value inside the program.

This is the case-sensitive operation.

If the condition is true it returns the output 0.

public class StringCompareTo{
public static void main(String args[])
{
String name = "AbdulKalam";
System.out.println(name.compareTo("AbdulKalam"));
}
}

Output :

0

5. “compareToIgnoreCase” Method

This is the same method as CompareTo but it is not case-sensitive.

It ignores the case and checks for the values.

public class StringCompareTo{
        public static void main(String args[])
        {
        String name = "AbdulKalam";
        System.out.println(name.compareToIgnoreCase("ABDULKALAM"));
        }
}

Output :

0

6. “Contain” Method

Contain method is used to find out if actual value of String inside the program contains small sequence of characters.

This is the case-sensitive operation. The output will be a boolean value.

public class StringContains{
public static void main(String args[])
{
String name = "AbdulKalam";
System.out.println(name.contains("ala"));
System.out.println(name.contains("abc"));
System.out.println(name.contains("abdul"));
}
}

Output :

true

false

false

7. “endsWith” Method

endsWith method is used to find the actual value of String inside the program ends with user-defined value.

This is the case-sensitive operation. The output will be a boolean value.

public class StringContains{
public static void main(String args[])
{
String name = "AbdulKalam";
System.out.println(name.endsWith("m"));
System.out.println(name.endsWith("am"));
System.out.println(name.endsWith("kalam"));
System.out.println(name.endsWith("abdul"));
}
}

Output :

true

true

false

false

8. “replace” Method

replace Method will replace the old content with the new content.

both char and Strings are applicable.

public class StringReplace{  
public static void main(String args[]){  
String views ="India is my country";  
String replaceVal=views.replace('m','A');//replaces all occurrences of 'a' to 'e'  
System.out.println(replaceVal);  
}
}  

Output :

India is Ay country


public class StringReplace{
public static void main(String args[]){
String views ="India is my country";
String replaceVal=views.replace("is","was");//replaces all occurrences of 'is' to 'was'   
System.out.println(replaceVal);   
}
}  

Output :

India was my country

9. “replaceAll” Method

replaceAll method replaces all the occurrences of the String values inside the program with the user-defined value.

public class StringReplaceAll{  
public static void main(String args[]){  
String something ="google is a very good website";  
String replaceVal=something.replaceAll("o","a");
System.out.println(replaceVal);  
}
}

Output :

gaagle is a very gaad website

public class StringReplaceAll{  
public static void main(String args[]){
String something ="google is a very good website. And it is the biggest company in the world";    
String replaceVal=something.replaceAll("is","was");
System.out.println(replaceVal);   
}
}  

Output :

google was a very good website. And it was the biggest company in the world

10. “tolowercase” Method

tolowercase method is used to print the values of the String inside the program in lower-case.

public class LowercaseExample{  
public static void main(String args[]){  
String StringVal ="JAVA IS A PROGRAMMING LANGUAGE";  
String StringValLower = StringVal.toLowerCase();  
System.out.println(StringvalLower);  
}
}

Output :

java is a programming language

11. “touppercase” Method

touppercase method is used to print the values of the String inside the program in upper-case.

public class UppercaseExample{  
public static void main(String args[]){  
String StringVal = "hello java";  
String StringValUpper = StringVal.toUpperCase();  
System.out.println(StringValUpper);  
}
}  

Output :

HELLO JAVA

12. “isEmpty” Method

isempty method is used to check the String values declared inside the program is empty or not.

The output will be a boolean value.

public class StringEmpty{
public static void main(String args[])
{
String name = "SomeName";
String name1 = "";
System.out.println(name.isEmpty());
System.out.println(name1.isEmpty());
}
}

Output :

false

true


13. “valueOf” Method

valueOf method is used to convert different data-type values to String.

public static String valueOf(boolean b)  
public static String valueOf(char c)  
public static String valueOf(int i)  
public static String valueOf(long l)  
public static String valueOf(float f)  
public static String valueOf(double d)  
public static String valueOf(Object o)

Example Program :

public class StringValueOf{
public static void main(String args[])
{
int a = 10;
String aVal = String.valueOf(a);
System.out.println(aVal);
char b = 'A';
String bVal = String.valueOf(b);
System.out.println(bVal);
float c = 10.5f;
String cVal = String.valueOf(c);
System.out.println(cVal);
double d = 1234.5632d;
String dVal = String.valueOf(d);
System.out.println(dVal);
// Adding these values
String e = aVal + bVal + cVal + dVal;
System.out.println("The value of e = " + e);
}
}

Output :

10

A

10.5

1234.5632

The value of e = 10A10.51234.5632