Java Strings
Strings are implemented and used as objects of the String class. A detailed explanation of classes will come after learning about classes. Here, let’s look briefly at how to declare and use strings.
Displaying Strings
Strings can be declared and used immediately. By contrast, in C, strings are not easy to use because of memory-related concerns.
StringJava.java
package com.devkuma.tutorial.string;
public class StringJava {
public static void main(String[] args) {
String str = "This is java.";
System.out.println(str);
}
}
Execution result:
This is java.
String Concatenation
A String can also be combined with other data types.
package com.devkuma.tutorial.string;
public class StringConcat {
public static void main(String[] args) {
int i = 7;
System.out.println("The value of this i variable is " + i);
}
}
Execution result:
The value of this i variable is 7
The value of integer i is first converted to a string and then concatenated with the next string.
String Methods
Because a string is a class type, it has several methods.
Typical methods include length(), which gets the string length, charAt(), which gets the character at a specified index in the string, and equals(), which compares whether strings are equal. The details will be covered after learning about classes.
package com.devkuma.tutorial.string;
public class StringMethod {
public static void main(String[] args) {
String str1 = "abcdefghijklmnopqrstuvwxyz";
String str2 = "This is java";
String str3 = "abcdefghijklmnopqrstuvwxyz";
System.out.println("length=" + str1.length());
System.out.println("charAt=" + str1.charAt(3));
System.out.println("str1 equals str2=" + str1.equals(str2));
System.out.println("str1 equals str3=" + str1.equals(str3));
}
}
Execution result:
length=26
charAt=d
str1 equals str2=false
str1 equals str3=true