Skip to main content

Introduction to Java Programming

  What is Java? Java is a programming language and a platform. Java is a high-level, robust, object-oriented and secure programming language. Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year 1995. James Gosling is known as the father of Java. Firstly, it was called  Greentalk  and the file extension was  .gt . After that, it was called  Oak . Initially Java was designed for small, embedded systems in electronic appliances like set-top boxes. Platform:  Any hardware or software environment in which a program runs, is known as a platform. Since Java has a runtime environment (JRE) and API(Application Programming Interface), it is called a platform. The principles for creating Java programming were "Simple, Robust, Portable, Platform-independent, Secured, High performance, Multithreaded, Architecture neutral, Object-oriented, Interpreted, and Dynamic". Currently, Java is used in internet programming, mobile devices, g...

8. Strings and String Methods in Java

 

Strings

  • Generally, strings are a sequence of characters, but in Java strings are objects.
  • String is immutable which means it cannot be changed cannot be changed. Whenever we change any string, a new instance is created.
  • The String is a class but can be used as a reference data type.

Different ways to create a string in java:

  1. By using string literal.
  2. By using the new keyword.

String using string literal

  • We use double quotes ("") to create string using string literal.
  • JVM verifies if the same string is already present in the string constant pool or not.
  • If it is already present, then JVM returns a reference to the pooled instance, otherwise, a new string instance is created.

String using new keyword

  • When we create a string using new, a new object is always created in the heap memory.
class StringJava {
    public static void main(String[] arr) {
        char[] str = { 'D', 'e', 'e', 'p', 'a', 'k' };
        String s = new String(str);
        System.out.println("The string is: " + s);

        String user = "Name : "; // Here, 'user' is a reference variable
        and 'Name : ' (pointed by 'user') is stored in string constant pool

        String name = new String("Deepak Sharma");

        System.out.print(user);
        System.out.println(name);
    }
}

Different ways to print in Java

We can use the following ways to print in Java:

  • System.out.print() -> Simply prints anything as string inside the inverted commas except escape sequences.
  • System.out.println() -> Prints a new line at the end.
  • System.out.printf()
  • System.out.format()
class PrintingWays {
    public static void main(String[] arr) {
        int d = 25;
        float m = 4.21f;
        char c = 'D';
       
        String name = new String("Deepak Chandra Sharma");
        System.out.printf("The int value is %d \nThe float value is %f\n", d, m);
        System.out.printf("The character is %c\nThe string is %s", c, name);
       
        System.out.format("\nThe int value is %d \nThe float value is %f\n", d, m);
        System.out.format("The character is %c\nThe string is %s", c, name);
    }
}

Output :

The int value is 25
The float value is 4.210000
The character is D
The string is Deepak Chandra Sharma
The int value is 25
The float value is 4.210000
The character is D
The string is Deepak Chandra Sharma

String Methods in Java

String methods operate on Java Strings. Some of the commonly used String methods are:

MethodsDescription
length()Returns the length of String.
toLowerCase()Converts all the characters of the string to the lower case letters.
toUpperCase()Converts all the characters of the string to the upper case letters.
trim()Removes beginning and ending spaces of the string.
substring(start_index)Returns a substring from start index to the end.
substring(start_index, end_index)Returns a substring from the start index to the end index.
replace("old character", "new character")It replaces all occurences of the specified char value.
startsWith("character")Returns true if the string begins with "character".
endsWith("character")Returns true if the string ends with "character".
charAt(index)Returns the character at a given index position.
indexOf("character")Returns the index of the first occurrence of the specified character in given string.
lastIndexOf("character")Returns the last index of the specified character.
equals("other_string")Returns true if the string equals to the other_string in inverted commas.
equalsIgnoreCase("other_string")Returns true if the string equals to the other_string ignoring the case of characters.

class Main {
    public static void main(String arr[]) {
        String name = "  DEEPAK sharma  ";
        int len = name.length();
        System.out.println("The length of string is : " + len);
        String low = name.toLowerCase();
        System.out.println("The lower case string is : " + low);
        String up = name.toUpperCase();
        System.out.println("The upper case string is : " + up);
        System.out.println("The trimmed string is : " + name.trim());
        System.out.println("The sub-string from sixth position is : " + name.substring(5));
        System.out.println("The sub-string from sixth position to thirteenth position is : " + name.substring(5, 13));
        System.out.println("The new string with some replaced words is : '" + name.replace('a', 'e'));
        System.out.println("The new string with a group of replaced words is : '" + name.replace("a", "Aa"));
        System.out.println("Is the string starts with '  DEE' ?: " + name.startsWith("  DEE"));
        System.out.println("Is the string ends with 'ma' ?: " + name.endsWith("ma"));
        System.out.println("What is the character at position 3 ?: " + name.charAt(2));
        System.out.println("What is the index of 'a' ?: " + name.indexOf("a"));
        System.out.println("What is the index of 'a' counting starting from position 3 ?: " + name.indexOf("a", 2));
        System.out.println("What is the last index of 'a' ?: " + name.lastIndexOf("a"));
        System.out.println("What is the last index of 'a' checking from position 17 : " + name.lastIndexOf("a", 16));
        System.out.println("Is the string equals to '  DEEPAK sharma  ' ?: " + name.equals("  DEEPAK sharma  "));
        System.out.println("Is the string equals to '  Deepak Sharma  ' ignoring sensitivity of cases ?: "
                + name.equalsIgnoreCase("  Deepak Sharma  "));
    }
}

Output :

The length of string is : 17
The lower case string is : deepak sharma
The upper case string is : DEEPAK SHARMA
The trimmed string is : DEEPAK sharma
The sub-string from sixth position is : PAK sharma
The sub-string from sixth position to thirteenth position is : PAK shar
The new string with some replaced words is : ' DEEPAK sherme
The new string with a group of replaced words is : ' DEEPAK shAarmAa
Is the string starts with ' DEE' ?: true
Is the string ends with 'ma' ?: false
What is the character at position 3 ?: D
What is the index of 'a' ?: 11
What is the index of 'a' counting starting from position 3 ?: 11
What is the last index of 'a' ?: 14
What is the last index of 'a' checking from position 17 : 14
Is the string equals to ' DEEPAK sharma ' ?: true
Is the string equals to ' Deepak Sharma ' ignoring sensitivity of cases ?: true

Note: We can also compare with == operator, but this checks the object reference while equals() methods checks the value. If two strings having same value but one will be in heap and other in the String constant pool, then == will return false, while equals() method will return true.

Previous

Next

Comments