[Go to site: main page, start]

0% found this document useful (0 votes)
10 views12 pages

01 Java Coding

Uploaded by

apnacourse26
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views12 pages

01 Java Coding

Uploaded by

apnacourse26
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Coding

Complete Notes for Capgemini L1 Exam

Topics Covered in This PDF


• OOP Concepts — Classes, Objects, Inheritance, Polymorphism

• Abstraction & Encapsulation — Interface vs Abstract Class

• Java Collections Framework — List, Set, Map, Queue

• Java 8+ Features — Lambda, Streams, Optional

• String Manipulation — Common Methods & Patterns

• Exception Handling — try/catch/finally, Custom Exceptions

• Common Coding Patterns for Exam Questions

Capgemini L1 Exam Prep | Java Foundation Track | 120 min | 17 Questions


Chapter 1: Object-Oriented Programming (OOP)
OOP is the foundation of Java. Every program you write in Java revolves around 4 pillars: Encapsulation,
Inheritance, Polymorphism, and Abstraction. Understanding these deeply will help you write cleaner code
and ace MCQs.

1.1 Classes and Objects


A class is a blueprint/template. An object is a real-world instance created from that blueprint.
// Class definition
public class Car {
// Instance variables (state)
String brand;
int speed;

// Constructor — called when object is created


public Car(String brand, int speed) {
[Link] = brand; // 'this' refers to current object
[Link] = speed;
}

// Method (behavior)
public void accelerate(int increase) {
[Link] += increase;
[Link](brand + " now at " + speed + " km/h");
}
}

// Creating objects
Car c1 = new Car("Toyota", 60);
Car c2 = new Car("BMW", 80);
[Link](20); // Toyota now at 80 km/h

TIP: this keyword: refers to the current object. Used to distinguish between instance variable and
parameter with same name.

1.2 Encapsulation
Wrapping data (variables) and methods together, and hiding internal details using access modifiers. Think
of it as a capsule that protects data.
public class BankAccount {
private double balance; // private = hidden from outside

public double getBalance() { // getter


return balance;
}
public void deposit(double amount) { // setter with validation
if (amount > 0) balance += amount;
}
}

// Usage:
BankAccount acc = new BankAccount();
[Link](1000);
[Link]([Link]()); // 1000.0
// [Link] = -5000; ERROR! private field

private Accessible only within the same class

default Accessible within the same package

protected Accessible in same package + subclasses

public Accessible from everywhere

1.3 Inheritance
A child class (subclass) inherits properties and methods from a parent class (superclass). Use keyword
extends. Java supports single inheritance only (a class can extend only one class).
// Parent class
public class Animal {
String name;
public Animal(String name) { [Link] = name; }

public void eat() {


[Link](name + " is eating");
}
public void sleep() {
[Link](name + " is sleeping");
}
}

// Child class
public class Dog extends Animal {
String breed;
public Dog(String name, String breed) {
super(name); // calls parent constructor
[Link] = breed;
}
public void bark() {
[Link](name + " says: Woof!");
}
}

// Usage
Dog d = new Dog("Rex", "Labrador");
[Link](); // inherited from Animal
[Link](); // Dog's own method
[Link](); // inherited from Animal

TIP: super keyword: used to call the parent class constructor or method. super() must be the FIRST
statement in the child constructor.

1.4 Polymorphism
Poly = many, morph = forms. One interface, many implementations. Two types: Compile-time (Method
Overloading) and Runtime (Method Overriding).

Method Overloading (Compile-time Polymorphism)


Same method name, different parameters in the SAME class.
public class Calculator {
// Same name, different params — overloading
public int add(int a, int b) { return a + b; }
public double add(double a, double b) { return a + b; }
public int add(int a, int b, int c) { return a + b + c; }
}

Calculator c = new Calculator();


[Link](2, 3); // calls first method -> 5
[Link](2.5, 3.5); // calls second method -> 6.0
[Link](1, 2, 3); // calls third method -> 6

Method Overriding (Runtime Polymorphism)


Child class provides its own implementation of a method already in the parent.
public class Shape {
public double area() { return 0; }
}

public class Circle extends Shape {


double radius;
public Circle(double r) { [Link] = r; }

@Override
public double area() {
return [Link] * radius * radius;
}
}

public class Rectangle extends Shape {


double w, h;
public Rectangle(double w, double h) { this.w = w; this.h = h; }

@Override
public double area() { return w * h; }
}

// Runtime polymorphism: Shape reference, actual object determines method


Shape s1 = new Circle(5);
Shape s2 = new Rectangle(4, 6);
[Link]([Link]()); // 78.53 — [Link]() called
[Link]([Link]()); // 24.0 — [Link]() called

NOTE: Always use @Override annotation when overriding — it lets the compiler verify you are
correctly overriding.

