Java
Beginner
1 min read
Strings, StringBuilder, and Variable Scope
Example
public class StringsAndScope {
// Class-level constant (static final)
private static final int MAX_ITEMS = 100;
// Instance variable
private String label;
public StringsAndScope(String label) {
this.label = label; // 'this' disambiguates instance vs parameter
}
public void demonstrateStrings() {
// String immutability
String s = "hello";
s.toUpperCase(); // returns new String, does NOT modify s
System.out.println(s); // still "hello"
String upper = s.toUpperCase(); // must capture return value
System.out.println(upper); // "HELLO"
// Common String methods
String text = " Java Programming ";
System.out.println(text.trim()); // "Java Programming"
System.out.println(text.trim().length()); // 16
System.out.println(text.contains("Java")); // true
System.out.println(String.join(", ", "a", "b", "c")); // "a, b, c"
// StringBuilder for efficient concatenation
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 5; i++) {
sb.append("item").append(i);
if (i < 5) sb.append(", ");
}
System.out.println(sb.toString()); // "item1, item2, item3, item4, item5"
sb.reverse();
System.out.println(sb.toString());
// Block scope demo
int outer = 10;
{
int inner = 20; // only visible inside this block
System.out.println("inner + outer = " + (inner + outer));
}
// System.out.println(inner); // compile error — inner is out of scope
System.out.println("MAX_ITEMS = " + MAX_ITEMS);
System.out.println("label = " + label);
}
public static void main(String[] args) {
new StringsAndScope("demo").demonstrateStrings();
}
}