Java Strings



In this chapter we are going to be learning about Java strings. String is a non primitive data type and user can define the length of the string variable.

When we have to store some text in Java we use string variable. The text may be a single character, a word, a sentence or a whole program; we can store any length of text inside string variable.

String is used extensively in Java programming language. In this lesion we will also discuss about array so make sure you go through our array chapter first and then learn about Java strings.

First we will learn how a string variable declared in Java. Declaration means letting Java know that a string variable has been created and some text values will be stored inside the variable.

In order to declare a string variable in Java, we have to use the keyword “String”. Find below the syntax of Java strings.

 

How to Declare Java Strings:

import java.util.Scanner;

 

public class JavaOperators {

 

     public static void main(String[] args) {

 

        String website = "LearnJava.Blogspot.Com";

        System.out.println(website);

         

     }

 

}

 

Make sure when you declare a string variable, you have to remember that you have to write “String” with first letter in capital.

If there are spaces between two words declared inside a string variable, there is no harm because spaces are also a valid character in Java strings.

Since, space is a valid character in Java string, we can even store big paragraphs with spaces inside a Java string variable.

Not only that we can even store a long essay in a string variable unless the memory is full.

In the above program we have seen predefined string values. But what if we want user to enter string values and we want them to store in variables. We can perform the same task through user input. Check in below program.

import java.util.Scanner;

 

public class JavaOperators {

 

     public static void main(String[] args) {

 

              String name;

              Scanner sc = new Scanner (System.in);

              System.out.println("Enter your name");

              name = sc.nextLine();

              System.out.println("Your name is "+name);

             

         

     }

 

}

 

Now we are going to be performing some of the functions on string variable. These functions are important. So understand them carefully.

In order to concatenate two string variables and insert them into one single string variable, we use “+” operator. See the below program.

import java.util.Scanner;

 

public class JavaOperators {

 

     public static void main(String[] args) {

 

              String firstname;

              String lastname;

              String fullname;

              Scanner sc = new Scanner (System.in);

              System.out.println("Enter your first name");   

              firstname = sc.nextLine();

              System.out.println("Enter your last name");

              lastname = sc.nextLine();

              System.out.println("Your full name is "+ firstname + " " + lastname);

             

         

     }

 

}

 

In the above program we have concatenate two variable by “+” operator and stored the concatenated variable in a third String variable.

When we print the concatenated variable, we have to use a space (Inside semicolon) between the two variables name so as to print the space.

Once the execution of the program will be over, the space will be deleted from the memory because we did not store the same in any variable.

 

Java length() Method:

We can ascertain the length of any string variable with the help of “length” method. This “length” method already exists in Java as a String method. We have to call this method in order to get the length of the string.

import java.util.Scanner;

 

public class JavaOperators {

 

     public static void main(String[] args) {

 

              String firstname;

              String lastname;

              Scanner sc = new Scanner (System.in);

              System.out.println("Enter your first name");   

              firstname = sc.nextLine();

              System.out.println("Enter your last name");

              lastname = sc.nextLine();

              String fullname = firstname + " " + lastname;

              System.out.println("Your full name is "+ firstname + " " + lastname);

              System.out.println("Length of Full Name is "+ fullname.length());

             

         

     }

 

}

 

With the help of above program we can easily ascertain the length of any string variable.

 

Java charAt() Method:

Java charAt() is also a pre-defined method in Java programming language which can be used to find what character is there at a given position in any particular string variable.

We can use charAt() method to print all the characters one by one with the help of a for loop. When we apply charAt() method on string variable, each character of the string will be assigned an index value just like an array. We all know that in order to print certain things repeatedly we have to use a loop.

Since we can access each character of a string, apart from printing each characters, we can also perform some other tasks on the strings, such as we can manipulate or delete some character.

In below program we have called the charAt() method to print string values repeatedly with the help of a for loop.

import java.util.Scanner;

 

public class JavaOperators {

 

     public static void main(String[] args) {

 

              String firstname;

              String lastname;

              Scanner sc = new Scanner (System.in);

              System.out.println("Enter your first name");   

              firstname = sc.nextLine();

              System.out.println("Enter your last name");

              lastname = sc.nextLine();

              String fullname = firstname + " " + lastname;

              System.out.println("Your full name is "+ fullname);

              System.out.println("Length of Full Name is "+ fullname.length());

             

              //charAt() method

             

              System.out.println("Printing each character of fullname");

 

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

                   System.out.println(fullname.charAt(i));

              }

             

         

     }

 

}

 

How to compare two strings in Java:

We can compare two string values in Java with the help of compareTo() method. This compareTo() is a predefined method in Java language and this method returns “0” if two strings are equal.

In case string1 is greater than string2, compareTo() method returns a positive integer value which can be any value.

In case string1 is less than string2, compareTo() method returns a negative integer value which can be any value.

import java.util.Scanner;

 

public class JavaOperators {

 

     public static void main(String[] args) {

 

              String firstname="Akshay";

              String lastname="Kumar";

             

              if(firstname.compareTo(lastname)==0) {

                   System.out.println("Both Strings are equal-"+firstname.compareTo(lastname));

                  

              }else {

 

                   System.out.println("Both Strings are not equal-"+firstname.compareTo(lastname));

              }

             

              // above program returns -> Both Strings are not equal--10

 

             

               String name1="Akshay";

              String name2="Akshay";

             

              if(name1.compareTo(name2)==0) {

                   System.out.println("Both Strings are equal-"+name1.compareTo(name2));

                  

              }else {

 

                   System.out.println("Both Strings are not equal-"+name1.compareTo(name2));

              }

             

              // above program returns -> Both Strings are equal-0

 

         

     }

 

}

 

Always Remember that in order to compare two strings, you should always use compareTo() method and not comparison operator “==” because in some cases comparison operator may return some other values which might lead to unexpected result or error.

 

Java Substrings:

Java substrings are part of entire string variable. Suppose there is a string variable in Java and inside the string variable there may be some string values stored. Now when we take some part of the entire string, we call it as sub string.

In order to access the substring we have a predefined method in Java language which is substring(). The substring() method takes two parameters. The first parameter is the index value of the first character of the substring which we want to access and the 2nd parameter is the end character’s index value of the substring.

import java.util.Scanner;

 

public class JavaOperators {

 

     public static void main(String[] args) {

 

              String firstname="Akshay Kumar";

             

             

              String lastname = firstname.substring(7);

             

              System.out.println(lastname);

                       

     }

 

}

 

The above program will only print the surname as we are using the method substring() and we also have passed the parameter from where we want to pick the value.

In the above program you can see we did not pass any ending index. When we do not pass any ending index, the method will by default pick the remaining characters after the first index position as defined.

When we pass both beginning and ending index values the method will pick only values from 1st index position till last index position. One think you should remember the land index position is not inclusive of the substring, which means suppose you pass and parameter substring(2,5), the method will take substring from index position 2 to index position 4 only and thus the last index value is always exclusive of substring.

 

Conclusion:

We hope the above lesion was informative and helpful. We have covered more important topics of Java programming language in our next lessons.

Java Strings Java Strings Reviewed by Technobits on November 20, 2022 Rating: 5

No comments:

Powered by Blogger.