Java Strings: Full Beginner Programs Guide
Program 1: Hello String (create and print)
import [Link];
public class HelloString {
public static void main(String[] args) {
String greeting = "Hello";
String name = "Gia";
[Link](greeting);
[Link](name);
}
}
Output:
Hello
Gia
Program 2: Concatenate Strings and Mix with Numbers
import [Link];
public class ConcatAndNumber {
public static void main(String[] args) {
String first = "Good";
String second = "Morning";
[Link](first + " " + second);
int age = 15;
[Link]("I am " + age + " years old.");
}
}
Output:
Good Morning
I am 15 years old.
Program 3: length() and charAt()
import [Link];
public class LengthAndCharAt {
public static void main(String[] args) {
String word = "hello";
[Link]("length: " + [Link]());
[Link]("char at 0: " + [Link](0));
[Link]("char at 4: " + [Link](4));
}
}
Output:
length: 5
char at 0: h
char at 4: o
Program 4: Compare Strings with equals()
import [Link];
public class CompareStrings {
public static void main(String[] args) {
String a = "Hi";
String b = new String("Hi");
[Link]("[Link](b): " + [Link](b));
[Link]("a == b: " + (a == b));
}
}
Output:
[Link](b): true
a == b: false
Program 5: toUpperCase() and toLowerCase()
import [Link];
public class CaseMethods {
public static void main(String[] args) {
String word = "Java";
[Link]([Link]());
[Link]([Link]());
}
}
Output:
JAVA
java
Program 6: indexOf() and trim()
import [Link];
public class IndexOfAndTrim {
public static void main(String[] args) {
String s = " banana ";
[Link]("Before trim: '" + s + "'");
String t = [Link]();
[Link]("After trim: '" + t + "'");
[Link]("Index of 'a': " + [Link]("a"));
[Link]("Index of \"na\": " + [Link]("na"));
[Link]("Index of 'z' (not found): " + [Link]("z"));
}
}
Output:
Before trim: ' banana '
After trim: 'banana'
Index of 'a': 1
Index of "na": 2
Index of 'z' (not found): -1
Program 7: Loop Through a String
import [Link];
public class LoopThroughString {
public static void main(String[] args) {
String word = "apple";
for (int i = 0; i < [Link](); i++) {
[Link]([Link](i));
}
}
}
Output:
a
p
p
l
e
Program 8: Count How Many Times 'a' Appears
import [Link];
public class CountA {
public static void main(String[] args) {
Scanner input = new Scanner([Link]);
[Link]("Enter a word: ");
String word = [Link]();
int count = 0;
for (int i = 0; i < [Link](); i++) {
if ([Link](i) == 'a') {
count++;
}
}
[Link]("Number of 'a' characters: " + count);
[Link]();
}
}
Output:
Enter a word: banana
Number of 'a' characters: 3