Common Interfaces in java.lang
Interface | Purpose | Key Methods |
---|---|---|
Appendable | Allows an object to receive appended character sequences. Implemented by classes like StringBuilder , StringBuffer , Writer . | append(CharSequence csq) , append(char c) |
CharSequence | Represents a readable sequence of char values. Implemented by String , StringBuilder , StringBuffer , CharBuffer . | length() , charAt(int index) , subSequence(int start, int end) |
Cloneable | Marks classes whose objects can be cloned using Object.clone() . (Marker interface — no methods). | (No methods) |
Comparable<T> | Defines a natural ordering for objects of a class. Used in sorting. Implemented by String , Integer , Double , etc. | compareTo(T o) |
Iterable<T> | Allows an object to be the target of an enhanced for loop (for-each ). Implemented by Collection , List , Set , etc. | iterator() |
Readable | Represents a source of characters that can be read into a CharBuffer . | read(CharBuffer cb) |
Runnable | Represents a task that can be executed by a thread. Implemented by Thread and custom task classes. | run() |
Quick Examples
Comparable
class Student implements Comparable<Student> {
int marks;
Student(int marks) { this.marks = marks; }
@Override
public int compareTo(Student other) {
return Integer.compare(this.marks, other.marks);
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student(80);
Student s2 = new Student(90);
System.out.println(s1.compareTo(s2)); // negative (less than)
}
}
Runnable
class MyTask implements Runnable {
@Override
public void run() {
System.out.println("Task is running");
}
}
public class Main {
public static void main(String[] args) {
Thread t = new Thread(new MyTask());
t.start();
}
}
Marker Interfaces
Some interfaces like Cloneable
have no methods — they are “marker interfaces” used by the JVM or APIs to check if a class has special capabilities.
✅ Summary
java.lang
interfaces are fundamental building blocks.- Some define contracts (
Comparable
,Runnable
), others are markers (Cloneable
). - Many are implemented by core Java classes (
String
,Thread
,StringBuilder
, etc.).