1.5 Abstraction
Hiding implementation details, showing only essential features. Achieved through Abstract Classes and
Interfaces.

Abstract Class
public abstract class Vehicle {
String brand;
// Abstract method: no body, subclass MUST implement
public abstract void start();

// Concrete method: has body


public void stop() {
[Link](brand + " stopped.");
}
}

public class Motorcycle extends Vehicle {


@Override
public void start() {
[Link]("Motorcycle kick-started!");
}
}
// Cannot do: Vehicle v = new Vehicle(); — ERROR, abstract class can't be instantiated

Interface
public interface Flyable {
// All methods are public abstract by default
void fly();
void land();

// Java 8+: default method (has a body)


default void refuel() {
[Link]("Refueling...");
}
}

public class Airplane implements Flyable {


@Override
public void fly() { [Link]("Airplane taking off!"); }
@Override
public void land() { [Link]("Airplane landing!"); }
}

Can have constructors, instance variables, concrete methods.


Abstract Class Single inheritance.

No constructors. Variables are public static final. Multiple


Interface implementation allowed.

When subclasses share common state/behavior (IS-A


When to use AC relationship)

When to use I When unrelated classes share capability (CAN-DO relationship)


Chapter 2: Java Collections Framework
Collections Framework provides ready-made data structures. You do NOT need to implement them from
scratch. Key interfaces: List, Set, Map, Queue.

2.1 List — Ordered, Allows Duplicates


import [Link].*;

// ArrayList — dynamic array, fast random access


List<String> fruits = new ArrayList<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Apple"); // duplicates allowed
[Link](1, "Mango"); // insert at index 1

[Link]([Link](0)); // Apple
[Link]([Link]()); // 4
[Link]("Banana");
[Link](0); // remove by index
[Link](fruits); // sort alphabetically

// Iterate
for (String f : fruits) [Link](f);

// LinkedList — fast insert/delete, slow random access


LinkedList<Integer> nums = new LinkedList<>();
[Link](10);
[Link](20);
[Link](15);
[Link]([Link]()); // 10

2.2 Set — No Duplicates


// HashSet — no order, O(1) operations
Set<String> set = new HashSet<>();
[Link]("Dog"); [Link]("Cat"); [Link]("Dog"); // Dog added once
[Link]([Link]()); // 2

// LinkedHashSet — insertion order maintained


Set<String> linked = new LinkedHashSet<>();
[Link]("Banana"); [Link]("Apple"); [Link]("Cherry");
// prints: Banana Apple Cherry (in insertion order)

// TreeSet — sorted order


Set<Integer> tree = new TreeSet<>();
[Link](5); [Link](1); [Link](3);
[Link](tree); // [1, 3, 5] — sorted!

// Check membership
[Link]([Link]("Cat")); // true

2.3 Map — Key-Value Pairs


// HashMap — unordered, one null key allowed
Map<String, Integer> scores = new HashMap<>();
[Link]("Alice", 95);
[Link]("Bob", 87);
[Link]("Alice", 99); // overwrites previous value
[Link]([Link]("Alice")); // 99
[Link]([Link]("Charlie", 0)); // 0

// Iterate map
for ([Link]<String, Integer> entry : [Link]()) {
[Link]([Link]() + " -> " + [Link]());
}

// LinkedHashMap — insertion order


// TreeMap — sorted by key
Map<String, Integer> sorted = new TreeMap<>(scores);

// Common operations
[Link]("Bob"); // true
[Link](99); // true
[Link]("Bob");
[Link](); // 1

2.4 Queue and Stack


// Queue — FIFO (First In First Out)
Queue<String> queue = new LinkedList<>();
[Link]("first"); // add to back
[Link]("second");
[Link]("third");
[Link]([Link]()); // removes and returns "first"
[Link]([Link]()); // returns "second" without removing

// Stack — LIFO (Last In First Out)


Stack<Integer> stack = new Stack<>();
[Link](10);
[Link](20);
[Link](30);
[Link]([Link]()); // 30
[Link]([Link]()); // 20

// Deque (double-ended) — modern alternative to Stack


Deque<String> deque = new ArrayDeque<>();
[Link]("A"); [Link]("B"); // push to front
[Link]("C"); // add to back
[Link]([Link]()); // B (front)
Chapter 3: Java 8+ Features

3.1 Lambda Expressions


Lambda is a short block of code which takes in parameters and returns a value. Think of it as an
anonymous function. Syntax: (params) -> expression
// Before Java 8 — anonymous class
Runnable r1 = new Runnable() {
@Override
public void run() { [Link]("Running!"); }
};

// Java 8 Lambda — much cleaner!


Runnable r2 = () -> [Link]("Running!");

// With parameters
Comparator<String> comp = (a, b) -> [Link](b);

// Sort list with lambda


List<String> names = [Link]("Charlie", "Alice", "Bob");
[Link]((a, b) -> [Link](b));
// Or even shorter with method reference:
[Link](String::compareTo);

