Strings in Java
Strings in Java
• String str2=“Programming”;
How To Access Individual Characters from String
Output:
o
• Use length() Method
• Returns number of characters in string
Example:
String str=“Java”;
System.out.println(str.length());
Output:
4
How To Input String?
• Use Scanner class and next() or nextLine() Methods
import java.util.Scanner;
public class StringInput {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
String name;
System.out.print("What is your name?");
name = input.next( ); //get one word string, no space
Or
name=input.nextLine(); //get multiple word string-(space)
System.out.print(“Your Name is:”+name);
}
}
How To Input String? Method-II
• Use JOptionPane Class, showInputDialog() method
import javax.swing.JOptionPane;
class StringInput2
{
public static void main(String[] args)
{
String name=JOptionPane.showInputDialog("Enter Name");
System.out.println(name);
JOptionPane.showMessageDialog(null,name);
System.exit(0);
}
}
Display All Chars of String
}
}
String Comparison
string 1
String Comparison
Example:
• String s1=“abc”;
• String s2=“abc”;
• If(s1.equals(s2))
JOptionPane.showMessageDialog(null,“Same”);
else
JOptionPane.showMessageDialog(null,“Different”);
String Concatenation
• Use concat() Method or + Operator
• Returns concatenated String
Example:
• String s1=“Hello”;
• String s2=“ Java”;
• String s3=s1.concat(s2);
• String s4=s1 + s2;
JOptionPane.showMessageDialog(null,s3);
JOptionPane.showMessageDialog(null,s4);