← Back to Courses
© 2025 sampathirao yoganandh
Week 6 · CO-1

Static, this, final & String Handling

Static fields/methods/blocks, this reference, final keyword, String handling  CO-1

Static Members

The static keyword belongs to the class rather than to any instance. Static members are shared across all objects of a class.

FeatureStaticNon-Static (Instance)
MemoryAllocated once (class load)Allocated per object
AccessClassName.memberobjectRef.member
Can accessOnly static members directlyBoth static and instance
ExampleMath.PI, Math.sqrt()obj.length, obj.getArea()
class Counter {
    static int count = 0; // shared by all objects
    int id;

    Counter() {
        count++;
        id = count;
    }

    static void showCount() {
        // can NOT access 'id' here — id is instance variable
        System.out.println("Total objects: " + count);
    }
}

Counter c1 = new Counter();
Counter c2 = new Counter();
Counter.showCount(); // Output: Total objects: 2

Static Block

A static block is executed once, when the class is first loaded into memory — before the main() method runs. Used for complex static initializations.

class Config {
    static String dbUrl;
    static int port;

    static {  // runs once at class load time
        dbUrl = "jdbc:mysql://localhost/college";
        port  = 3306;
        System.out.println("Config loaded.");
    }
}

this Reference

The this keyword refers to the current class instance. Its four main uses:

  1. Differentiate instance variable from local variable with the same name
  2. Pass the current object as an argument to a method
  3. Return the current object from a method (method chaining)
  4. Call another constructor in the same class using this()
class Builder {
    int x, y;

    Builder setX(int x) { this.x = x; return this; } // method chaining
    Builder setY(int y) { this.y = y; return this; }

    Builder(int x) {
        this(x, 0); // calls Builder(int,int) — must be first line
    }
    Builder(int x, int y) { this.x = x; this.y = y; }
}

// Method chaining usage
Builder b = new Builder(0).setX(10).setY(20);

final Keyword

The final keyword restricts further modification.

Applied ToEffect
VariableBecomes a constant — cannot be reassigned
MethodCannot be overridden in subclass
ClassCannot be extended (inherited)
final class Immutable {         // cannot be subclassed
    final double PI = 3.14159;    // constant

    final void show() {            // cannot be overridden
        System.out.println("PI = " + PI);
    }
}
📌 Key PointThe String class in Java is declared final — you cannot extend String. This is why String is immutable.

String Class

Strings in Java are immutable objects of the java.lang.String class. Once created, their value cannot be changed.

Important String Methods

MethodDescriptionExample
length()Returns string length"Java".length() → 4
charAt(i)Returns char at index i"Java".charAt(1) → 'a'
substring(s,e)Extracts [s,e)"Hello".substring(1,4) → "ell"
indexOf(str)First occurrence index"Hello".indexOf("l") → 2
toUpperCase()Converts to uppercase"java".toUpperCase() → "JAVA"
toLowerCase()Converts to lowercase"JAVA".toLowerCase() → "java"
trim()Removes leading/trailing spaces" hi ".trim() → "hi"
replace(o,n)Replace all occurrences"aaa".replace('a','b') → "bbb"
equals(s)Content comparison"hi".equals("hi") → true
equalsIgnoreCase(s)Case-insensitive compare"Hi".equalsIgnoreCase("hi") → true
split(regex)Splits into array"a,b,c".split(",") → ["a","b","c"]
contains(s)Checks if substring present"Hello".contains("ell") → true
startsWith(s)Checks prefix"Java".startsWith("Ja") → true
⚠️ ImportantNever compare strings with ==. Use .equals(). The == operator compares references (memory addresses), not content.

StringBuffer & StringBuilder

FeatureStringStringBufferStringBuilder
MutableNoYesYes
Thread-safeYes (immutable)Yes (synchronized)No
PerformanceSlow (creates new object)ModerateFastest
Use whenFixed stringsMulti-threaded envSingle-threaded
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");   // Hello World
sb.insert(5, ",");      // Hello, World
sb.reverse();            // dlroW ,olleH
sb.delete(0, 6);        // ,olleH
sb.replace(0, 1, "!");  // !olleH
System.out.println(sb.toString());

StringTokenizer

StringTokenizer (in java.util) splits a string into tokens based on a delimiter.

import java.util.StringTokenizer;

String csv = "Ravi,22,Computer Science,9.1";
StringTokenizer st = new StringTokenizer(csv, ",");

while (st.hasMoreTokens()) {
    System.out.println(st.nextToken());
}
// Output: Ravi  22  Computer Science  9.1
📄

Download PDF Notes

Save these notes as a PDF for offline reference

View / Download PDF