Static Members
The static keyword belongs to the class rather than to any instance. Static members are shared across all objects of a class.
| Feature | Static | Non-Static (Instance) |
|---|---|---|
| Memory | Allocated once (class load) | Allocated per object |
| Access | ClassName.member | objectRef.member |
| Can access | Only static members directly | Both static and instance |
| Example | Math.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: 2Static 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:
- Differentiate instance variable from local variable with the same name
- Pass the current object as an argument to a method
- Return the current object from a method (method chaining)
- 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 To | Effect |
|---|---|
| Variable | Becomes a constant — cannot be reassigned |
| Method | Cannot be overridden in subclass |
| Class | Cannot 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
| Method | Description | Example |
|---|---|---|
| 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
| Feature | String | StringBuffer | StringBuilder |
|---|---|---|---|
| Mutable | No | Yes | Yes |
| Thread-safe | Yes (immutable) | Yes (synchronized) | No |
| Performance | Slow (creates new object) | Moderate | Fastest |
| Use when | Fixed strings | Multi-threaded env | Single-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