Java Doc
Table of Contents
1. Data Types
2. Simple statements: printing & for-loop
3. Object-Oriented Programming (OOP) in Java
o Classes & Objects
o Encapsulation
o Inheritance
o Polymorphism (compile-time & runtime)
o Abstraction
o Constructors & this keyword
o static keyword
4. Input from the user
5. Arrays and common operations (methods)
6. ArrayList and its common methods
7. String and its common methods
8. Wrapper classes
9. Interfaces
10. Quick reference: common pitfalls & best practices
1. Data Types
Java is statically typed: every variable has a type known at compile-time.
Primitive data types (8)
• byte — 8-bit signed (-128 to 127)
• short — 16-bit signed
• int — 32-bit signed (default for integers)
• long — 64-bit signed (use L suffix for literals, e.g., 123L)
• float — 32-bit floating point (use f suffix: 1.2f)
• double — 64-bit floating point (default for decimals)
• char — 16-bit Unicode character (single quotes \'a\')
• boolean — true or false
Memory & performance note: int and double are most commonly used. Use smaller
types (byte, short) only when memory matters.
Reference types (objects)
• Any class, interface, or array type: e.g., String, Integer, int[],
ArrayList<String>.
• Reference variables hold pointers to objects stored on the heap. They can be null.
Type conversion
• Widening (implicit): int → long → float → double.
• Narrowing (explicit cast): (int) 3.9.
• Autoboxing/unboxing: automatic conversion between primitives and wrappers (e.g.,
int ↔ Integer).
2. Simple statements: printing & for-loop
Printing
[Link]("Hello, world!"); // prints with newline
[Link]("No newline"); // prints without newline
[Link]("Name: %s, Age: %d\n", name, age); // formatted output
For-loop (classic and enhanced)
// classic for-loop
for (int i = 0; i < 5; i++) {
[Link](i);
}
// enhanced for-loop (for-each) for arrays and Iterable
int[] arr = {1, 2, 3};
for (int x : arr) {
[Link](x);
}
3. Object-Oriented Programming (OOP) in Java
Java is built around OOP. Key pillars: Encapsulation, Inheritance, Polymorphism,
Abstraction.
Classes & Objects
public class Person {
// fields
private String name;
private int age;
// constructor
public Person(String name, int age) {
[Link] = name;
[Link] = age;
}
// method
public void sayHello() {
[Link]("Hi, I'm " + name);
}
}
// usage
Person p = new Person("Riya", 21);
[Link]();
Encapsulation
• Keep fields private and expose public getters/setters.
• Validates data and hides internal representation.
public void setAge(int age) {
if (age >= 0) [Link] = age;
}
Inheritance
• extends keyword; single inheritance for classes.
• super to call parent constructor/methods.
class Employee extends Person {
private String empId;
public Employee(String name, int age, String empId) {
super(name, age);
[Link] = empId;
}
}
Polymorphism
• Compile-time (method overloading) — multiple methods with same name but
different parameters.
• Runtime (method overriding) — subclass provides specific implementation of a
method.
// Overloading
public void print(String s) {}
public void print(int n) {}
// Overriding
@Override
public String toString() { return "..."; }
Abstraction
• Achieved using abstract classes and interfaces.
• abstract class may have concrete methods and state; interface (Java 8+) may have
default/static methods.
Constructors & this
• No-arg constructor provided if none defined.
• this(...) calls another constructor in same class.
static keyword
• static fields/methods belong to the class, not instances. Use for constants or
utilities.
4. Input from the user
Common options: Scanner (standard), BufferedReader with InputStreamReader, and
Console (when available).
Using Scanner (simple)
import [Link];
Scanner sc = new Scanner([Link]);
[Link]("Enter name: ");
String name = [Link]();
[Link]("Enter age: ");
int age = [Link]();
[Link](); // consume newline if mixing nextInt() & nextLine()
Notes: Scanner is easy but slower than buffered readers for large input. Always close
Scanner when done: [Link]();.
Using BufferedReader (fast)
import [Link];
import [Link];
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
String line = [Link]();
int x = [Link]([Link]());
5. Arrays and common operations (methods)
Java arrays are fixed-size, typed containers.
Declaration & initialization
int[] a = new int[5];
int[] b = {1, 2, 3};
String[] s = new String[]{"a", "b"};
Common operations
• [Link] — size of array.
• Iterate with for-loop or enhanced for-loop.
for (int i = 0; i < [Link]; i++) { /* ... */ }
for (int x : b) { /* ... */ }
Utility methods from [Link]
import [Link];
[Link](a); // print array
[Link](a); // sort
int idx = [Link](a, key); // binary search (array must be
sorted)
int[] copy = [Link](a, newLength);
[Link](a, b);
[Link](a, 0);
Multi-dimensional arrays
int[][] mat = new int[3][4];
mat[0][1] = 5;
Time complexity: indexing O(1), scanning O(n), sorting O(n log n) with [Link]().
6. ArrayList and its common methods
ArrayList is a resizable array implementation of List interface.
Import & creation
import [Link];
ArrayList<String> list = new ArrayList<>();
ArrayList<Integer> nums = new ArrayList<>(10); // initial capacity
Common methods
• add(E e) — append element.
• add(int index, E e) — insert at index.
• get(int index) — get element.
• set(int index, E e) — replace element.
• remove(int index) / remove(Object o) — remove by index or value.
• size() — current size.
• isEmpty() — check empty.
• contains(Object o) — membership test.
• indexOf(Object o) / lastIndexOf(Object o).
• clear() — remove all elements.
• toArray() — convert to array.
[Link]("apple");
String first = [Link](0);
[Link]("apple");
int n = [Link]();
Performance - get and set are O(1). - add(e) amortized O(1) (may be O(n) when resizing). -
add(index, e) and remove(index) are O(n) due to shifting.
7. String and its common methods
Strings are immutable objects of [Link].
Creation
String s1 = "hello"; // string pool
String s2 = new String("hello"); // new object
Common methods
• length()
• charAt(int index)
• substring(int beginIndex) / substring(int begin, int end)
• indexOf(String) / lastIndexOf(String)
• contains(CharSequence)
• equals(Object) and equalsIgnoreCase(String)
• compareTo(String)
• toLowerCase() / toUpperCase()
• trim() — remove leading/trailing whitespace
• replace(CharSequence, CharSequence) / replaceAll(String regex, String
replacement)
• split(String regex) — returns String[]
• startsWith / endsWith
• format(...) and StringBuilder for heavy concatenation
StringBuilder / StringBuffer
• Use StringBuilder for efficient mutable string operations (not thread-safe).
• StringBuffer is thread-safe (synchronized) but slower.
StringBuilder sb = new StringBuilder();
[Link]("Hello").append(' ').append("World");
String result = [Link]();
Note: Concatenating many strings with + inside loops creates many temporary String
objects; prefer StringBuilder.
8. Wrapper Classes
For each primitive, Java provides a wrapper class in [Link]: - Byte, Short, Integer,
Long, Float, Double, Character, Boolean.
Uses
• Required when primitives are stored in collections (ArrayList<Integer>).
• Provide utility methods: [Link](String), [Link](...).
Autoboxing / Unboxing
Integer a = 5; // autoboxing
int b = a; // unboxing
Caveat: Using wrappers can introduce NullPointerException if the wrapper is null and
you unbox it.
9. Interfaces
An interface declares a contract of methods a class must implement. Since Java 8,
interfaces can have default and static methods; since Java 9, private methods.
Basic interface
public interface Drawable {
void draw(); // public abstract by default
}
class Circle implements Drawable {
@Override
public void draw() {
[Link]("Drawing circle");
}
}
Multiple inheritance of type
A class can implement multiple interfaces.
interface A { void a(); }
interface B { void b(); }
class C implements A, B { ... }
Default & static methods (since Java 8)
public interface Logger {
default void log(String msg) { [Link](msg); }
static void info(String msg) { [Link]("INFO: " + msg); }
}
Functional interfaces
• Single abstract method (SAM). Usable with lambda expressions. Examples:
Runnable, Comparator<T>, Function<T,R>.
Runnable r = () -> [Link]("Run");
10. Quick reference: common pitfalls & best practices
• Nulls: Always validate references before use. Prefer [Link]() for
defensive programming.
• Equality: Use equals() for object equality (not ==), except == for primitives and
reference identity.
• Immutable objects: String is immutable; use StringBuilder for heavy
modifications.
• Concurrency: For thread safety, explore synchronized, volatile, and concurrent
collections in [Link].
• Resource management: Use try-with-resources for I/O: try (BufferedReader br
= ...) { ... }.
• Avoid premature optimization: Write clear code, then profile.
Appendix — Examples
Simple program: read names, store in ArrayList, print sorted
import [Link].*;
public class NamesApp {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
ArrayList<String> names = new ArrayList<>();
[Link]("Enter names (blank line to stop):");
while (true) {
String line = [Link]();
if ([Link]().isEmpty()) break;
[Link]([Link]());
}
[Link](names);
[Link]("Sorted names:");
for (String n : names) [Link](n);
[Link]();
}
}