DEV Community

Cover image for 2. Basic String operations
Souravsing Pardeshi
Souravsing Pardeshi

Posted on

2. Basic String operations

Declaring string and assigning value to it

public class main{
    public static void main(String[] args){
        String str1 = " hello world";
        System.out.println(str1);
    }
}
Enter fullscreen mode Exit fullscreen mode

Concatination of strings

public class main{
    public static void main(String[] args){
        String str1 = " hello world";
        String str2 = "India";
        String str3 = str1+str2;
        System.out.println(str3);
    }
}
Enter fullscreen mode Exit fullscreen mode

Accessing element from its position

public class main{
    public static void main(String[] args){
        String str1 = " hello world";
        //charAt(pos) is used to access element in string at pos position.
        System.out.println(str1.charAt(2));
    }
}
Enter fullscreen mode Exit fullscreen mode

Getting substring from string

public class main{
    public static void main(String[] args){
        String str1 = " hello world";
        //substring get substring from a string by accepting starting and ending position.
        System.out.println(str1.substring(2,4));
    }
}
Enter fullscreen mode Exit fullscreen mode

Using split method

public class main{
    public static void main(String[] args){
        String str1 = "A,B,C,D";
        String str2 = "H I J k";
        //will split string by using , as identifier
        String [] arr1 = str1.split(",");
        // will split string by using space as identifier
        String [] arr2 = str2.split(" ");
    }
}
Enter fullscreen mode Exit fullscreen mode

String inbuilt methods

public class main{
    public static void main(String[] args){
        String str1 = " hello world";
        // will return length of string
        System.out.println(str1.length());
        // will convert all char to uppercase
        System.out.println(str1.toUpperCase());
        //check if string starts with "h"
        System.out.println(str1.startsWith("h"));
        //check if string ends with "h"
        System.out.println(str1.endsWith("h"));
        //will find index of "ll"
        System.out.println(str1.indexOf("ll"));
        // will return index of last occurence if "hello"
        System.out.println(str1.lastIndexOf("hello"));
        //will replace hello with bye
        System.out.println(str1.replace("hello", "bye"));
        System.out.println(str1);
        System.out.println(Integer.toBinaryString(a));
        System.out.println(Integer.toHexString(a));
        System.out.println(Integer.parseInt(Integer.toString(a)));
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)