String in java language.

                        String in java


■ Declaration->

                            String name = "Ved";

■ Taking Input->

     Scanner sc = new Scanner(System.in);

     String name = sc.next();


               String function in java 


1● Concatenation-> 

                                    Joining 2 strings

example->

String firstName = "ved";

String secondName = "varshney";

String fullName = firstName + " " + secondName;

System.out.println(fullName);

_____________________________________________

 2● length ->

                      Print length of a String

example->

String firstName = "ved";

String secondName = "varshney";

String fullName = firstName + " " + secondName;

System.out.println(fullName.length());

______________________________________________

3● charAt->

                      Access characters of a string

example->

String firstName = "ved";

String secondName = "varshney";

String fullName = firstName + " " + secondName;

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

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

}

_______________________________________________

4● compare->

                          Compare 2 strings

example->

import java.util.*;

public class Strings {

public static void main(String args[]) {

String name1 = "ved";

String name2 = "ved";

if(name1.compareTo(name2)) {

System.out.println("They are the same string");

} else {

System.out.println("They are different strings");

}

//DO NOT USE == to check for string equality

//Gives correct answer here

if(name1 == name2) {

System.out.println("They are the same string");

} else {

System.out.println("They are different strings");

}

//Gives incorrect answer here

if(new String("ved") == new String("ved")) {

System.out.println("They are the same string");

} else {

System.out.println("They are different strings");

}

}

}

_____________________________________________

5● Substring->

                             The substring of a string is a subpart of it.

example->

class Strings {

public static void main(String args[]) {

String name = "vedvarshney";

System.out.println(name.substring(0, 3));

______________________________________________

Comments

Popular posts from this blog

Introduction of java Programming language.

Stack data structure.