[Link](names); // [Alice, Bob, Charlie]

3.2 Streams API


Streams let you process collections in a functional, declarative way. Key operations: filter, map, collect,
reduce, forEach, sorted, distinct, count.
import [Link].*;

List<Integer> numbers = [Link](1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

// filter — keep elements matching condition


List<Integer> evens = [Link]()
.filter(n -> n % 2 == 0)
.collect([Link]());
// [2, 4, 6, 8, 10]

// map — transform each element


List<Integer> doubled = [Link]()
.map(n -> n * 2)
.collect([Link]());
// [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

// filter + map + collect combo


List<String> names = [Link]("Alice", "Bob", "Anna", "Charlie");
List<String> aNames = [Link]()
.filter(name -> [Link]("A"))
.map(String::toUpperCase)
.sorted()
.collect([Link]());
// [ALICE, ANNA]

// reduce — combine all elements


int sum = [Link]()
.reduce(0, (a, b) -> a + b); // 55

// count
long count = [Link]().filter(n -> n > 5).count(); // 5

// findFirst
Optional<Integer> first = [Link]()
.filter(n -> n > 7)
.findFirst();
[Link]([Link]::println); // 8

3.3 Optional
Optional is a container that may or may not contain a non-null value. It helps avoid NullPointerException.
Optional<String> opt1 = [Link]("Hello");
Optional<String> opt2 = [Link]();
Optional<String> opt3 = [Link](null); // won't throw NPE

[Link](); // true
[Link](); // false
[Link](); // "Hello"
[Link]("Default"); // "Default"
[Link](() -> "N/A"); // "N/A"
[Link]([Link]::println); // Hello

// Common stream pattern


List<String> list = [Link]("apple", "banana", "cherry");
String result = [Link]()
.filter(s -> [Link]("b"))
.findFirst()
.orElse("not found");
[Link](result); // banana

3.4 String Manipulation (Exam Favorite!)


String s = "Hello World";

// Length, case
[Link](); // 11
[Link](); // "HELLO WORLD"
[Link](); // "hello world"

// Substrings and searching


[Link](6); // "World"
[Link](0, 5); // "Hello"
[Link]("World"); // 6
[Link]("World"); // true
[Link]("He"); // true
[Link]("ld"); // true

// Splitting and trimming


String csv = " apple,banana,cherry ";
[Link](); // "apple,banana,cherry"
String[] parts = [Link]().split(","); // ["apple","banana","cherry"]

// Replace
[Link]("World", "Java"); // "Hello Java"
[Link]("[aeiou]", "*"); // "H*ll* W*rld" (regex)

// Character access
[Link](0); // 'H'
[Link](); // char array

// StringBuilder — mutable, faster for concatenation in loops


StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5; i++) [Link](i).append("-");
[Link]([Link]()); // 0-1-2-3-4-
[Link](); // reverse the string
[Link](0, ">>"); // insert at position
[Link](0, 2); // delete chars from 0 to 2

// [Link]
String msg = [Link]("Name: %s, Age: %d", "Alice", 30);

// Check palindrome
String word = "racecar";
String rev = new StringBuilder(word).reverse().toString();
boolean isPalin = [Link](rev); // true
Chapter 4: Exception Handling
// Basic try-catch-finally
public static int divide(int a, int b) {
try {
return a / b;
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero: " + [Link]());
return -1;
} catch (Exception e) {
[Link]("Unexpected error: " + [Link]());
return -1;
} finally {
[Link]("Finally always runs!"); // cleanup code
}
}

// Multiple exceptions in one catch (Java 7+)


try {
int[] arr = new int[5];
arr[10] = 1;
} catch (ArrayIndexOutOfBoundsException | NullPointerException e) {
[Link]("Array or null error: " + [Link]());
}

// Custom Exception
public class InsufficientFundsException extends Exception {
private double amount;
public InsufficientFundsException(double amount) {
super("Insufficient funds! Need: " + amount + " more.");
[Link] = amount;
}
public double getAmount() { return amount; }
}

public void withdraw(double amount) throws InsufficientFundsException {


if (amount > balance) {
throw new InsufficientFundsException(amount - balance);
}
balance -= amount;
}

// try-with-resources (auto closes resources)


try (BufferedReader br = new BufferedReader(new FileReader("[Link]"))) {
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
} catch (IOException e) {
[Link]();
}

Must be declared with throws or caught. E.g., IOException,


Checked Exceptions SQLException
RuntimeExceptions — not required to catch. E.g., NPE,
Unchecked Exceptions ArrayIndexOutOfBounds

Serious problems, not exceptions. E.g., StackOverflowError,


Error OutOfMemoryError

EXAM: Exam tip: "finally" block ALWAYS executes even if exception is thrown or return statement is
reached in try/catch.

You might also like