0% found this document useful (0 votes)
2 views510 pages

Tcs Ipa Java

Java is a high-level, object-oriented programming language developed by Sun Microsystems in 1995, designed to be platform-independent with the principle of 'Write Once, Run Anywhere.' Key features include object-oriented principles, security, robustness, portability, and dynamic behavior. The document also covers Java's execution process, the differences between JDK, JRE, and JVM, and various types of variables and data types in Java.

Uploaded by

maneruturaj18
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)
2 views510 pages

Tcs Ipa Java

Java is a high-level, object-oriented programming language developed by Sun Microsystems in 1995, designed to be platform-independent with the principle of 'Write Once, Run Anywhere.' Key features include object-oriented principles, security, robustness, portability, and dynamic behavior. The document also covers Java's execution process, the differences between JDK, JRE, and JVM, and various types of variables and data types in Java.

Uploaded by

maneruturaj18
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

CORE JAVA FOR TCS IPA – Chapter 1: Introduction

to Java (Detailed Notes + MCQs)

What is Java?
Java is a high-level, object-oriented programming language developed by Sun Microsystems (now Oracle) in
1995.

Java was designed with the principle:

"Write Once, Run Anywhere (WORA)"

This means that a Java program is compiled only once and can run on any operating system (Windows,
Linux, macOS) that has a Java Virtual Machine (JVM).

Example:

Suppose you write a Java program on Windows.

public class Hello {


public static void main(String[] args){
[Link]("Hello");
}
}

After compilation, the generated .class file can run on Windows, Linux, or macOS without changing the
code.

Features of Java
1. Object-Oriented
Everything in Java revolves around objects and classes.

The four pillars of OOP are:

• Encapsulation
• Inheritance
• Polymorphism

1
• Abstraction

TCS MCQ

Which programming paradigm does Java mainly follow?

A) Procedural B) Functional C) Object-Oriented D) Logical

Answer: C

Explanation: Java is primarily an Object-Oriented Programming (OOP) language.

2. Platform Independent
This is the most frequently asked Java MCQ.

Java source code is converted into Bytecode.

Bytecode is platform independent.

The JVM of each operating system converts Bytecode into machine code.

Hence the same Bytecode runs on every OS.

Flow:

Java Source Code (.java)

Compiler (javac)

Bytecode (.class)

JVM

Machine Code

2

Output

Example:

The same [Link] file works on Windows, Linux, and macOS.

Important Interview Point

Java is Platform Independent.

JVM is Platform Dependent.

Bytecode is Platform Independent.

Machine Code is Platform Dependent.

3. Secure
Java is considered secure because:

• No pointers • Bytecode verifier checks code before execution • Automatic memory management • Class
Loader prevents unauthorized classes

4. Robust
Robust means reliable.

Java becomes robust because of:

• Exception Handling • Garbage Collection • Strong Memory Management • Type Checking

5. Portable
Java programs can be moved from one system to another without modification.

Reason: Bytecode is independent of the operating system.

3
6. Distributed
Java supports distributed applications through networking packages like:

[Link]

Example:

Client-Server Applications

7. Multithreaded
Java can execute multiple tasks simultaneously.

Example:

One thread downloads a file.

Another thread plays music.

Another thread updates the screen.

8. Dynamic
Java loads classes during runtime.

This allows programs to change behavior dynamically.

9. Architecture Neutral
Java Bytecode does not depend on CPU architecture.

It works on:

• Intel • AMD • ARM

10. High Performance


Java is faster than many interpreted languages because of the Just-In-Time (JIT) Compiler.

4
JIT converts Bytecode into Machine Code during execution.

Java Program Execution


Suppose the file is:

[Link]

Compile:

javac [Link]

Compiler creates:

[Link]

Run:

java Hello

Execution Process:

Step 1

Write

[Link]

Step 2

Compile

javac [Link]

Step 3

Compiler generates

[Link]

5

Step 4

JVM loads Bytecode

Step 5

JIT converts Bytecode into Machine Code

Step 6

CPU executes Machine Code

Output appears

JDK vs JRE vs JVM


JVM (Java Virtual Machine)
Purpose:

Runs Java Bytecode.

Responsibilities:

• Loads class files • Executes Bytecode • Performs Garbage Collection • Manages memory

Cannot compile Java code.

JRE (Java Runtime Environment)


Contains:

• JVM • Java Libraries • Supporting Files

6
Purpose:

Runs Java applications.

Cannot compile Java source code.

JDK (Java Development Kit)


Contains:

• JRE • JVM • javac Compiler • Debugger • Development Tools

Purpose:

Develop + Compile + Run Java applications.

Relationship
JDK

contains

JRE

contains

JVM

Memory Trick:

Develop → JDK

Run → JRE

7
Execute → JVM

Important Commands
Compile

javac [Link]

Run

java Hello

File Created

[Link]

Most Important TCS MCQs


MCQ 1

Java is developed by

A) Microsoft B) Oracle C) Google D) IBM

Answer: B

Explanation: Originally by Sun Microsystems, now owned by Oracle.

MCQ 2

Which feature makes Java platform independent?

A) JVM B) Bytecode C) Compiler D) JDK

Answer: B

Explanation: The compiler generates Bytecode, which can run on any platform with a JVM.

8
MCQ 3

Java follows

A) Procedural Programming B) Object-Oriented Programming C) Functional Programming D) Logic


Programming

Answer: B

MCQ 4

Extension of Java source file?

A) .class B) .java C) .exe D) .jar

Answer: B

MCQ 5

Extension of compiled Java file?

A) .java B) .class C) .jar D) .exe

Answer: B

MCQ 6

Which command compiles a Java program?

A) java Program B) javac [Link] C) compile [Link] D) java [Link]

Answer: B

MCQ 7

Which command executes a Java program?

A) javac [Link] B) java Program C) run Program D) execute Program

Answer: B

9
MCQ 8

Which component converts Bytecode into Machine Code?

A) Compiler B) JVM C) JDK D) JRE

Answer: B

Explanation: The JVM executes Bytecode, and the JIT compiler inside the JVM converts frequently used
Bytecode into Machine Code.

MCQ 9

Which contains the Java compiler?

A) JVM B) JRE C) JDK D) Bytecode

Answer: C

MCQ 10

Which can run Java applications?

A) JDK B) JRE C) JVM D) Both JDK and JRE

Answer: D

Explanation: JDK includes the JRE, so both can run Java applications.

MCQ 11

Which cannot compile Java programs?

A) JVM B) JRE C) Both JVM and JRE D) JDK

Answer: C

MCQ 12

Which statement is TRUE?

10
A) JDK contains JVM. B) JVM contains JDK. C) JRE contains JDK. D) Compiler is inside JVM.

Answer: A

MCQ 13

Java follows the principle:

A) Write Once Run Anywhere B) Write Everywhere Run Once C) Compile Everywhere D) Run Anywhere
Compile Anywhere

Answer: A

MCQ 14

Which of the following is NOT a feature of Java?

A) Portable B) Secure C) Pointer Support D) Robust

Answer: C

Explanation: Java does not support pointers directly.

MCQ 15

Which Java feature allows multiple tasks to execute simultaneously?

A) Dynamic B) Portable C) Multithreading D) Architecture Neutral

Answer: C

Quick Revision (1-Minute)


✔ Java is Object-Oriented.

✔ Java follows WORA (Write Once, Run Anywhere).

✔ Bytecode makes Java Platform Independent.

✔ JVM executes Bytecode.

11
✔ JRE = JVM + Libraries.

✔ JDK = JRE + Compiler + Development Tools.

✔ Source File = .java

✔ Compiled File = .class

✔ Compile Command = javac [Link]

✔ Run Command = java FileName

✔ JIT Compiler improves performance by converting Bytecode to Machine Code during execution.

✔ JDK > JRE > JVM (Remember this hierarchy).

12
CORE JAVA FOR TCS IPA – Chapter 2: Variables
(Detailed Notes + MCQs)

What is a Variable?
A variable is a named memory location used to store data. Every variable has:

• A data type (e.g., int, double, boolean)


• A name (identifier)
• A value

Example:

int age = 21;

Here:

• int → Data Type


• age → Variable Name
• 21 → Value

Types of Variables in Java


Java has three types of variables:

1. Local Variable
2. Instance Variable
3. Static Variable (Class Variable)

Understanding the difference between these is one of the most frequently tested concepts in TCS MCQs.

1. Local Variable
A local variable is declared inside a method, constructor, or block.

Example:

1
public class Test {
public static void main(String[] args) {

int x = 10;

[Link](x);

}
}

Here,

x is a local variable.

Characteristics

✔ Declared inside methods or blocks

✔ Memory allocated only when the method executes

✔ Destroyed after the method finishes

✔ Accessible only inside that method

✔ No default value

You must initialize a local variable before using it.

Example:

public class Test {

public static void main(String[] args) {

int x;

[Link](x);

Output:

2
Compile-Time Error
variable x might not have been initialized

Reason:

Local variables do not receive default values from Java.

2. Instance Variable
An instance variable is declared inside a class but outside all methods, constructors, and blocks.

Example:

public class Student {

int marks = 80;

marks is an instance variable.

Each object gets its own copy.

Example:

Student s1 = new Student();

Student s2 = new Student();

Memory:

s1 → marks = 80

s2 → marks = 80

If s1 changes its marks:

[Link] = 90;

3
Now:

s1 → 90

s2 → 80

Each object has its own separate copy.

Characteristics

✔ Declared inside class

✔ Outside methods

✔ Created when object is created

✔ Destroyed when object is destroyed

✔ Gets default value automatically

3. Static Variable (Class Variable)


Declared using the static keyword.

Example:

public class Student {

static String college = "KIT";

Now,

Every object shares the same variable.

Example:

4
Student s1 = new Student();

Student s2 = new Student();

Memory:

college

KIT

s1

s2

Only one copy exists.

If

[Link] = "MIT";

Then

Both objects see

MIT

Characteristics

✔ One copy for entire class

✔ Shared among all objects

✔ Memory allocated once when class loads

✔ Saves memory

✔ Gets default values automatically

5
Comparison Table
Feature Local Variable Instance Variable Static Variable

Declared Inside method Inside class Inside class using static

Memory Stack Heap Method Area (Class Area)

Default Value No Yes Yes

Scope Method only Entire object Entire class

Lifetime Until method ends Until object is destroyed Until program ends/class unloaded

Shared No No Yes

Default Values of Variables


Only

✔ Instance Variables

✔ Static Variables

receive default values.

Local variables never receive default values.

Data Type Default Value

byte 0

short 0

int 0

long 0L

float 0.0f

double 0.0

char '\u0000' (null character)

boolean false

Object null

6
Example

public class Test {

int x;

boolean flag;

char ch;

String name;

public static void main(String[] args) {

Test t = new Test();

[Link](t.x);

[Link]([Link]);

[Link]((int)[Link]);

[Link]([Link]);

Output:

false

null

Explanation:

Java automatically initializes instance variables.

7
Scope of Variables
Local Variable
Accessible only inside its method.

Instance Variable
Accessible through object.

Static Variable
Accessible using class name.

Example:

[Link]

Memory Allocation
Local Variable

Stack Memory

Instance Variable

Heap Memory

Static Variable

Method Area (Class Area)

8
Frequently Asked TCS MCQs
MCQ 1

Which variable does NOT get a default value?

A) Instance Variable

B) Static Variable

C) Local Variable

D) Object Variable

Answer: C

Explanation: Local variables must be initialized before use.

MCQ 2

Which variable is shared among all objects?

A) Local Variable

B) Instance Variable

C) Static Variable

D) Constructor

Answer: C

MCQ 3

Where is a local variable declared?

A) Inside method

B) Outside class

C) Inside package

D) Inside JVM

9
Answer: A

MCQ 4

Default value of an int instance variable?

A) null

B) 0

C) 0.0

D) Undefined

Answer: B

MCQ 5

Default value of boolean?

A) true

B) false

C) null

D) 0

Answer: B

MCQ 6

Default value of char?

A) '0'

B) '\u0000'

C) null

D) Empty String

10
Answer: B

MCQ 7

Default value of Object reference?

A) 0

B) false

C) null

D) '\u0000'

Answer: C

MCQ 8

Which memory stores local variables?

A) Heap

B) Stack

C) Method Area

D) JVM Cache

Answer: B

MCQ 9

Which memory stores instance variables?

A) Stack

B) Heap

C) Registers

D) Cache

11
Answer: B

MCQ 10

Which memory stores static variables?

A) Stack

B) Heap

C) Method Area (Class Area)

D) CPU Registers

Answer: C

MCQ 11 (Output Based)

public class Test {

int x;

public static void main(String[] args) {

Test t = new Test();

[Link](t.x);

Options:

A) Compile Error

B) null

C) 0

D) Garbage Value

Answer: C

12
Explanation: x is an instance variable, so it gets the default value 0 .

MCQ 12 (Output Based)

public class Test {

public static void main(String[] args) {

int x;

[Link](x);

Options:

A) 0

B) null

C) Compile-Time Error

D) Garbage Value

Answer: C

Explanation: Local variables must be initialized before use.

Memory Trick
LIS Rule

• L = Local → No default value


• I = Instance → Own copy for every object
• S = Static → Shared by all objects

13
One-Minute Revision
✔ Java has 3 variable types: Local, Instance, Static.

✔ Local variables:

• Declared inside methods


• Stored in Stack
• No default value

✔ Instance variables:

• Declared inside class


• Stored in Heap
• Separate copy for each object
• Default values available

✔ Static variables:

• Declared using static


• Shared among all objects
• Stored in Method Area (Class Area)
• Default values available

✔ Remember:

• Local → Stack → No Default


• Instance → Heap → Own Copy
• Static → Class Area → Shared Copy

14
CORE JAVA FOR TCS IPA – Chapter 3: Data Types
(Detailed Notes + MCQs)

What is a Data Type?


A data type specifies:

• What type of value a variable can store.


• How much memory is allocated.
• What operations can be performed on that value.

Example:

int age = 22;

Here:

• int → Data Type


• age → Variable
• 22 → Value

Without a data type, Java cannot determine how to store the value in memory.

Types of Data Types


Java has 2 categories of data types.

Data Types

├── Primitive Data Types (8)

└── Non-Primitive (Reference) Data Types

Primitive Data Types


Primitive data types store the actual value.

There are 8 primitive data types.

1
byte

short

int

long

float

double

char

boolean

These are predefined by Java.

Non-Primitive (Reference) Data Types


These store the reference (address) of an object instead of the actual object.

Examples:

• String
• Arrays
• Classes
• Interfaces
• Objects
• Enums

Example:

String name = "Harshad";

Here,

name stores the reference to the String object.

2
Primitive Data Types in Detail
1. byte
Size:

1 Byte = 8 bits

Range:

-128 to 127

Example

byte a = 100;

Use:

Used when memory saving is important.

2. short
Size

2 Bytes

Range

-32,768 to 32,767

Example

short marks = 30000;

3
3. int
Most commonly used integer type.

Size

4 Bytes

Range

-2^31 to (2^31)-1

Example

int salary = 50000;

If you write

int x = 10;

then 10 is considered an int literal.

4. long
Size

8 Bytes

Used for very large integers.

Example

long population = 8000000000L;

Notice the suffix

4
L

Without L

long x = 5000000000;

Compile Error

Reason:

The compiler considers it an int literal first.

Always use

5000000000L

5. float
Stores decimal numbers.

Size

4 Bytes

Example

float price = 99.5f;

Notice

must be written.

Without f

5
float x = 10.5;

Compile Error

Reason:

10.5 is a double literal by default.

6. double
Most commonly used decimal datatype.

Size

8 Bytes

Example

double pi = 3.14159;

No suffix required.

float vs double

float double

4 Bytes 8 Bytes

Less precision Higher precision

Suffix f required No suffix

Faster but less accurate More accurate

Example

float a = 12.5f;

double b = 12.5;

6
7. char
Stores a single Unicode character.

Size

2 Bytes

Example

char grade = 'A';

Character literals always use

Single Quotes

Wrong

char c = "A";

Compile Error

Correct

char c = 'A';

ASCII / Unicode Example

char ch = 65;

[Link](ch);

Output

Because

7
ASCII value of A = 65

8. boolean
Stores only two values.

true

false

Size

JVM dependent

Example

boolean flag = true;

Cannot store

Yes

No

Wrong

boolean b = 1;

Compile Error

8
Memory Table (Must Memorize)
Data Type Size Default Value Example

byte 1 Byte 0 byte a=10;

short 2 Bytes 0 short s=100;

int 4 Bytes 0 int x=5;

long 8 Bytes 0L long l=10L;

float 4 Bytes 0.0f float f=5.5f;

double 8 Bytes 0.0 double d=5.5;

char 2 Bytes '\u0000' char c='A';

boolean JVM Dependent false boolean b=true;

Default Decimal Literal


One of the most frequently asked TCS MCQs.

Example

double d = 10.5;

Works perfectly.

Now

float f = 10.5;

Compile Error

Reason:

Decimal numbers are double by default.

Correct

9
float f = 10.5f;

Remember

Decimal → double

Float requires f/F suffix

Type Conversion
Widening (Implicit Conversion)
Smaller datatype → Bigger datatype

No data loss.

byte

short

int

long

float

double

Example

10
int x = 100;

double d = x;

Output

100.0

Narrowing (Explicit Conversion)


Bigger datatype → Smaller datatype

May lose data.

Example

double d = 10.8;

int x = (int)d;

Output

10

Decimal part is removed.

Type Casting
Example

int x = 65;

char c = (char)x;

[Link](c);

Output

11
A

Frequently Asked TCS MCQs


MCQ 1
How many primitive data types are present in Java?

A) 6

B) 7

C) 8

D) 9

Answer: C

Explanation: Java has exactly 8 primitive data types.

MCQ 2
Which is the largest integer datatype?

A) int

B) short

C) long

D) byte

Answer: C

Explanation: long is an 8-byte integer type and can store larger integer values than int .

MCQ 3
Default decimal literal is

12
A) float

B) double

C) long

D) int

Answer: B

Explanation: Any decimal value (e.g., 10.5 ) is treated as a double unless you add the f suffix.

MCQ 4
Which datatype stores a single character?

A) String

B) char

C) Character[]

D) byte

Answer: B

MCQ 5
Size of char?

A) 1 Byte

B) 2 Bytes

C) 4 Bytes

D) JVM dependent

Answer: B

Explanation: Java uses Unicode, so char occupies 2 bytes.

13
MCQ 6
Which datatype stores only true or false?

A) bool

B) bit

C) boolean

D) logical

Answer: C

MCQ 7
Which statement is correct?

float f = 10.5;

A) Correct

B) Runtime Error

C) Compile-Time Error

D) Prints 10.5

Answer: C

Explanation: 10.5 is a double literal. Use:

float f = 10.5f;

MCQ 8
Output?

14
char ch = 65;

[Link](ch);

A) 65

B) A

C) Compile Error

D) null

Answer: B

Explanation: 65 is the Unicode/ASCII value of 'A' .

MCQ 9
Output?

double d = 15.9;

int x = (int)d;

[Link](x);

A) 15

B) 16

C) 15.9

D) Compile Error

Answer: A

Explanation: Explicit casting removes the decimal part.

MCQ 10
Which is NOT a primitive datatype?

15
A) int

B) String

C) char

D) boolean

Answer: B

Explanation: String is a reference (non-primitive) datatype.

MCQ 11
What is the size of double ?

A) 2 Bytes

B) 4 Bytes

C) 8 Bytes

D) JVM dependent

Answer: C

MCQ 12
Output?

long x = 100;

[Link](x);

A) 100

B) 100L

C) Compile Error

D) Runtime Error

16
Answer: A

Explanation: The L suffix is optional when the value fits within the int range.

MCQ 13
Which conversion is automatic?

A) double → int

B) long → byte

C) int → double

D) float → short

Answer: C

Explanation: Converting from a smaller type to a larger type is called widening, and Java performs it
automatically.

MCQ 14
What is the default value of a boolean instance variable?

A) true

B) false

C) null

D) 0

Answer: B

MCQ 15
Which of the following is the correct declaration?

A)

17
char c = "A";

B)

char c = 'A';

C)

char c = A;

D)

char c = "65";

Answer: B

Explanation: char stores a single character enclosed in single quotes.

Common Mistakes Asked in TCS


❌ Wrong

float f = 5.5;

✔ Correct

float f = 5.5f;

❌ Wrong

char c = "A";

✔ Correct

18
char c = 'A';

❌ Wrong

boolean b = 1;

✔ Correct

boolean b = true;

❌ Wrong

long l = 5000000000;

✔ Correct

long l = 5000000000L;

Memory Trick
Remember the sizes using this sequence:

byte → 1

short → 2

int → 4

long → 8

float → 4

double → 8

char → 2

19
boolean → JVM Dependent

Or simply remember:

• 1 Byte → byte
• 2 Bytes → short, char
• 4 Bytes → int, float
• 8 Bytes → long, double

One-Minute Revision
✔ Java has 8 primitive data types.

✔ Data types are divided into Primitive and Reference (Non-Primitive).

✔ Largest integer datatype = long.

✔ Default decimal datatype = double.

✔ float requires f/F suffix.

✔ long values beyond the int range require L/l suffix.

✔ char stores a single Unicode character using single quotes.

✔ boolean stores only true or false.

✔ Widening conversion is automatic; narrowing requires explicit casting.

✔ These concepts are among the most frequently tested in TCS IPA Java MCQs.

20
CORE JAVA FOR TCS IPA – Chapter 4: Operators
(Detailed Notes + MCQs)

What is an Operator?
An operator is a special symbol used to perform operations on variables or values.

Example:

int a = 10;
int b = 20;
int c = a + b;

Here,

+ is an operator.

Types of Operators in Java


Java has the following types of operators:

1. Arithmetic Operators

2. Unary Operators

3. Relational Operators

4. Logical Operators

5. Bitwise Operators

6. Shift Operators

7. Assignment Operators

8. Ternary Operator

9. instanceof Operator

1
1. Arithmetic Operators
Used for mathematical calculations.

Operator Meaning Example

+ Addition a+b

- Subtraction a-b

* Multiplication a*b

/ Division a/b

% Modulus (Remainder) a%b

Example

int a = 15;
int b = 4;

[Link](a+b);
[Link](a-b);
[Link](a*b);
[Link](a/b);
[Link](a%b);

Output

19

11

60

Explanation:

15/4 = 3 (Integer division)

15%4 = 3 (Remainder)

2
Integer Division
Example

[Link](10/3);

Output

Because both operands are integers.

Now,

[Link](10.0/3);

Output

3.333333...

One operand is double.

Modulus Operator %
Returns remainder.

Example

17 % 5

Output

3
Unary Operators
Unary means working on only one operand.

++

--
!

Increment Operator (++)


Increases value by 1.

There are two types:

Pre Increment

++a

Increment first

Use later

Example

int a=5;

[Link](++a);

Output

4
Post Increment

a++

Use first

Increment later

Example

int a=5;

[Link](a++);

Output

Now

a becomes

Decrement (--)
Same logic.

--a

Decrease first.

a--

Use first.

Decrease later.

5
TCS Output Questions
Question 1

int x=5;

[Link](x++);
[Link](x);

Output

Question 2

int x=5;

[Link](++x);

Output

Question 3

int x=5;

[Link](x++ + ++x);

Step

5 + 7

6
Output

12

Relational Operators
Used to compare two values.

Always return

true

or

false

Operator Meaning

> Greater than

< Less than

>= Greater than or equal

<= Less than or equal

== Equal

!= Not Equal

Example

int a=10;

[Link](a>5);

Output

true

7
== vs =
One of the most asked MCQs.

Assignment Operator

==

Comparison Operator

Example

int a=10;

Assignment

Example

a==10

Comparison

Returns

true

Logical Operators
Used with boolean values.

Operator Meaning

&& Logical AND

! Logical NOT

8
Logical AND (&&)
Returns true only if both conditions are true.

Truth Table

A B Result

T T T

T F F

F T F

F F F

Example

int age=20;

[Link](age>18 && age<30);

Output

true

Logical OR (||)
Returns true if any one condition is true.

Truth Table

A B Result

T T T

T F T

F T T

F F F

9
Logical NOT (!)
Reverses boolean.

Example

boolean b=true;

[Link](!b);

Output

false

Difference Between && and &


Most Important TCS Question

&& (Logical AND)


✔ Short Circuit Operator

If the first condition is false,

Java does NOT evaluate the second condition.

Example

int a=5;

if(a>10 && ++a>5)


{
}

[Link](a);

Output

10
5

Reason:

First condition is false.

Second condition never executes.

& (Bitwise AND / Logical AND)


Always evaluates both conditions.

Example

int a=5;

if(a>10 & ++a>5)


{
}

[Link](a);

Output

Reason:

Even though the first condition is false,

second condition executes.

Comparison
&& &

Short Circuit No Short Circuit

Second condition may not execute Always executes both

11
&& &

Faster Slightly slower

Used with boolean expressions Used with booleans and bits

Bitwise Operators
Operate on binary numbers.

Operator Meaning

& AND

| OR

^ XOR

~ Complement

Example

5 = 0101

3 = 0011

Bitwise AND

0101

0011

-----

0001

Output

12
XOR (^)
Rule

Same → 0

Different → 1

Example

5 ^ 3

Complement (~)
Flips every bit.

Example

[Link](~5);

Output

-6

TCS sometimes asks this directly.

Shift Operators
Operator Meaning

<< Left Shift

>> Right Shift

13
Operator Meaning

>>> Unsigned Right Shift

Example

5<<1

Binary

0101

1010

Output

10

Example

8>>1

Output

Memory Trick

Left Shift

Right Shift

14
2

Assignment Operators
Operator Meaning

= Assignment

+= Add and Assign

-= Subtract and Assign

*= Multiply and Assign

/= Divide and Assign

%= Modulus and Assign

Example

int x=10;

x+=5;

Equivalent to

x=x+5;

Output

15

Ternary Operator
Syntax

condition ? value1 : value2;

15
Example

int a=10;

String result=(a>5)?"Yes":"No";

Output

Yes

instanceof Operator
Checks whether an object belongs to a particular class.

Example

String s="Java";

[Link](s instanceof String);

Output

true

Operator Precedence (Important)


Highest → Lowest

()

Unary (++ -- !)

* / %

+ -

<< >>

16
< <= > >=

== !=

&

&&

||

?:

Remember:

BODMAS does not fully apply in Java. Java follows operator precedence rules.

Frequently Asked TCS MCQs


MCQ 1

Largest precedence among these?

A) +

B) *

C) ==

D) &&

Answer: B

MCQ 2

Difference between && and &

17
A) Both are same

B) && uses Short Circuit Evaluation

C) & is faster

D) None

Answer: B

MCQ 3

Output

int a=5;

[Link](a++);

A) 5

B) 6

C) Compile Error

D) Runtime Error

Answer: A

MCQ 4

Output

int a=5;

[Link](++a);

A) 5

B) 6

C) 7

18
D) Error

Answer: B

MCQ 5

Output

[Link](10/3);

A) 3

B) 3.33

C) 3.0

D) Compile Error

Answer: A

MCQ 6

Output

[Link](10%3);

A) 0

B) 1

C) 3

D) 10

Answer: B

MCQ 7

Output

19
[Link](5<<1);

A) 5

B) 10

C) 2

D) 20

Answer: B

MCQ 8

Output

[Link](8>>1);

A) 4

B) 8

C) 16

D) 2

Answer: A

MCQ 9

Output

int x=10;

x+=5;

[Link](x);

A) 10

20
B) 15

C) 5

D) Error

Answer: B

MCQ 10

Which operator checks object type?

A) typeof

B) instanceof

C) is

D) classof

Answer: B

MCQ 11

Output

boolean b=true;

[Link](!b);

A) true

B) false

C) 1

D) Error

Answer: B

21
MCQ 12

Output

[Link](~5);

A) 5

B) -5

C) -6

D) 6

Answer: C

Explanation: ~ flips all bits. For 5 , the result is -6 in Java's two's complement representation.

Common Mistakes Asked in TCS


❌ Wrong

if(a=10)

✔ Correct

if(a==10)

❌ Wrong

Using & when short-circuit evaluation is expected.

✔ Prefer

&&

for logical conditions.

22
Memory Tricks
Arithmetic

+ - * / %

Relational

> < >= <= == !=

Logical

&& || !

Bitwise

& | ^ ~

Shift

<< >> >>>

Assignment

= += -= *= /= %=

One-Minute Revision
✔ Arithmetic operators perform mathematical operations.

✔ ++a → Increment first, then use.

✔ a++ → Use first, then increment.

✔ = is assignment, == is comparison.

23
✔ && uses short-circuit evaluation.

✔ & always evaluates both operands.

✔ 10 / 3 = 3 (integer division).

✔ 10 % 3 = 1 (remainder).

✔ 5 << 1 = 10 .

✔ 8 >> 1 = 4 .

✔ += means add and assign.

✔ instanceof checks the object's type.

These concepts are among the highest-frequency MCQ topics in TCS IPA Core Java.

24
CORE JAVA FOR TCS IPA – Chapter 5: Control
Statements (Detailed Notes + MCQs)

What are Control Statements?


Control statements control the flow of execution of a program.

Normally, Java executes statements one by one from top to bottom.

Sometimes, we need to:

• Execute code only if a condition is true.


• Repeat a block of code multiple times.
• Exit from a loop.
• Skip certain iterations.

Control statements help us achieve this.

Types of Control Statements


Java control statements are divided into three categories.

Control Statements

├── Decision Making


│ ├── if
│ ├── if-else
│ ├── else-if ladder
│ ├── nested if
│ └── switch

├── Looping
│ ├── for
│ ├── while
│ └── do-while

└── Jump Statements
├── break

1
├── continue
└── return

1. if Statement
Used when you want to execute code only if a condition is true.

Syntax

if(condition){
// statements
}

Example

int age = 20;

if(age >= 18){


[Link]("Eligible to Vote");
}

Output

Eligible to Vote

If the condition is false, nothing executes.

2. if-else Statement
Used when there are two possible outcomes.

Syntax

if(condition){
// True block
}
else{

2
// False block
}

Example

int marks = 35;

if(marks >= 40){


[Link]("Pass");
}
else{
[Link]("Fail");
}

Output

Fail

3. else-if Ladder
Used when multiple conditions need to be checked.

Example

int marks = 82;

if(marks >= 90){


[Link]("Grade A");
}
else if(marks >= 75){
[Link]("Grade B");
}
else if(marks >= 60){
[Link]("Grade C");
}
else{
[Link]("Fail");
}

Output

3
Grade B

Only the first matching condition executes.

4. Nested if
An if statement inside another if statement.

Example

int age = 22;


boolean citizen = true;

if(age >= 18){


if(citizen){
[Link]("Eligible");
}
}

Output

Eligible

5. switch Statement
Used when multiple cases depend on the same expression.

Syntax

switch(expression){

case value1:
statements;
break;

case value2:
statements;
break;

4
default:
statements;
}

Example

int day = 3;

switch(day){

case 1:
[Link]("Monday");
break;

case 2:
[Link]("Tuesday");
break;

case 3:
[Link]("Wednesday");
break;

default:
[Link]("Invalid");
}

Output

Wednesday

break in switch
break exits the switch after executing a matching case.

Without break , Java executes the next cases also.

Example

int n = 2;

5
switch(n){

case 1:
[Link]("One");

case 2:
[Link]("Two");

case 3:
[Link]("Three");
}

Output

Two
Three

This is called Fall Through.

default Case
Executed when no case matches.

Example

int n = 10;

switch(n){

case 1:
[Link]("One");
break;

default:
[Link]("Invalid");
}

Output

Invalid

6
Datatypes Allowed in switch
Allowed

byte

short

char

int

String (Java 7+)

enum

Not Allowed

long

float

double

boolean

Memory Trick

Allowed

B S C I S E

(Byte Short Char Int String Enum)

switch with String


Since Java 7,

Strings are allowed.

7
Example

String day = "Monday";

switch(day){

case "Monday":
[Link]("Start");
break;

case "Sunday":
[Link]("Holiday");
}

Output

Start

6. for Loop
Used when the number of iterations is known.

Syntax

for(initialization; condition; update){


statements;
}

Example

for(int i=1;i<=5;i++){
[Link](i);
}

Output

1
2
3

8
4
5

Execution Order

Initialization

Condition

Statements

Update

Condition

Infinite for Loop

for(;;){
[Link]("Java");
}

Runs forever.

7. while Loop
Checks the condition first.

Syntax

9
while(condition){
statements;
}

Example

int i=1;

while(i<=5){

[Link](i);

i++;
}

Output

1
2
3
4
5

Infinite while Loop

while(true){

Runs forever.

8. do-while Loop
Difference:

Runs at least one time.

Syntax

10
do{

statements;

}while(condition);

Example

int i=10;

do{

[Link](i);

}while(i<5);

Output

10

Condition is false,

but the loop executes once.

Difference
while do-while

Checks condition first Executes first

May execute zero times Executes at least once

break Statement
Immediately exits the loop.

Example

11
for(int i=1;i<=5;i++){

if(i==3)
break;

[Link](i);
}

Output

1
2

continue Statement
Skips the current iteration.

Example

for(int i=1;i<=5;i++){

if(i==3)
continue;

[Link](i);
}

Output

1
2
4
5

return Statement
Terminates the current method immediately.

12
Example

public static void test(){

[Link]("A");

return;

// [Link]("B"); // Unreachable
}

Anything after return inside the same block is unreachable.

break vs continue vs return


break continue return

Exits loop/switch Skips current iteration Exits method

Execution continues after loop Continues next iteration Method ends immediately

Frequently Asked TCS MCQs


MCQ 1
Which control statement is used to make decisions?

A) for

B) if

C) while

D) break

Answer: B

MCQ 2
Which loop executes at least once?

13
A) for

B) while

C) do-while

D) none

Answer: C

Explanation: The condition is checked after the first execution.

MCQ 3
Which statement exits a loop immediately?

A) continue

B) return

C) break

D) exit

Answer: C

MCQ 4
Which statement skips the current iteration?

A) break

B) continue

C) return

D) goto

Answer: B

14
MCQ 5
Which statement exits the current method?

A) continue

B) break

C) return

D) exit

Answer: C

MCQ 6
Can switch use String ?

A) No

B) Yes (Java 7 onwards)

C) Only Java 8

D) Only Java 11

Answer: B

MCQ 7
Which datatype is NOT allowed in switch ?

A) char

B) int

C) long

D) String

Answer: C

15
MCQ 8
Output

int i=1;

while(i<=3){

[Link](i);

i++;
}

A) 123

B) 321

C) Infinite

D) Error

Answer: A

MCQ 9
Output

for(int i=1;i<=5;i++){

if(i==3)

break;

[Link](i);
}

A) 12345

B) 12

C) 1245

16
D) Error

Answer: B

MCQ 10
Output

for(int i=1;i<=5;i++){

if(i==3)

continue;

[Link](i);
}

A) 12345

B) 12

C) 1245

D) 345

Answer: C

MCQ 11
Output

int i=10;

do{

[Link](i);

}while(i<5);

A) Nothing

17
B) 10

C) Infinite

D) Compile Error

Answer: B

Explanation: do-while executes once before checking the condition.

MCQ 12
What happens if break is omitted in a switch case?

A) Compile Error

B) Runtime Error

C) Fall Through occurs

D) Program terminates

Answer: C

MCQ 13
Which of the following creates an infinite loop?

A)

for(;;){}

B)

while(true){}

C)

do{}while(true);

18
D) All of the above

Answer: D

MCQ 14
Which statement about switch is TRUE?

A) switch supports double .

B) switch supports String from Java 7 onwards.

C) switch supports boolean .

D) switch supports float .

Answer: B

MCQ 15
Execution order in a for loop is:

A) Condition → Initialization → Update

B) Initialization → Condition → Statements → Update

C) Statements → Condition → Update

D) Update → Statements → Condition

Answer: B

Common Mistakes Asked in TCS


❌ Wrong

switch(5.5)

✔ Correct

19
switch(5)

❌ Wrong

switch(true)

✔ boolean is not allowed in switch .

❌ Wrong

Forgetting break when fall-through is not intended.

Memory Tricks
Allowed in switch

B S C I S E

Byte

Short

Char

Int

String

Enum

Not Allowed

long

float

double

20
boolean

One-Minute Revision
✔ if executes code only when the condition is true.

✔ if-else chooses between two blocks.

✔ else-if ladder checks multiple conditions.

✔ Nested if means an if inside another if .

✔ switch is used for multiple fixed choices.

✔ String is supported in switch from Java 7 onwards.

✔ switch allows: byte , short , char , int , String , and enum .

✔ switch does not allow: long , float , double , or boolean .

✔ for is ideal when the number of iterations is known.

✔ while checks the condition before executing.

✔ do-while executes at least once.

✔ break exits the loop or switch.

✔ continue skips the current iteration.

✔ return exits the current method immediately.

TCS Tip: The most frequently asked questions from this chapter involve:

• switch supported data types


• break vs continue vs return
• for , while , and do-while output questions
• Fall-through behavior in switch

21
CORE JAVA FOR TCS IPA – Chapter 6: Arrays
(Detailed Notes + MCQs)

What is an Array?
An array is a collection of elements of the same data type stored in contiguous memory locations.

Instead of creating multiple variables, we can store many values in a single array.

Example:

Instead of writing

int m1 = 80;
int m2 = 85;
int m3 = 90;
int m4 = 95;
int m5 = 88;

We can write

int[] marks = {80,85,90,95,88};

Advantages:

✔ Stores multiple values using one variable.

✔ Easy to process using loops.

✔ Faster access using index.

Characteristics of Arrays
✔ Fixed size.

✔ Stores same data type.

✔ Indexed from 0.

1
✔ Arrays are Objects in Java.

✔ Stored in Heap Memory.

✔ Gets default values automatically.

Array Declaration
There are two valid ways.

Method 1

int arr[];

Method 2

int[] arr;

Both are correct.

TCS MCQ:

Which declaration is correct?

A)

int arr[];

B)

int[] arr;

C) Both

D) None

Answer:

2
Array Creation
Syntax

datatype[] arrayName = new datatype[size];

Example

int[] arr = new int[5];

Memory

Index

0 1 2 3 4

0 0 0 0 0

Five integers are created.

Array Initialization
Method 1

int[] arr = {10,20,30,40};

Method 2

int[] arr = new int[]{10,20,30,40};

Method 3

int[] arr = new int[4];

3
arr[0]=10;

arr[1]=20;

arr[2]=30;

arr[3]=40;

All are correct.

Accessing Elements
Index starts from

Example

int[] arr = {10,20,30};

[Link](arr[0]);

[Link](arr[2]);

Output

10

30

Indexing

Index

0 1 2 3

4
10 20 30 40

Remember

First index = 0

Last index = length - 1

Array Length
Length is a property.

Syntax

[Link]

Not

[Link]()

Example

int[] arr={10,20,30,40};

[Link]([Link]);

Output

Why length is not length()


Arrays are objects with a built-in field named length .

Strings use

5
length()

Collections use

size()

Memory Trick

Array

length

String

length()

ArrayList

size()

This is one of the favorite TCS MCQs.

Default Values of Arrays


Arrays receive default values exactly like instance variables.

Data Type Default Value

byte 0

short 0

int 0

long 0L

float 0.0f

6
Data Type Default Value

double 0.0

char '\u0000'

boolean false

Object null

Example

int[] arr = new int[3];

[Link](arr[0]);

[Link](arr[1]);

Output

Array Traversal
Using for loop

int[] arr={10,20,30};

for(int i=0;i<[Link];i++){

[Link](arr[i]);
}

Output

10

20

7
30

Enhanced for Loop (For-each)


Syntax

for(datatype variable : array){

Example

int[] arr={10,20,30};

for(int x:arr){

[Link](x);
}

Output

10

20

30

Advantages

✔ Simple

✔ No index required

Disadvantage

Cannot modify array index directly.

8
Multidimensional Arrays
Example

int[][] arr={

{1,2},

{3,4}

};

Memory

1 2

3 4

Access

[Link](arr[1][0]);

Output

ArrayIndexOutOfBoundsException
Most common runtime exception.

Example

int[] arr={10,20,30};

[Link](arr[5]);

Output

9
ArrayIndexOutOfBoundsException

Reason

Valid indices are

Arrays Class ([Link])


Frequently asked in TCS.

sort()

import [Link];

int[] arr={30,10,20};

[Link](arr);

[Link]([Link](arr));

Output

[10,20,30]

binarySearch()

int[] arr={10,20,30,40};

[Link]([Link](arr,30));

Output

10
2

Array must be sorted.

fill()

int[] arr=new int[5];

[Link](arr,7);

Output

7 7 7 7 7

equals()

[Link](a,b)

Checks content equality.

Arrays are Objects


Important TCS Concept.

Every array in Java is an object.

Example

int[] arr=new int[5];

[Link](arr instanceof Object);

Output

11
true

Reason

Arrays inherit from Object .

Frequently Asked TCS MCQs


MCQ 1
Arrays are

A) Primitive Data Types

B) Classes

C) Objects

D) Interfaces

Answer: C

MCQ 2
Array indexing starts from

A) 1

B) 0

C) -1

D) Depends on JVM

Answer: B

MCQ 3
Length of array is obtained using

12
A) length()

B) size()

C) length

D) getLength()

Answer: C

MCQ 4
Which receives default values?

A) Local Variables

B) Arrays

C) Parameters

D) Methods

Answer: B

MCQ 5
Default value of an int array element?

A) null

B) 0

C) Garbage Value

D) Undefined

Answer: B

MCQ 6
Output

13
int[] arr=new int[3];

[Link](arr[2]);

A) null

B) 0

C) Compile Error

D) Runtime Error

Answer: B

MCQ 7
Output

int[] arr={10,20,30};

[Link]([Link]);

A) 2

B) 3

C) 4

D) Error

Answer: B

MCQ 8
Output

int[] arr={10,20};

[Link](arr[2]);

14
A) null

B) 0

C) Compile Error

D) ArrayIndexOutOfBoundsException

Answer: D

MCQ 9
Which package contains Arrays class?

A) [Link]

B) [Link]

C) [Link]

D) [Link]

Answer: C

MCQ 10
Which method sorts an array?

A) [Link]()

B) [Link]()

C) [Link]()

D) sortArray()

Answer: B

MCQ 11
Output

15
int[] arr={10,20,30};

for(int x:arr){

[Link](x);
}

A) 102030

B) 123

C) Error

D) Infinite

Answer: A

MCQ 12
Which loop is specially designed for arrays?

A) while

B) for

C) Enhanced for loop

D) do-while

Answer: C

MCQ 13
Which statement is TRUE?

A) Arrays are primitive data types.

B) Arrays are objects.

C) Arrays cannot store objects.

D) Arrays are interfaces.

16
Answer: B

MCQ 14
Last valid index of an array of size 10?

A) 10

B) 9

C) 8

D) 11

Answer: B

Explanation:

Last Index = Length - 1

MCQ 15
Which method converts an array into a readable String?

A) [Link]()

B) [Link]()

C) [Link]()

D) [Link]()

Answer: B

Common Mistakes Asked in TCS


❌ Wrong

[Link]()

17
✔ Correct

[Link]

❌ Wrong

arr[5]

When size is 5.

Valid indices

0–4

❌ Wrong

[Link]()

on an unsorted array.

Always sort first.

Memory Tricks
Remember

Array

length

String

18
length()

ArrayList

size()

Remember

First Index = 0

Last Index = length - 1

One-Minute Revision
✔ Arrays store multiple values of the same data type.

✔ Arrays are Objects in Java.

✔ Arrays are stored in Heap Memory.

✔ Arrays get default values like instance variables.

✔ Array indexing starts at 0.

✔ Last index = length - 1.

✔ Array length is accessed using [Link], not length().

✔ Use the enhanced for loop for easy traversal.

✔ Accessing an invalid index throws ArrayIndexOutOfBoundsException.

✔ Important Arrays class methods:

• sort()
• binarySearch()
• fill()
• equals()

19
• toString()

TCS Tip: Questions on [Link] vs length() , default values, array indexing, exceptions, and output-
based programs appear very frequently in TCS IPA Java assessments.

20
CORE JAVA FOR TCS IPA – Chapter 7: String
(Detailed Notes + MCQs)

What is a String?
A String is a sequence of characters.

Example:

String name = "Harshad";

Here,

H a r s h a d

is a String.

Unlike C/C++, Java provides a built-in String class.

The String class belongs to the [Link] package, which is automatically imported.

Why is String Important?


Strings are used almost everywhere:

• Names
• Passwords
• URLs
• Email IDs
• JSON
• File Paths

More than 60% of Java applications use Strings.

This is why TCS asks many String-based MCQs.

1
String is Immutable
The most important concept.

Immutable means:

Once a String object is created, its value cannot be changed.

Example

String s = "Java";

[Link](" Programming");

[Link](s);

Output

Java

Why?

Because

concat()

creates a new String.

It does not modify the existing String.

Correct

String s = "Java";

s = [Link](" Programming");

[Link](s);

Output

2
Java Programming

Memory

Before

Java

After concat()

Java

Programming

(New Object)

s still points to old object.

After assignment

Java Programming

Why Strings are Immutable?


Reasons

• Security
• Thread Safety
• String Pool Optimization
• HashMap Keys
• Performance

3
Ways to Create Strings
Method 1 (String Literal)

String s = "Hello";

Stored inside

String Constant Pool (SCP)

Most commonly used.

Method 2 (Using new)

String s = new String("Hello");

Creates an object in

• Heap Memory

and also uses the String Constant Pool if the literal is not already present.

String Constant Pool (SCP)


Special memory area inside Heap.

Stores only one copy of identical String literals.

Example

String s1 = "Java";

String s2 = "Java";

String s3 = "Java";

Memory

4
SCP

Java

s1

s2

s3

Only one object is created.

Objects Created
Example

String s1 = "abc";

String s2 = "abc";

Objects created?

One

Reason

Both refer to the same SCP object.

Now

String s = new String("abc");

Objects created?

5
Two

One

String Pool

One

Heap

Memory

Heap

abc

Reference

SCP

abc

This is one of the most frequently asked TCS MCQs.

== vs equals()
Very Important

==
Checks reference (memory address).

Example

6
String s1 = "Java";

String s2 = "Java";

[Link](s1 == s2);

Output

true

Both refer to the same object.

Now

String s1 = new String("Java");

String s2 = new String("Java");

[Link](s1 == s2);

Output

false

Different objects.

equals()
Checks content.

Example

String s1 = new String("Java");

String s2 = new String("Java");

[Link]([Link](s2));

Output

7
true

Because contents are equal.

Comparison Table
== equals()

Compares reference Compares content

Returns true if both refer to same object Returns true if values are equal

Operator Method

Memory Trick

==

Address

equals()

Content

Important String Methods


1. length()
Returns number of characters.

String s = "Harshad";

[Link]([Link]());

Output

8
7

2. charAt(index)
Returns character at given index.

String s = "Java";

[Link]([Link](2));

Output

3. substring()
Extracts part of String.

String s = "Programming";

[Link]([Link](3));

Output

gramming

Another example

[Link]([Link](3,7));

Output

gram

9
4. indexOf()
Returns first occurrence.

String s = "banana";

[Link]([Link]('a'));

Output

5. lastIndexOf()
Returns last occurrence.

[Link]("banana".lastIndexOf('a'));

Output

6. replace()

String s = "Java";

[Link]([Link]('a','o'));

Output

Jovo

10
7. trim()
Removes leading and trailing spaces.

String s = " Java ";

[Link]([Link]());

Output

Java

8. contains()
Checks whether substring exists.

[Link]("Programming".contains("gram"));

Output

true

9. startsWith()

[Link]("Programming".startsWith("Pro"));

Output

true

10. endsWith()

[Link]("Programming".endsWith("ing"));

11
Output

true

11. equalsIgnoreCase()

[Link]("JAVA".equalsIgnoreCase("java"));

Output

true

12. split()

String s="Java Python C";

String[] arr=[Link](" ");

Output

Java

Python

13. toUpperCase()

"java".toUpperCase()

Output

JAVA

12
14. toLowerCase()

"JAVA".toLowerCase()

Output

java

15. isEmpty()

"".isEmpty()

Output

true

16. concat()

"Java".concat(" Programming")

Output

Java Programming

Remember

concat() does not modify the original String because Strings are immutable.

StringBuffer
Mutable.

Thread Safe.

13
Slower.

Example

StringBuffer sb = new StringBuffer("Java");

[Link](" Programming");

[Link](sb);

Output

Java Programming

StringBuilder
Mutable.

Not Thread Safe.

Faster.

Example

StringBuilder sb = new StringBuilder("Java");

[Link](" Programming");

[Link](sb);

Output

Java Programming

14
String vs StringBuffer vs StringBuilder
Feature String StringBuffer StringBuilder

Mutable ❌ No ✅ Yes ✅ Yes

Thread Safe Yes Yes No

Performance Slow for modification Slower Fastest

Memory Creates new object on modification Same object Same object

Memory Trick

String

Immutable

Safe

StringBuffer

Mutable

Thread Safe

Slow

StringBuilder

Mutable

Not Thread Safe

15

Fastest

Frequently Asked TCS MCQs


MCQ 1

String is

A) Mutable

B) Immutable

C) Interface

D) Abstract

Answer: B

MCQ 2

Output

String s="Java";

[Link](" Programming");

[Link](s);

A) Java Programming

B) Java

C) Programming

D) Error

Answer: B

16
MCQ 3

String s1="abc";

String s2="abc";

Objects created?

A) 1

B) 2

C) 3

D) 4

Answer: A

MCQ 4

new String("abc")

Objects created?

A) 1

B) 2

C) 3

D) Depends

Answer: B

MCQ 5

Difference between == and equals() ?

A) Both compare content

B) == compares references, equals() compares content

17
C) equals() compares references

D) No difference

Answer: B

MCQ 6

Fastest mutable String class?

A) String

B) StringBuffer

C) StringBuilder

D) Character

Answer: C

MCQ 7

Which String class is thread safe?

A) StringBuilder

B) StringBuffer

C) String

D) Character

Answer: B

MCQ 8

Output

[Link]("Java".length());

A) 3

18
B) 4

C) 5

D) Error

Answer: B

MCQ 9

Output

[Link]("Java".charAt(1));

A) J

B) a

C) v

D) Error

Answer: B

MCQ 10

Output

[Link]("Programming".substring(3,7));

A) gram

B) gramming

C) Prog

D) amm

Answer: A

19
MCQ 11

Output

[Link]("banana".indexOf('a'));

A) 0

B) 1

C) 3

D) 5

Answer: B

MCQ 12

Output

[Link]("JAVA".equalsIgnoreCase("java"));

A) true

B) false

C) Error

D) Null

Answer: A

MCQ 13

Output

[Link]("".isEmpty());

A) true

20
B) false

C) Error

D) null

Answer: A

MCQ 14

Which method removes leading and trailing spaces?

A) strip()

B) trim()

C) remove()

D) replace()

Answer: B

MCQ 15

Which method converts a String into an array?

A) split()

B) divide()

C) break()

D) parse()

Answer: A

Common Mistakes Asked in TCS


❌ Wrong

21
if(s1==s2)

when comparing String contents.

✔ Correct

if([Link](s2))

❌ Thinking concat() changes the original String.

✔ It creates a new String.

❌ Using length instead of length() for Strings.

✔ Correct

[Link]()

Memory Tricks
Remember

Array

length

String

length()

ArrayList

22
size()

Remember

==

Reference

equals()

Content

Remember

String

Immutable

StringBuffer

Mutable

Thread Safe

StringBuilder

Mutable

23
Not Thread Safe

Fastest

One-Minute Revision
✔ Strings are immutable.

✔ String literals are stored in the String Constant Pool (SCP).

✔ "abc" creates one object (if not already in the pool).

✔ new String("abc") creates two objects (one in the SCP, one in the Heap).

✔ == compares references.

✔ equals() compares contents.

✔ length() returns the number of characters.

✔ charAt() returns the character at a specific index.

✔ substring() extracts part of a String.

✔ trim() removes leading and trailing spaces.

✔ split() divides a String into an array.

✔ StringBuffer is mutable and thread safe.

✔ StringBuilder is mutable, not thread safe, and the fastest for string modifications.

TCS Tip: This is the highest-weightage Java topic. Be prepared for output-based questions, String Pool,
immutability, == vs equals() , String methods, and StringBuffer vs StringBuilder comparisons.

24
CORE JAVA FOR TCS IPA – Chapter 8: Object-
Oriented Programming (OOP) Concepts (Detailed
Notes + MCQs)

What is Object-Oriented Programming (OOP)?


Object-Oriented Programming (OOP) is a programming paradigm that organizes software around objects
rather than functions.

Java is primarily an Object-Oriented Programming (OOP) language.

The four pillars of OOP are:

• Encapsulation
• Inheritance
• Polymorphism
• Abstraction

These topics will be covered in later chapters.

What is a Class?
A class is a blueprint or template used to create objects.

It defines:

• Variables (Data Members)


• Methods (Functions)
• Constructors

Think of a class as a design or blueprint.

Example:

Blueprint of a House

Many Houses can be built.

1
Similarly,

Class

Many Objects can be created.

Example of Class

class Student{

int rollNo;
String name;

void display(){

[Link](rollNo+" "+name);

Here,

Student is a Class.

It contains

• Variables
• Method

No memory is allocated for a class until an object is created.

What is an Object?
An object is an instance of a class.

It is a real-world entity.

Example

2
Student s1 = new Student();

Here

Student

Class

s1

Object

Memory is allocated when an object is created.

Real-Life Example
Class

Car

Objects

BMW

Audi

Tesla

Class

Student

Objects

3
Harshad

Rahul

Amit

Creating an Object
Syntax

ClassName objectName = new ClassName();

Example

Student s = new Student();

Explanation

Student

Class

Reference Variable

new

Creates Object

Student()

4
Calls Constructor

Accessing Variables and Methods


Use the dot (.) operator.

Example

Student s = new Student();

[Link] = 101;

[Link] = "Harshad";

[Link]();

Output

101 Harshad

Memory Representation

Heap Memory

------------------

Student Object

rollNo = 101

name = Harshad

------------------

Reference

5

The object is stored in Heap Memory.

The reference variable is stored in Stack Memory.

Constructor
A constructor is a special method used to initialize an object.

It is automatically called when an object is created.

Example

class Student{

Student(){

[Link]("Constructor Called");

public class Main{

public static void main(String[] args){

Student s = new Student();

Output

Constructor Called

6
Characteristics of Constructor
✔ Same name as the class

✔ No return type

✔ Called automatically

✔ Used to initialize objects

✔ Can be overloaded

✔ Cannot be inherited

✔ Cannot be static

✔ Cannot be final

✔ Cannot be abstract

Rules for Constructor


Rule 1

Constructor name must be exactly the same as the class name.

Correct

class Student{

Student(){

Wrong

class Student{

void student(){

7
}

This is a method, not a constructor.

Rule 2

Constructor has no return type.

Wrong

int Student(){

Wrong

void Student(){

Both are methods.

Types of Constructors
Java has three commonly discussed constructor types.

1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor (User-defined)

1. Default Constructor
A constructor with no parameters.

Example

8
class Student{

Student(){

[Link]("Default Constructor");

Output

Default Constructor

Compiler-Provided Default Constructor


If you do not write any constructor, Java automatically provides one.

Example

class Student{

Internally,

Java creates

Student(){

This is called the default constructor provided by the compiler.

Important:

If you write any constructor, the compiler does not create the default constructor.

9
2. Parameterized Constructor
A constructor with parameters.

Example

class Student{

int id;

Student(int x){

id = x;

Creating Object

Student s = new Student(101);

[Link]([Link]);

Output

101

Advantages

✔ Initialize object during creation.

✔ Reduces extra assignment statements.

3. Copy Constructor (User-Defined)


Java does not provide a built-in copy constructor like C++.

We create it ourselves.

10
Example

class Student{

int id;

Student(int x){

id = x;

Student(Student s){

id = [Link];

Now,

Student s1 = new Student(101);

Student s2 = new Student(s1);

Both objects have the same values.

Constructor Overloading
Java allows multiple constructors with different parameter lists.

Example

class Student{

Student(){

[Link]("Default");

11
Student(int x){

[Link](x);

Output

Default

100

This is called Constructor Overloading.

Constructor vs Method
Constructor Method

Same name as class Any valid name

No return type Must have return type (except void)

Called automatically Called explicitly

Initializes object Performs operations

Cannot be static Can be static

Important Constructor Facts


Can constructor be static?

❌ No

Can constructor return value?

❌ No

Can constructor be final?

12
❌ No

Can constructor be abstract?

❌ No

Can constructor be overloaded?

✅ Yes

Can constructor be overridden?

❌ No

Can constructor call another constructor?

✅ Yes (using this() – covered in the next chapter)

Frequently Asked TCS MCQs


MCQ 1
A class is

A) Object

B) Blueprint

C) Variable

D) Method

Answer: B

MCQ 2
An object is

A) Blueprint

B) Instance of Class

13
C) Constructor

D) Variable

Answer: B

MCQ 3
Constructor is called

A) Manually

B) Automatically when object is created

C) During compilation

D) By JVM shutdown

Answer: B

MCQ 4
Which statement about constructors is TRUE?

A) Constructor has a return type.

B) Constructor name must match the class name.

C) Constructor can be static.

D) Constructor can be abstract.

Answer: B

MCQ 5
Can a constructor have a return type?

A) Yes

B) No

14
C) Only void

D) Only int

Answer: B

MCQ 6
Can a constructor be static?

A) Yes

B) No

C) Only private

D) Only protected

Answer: B

MCQ 7
Which constructor is automatically provided by the compiler (if no constructor is written)?

A) Parameterized Constructor

B) Copy Constructor

C) Default Constructor

D) Static Constructor

Answer: C

MCQ 8
Java supports

A) Constructor Overloading

B) Constructor Overriding

15
C) Both

D) Neither

Answer: A

MCQ 9
Output

class Student{

Student(){

[Link]("Hello");

public class Main{

public static void main(String[] args){

Student s = new Student();

A) Hello

B) Error

C) Nothing

D) null

Answer: A

16
MCQ 10
Which keyword creates an object?

A) create

B) class

C) new

D) object

Answer: C

MCQ 11
Where are objects stored?

A) Stack Memory

B) Heap Memory

C) CPU Cache

D) Registers

Answer: B

MCQ 12
What is stored in Stack Memory?

A) Object

B) Reference Variable

C) Array Elements

D) Class Definition

Answer: B

17
MCQ 13
Which is NOT a characteristic of a constructor?

A) Same name as class

B) No return type

C) Can be static

D) Initializes objects

Answer: C

MCQ 14
Which statement is FALSE?

A) Constructors can be overloaded.

B) Constructors are automatically called.

C) Constructors can be overridden.

D) Constructors initialize objects.

Answer: C

MCQ 15
Which of the following is correct?

Student s = new Student();

A) Student is an object.

B) s is the class.

C) new creates an object.

D) Student() is a method.

18
Answer: C

Common Mistakes Asked in TCS


❌ Wrong

void Student(){

This is a method, not a constructor.

❌ Wrong

static Student(){

Constructors cannot be static .

❌ Wrong

int Student(){

Constructors cannot have a return type.

Memory Tricks
Remember

Class

19
Blueprint

Creates

Objects

Remember

Constructor

Same Name

No Return Type

Automatic Call

Remember

Default

No Parameters

Parameterized

Parameters

Copy

20

Object as Parameter

One-Minute Revision
✔ A Class is a blueprint.

✔ An Object is an instance of a class.

✔ Objects are created using the new keyword.

✔ Objects are stored in Heap Memory.

✔ Reference variables are stored in Stack Memory.

✔ A Constructor initializes objects.

✔ Constructor name must be the same as the class name.

✔ Constructors have no return type.

✔ Constructors are called automatically when an object is created.

✔ Constructors cannot be static , final , or abstract .

✔ Constructors can be overloaded but cannot be overridden.

✔ If no constructor is written, Java provides a default constructor.

TCS Tip: This chapter is frequently tested through concept-based MCQs, output questions, and
constructor-related interview questions. Master this chapter before moving to this , super ,
Inheritance, and Polymorphism.

21
CORE JAVA FOR TCS IPA – Chapter 9: this Keyword
(Detailed Notes + MCQs)

What is this Keyword?


The this keyword is a reference variable that refers to the current object.

Whenever an object calls a method or constructor, Java automatically passes the reference of that object
using this .

Example:

class Student{

void display(){

[Link](this);

public static void main(String[] args){

Student s = new Student();

[Link]();

Output

Student@15db9742

(The exact address/hashcode may differ.)

Here, this refers to the object s .

1
Why do we need this ?
Suppose we have

class Student{

int id;

Student(int id){

id = id;

Problem:

Both variables have the same name.

Java gets confused.

Here,

id = id;

means

Local Variable = Local Variable

The instance variable remains unchanged.

Correct way

class Student{

int id;

Student(int id){

[Link] = id;

2
}

Meaning

Current Object's id = Local Variable id

This is the most common use of this .

Uses of this
The this keyword has five major uses.

1. Refer to current instance variable.


2. Invoke current class method.
3. Invoke current class constructor.
4. Pass current object as an argument.
5. Return current object.

These are frequently asked in interviews and TCS MCQs.

1. Refer Current Instance Variable


Example

class Student{

int age;

Student(int age){

[Link] = age;

void display(){

[Link](age);

3
}

Output

20

Explanation

[Link]

Instance Variable

age

Local Variable

2. Invoke Current Class Method


Example

class Demo{

void show(){

[Link]("Show");

void display(){

[Link]();

4
Output

Show

Actually,

[Link]();

is the same as

show();

Java adds this automatically.

3. Invoke Current Constructor


One constructor can call another constructor using

this();

Example

class Student{

Student(){

this(100);

[Link]("Default");

Student(int x){

[Link](x);

5
}

Output

100

Default

Execution

Student()

this(100)

Student(int)

Back to Student()

Rules of this()
✔ Used to call another constructor.

✔ Must be the first statement inside the constructor.

Wrong

Student(){

[Link]("Hello");

this(10);

6
Compile-Time Error

Correct

Student(){

this(10);

[Link]("Hello");

4. Pass Current Object


Example

class Demo{

void display(Demo d){

void show(){

display(this);

this sends the current object as a parameter.

5. Return Current Object


Example

class Demo{

Demo show(){

7
return this;

Used in Method Chaining.

this Cannot Be Used in Static Method


Very Important TCS MCQ

Example

class Test{

static void show(){

[Link](this);

Compile-Time Error

Why?

Because

Static methods belong to the class, not to any object.

Since this refers to the current object, and static methods execute without creating an object, there is
no current object.

Hence,

this

❌ Not Allowed

8
Memory Trick

Object Exists

this Exists

No Object

No this

this vs Local Variable


Example

class Student{

int age = 20;

void display(){

int age = 30;

[Link](age);

[Link]([Link]);

Output

30

20

Explanation

9
age

Local Variable

[Link]

Instance Variable

this vs super
this super

Refers to current object Refers to parent object

Access current class members Access parent class members

Calls current constructor Calls parent constructor

super will be covered in the next chapter.

Frequently Asked TCS MCQs


MCQ 1
What does this refer to?

A) Parent Object

B) Current Object

C) JVM

D) Class

Answer: B

10
MCQ 2
Can this be used inside a static method?

A) Yes

B) No

C) Only in Java 8

D) Only in constructors

Answer: B

Explanation:

Static methods belong to the class.

this belongs to objects.

MCQ 3
Which statement is correct?

[Link] = id;

A) Local Variable = Local Variable

B) Instance Variable = Local Variable

C) Local Variable = Instance Variable

D) None

Answer: B

MCQ 4
How many major uses of this are commonly discussed?

A) 2

11
B) 3

C) 5

D) 6

Answer: C

MCQ 5
Which statement invokes another constructor?

A)

super();

B)

this();

C)

new();

D)

call();

Answer: B

MCQ 6
Where should this() be written?

A) Anywhere

B) Last statement

C) First statement of constructor

12
D) Inside main()

Answer: C

MCQ 7
Can this be returned from a method?

A) Yes

B) No

C) Only in constructors

D) Only in abstract methods

Answer: A

MCQ 8
Output

class Test{

int x=10;

void show(){

[Link](this.x);

A) 0

B) 10

C) Error

D) null

13
Answer: B

MCQ 9
Output

class Test{

int x;

Test(int x){

this.x=x;

Purpose of this.x ?

A) Local Variable

B) Instance Variable

C) Static Variable

D) Method

Answer: B

MCQ 10
Which is FALSE?

A) this refers to current object.

B) this can call another constructor.

C) this can be used in static methods.

D) this can return current object.

14
Answer: C

MCQ 11
Which keyword passes the current object as a parameter?

A) super

B) new

C) this

D) static

Answer: C

MCQ 12
Output

class Test{

Test(){

this(5);

[Link]("A");

Test(int x){

[Link](x);

public static void main(String[] args){

new Test();

15
}

A)

A
5

B)

5
A

C)

D) Error

Answer: B

Common Mistakes Asked in TCS


❌ Wrong

static void show(){

[Link](this);

Compile-Time Error

❌ Wrong

Student(){

[Link]("Hi");

16
this(10);

this() must be the first statement.

❌ Wrong

id=id;

✔ Correct

[Link]=id;

Memory Tricks
Remember

this

Current Object

Remember

[Link]

Instance Variable

Remember

17
this()

Current Constructor

Remember

Static Method

No Object

No this

One-Minute Revision
✔ this refers to the current object.

✔ [Link] accesses the instance variable.

✔ [Link]() calls another method of the current class.

✔ this() calls another constructor in the same class.

✔ this() must be the first statement in a constructor.

✔ this can be passed as a method argument.

✔ this can be returned from a method.

✔ this cannot be used inside a static method.

✔ [Link] = id; resolves the conflict between instance and local variables.

18
TCS Tip: Questions involving [Link] = id , this() constructor calls, constructor execution order,
and why this is not allowed in static methods are asked very frequently in TCS IPA Java assessments.

19
CORE JAVA FOR TCS IPA – Chapter 10: static
Keyword (Detailed Notes + MCQs)

What is static ?
The static keyword belongs to the class, not to individual objects.

It means there is only one copy of the member, shared by all objects.

Without static :

Each object gets its own copy.

With static :

Only one shared copy exists.

Why is static Used?


Suppose every student belongs to the same college.

Without static

class Student{

String college = "KIT";

If 1000 objects are created,

Memory stores

KIT

KIT

KIT

1
KIT

1000 Times

Memory is wasted.

Now

class Student{

static String college = "KIT";

Only one copy is stored.

All objects share it.

Memory

Student Class

college = KIT

s1

s2

s3

s4

Types of Static Members


Java allows four static members.

1. Static Variable
2. Static Method

2
3. Static Block
4. Static Nested Class (Advanced)

For TCS IPA,

focus on the first three.

1. Static Variable
Also called a Class Variable.

Example

class Student{

static String college = "KIT";

Creating Objects

Student s1 = new Student();

Student s2 = new Student();

Memory

college

KIT

s1

s2

Both objects use the same variable.

3
Accessing Static Variables
Preferred way

[Link]

Although

[Link]

also works,

using the class name is recommended.

Static Variable Example

class Student{

static String college = "KIT";

public class Main{

public static void main(String[] args){

Student s1 = new Student();

Student s2 = new Student();

[Link]([Link]);

[Link]([Link]);

Output

4
KIT

KIT

2. Static Method
A static method belongs to the class.

Example

class Demo{

static void show(){

[Link]("Hello");

Calling

[Link]();

Output

Hello

No object required.

Why is main() Static?


The JVM calls

main()

without creating any object.

5
Hence,

main() must be

static

This is one of the most frequently asked interview questions.

Static Method Rules


✔ Can access static variables directly.

✔ Can call static methods directly.

✔ Cannot access instance variables directly.

✔ Cannot call non-static methods directly.

✔ Cannot use this .

✔ Cannot use super .

Static Method Example

class Demo{

static int x = 10;

static void display(){

[Link](x);

Output

6
10

Can Static Method Access Instance Variable?


Example

class Demo{

int x = 10;

static void show(){

[Link](x);

Compile-Time Error

Reason

Instance variables belong to objects.

Static methods belong to the class.

No object exists.

Correct

class Demo{

int x = 10;

static void show(){

Demo d = new Demo();

[Link](d.x);

7
}

Now it works.

Memory Trick

Static Method

No Object

No Instance Variable

Can Static Method Call Non-Static Method?


Wrong

class Demo{

void display(){

static void show(){

display();

Compile-Time Error

Correct

8
Demo d = new Demo();

[Link]();

Static Block
A static block is used to initialize static data.

Syntax

class Demo{

static{

[Link]("Static Block");

Static block executes only once, when the class is loaded.

Static Block Example

class Demo{

static{

[Link]("Static Block");

public static void main(String[] args){

[Link]("Main Method");

9
Output

Static Block

Main Method

Reason

Class loads first,

then main() runs.

Multiple Static Blocks


Example

class Demo{

static{

[Link]("First");

static{

[Link]("Second");

Output

First

Second

They execute in the order they appear.

10
Execution Order
One of the most important TCS questions.

Suppose

class Demo{

static{

[Link]("Static");

Demo(){

[Link]("Constructor");

public static void main(String[] args){

[Link]("Main");

new Demo();

Output

Static

Main

Constructor

Execution Order

Static Block

11
Main Method

Constructor

Memory Trick

Load Class

Static Block

main()

Object Creation

Constructor

Static vs Instance
Static Instance

Belongs to Class Belongs to Object

One Copy Multiple Copies

Shared Separate for every object

Access using Class Name Access using Object

Memory allocated once Memory allocated per object

12
Static vs Non-Static Method
Static Method Non-Static Method

Belongs to class Belongs to object

Called without object Requires object

Cannot access instance members directly Can access both static and instance members

Cannot use this Can use this

Frequently Asked TCS MCQs


MCQ 1
The static keyword belongs to

A) Object

B) Class

C) Constructor

D) Method

Answer: B

MCQ 2
Static variables are also called

A) Instance Variables

B) Local Variables

C) Class Variables

D) Global Variables

Answer: C

13
MCQ 3
How many copies of a static variable exist?

A) One per object

B) One per method

C) One per class

D) Unlimited

Answer: C

MCQ 4
Can a static method access an instance variable directly?

A) Yes

B) No

C) Only using this

D) Only in Java 8

Answer: B

MCQ 5
Why is main() declared as static?

A) To increase speed

B) JVM calls it without creating an object

C) To save memory

D) Because constructors are static

Answer: B

14
MCQ 6
Can a static method use this ?

A) Yes

B) No

C) Only in constructors

D) Only in interfaces

Answer: B

MCQ 7
When does a static block execute?

A) After constructor

B) Before object creation

C) When the class is loaded

D) Every time an object is created

Answer: C

MCQ 8
How many times does a static block execute?

A) Every object creation

B) Every method call

C) Only once

D) Never

Answer: C

15
MCQ 9
Output

class Test{

static{

[Link]("A");

public static void main(String[] args){

[Link]("B");

A)

B)

C) Error

D) Nothing

Answer: A

MCQ 10
Output

16
class Test{

static{

[Link]("Static");

Test(){

[Link]("Constructor");

public static void main(String[] args){

[Link]("Main");

new Test();

A)

Main

Static

Constructor

B)

Static

Main

Constructor

C)

17
Constructor

Static

Main

D) Error

Answer: B

MCQ 11
Which statement is TRUE?

A) Static methods require an object.

B) Static variables belong to objects.

C) Static methods belong to the class.

D) Constructors can be static.

Answer: C

MCQ 12
Which member is shared among all objects?

A) Instance Variable

B) Local Variable

C) Static Variable

D) Constructor

Answer: C

18
MCQ 13
Can constructors be static?

A) Yes

B) No

C) Only private

D) Only public

Answer: B

MCQ 14
Which of the following is NOT allowed in a static method?

A) Calling another static method

B) Accessing a static variable

C) Using this

D) Creating an object

Answer: C

MCQ 15
Execution order is

A)

Constructor

Main

19
Static Block

B)

Main

Constructor

Static Block

C)

Static Block

Main

Constructor

D)

Constructor

Static Block

Main

Answer: C

20
Common Mistakes Asked in TCS
❌ Wrong

static void show(){

[Link](this);

Compile-Time Error

❌ Wrong

static void show(){

[Link](age);

where age is an instance variable.

Need an object.

❌ Thinking a static block executes every time an object is created.

✔ Static block executes only once.

Memory Tricks
Remember

static

Class

21

One Copy

Shared

Remember

Static Method

No Object

No this

No Instance Variables

Remember

Execution Order

Static Block

Main

Constructor

22
One-Minute Revision
✔ static belongs to the class, not the object.

✔ Static variables are shared by all objects.

✔ Static methods can be called using the class name.

✔ main() is static because the JVM invokes it without creating an object.

✔ Static methods cannot directly access instance variables or non-static methods.

✔ Static methods cannot use this or super .

✔ Static blocks execute once, when the class is loaded.

✔ Execution order:

Static Block → Main Method → Constructor

TCS Tip: Focus on execution order, static block output questions, static vs instance members, and why
main() is static. These are among the most frequently asked Java MCQ topics in TCS IPA.

23
CORE JAVA FOR TCS IPA
Chapter 11 | Inheritance — Detailed Notes & MCQs

1. What is Inheritance?
Inheritance is the process by which one class acquires the properties and methods of another class.
It promotes code reusability.

Inheritance represents an IS-A Relationship.

✔ Dog IS-A Animal


✔ Car IS-A Vehicle
✔ Student IS-A Person
In Java, the child class inherits the properties of the parent class.

2. Why Do We Need Inheritance?


Without Inheritance
class Dog{
void eat(){
[Link]("Eating");
}
}

class Cat{
void eat(){
[Link]("Eating");
}
}
The same code is repeated.

Using Inheritance
class Animal{
void eat(){
[Link]("Eating");
}
}

class Dog extends Animal{


}
Dog automatically gets the eat() method.

Advantages
✔ Code Reusability
✔ Less Code
✔ Easy Maintenance

Core Java for TCS IPA — Chapter 11: Inheritance Page 1


✔ Supports Method Overriding
✔ Improves Readability

3. Parent Class and Child Class


class Animal{
void eat(){
[Link]("Eating");
}
}

class Dog extends Animal{


void bark(){
[Link]("Barking");
}
}

Animal Parent Class / Superclass / Base Class

Dog Child Class / Subclass / Derived Class

4. extends Keyword
Inheritance is achieved using extends.

Syntax
class Child extends Parent{
}

Example
class Animal{
void eat(){
[Link]("Eating");
}
}

class Dog extends Animal{


void bark(){
[Link]("Barking");
}
}

public class Main{


public static void main(String[] args){
Dog d = new Dog();
[Link]();
[Link]();
}
}
Output: Eating, Barking

5. Types of Inheritance
Core Java for TCS IPA — Chapter 11: Inheritance Page 2
Java supports:

✔ Single Inheritance
✔ Multilevel Inheritance
✔ Hierarchical Inheritance
Java does NOT support:

■ Multiple Inheritance (through classes)

5.1 Single Inheritance


One Parent → One Child (Animal → Dog)
class Animal{
void eat(){
[Link]("Eating");
}
}

class Dog extends Animal{


}

5.2 Multilevel Inheritance


One class inherits another, which inherits another. (Animal → Dog → Puppy)
class Animal{
void eat(){
[Link]("Eating");
}
}

class Dog extends Animal{


void bark(){
[Link]("Bark");
}
}

class Puppy extends Dog{


void sleep(){
[Link]("Sleep");
}
}
Output: Eating, Bark, Sleep

5.3 Hierarchical Inheritance


One Parent → Multiple Children (Animal → Dog, Cat, Cow)
class Animal{
void eat(){
[Link]("Eating");
}
}

class Dog extends Animal{


}

Core Java for TCS IPA — Chapter 11: Inheritance Page 3


class Cat extends Animal{
}
Both Dog and Cat inherit eat().

6. Multiple Inheritance
Java does NOT support multiple inheritance using classes.
// Wrong
class C extends A, B{
}
■ Compile-Time Error

Why Doesn't Java Support Multiple Inheritance?


Because of the Diamond Problem.

Suppose class A has method show(). Classes B and C both extend A and both override show(). Now
class D inherits from both B and C — which show() should D execute? This ambiguity is the Diamond
Problem.

Java avoids this problem by not allowing multiple inheritance through classes.

7. Multiple Inheritance Using Interfaces


Java supports multiple inheritance using interfaces.
interface A{
void show();
}

interface B{
void display();
}

class C implements A,B{


public void show(){
}
public void display(){
}
}
This is perfectly valid.

8. IS-A Relationship
Inheritance represents IS-A.

✔ Dog IS-A Animal


✔ Car IS-A Vehicle
Not Car HAS-A Engine — HAS-A represents Composition, not inheritance.

Core Java for TCS IPA — Chapter 11: Inheritance Page 4


9. Object Creation
Dog d = new Dog();
The object gets:

✔ Parent members
✔ Child members

10. Constructor in Inheritance


When a child object is created, the Parent constructor executes first, then the Child constructor.
class Animal{
Animal(){
[Link]("Animal");
}
}

class Dog extends Animal{


Dog(){
[Link]("Dog");
}
}
Output: Animal, Dog

Reason: Java automatically calls super();

11. Inheritance vs Composition


Inheritance Composition

IS-A Relationship HAS-A Relationship

Uses extends Uses objects

Reuses parent class Reuses object

✔ Dog IS-A Animal — Inheritance


✔ Car HAS-A Engine — Composition

Core Java for TCS IPA — Chapter 11: Inheritance Page 5


12. Frequently Asked TCS MCQs
MCQ 1. Inheritance represents
A) HAS-A
B) IS-A
C) PART-OF
D) NONE
Answer: B

MCQ 2. Which keyword is used for inheritance?


A) inherit
B) extends
C) implements
D) super
Answer: B

MCQ 3. Java supports


A) Single Inheritance
B) Multilevel Inheritance
C) Hierarchical Inheritance
D) All of the above
Answer: D

MCQ 4. Java does NOT support


A) Single
B) Multilevel
C) Hierarchical
D) Multiple Inheritance using classes
Answer: D

MCQ 5. Why doesn't Java support multiple inheritance using classes?


A) Memory Problem
B) Diamond Problem
C) Speed Problem
D) Security Problem
Answer: B

MCQ 6. Java supports multiple inheritance through


A) Classes
B) Objects
C) Interfaces
D) Constructors
Answer: C

Core Java for TCS IPA — Chapter 11: Inheritance Page 6


MCQ 7. Which relationship is represented by inheritance?
A) HAS-A
B) IS-A
C) PART-OF
D) NONE
Answer: B

MCQ 8. Output of: class A{ void show(){ [Link]("A"); } } class B extends A{ }


public class Main{ public static void main(String[] args){ B obj = new B(); [Link](); } }
A) A
B) B
C) Error
D) null
Answer: A

MCQ 9. Which inheritance type has one parent and one child?
A) Single
B) Multiple
C) Hierarchical
D) Hybrid
Answer: A

MCQ 10. Which inheritance type has one parent and many children?
A) Single
B) Hierarchical
C) Multilevel
D) Multiple
Answer: B

MCQ 11. Which inheritance type forms a chain?


A) Single
B) Hierarchical
C) Multilevel
D) Hybrid
Answer: C

MCQ 12. Output of: class A{ A(){ [Link]("A"); } } class B extends A{ B(){
[Link]("B"); } } public class Main{ public static void main(String[] args){ new B(); }
}
A) B then A
B) A then B
C) Error
D) Nothing
Answer: B

Core Java for TCS IPA — Chapter 11: Inheritance Page 7


MCQ 13. Which class is called the Superclass?
A) Parent Class
B) Child Class
C) Object
D) Interface
Answer: A

MCQ 14. Which statement is FALSE?


A) Java supports multiple inheritance through interfaces.
B) Java supports multiple inheritance through classes.
C) Java supports hierarchical inheritance.
D) Java supports multilevel inheritance.
Answer: B

MCQ 15. Which keyword is used to implement multiple inheritance in Java?


A) extends
B) inherits
C) implements
D) super
Answer: C

Core Java for TCS IPA — Chapter 11: Inheritance Page 8


13. Common Mistakes Asked in TCS
■ Wrong:
class C extends A,B{
}
■ Compile-Time Error

■ Thinking Java completely does not support multiple inheritance.


✔ Correct: Java does not support multiple inheritance using classes, but does support it using
interfaces.
■ Confusing IS-A and HAS-A relationships.
✔ Remember: Dog IS-A Animal → Inheritance Car HAS-A Engine → Composition

14. Memory Tricks


Inheritance IS-A Relationship

extends Inheritance

Single 1 Parent → 1 Child

Multiple Inheritance Classes ■, Interfaces ✔

Constructor Order Parent Constructor → Child Constructor

15. One-Minute Revision


✔ Inheritance allows one class to acquire the properties and methods of another class.

✔ Inheritance represents an IS-A Relationship.

✔ Use the extends keyword for class inheritance.

✔ Java supports Single, Multilevel, and Hierarchical inheritance.

✔ Java does not support Multiple Inheritance through classes because of the Diamond Problem.

✔ Java supports Multiple Inheritance through interfaces using the implements keyword.

✔ Parent constructors execute before child constructors.

✔ Parent Class = Superclass = Base Class.

✔ Child Class = Subclass = Derived Class.

■ TCS Tip
The most frequently asked questions are: types of inheritance, the extends keyword, why multiple
inheritance is not supported by classes, multiple inheritance using interfaces, constructor execution
order, and IS-A vs HAS-A relationship.

Core Java for TCS IPA — Chapter 11: Inheritance Page 9


CORE JAVA FOR TCS IPA
Chapter 12 | Method Overloading & Method Overriding — Detailed Notes & MCQs

1. What is Polymorphism?
Polymorphism means “One Name, Many Forms.” In Java, polymorphism is of 2 types:

Compile-Time Polymorphism → Method Overloading

Run-Time Polymorphism → Method Overriding


This is one of the most important TCS IPA Java topics.

2. Method Overloading
Definition
Method Overloading means having multiple methods with the same name but different parameter
lists in the same class.

It is called Compile-Time Polymorphism because the compiler decides which method to call.

Rules of Method Overloading


Methods must have the same method name, and one of the following:

✔ Different number of parameters, OR


✔ Different type of parameters, OR
✔ Different order of parameters

Example 1 — Different Number of Parameters


class Calculator{
int add(int a,int b){
return a+b;
}
int add(int a,int b,int c){
return a+b+c;
}
public static void main(String[] args){
Calculator c=new Calculator();
[Link]([Link](10,20));
[Link]([Link](10,20,30));
}
}
Output: 30, 60

Example 2 — Different Data Types

Core Java for TCS IPA — Chapter 12: Method Overloading & Overriding Page 1
class Demo{
void show(int a){
[Link]("Integer");
}
void show(double a){
[Link]("Double");
}
}
Output: Integer, Double

Example 3 — Different Order


void display(int a,String b){
}

void display(String b,int a){


}
✔ Valid Overloading.

Invalid Overloading
Only changing the return type is NOT overloading.
// Wrong
int add(int a,int b){
return a+b;
}

double add(int a,int b){


return a+b;
}
■ Compile-Time Error

Reason: Return type alone cannot differentiate methods.

Method Overloading Features


✔ Same method name
✔ Different parameter list
✔ Same class
✔ Compile-Time Binding
✔ Faster execution

3. Method Overriding
Definition
Method Overriding means a child class provides its own implementation of a method already present
in the parent class.

It is called Run-Time Polymorphism because the JVM decides which method to execute during
runtime.

Rules of Method Overriding

Core Java for TCS IPA — Chapter 12: Method Overloading & Overriding Page 2
✔ Same name
✔ Same parameters
✔ Same return type (or covariant return type)
✔ Parent-Child relationship

Example
class Animal{
void sound(){
[Link]("Animal Sound");
}
}

class Dog extends Animal{


@Override
void sound(){
[Link]("Dog Barks");
}
}

public class Main{


public static void main(String[] args){
Animal a=new Dog();
[Link]();
}
}
Output: Dog Barks

Reason: Runtime decides which method to execute.

4. Dynamic Method Dispatch


Animal a = new Dog();
[Link]();

Reference Type → Animal

Object Type → Dog

Method Executed → Dog's method


This is called Dynamic Method Dispatch.

5. Methods That Cannot Be Overridden


1. final Method
class A{
final void show(){
}
}

class B extends A{
void show(){
}

Core Java for TCS IPA — Chapter 12: Method Overloading & Overriding Page 3
}
■ Compile-Time Error

Reason: final methods cannot be overridden.

2. private Method
Private methods are not inherited. Hence, they cannot be overridden.

3. static Method
Static methods belong to the class. They are hidden, not overridden.
class A{
static void show(){
[Link]("A");
}
}

class B extends A{
static void show(){
[Link]("B");
}
}
This is called Method Hiding, not overriding.

6. Overloading vs Overriding
Method Overloading Method Overriding

Same method name Same method name

Different parameters Same parameters

Same class Parent and Child classes

Compile-Time Polymorphism Run-Time Polymorphism

Compiler decides JVM decides

Inheritance not required Inheritance required

7. Method Hiding
Static methods cannot be overridden. Instead, they are hidden.
class A{
static void show(){
[Link]("A");
}
}

class B extends A{
static void show(){
[Link]("B");

Core Java for TCS IPA — Chapter 12: Method Overloading & Overriding Page 4
}
}
This is Method Hiding.

8. @Override Annotation
@Override
void show(){
}

Benefits
✔ Improves readability
✔ Compiler checks overriding errors

Core Java for TCS IPA — Chapter 12: Method Overloading & Overriding Page 5
9. Frequently Asked TCS MCQs
MCQ 1. Method Overloading is
A) Runtime Polymorphism
B) Compile-Time Polymorphism
C) Dynamic Binding
D) None
Answer: B

MCQ 2. Method Overriding is


A) Compile-Time Polymorphism
B) Runtime Polymorphism
C) Constructor Overloading
D) None
Answer: B

MCQ 3. Method Overloading requires


A) Same parameters
B) Different parameters
C) Different class
D) Different return type only
Answer: B

MCQ 4. Can return type alone overload methods?


A) Yes
B) No
C) Sometimes
D) Only in Java 8
Answer: B

MCQ 5. Method Overriding requires


A) Same name
B) Same parameters
C) Parent-Child relationship
D) All of the above
Answer: D

MCQ 6. Which methods cannot be overridden?


A) final
B) private
C) static
D) All of the above
Answer: D

Core Java for TCS IPA — Chapter 12: Method Overloading & Overriding Page 6
MCQ 7. Can constructors be overridden?
A) Yes
B) No
C) Only default constructor
D) Only parameterized constructor
Answer: B

MCQ 8. Can constructors be overloaded?


A) Yes
B) No
C) Only in interfaces
D) Only in abstract class
Answer: A

MCQ 9. Output of: class A{ void show(){ [Link]("A"); } } class B extends A{ void
show(){ [Link]("B"); } } public class Main{ public static void main(String[] args){ A
obj=new B(); [Link](); } }
A) A
B) B
C) Compile Error
D) Runtime Error
Answer: B

MCQ 10. Overloading occurs in


A) Same class
B) Different classes only
C) Interfaces only
D) Abstract classes only
Answer: A

MCQ 11. Which keyword helps verify overriding?


A) @Static
B) @Override
C) @Super
D) @Check
Answer: B

MCQ 12. Static methods are


A) Overridden
B) Hidden
C) Deleted
D) Overloaded only
Answer: B

Core Java for TCS IPA — Chapter 12: Method Overloading & Overriding Page 7
MCQ 13. Which statement is TRUE?
A) private methods can be overridden.
B) final methods can be overridden.
C) static methods participate in method hiding.
D) Constructors are overridden.
Answer: C

MCQ 14. Which type of polymorphism is faster?


A) Runtime
B) Compile-Time
C) Both are same
D) None
Answer: B
Explanation: Compile-time polymorphism is resolved by the compiler, so it has less overhead than runtime
method dispatch.

MCQ 15. Which of the following is NOT method overloading? int add(int a,int b) and double
add(int a,int b)
A) Valid overloading
B) Invalid because only return type changes
C) Runtime polymorphism
D) Constructor overloading
Answer: B

Core Java for TCS IPA — Chapter 12: Method Overloading & Overriding Page 8
10. Common Mistakes Asked in TCS
■ Wrong:
int add(int a,int b){
}

double add(int a,int b){


}
Only the return type changes. Not overloading.

■ Thinking static methods are overridden.


✔ They are hidden, not overridden.
■ Trying to override a final method.
✔ Compile-Time Error.

11. Memory Tricks


Overloading Same Name → Different Parameters → Compile Time

Overriding Same Signature → Inheritance → Runtime

Cannot Override final, private, static

12. One-Minute Revision


✔ Method Overloading = Same method name + Different parameters.

✔ Overloading provides Compile-Time Polymorphism.

✔ Method Overriding = Same method signature in parent and child classes.

✔ Overriding provides Run-Time Polymorphism.

✔ Overloading occurs in the same class.

✔ Overriding requires inheritance.

✔ Return type alone cannot overload a method.

✔ final methods cannot be overridden.

✔ private methods cannot be overridden because they are not inherited.

✔ static methods are hidden, not overridden.

✔ Use @Override to ensure correct method overriding.

13. TCS IPA Memory Shortcut


Feature Overloading Overriding

Method Name Same Same

Parameters Different Same

Core Java for TCS IPA — Chapter 12: Method Overloading & Overriding Page 9
Return Type Can differ (not alone) Same / Covariant

Class Same Class Parent & Child

Polymorphism Compile-Time Run-Time

Inheritance Not Required Required

Decision Taken By Compiler JVM

■ Most Expected TCS MCQs


• Difference between Overloading and Overriding.

• Can constructors be overloaded? → ■ Yes

• Can constructors be overridden? → ■ No

• Can final, private, and static methods be overridden? → ■ No

• Why is overloading called Compile-Time Polymorphism?

• Why is overriding called Run-Time Polymorphism?

TCS Tip: This chapter is one of the top 5 most important Java topics for TCS IPA. Be especially
confident with the comparison table and output-based questions involving overridden methods.

Core Java for TCS IPA — Chapter 12: Method Overloading & Overriding Page 10
CORE JAVA FOR TCS IPA
Chapter 13 | Polymorphism — Detailed Notes & MCQs

1. What is Polymorphism?
Polymorphism means “One Name, Many Forms.”

Poly = Many | Morphism = Forms

In Java, the same method name can behave differently depending on the situation.

Example: A person can be a Student, an Employee, and a Father — the same person, different
roles. Similarly, one method can have different behaviors.

2. Types of Polymorphism
Java supports two types of polymorphism:

Compile-Time Polymorphism Run-Time Polymorphism

Method Overloading Method Overriding

3. Compile-Time Polymorphism
Also called: Static Binding, Early Binding, Method Overloading

The compiler decides which method to execute.

Example
class Calculator{
int add(int a,int b){
return a+b;
}
int add(int a,int b,int c){
return a+b+c;
}
public static void main(String[] args){
Calculator c=new Calculator();
[Link]([Link](10,20));
[Link]([Link](10,20,30));
}
}
Output: 30, 60

Reason: The compiler knows which method to call during compilation.

Features of Compile-Time Polymorphism


✔ Method Overloading

Core Java for TCS IPA — Chapter 13: Polymorphism Page 1


✔ Different parameters
✔ Faster
✔ Compiler decides
✔ No inheritance required

4. Run-Time Polymorphism
Also called: Dynamic Binding, Late Binding, Method Overriding

The JVM decides which method to execute during runtime.

Example
class Animal{
void sound(){
[Link]("Animal Sound");
}
}

class Dog extends Animal{


@Override
void sound(){
[Link]("Dog Barks");
}
}

public class Main{


public static void main(String[] args){
Animal a=new Dog();
[Link]();
}
}
Output: Dog Barks

Reason: Reference type = Animal, Object type = Dog — JVM executes Dog's method.

5. Dynamic Method Dispatch


One of the most important TCS concepts.
Animal a = new Dog();
[Link]();

Reference → Animal

Object → Dog

Method executed → Dog's method


Runtime decides. The JVM decides the method during execution, not the compiler.

6. Compile-Time vs Run-Time Polymorphism


Compile-Time Run-Time

Core Java for TCS IPA — Chapter 13: Polymorphism Page 2


Method Overloading Method Overriding

Compiler decides JVM decides

Faster Slightly slower

No inheritance required Inheritance required

Static Binding Dynamic Binding

7. Advantages of Polymorphism
✔ Code Reusability
✔ Flexibility
✔ Loose Coupling
✔ Easy Maintenance
✔ Extensibility

8. Real-Life Example
Class Animal

Method sound()

Dog → Bark

Cat → Meow

Cow → Moo
Same method, different outputs — this is polymorphism.

9. Upcasting & Downcasting


Reference Variable Example
Animal a = new Dog();
✔ Allowed — a parent reference can hold a child object.

Reverse is NOT allowed:


Dog d = new Animal(); // Compile-Time Error

Upcasting
Animal a = new Dog();
Called Upcasting. Automatic. Frequently asked in TCS.

Downcasting
Animal a = new Dog();
Dog d = (Dog)a;

Core Java for TCS IPA — Chapter 13: Polymorphism Page 3


Called Downcasting. Requires explicit type casting.

Method Calls
Animal a = new Dog();
[Link]();
Dog's method executes.

10. Variables are NOT Polymorphic


class A{
int x=10;
}

class B extends A{
int x=20;
}

A obj=new B();
[Link](obj.x);
Output: 10

Reason: Variables use Reference Type. Methods use Object Type. Very Important TCS MCQ.

Core Java for TCS IPA — Chapter 13: Polymorphism Page 4


11. Frequently Asked TCS MCQs
MCQ 1. Polymorphism means
A) One Class
B) Many Forms
C) Multiple Objects
D) Encapsulation
Answer: B

MCQ 2. Compile-Time Polymorphism is achieved using


A) Inheritance
B) Method Overloading
C) Method Overriding
D) Interface
Answer: B

MCQ 3. Run-Time Polymorphism is achieved using


A) Constructor
B) Method Overloading
C) Method Overriding
D) Static Method
Answer: C

MCQ 4. Who decides Compile-Time Polymorphism?


A) JVM
B) Compiler
C) OS
D) CPU
Answer: B

MCQ 5. Who decides Runtime Polymorphism?


A) Compiler
B) JVM
C) IDE
D) OS
Answer: B

MCQ 6. Output of: Animal a = new Dog(); [Link]();


A) Animal Sound
B) Dog Barks
C) Compile Error
D) Runtime Error
Answer: B

Core Java for TCS IPA — Chapter 13: Polymorphism Page 5


MCQ 7. Which is TRUE?
A) Variables are polymorphic.
B) Methods are polymorphic.
C) Constructors are polymorphic.
D) Static methods are polymorphic.
Answer: B

MCQ 8. What is Upcasting?


A) Dog d=new Animal();
B) Animal a=new Dog();
C) Dog d=(Dog)new Animal();
D) None
Answer: B

MCQ 9. Which binding is used in Method Overloading?


A) Dynamic Binding
B) Static Binding
C) Runtime Binding
D) Late Binding
Answer: B

MCQ 10. Which binding is used in Method Overriding?


A) Static Binding
B) Compile Binding
C) Dynamic Binding
D) Early Binding
Answer: C

MCQ 11. Output of: class A{ int x=10; } class B extends A{ int x=20; } A obj=new B();
[Link](obj.x);
A) 20
B) 10
C) Error
D) Runtime Error
Answer: B
Explanation: Variables are resolved using the reference type, not the object type.

MCQ 12. Which statement is FALSE?


A) Overloading is Compile-Time Polymorphism.
B) Overriding is Run-Time Polymorphism.
C) Constructors participate in polymorphism.
D) JVM decides Runtime Polymorphism.
Answer: C

Core Java for TCS IPA — Chapter 13: Polymorphism Page 6


MCQ 13. Can static methods participate in Runtime Polymorphism?
A) Yes
B) No
C) Only in Java 8
D) Only with interfaces
Answer: B

MCQ 14. Can private methods be overridden?


A) Yes
B) No
C) Only in abstract classes
D) Only in interfaces
Answer: B

MCQ 15. Which is faster?


A) Runtime Polymorphism
B) Compile-Time Polymorphism
C) Both
D) None
Answer: B
Explanation: Compile-Time Polymorphism is resolved by the compiler.

Core Java for TCS IPA — Chapter 13: Polymorphism Page 7


12. Common Mistakes Asked in TCS
■ Thinking variables are polymorphic.
✔ Only methods participate in runtime polymorphism.
■ Thinking constructors can be overridden.
✔ Constructors cannot be overridden.
■ Thinking static methods are overridden.
✔ Static methods are hidden.

13. Memory Tricks


Compile-Time Overloading Compiler

Run-Time Overriding JVM

Reference Variable —

Object Method —

Remember: Animal a=new Dog(); → ✔ Upcasting

14. One-Minute Revision


✔ Polymorphism means One Name, Many Forms.

✔ Java has 2 types: Compile-Time (Method Overloading) and Run-Time (Method Overriding).

✔ Compile-Time Polymorphism uses Static Binding and is decided by the Compiler.

✔ Run-Time Polymorphism uses Dynamic Binding and is decided by the JVM.

✔ Methods are polymorphic, but variables are not.

✔ Animal a = new Dog(); is called Upcasting.

✔ Static, private, and final methods do not participate in runtime polymorphism.

15. TCS IPA Memory Shortcut


Topic Compile-Time Run-Time

Achieved By Method Overloading Method Overriding

Decided By Compiler JVM

Binding Static Binding Dynamic Binding

Inheritance Not Required Required

Speed Faster Slightly Slower

Core Java for TCS IPA — Chapter 13: Polymorphism Page 8


■ Most Expected TCS MCQ Takeaways
• Polymorphism means Many Forms.

• Compile-Time Polymorphism → Method Overloading.

• Run-Time Polymorphism → Method Overriding.

• Compiler decides Overloading.

• JVM decides Overriding.

• Animal a = new Dog(); → Upcasting.

• Variables are not polymorphic.

• Static methods are hidden, not overridden.

Core Java for TCS IPA — Chapter 13: Polymorphism Page 9


CORE JAVA FOR TCS IPA – Chapter 14:
Encapsulation (Detailed Notes + MCQs)

What is Encapsulation?
Encapsulation is the process of binding (wrapping) data (variables) and methods into a single unit.

In Java, a class is an example of encapsulation because it contains both variables and methods.

It is one of the four pillars of Object-Oriented Programming (OOP).

Definition
Encapsulation means:

Binding data and methods together into a single unit while protecting the data from
unauthorized access.

Why Do We Need Encapsulation?


Without encapsulation,

Anyone can directly modify data.

Example

```java id="f2d1p7" class Student{

int age;

public class Main{

public static void main(String[] args){

Student s = new Student();

1
[Link] = -50;

Here,

Invalid data is stored.

Encapsulation prevents this.

---

# How is Encapsulation Achieved?

Java achieves encapsulation using:

✔ **Private Variables**

✔ **Public Getter Methods**

✔ **Public Setter Methods**

Memory Trick

```text id="4c19xa"
Private Data

Getter

Read Data

Setter

Update Data

2
Private Variables
A private variable cannot be accessed directly outside the class.

Example

```java id="8m20tg" class Student{

private int age;

Wrong

```java id="e4z8v1"
Student s = new Student();

[Link] = 20;

Compile-Time Error

Reason

age is private.

Getter Method
Getter returns the value of a private variable.

Syntax

```java id="c7q2sx" public int getAge(){

return age;

Example

3
```java id="6c7q0m"
class Student{

private int age = 20;

public int getAge(){

return age;

Output

```text id="j8l6eq" 20

---

# Setter Method

Setter updates the value of a private variable.

Syntax

```java id="3n8v4f"
public void setAge(int age){

[Link] = age;

Example

```java id="4w1d9y" class Student{

private int age;

public void setAge(int age){

[Link] = age;

4
}

---

# Complete Example

```java id="5k4z1c"
class Student{

private int age;

public void setAge(int age){

[Link] = age;

public int getAge(){

return age;

public class Main{

public static void main(String[] args){

Student s = new Student();

[Link](21);

[Link]([Link]());

Output

```text id="0m8v2p" 21

---

5
# Encapsulation Diagram

```text id="v3d1pt"
User

Setter

Private Variable

Getter

User

The user cannot access the variable directly.

Advantages of Encapsulation
✔ Data Hiding

✔ Better Security

✔ Easy Maintenance

✔ Better Control Over Data

✔ Improves Reusability

✔ Makes Code Flexible

Data Hiding vs Encapsulation


Many students confuse these concepts.

6
Encapsulation Data Hiding

Wraps data and methods together Restricts direct access to data

Achieved using classes Achieved using private access modifier

Broader concept Part of encapsulation

Memory Trick

```text id="0w4tq7" Encapsulation

Wrap Data + Methods

Data Hiding

Private Variables

---

# Validation Using Setter

Setter methods can validate data.

Example

```java id="1f8n3v"
class Student{

private int age;

public void setAge(int age){

if(age > 0){

[Link] = age;

public int getAge(){

7
return age;

Now invalid values cannot be stored.

Naming Convention
Getter

```java id="8r3q7h" getVariableName()

Setter

```java id="7m6z1a"
setVariableName()

Example

```text id="9x5p2l" getAge()

setAge()

getName()

setName()

---

# Frequently Asked TCS MCQs

### MCQ 1

Encapsulation means

A) Hiding methods

B) Binding data and methods together

8
C) Multiple inheritance

D) Method overloading

**Answer:** B

---

### MCQ 2

Encapsulation is achieved using

A) Public Variables

B) Private Variables

C) Static Variables

D) Final Variables

**Answer:** B

---

### MCQ 3

Which methods are commonly used in encapsulation?

A) Constructor

B) Getter and Setter

C) Main Method

D) Static Method

**Answer:** B

---

### MCQ 4

Which keyword is used for data hiding?

A) public

B) protected

9
C) private

D) static

**Answer:** C

---

### MCQ 5

Getter method is used to

A) Update data

B) Read data

C) Delete data

D) Hide data

**Answer:** B

---

### MCQ 6

Setter method is used to

A) Read data

B) Update data

C) Delete data

D) Create objects

**Answer:** B

---

### MCQ 7

Output

```java id="6z2t5k"
class Test{

private int x = 10;

10
public int getX(){

return x;

public class Main{

public static void main(String[] args){

Test t = new Test();

[Link]([Link]());

A) 10

B) 0

C) Error

D) null

Answer: A

MCQ 8

Can private variables be accessed directly outside the class?

A) Yes

B) No

C) Only in subclasses

D) Only using static methods

Answer: B

11
MCQ 9

Which of the following provides better security?

A) Public Variables

B) Encapsulation

C) Static Methods

D) Constructors

Answer: B

MCQ 10

Which is TRUE?

A) Encapsulation hides methods.

B) Encapsulation wraps data and methods together.

C) Encapsulation allows direct access to private variables.

D) Getter updates variables.

Answer: B

MCQ 11

Which naming convention is correct for a getter?

A) age()

B) getAge()

C) setAge()

D) fetch()

Answer: B

12
MCQ 12

Which naming convention is correct for a setter?

A) age()

B) getAge()

C) setAge()

D) update()

Answer: C

MCQ 13

Which OOP concept improves data security?

A) Inheritance

B) Encapsulation

C) Polymorphism

D) Overloading

Answer: B

MCQ 14

Can setter methods perform validation?

A) Yes

B) No

C) Only in Java 8

D) Only in interfaces

Answer: A

13
MCQ 15

Which statement is FALSE?

A) Getter reads data.

B) Setter modifies data.

C) Private variables can be accessed directly outside the class.

D) Encapsulation uses private variables.

Answer: C

Common Mistakes Asked in TCS


❌ Wrong

```java id="9h2d4m" [Link] = 25;

when `age` is private.

✔ Correct

```java id="3v8m1q"
[Link](25);

❌ Thinking Getter modifies data.

✔ Getter reads data.

❌ Thinking Setter returns data.

✔ Setter usually has a void return type and updates data.

Memory Tricks
Remember

14
```text id="8c5j1r" Encapsulation

Binding

Data + Methods

---

Remember

```text id="4n7w2k"
private

Data Hiding

Remember

```text id="5m1q8v" Getter

Get

Read

---

Remember

```text id="2d9x6f"
Setter

Set

15

Update

One-Minute Revision
✔ Encapsulation means binding data and methods together into one unit.

✔ Achieved using private variables and public getter/setter methods.

✔ Getter is used to read data.

✔ Setter is used to modify/update data.

✔ Encapsulation provides data hiding, security, maintainability, and better control over data.

✔ Private variables cannot be accessed directly outside the class.

✔ Setter methods can perform validation before updating data.

🎯 TCS IPA Memory Shortcut

Concept Remember

Encapsulation Data + Methods

Data Hiding private

Getter Read Data

Setter Update Data

Main Benefit Security & Controlled Access

⭐ Most Expected TCS MCQs

• What is Encapsulation?
• How is Encapsulation achieved?
• Difference between Getter and Setter.
• Can private variables be accessed directly?
• Which access modifier provides data hiding?
• Advantages of Encapsulation.

16
CORE JAVA FOR TCS IPA – Chapter 15: Abstraction
(Detailed Notes + MCQs)

What is Abstraction?
Abstraction means hiding implementation details and showing only essential functionality to the user.

It is one of the four pillars of Object-Oriented Programming (OOP).

Example:

When you drive a car,

• You know how to start, accelerate, and brake.


• You do not need to know how the engine internally works.

This is Abstraction.

Definition
Abstraction is the process of hiding implementation details and exposing only the necessary features
to the user.

Why Do We Need Abstraction?


Without abstraction,

Users would have to understand every implementation detail.

With abstraction,

Users interact only with the required functionality.

Advantages:

✔ Security

✔ Simplicity

1
✔ Code Reusability

✔ Easy Maintenance

✔ Loose Coupling

How is Abstraction Achieved?


Java achieves abstraction using:

✔ Abstract Class

✔ Interface

Memory Trick

```text id="4mzq1r" Abstraction

Abstract Class

Interface

---

# Abstract Class

An abstract class is a class declared using the **abstract** keyword.

Syntax

```java id="7r2g6m"
abstract class Animal{

An abstract class cannot be instantiated.

Wrong

2
```java id="2p4v9d" Animal a = new Animal();

Compile-Time Error

---

# Abstract Method

An abstract method has **no body**.

Syntax

```java id="9n8j2f"
abstract void sound();

Example

```java id="5v6c1x" abstract class Animal{

abstract void sound();

The child class must provide the implementation.

---

# Example of Abstract Class

```java id="8d3h7m"
abstract class Animal{

abstract void sound();

class Dog extends Animal{

void sound(){

[Link]("Dog Barks");

3
}

public class Main{

public static void main(String[] args){

Animal a = new Dog();

[Link]();

Output

```text id="3f8x0w" Dog Barks

---

# Can an Abstract Class Have Normal Methods?

Yes.

Example

```java id="6j2y5t"
abstract class Animal{

void eat(){

[Link]("Eating");

Abstract classes can contain both:

✔ Abstract Methods

✔ Normal Methods

4
Can an Abstract Class Have a Constructor?
Yes.

Example

```java id="1c5v7z" abstract class Animal{

Animal(){

[Link]("Constructor Called");

The constructor executes when a child object is created.

---

# Can an Abstract Class Have Variables?

Yes.

Example

```java id="2q6k8n"
abstract class Animal{

int age = 10;

Important Facts About Abstract Classes


✔ Can have constructors

✔ Can have normal methods

✔ Can have abstract methods

5
✔ Can have variables

✔ Cannot create objects directly

Interface
An Interface is a blueprint that specifies what a class must do.

It is declared using the interface keyword.

Syntax

```java id="4t7m9p" interface Animal{

void sound();

Methods are **public and abstract** by default.

---

# Implementing an Interface

Use the **implements** keyword.

Example

```java id="7h3n1y"
interface Animal{

void sound();

class Dog implements Animal{

public void sound(){

[Link]("Dog Barks");

6
}

Output

```text id="5x9r2v" Dog Barks

---

# Interface Features

✔ Supports Multiple Inheritance

✔ No Constructors

✔ No Objects

✔ Methods are public and abstract (by default)

✔ Variables are public static final (constants)

---

# Java 8 Features in Interface

From Java 8,

Interfaces can have

✔ Default Methods

✔ Static Methods

Example

```java id="3w8f6r"
interface Test{

default void show(){

[Link]("Default");

static void display(){

7
[Link]("Static");

Java 9 Features in Interface


From Java 9,

Interfaces can also have

✔ Private Methods

Example

```java id="9m2k4q" interface Test{

private void helper(){

---

# Can an Interface Have a Constructor?

No.

Example

```java id="6x1p8b"
interface Demo{

Demo(){

8
Compile-Time Error

Reason

Interfaces cannot create objects,

so constructors are not allowed.

Abstract Class vs Interface


Abstract Class Interface

Uses abstract class Uses interface

Can have constructors Cannot have constructors

Can have abstract methods Methods are abstract by default

Can have normal methods Can have default & static methods (Java 8+)

Can have instance variables Variables are public static final

Uses extends Uses implements

extends vs implements
```java id="5p7c2d" class Dog extends Animal

Used for

Abstract Class / Class

---

```java id="4y1n8s"
class Dog implements Animal

Used for

9
Interface

Multiple Inheritance Using Interface


Example

```java id="8r6v5k" interface A{

interface B{

class C implements A,B{

Valid

---

# Frequently Asked TCS MCQs

### MCQ 1

Abstraction means

A) Data Hiding

B) Hiding implementation details

C) Method Overloading

D) Inheritance

**Answer:** B

---

### MCQ 2

Abstraction is achieved using

10
A) Abstract Class

B) Interface

C) Both A and B

D) Constructor

**Answer:** C

---

### MCQ 3

Can an abstract class have a constructor?

A) Yes

B) No

C) Only private

D) Only protected

**Answer:** A

---

### MCQ 4

Can an interface have a constructor?

A) Yes

B) No

C) Only default constructor

D) Only parameterized constructor

**Answer:** B

---

### MCQ 5

Can an abstract class have normal methods?

11
A) Yes

B) No

C) Only static methods

D) Only final methods

**Answer:** A

---

### MCQ 6

Can an abstract class have abstract methods?

A) Yes

B) No

C) Only one

D) Only protected

**Answer:** A

---

### MCQ 7

Can we create an object of an abstract class?

A) Yes

B) No

C) Only in Java 8

D) Only using `new`

**Answer:** B

---

### MCQ 8

Which keyword is used to implement an interface?

12
A) extends

B) inherits

C) implements

D) super

**Answer:** C

---

### MCQ 9

Java 8 introduced which methods in interfaces?

A) Abstract Methods

B) Default and Static Methods

C) Constructors

D) Private Variables

**Answer:** B

---

### MCQ 10

Java 9 introduced which feature in interfaces?

A) Constructors

B) Private Methods

C) Final Methods

D) Instance Variables

**Answer:** B

---

### MCQ 11

Which statement is TRUE?

13
A) Interfaces can have constructors.

B) Interfaces support multiple inheritance.

C) Abstract classes cannot have variables.

D) Abstract classes cannot have constructors.

**Answer:** B

---

### MCQ 12

Which keyword is used for an abstract class?

A) interface

B) class

C) abstract

D) final

**Answer:** C

---

### MCQ 13

Output

```java id="7z5r3n"
abstract class A{

abstract void show();

class B extends A{

void show(){

[Link]("Hello");

14
public class Main{

public static void main(String[] args){

A obj = new B();

[Link]();

A) Hello

B) Error

C) Nothing

D) null

Answer: A

MCQ 14

Which is NOT allowed?

A) Constructor in Abstract Class

B) Constructor in Interface

C) Default Method in Interface

D) Static Method in Interface

Answer: B

MCQ 15

Variables in an interface are

A) private

15
B) public static final

C) protected

D) instance variables

Answer: B

Common Mistakes Asked in TCS


❌ Wrong

```java id="2d8m5q" Animal a = new Animal();

when `Animal` is an abstract class.

✔ Abstract classes cannot be instantiated.

---

❌ Thinking interfaces can have constructors.

✔ Interfaces **cannot** have constructors.

---

❌ Using `extends` instead of `implements` for interfaces.

✔ Use

```java id="6k4x1p"
implements

Memory Tricks
Remember

```text id="8v3q7m" Abstraction

16
Hide Implementation

Show Functionality

---

Remember

```text id="3p6n8t"
Abstract Class

Constructor ✔

Normal Methods ✔

Abstract Methods ✔

Remember

```text id="9r2m4k" Interface

Constructor ❌

Default Method ✔ (Java 8)

Static Method ✔ (Java 8)

Private Method ✔ (Java 9)

---

Remember

```text id="1y7w5c"
Abstract Class

17
extends

Interface

implements

One-Minute Revision
✔ Abstraction hides implementation details and exposes only essential functionality.

✔ Java achieves abstraction using Abstract Classes and Interfaces.

✔ Abstract classes can have:

• Constructors
• Normal methods
• Abstract methods
• Variables

✔ Interfaces cannot have constructors.

✔ Interface methods are public and abstract by default.

✔ Java 8 introduced default and static methods in interfaces.

✔ Java 9 introduced private methods in interfaces.

✔ Use extends for abstract classes and implements for interfaces.

✔ Interfaces support multiple inheritance.

🎯 TCS IPA Memory Shortcut

Topic Abstract Class Interface

Constructor ✅ Yes ❌ No

Normal Methods ✅ Yes ✅ Default (Java 8+)

Abstract Methods ✅ Yes ✅ Yes

18
Topic Abstract Class Interface

Static Methods ✅ Yes ✅ Java 8+

Private Methods ✅ Yes ✅ Java 9+

Multiple Inheritance ❌ No ✅ Yes

Keyword extends implements

⭐ Most Expected TCS MCQs

• What is Abstraction?
• How is Abstraction achieved?
• Can an abstract class have a constructor? → ✅ Yes
• Can an interface have a constructor? → ❌ No
• Java 8 interface features → default & static methods
• Java 9 interface feature → private methods
• Difference between Abstract Class and Interface
• Which keyword is used with interfaces? → implements

19
CORE JAVA FOR TCS IPA – Chapter 16: Access
Modifiers (Detailed Notes + MCQs)

What are Access Modifiers?


Access Modifiers are keywords that define the visibility (accessibility) of classes, variables, methods, and
constructors.

They determine who can access a member of a class.

Java provides four access modifiers:

1. private
2. default (Package-Private)
3. protected
4. public

This is one of the most frequently asked TCS IPA Java MCQ topics.

Why Do We Need Access Modifiers?


Access modifiers help in:

✔ Data Security

✔ Encapsulation

✔ Controlled Access

✔ Better Code Organization

✔ Information Hiding

Types of Access Modifiers


```text id="3a9k7p" Access Modifiers

1
private

default

protected

public

---

# 1. private

The **most restrictive** access modifier.

A private member is accessible **only inside the same class**.

Example

```java id="5f2w8c"
class Student{

private int age = 20;

void show(){

[Link](age);

Wrong

```java id="1n6v4b" Student s = new Student();

[Link]([Link]);

Compile-Time Error

Reason

`age` is private.

---

2
# private Access Table

| Same Class | Same Package | Subclass | Other Package |


|------------|--------------|-----------|---------------|
| ✅ Yes | ❌ No | ❌ No | ❌ No |

Memory Trick

```text id="9m3d6r"
private

Only My Class

2. Default (Package-Private)
If no access modifier is specified,

Java assigns default access.

Example

```java id="7b1k9q" class Student{

int age;

Only classes within the **same package** can access it.

---

# Default Access Table

| Same Class | Same Package | Subclass | Other Package |


|------------|--------------|-----------|---------------|
| ✅ Yes | ✅ Yes | ❌ No | ❌ No |

Memory Trick

3
```text id="4r8y2n"
default

Same Package Only

3. protected
Protected members are accessible

✔ Inside the same class

✔ Inside the same package

✔ In subclasses

✔ In another package only through inheritance

Example

```java id="8x6c1t" class Animal{

protected void sound(){

[Link]("Sound");

Subclass

```java id="3q5m7v"
class Dog extends Animal{

void display(){

sound();

4
}

Works correctly.

protected Access Table


Same Class Same Package Subclass Other Package

✅ Yes ✅ Yes ✅ Yes ✅ Yes (through inheritance)

Memory Trick

```text id="2w4f9s" protected

Package + Child Class

---

# 4. public

The **least restrictive** access modifier.

Public members are accessible from **anywhere**.

Example

```java id="6v7h3k"
public class Student{

public void display(){

[Link]("Hello");

Can be accessed from any package.

5
public Access Table
Same Class Same Package Subclass Other Package

✅ Yes ✅ Yes ✅ Yes ✅ Yes

Memory Trick

```text id="5t1q8m" public

Accessible Everywhere

---

# Complete Access Modifier Table

## ⭐ Must Memorize (Very Important for TCS)

| Modifier | Same Class | Same Package | Subclass | Other Package |


|----------|------------|--------------|-----------|---------------|
| **private** | ✅ Yes | ❌ No | ❌ No | ❌ No |
| **default** | ✅ Yes | ✅ Yes | ❌ No | ❌ No |
| **protected** | ✅ Yes | ✅ Yes | ✅ Yes | ✅ Yes (through inheritance) |
| **public** | ✅ Yes | ✅ Yes | ✅ Yes | ✅ Yes |

This table is one of the **highest probability MCQs** in TCS IPA.

---

# Accessibility Order

```text id="7n8w2j"
private

default

protected

6
public

As we move downward,

Accessibility increases.

Which Modifier is Most Secure?


Answer

```text id="1m4r6v" private

---

# Which Modifier is Least Restrictive?

Answer

```text id="8q9y5c"
public

Access Modifiers for Classes


Top-level classes can have only:

✔ public

✔ default

Not Allowed

❌ private

❌ protected

Example

Correct

7
```java id="9p6d4t" public class Demo{

Correct

```java id="4c2n8f"
class Demo{

Wrong

```java id="2k7m5q" private class Demo{

Compile-Time Error

---

# Access Modifiers for Methods & Variables

Methods and variables can use all four modifiers.

```text id="6b1x4n"
private

default

protected

public

Frequently Asked TCS MCQs


MCQ 1

Which access modifier is the most restrictive?

A) public

8
B) protected

C) private

D) default

Answer: C

MCQ 2

Which access modifier allows access from everywhere?

A) protected

B) default

C) public

D) private

Answer: C

MCQ 3

Which modifier allows access only within the same class?

A) protected

B) public

C) private

D) default

Answer: C

MCQ 4

Default access modifier allows access within

A) Same Class Only

9
B) Same Package

C) Same Package + Subclass

D) Everywhere

Answer: B

MCQ 5

Protected members can be accessed

A) Only in same class

B) Only in same package

C) Same package and subclasses

D) Everywhere without inheritance

Answer: C

MCQ 6

Which modifier provides maximum accessibility?

A) protected

B) default

C) public

D) private

Answer: C

MCQ 7

Which modifier provides maximum security?

A) public

10
B) private

C) protected

D) default

Answer: B

MCQ 8

Which modifiers are allowed for top-level classes?

A) private and protected

B) public and default

C) protected and default

D) all four

Answer: B

MCQ 9

Can a top-level class be private?

A) Yes

B) No

C) Only in Java 8

D) Only abstract classes

Answer: B

MCQ 10

Can a top-level class be protected?

A) Yes

11
B) No

C) Only nested classes

D) Only interfaces

Answer: B

MCQ 11

Which statement is TRUE?

A) Private members are inherited.

B) Private members are accessible outside the class.

C) Private members are accessible only within the same class.

D) Private members are public by default.

Answer: C

MCQ 12

Protected members in another package are accessible

A) Directly

B) Only through inheritance

C) Never

D) Only using objects

Answer: B

MCQ 13

Arrange the access modifiers from least accessible to most accessible.

A)

12
```text id="8f5z2j" public

protected

default

private

B)

```text id="3r7v1n"
private

default

protected

public

C)

```text id="5m4k8p" default

private

protected

public

D)

```text id="9x2c6w"
protected

private

public

default

Answer: B

13
MCQ 14

Which modifier is package-private?

A) private

B) default

C) protected

D) public

Answer: B

MCQ 15

Which statement is FALSE?

A) Public members are accessible everywhere.

B) Default members are accessible outside the package.

C) Protected members are accessible in subclasses.

D) Private members are accessible only within the same class.

Answer: B

Common Mistakes Asked in TCS


❌ Thinking default means "accessible everywhere."

✔ Default means same package only.

❌ Thinking protected means "accessible everywhere."

✔ In another package, it is accessible only through inheritance.

❌ Declaring a top-level class as private .

14
Compile-Time Error.

Memory Tricks
Remember

```text id="2n8y6q" private

Only My Class

---

Remember

```text id="4k1v9m"
default

Same Package

Remember

```text id="7p3r5x" protected

Package + Child Class

---

Remember

```text id="9d6w2t"
public

15
Everywhere

Remember

```text id="5q7m1k" Accessibility

private

default

protected

public ```

One-Minute Revision
✔ Java has 4 Access Modifiers:

• private
• default
• protected
• public

✔ private → Accessible only within the same class.

✔ default → Accessible within the same package.

✔ protected → Accessible in the same package and in subclasses (including other packages through
inheritance).

✔ public → Accessible from anywhere.

✔ Top-level classes can only be public or default.

✔ Methods and variables can use all four access modifiers.

16
🎯 TCS IPA Memory Shortcut

Modifier Access

private Same Class Only

default Same Package

protected Same Package + Subclass

public Everywhere

⭐ Must Memorize Table (Highest Weightage)

Modifier Same Class Same Package Subclass Other Package

private ✅ ❌ ❌ ❌

default ✅ ✅ ❌ ❌

protected ✅ ✅ ✅ ✅ (through inheritance)

public ✅ ✅ ✅ ✅

⭐ Most Expected TCS MCQs

• Which is the most restrictive access modifier? → private


• Which is accessible everywhere? → public
• What is the default access modifier? → Package-Private
• Can a top-level class be private? → No
• Protected members in another package are accessible only through inheritance.

17
CORE JAVA FOR TCS IPA – Chapter 17: final
Keyword (Detailed Notes + MCQs)

What is the final Keyword?


The final keyword is used to restrict modification in Java.

Depending on where it is used, final has different meanings.

It can be applied to:

✔ Variable

✔ Method

✔ Class

Memory Trick

```text id="a8d4m1" final

Cannot Change

---

# Uses of `final`

| Used With | Meaning |


|------------|---------|
| Variable | Cannot change value |
| Method | Cannot override |
| Class | Cannot inherit |

This table is frequently asked in TCS IPA.

---

# 1. final Variable

A **final variable** can be assigned **only once**.

1
After initialization, its value **cannot be changed**.

Example

```java id="n3x8v2"
class Demo{

final int x = 10;

void display(){

[Link](x);

Output

```text id="r2m6q8" 10

---

# Trying to Modify a final Variable

```java id="h5w9c4"
class Demo{

final int x = 10;

void show(){

x = 20;

Output

```text id="u7k1n5" Compile-Time Error

2
Reason

A final variable cannot be reassigned.

---

# Blank final Variable

A final variable may be declared without initialization.

It must be initialized **exactly once**.

Example

```java id="k4f7d9"
class Demo{

final int x;

Demo(){

x = 100;

Valid

final Reference Variable


Example

```java id="v1j5r8" final Student s = new Student();

You **cannot change the reference**.

Wrong

```java id="p8z3w6"
s = new Student();

3
Compile-Time Error

But you can modify the object's data.

```java id="m6n2y4" [Link] = 20;

Valid

Memory Trick

```text id="d9q7b3"
final Reference

Reference Fixed

Object Can Change

2. final Method
A final method cannot be overridden by a child class.

Example

```java id="t4v6x1" class Animal{

final void sound(){

[Link]("Animal Sound");

Wrong

```java id="g7m9c5"
class Dog extends Animal{

4
void sound(){

[Link]("Dog Bark");

Output

```text id="y5r8p2" Compile-Time Error

Reason

Final methods cannot be overridden.

---

# Can final Methods Be Overloaded?

Yes.

Example

```java id="e2w7h4"
class Demo{

final void show(){

final void show(int x){

Valid

Reason

Overloading is different from overriding.

5
3. final Class
A final class cannot be inherited.

Example

```java id="b8k4n7" final class Animal{

Wrong

```java id="q3m6v9"
class Dog extends Animal{

Output

```text id="x6p1r5" Compile-Time Error

Reason

Final classes cannot be extended.

---

# Example: String Class

One of the most important TCS MCQs.

The **String** class is a **final class**.

```java id="j5c2x8"
public final class String{

Therefore,

You cannot write

```java id="s4v7m1" class MyString extends String{

6
}

Compile-Time Error

Reason

String is final.

---

# Why is String final?

Reasons

✔ Security

✔ Immutability

✔ Better Performance

✔ Reliable Hashing

---

# final vs finally vs finalize()

Very Important TCS Question

| final | finally | finalize() |


|--------|----------|------------|
| Keyword | Block | Method |
| Used to restrict changes | Used in Exception Handling | Called by Garbage
Collector |
| Compile-Time Feature | Executes after try/catch | Cleanup before object
destruction |

Memory Trick

```text id="z7m5d2"
final

Keyword

finally

7

Exception Handling

finalize()

Garbage Collection

final with Methods and Variables


Example

```java id="l2x9v6" final int MAX = 100;

final void display(){

[Link](MAX);

Valid

---

# Can Constructors Be final?

No.

Wrong

```java id="w6n8p4"
final Demo(){

Compile-Time Error

Reason

8
Constructors are not inherited,

so making them final has no meaning.

Can Abstract Methods Be final?


No.

Wrong

```java id="r5y2k9" abstract final void show();

Compile-Time Error

Reason

Abstract methods **must** be overridden,

while final methods **cannot** be overridden.

Both contradict each other.

---

# Frequently Asked TCS MCQs

### MCQ 1

The `final` keyword is used to

A) Increase speed

B) Restrict modification

C) Hide data

D) Create objects

**Answer:** B

---

### MCQ 2

9
A final variable

A) Can be changed

B) Can be assigned only once

C) Must always be static

D) Is always private

**Answer:** B

---

### MCQ 3

A final method

A) Can be overridden

B) Cannot be overridden

C) Cannot be overloaded

D) Must be abstract

**Answer:** B

---

### MCQ 4

A final class

A) Can be inherited

B) Cannot be inherited

C) Must be abstract

D) Can only contain final methods

**Answer:** B

---

### MCQ 5

10
Which class is final in Java?

A) Object

B) System

C) String

D) Scanner

**Answer:** C

---

### MCQ 6

Can a final method be overloaded?

A) Yes

B) No

C) Only in interfaces

D) Only in abstract classes

**Answer:** A

---

### MCQ 7

Can constructors be final?

A) Yes

B) No

C) Only private constructors

D) Only default constructors

**Answer:** B

---

### MCQ 8

11
Can abstract methods be final?

A) Yes

B) No

C) Only protected methods

D) Only static methods

**Answer:** B

---

### MCQ 9

Which statement is TRUE?

A) final variables can be reassigned.

B) final methods can be overridden.

C) final classes cannot be inherited.

D) String is not final.

**Answer:** C

---

### MCQ 10

Output

```java id="f8k3v7"
final int x = 10;

x = 20;

A) 20

B) 10

C) Compile-Time Error

D) Runtime Error

12
Answer: C

MCQ 11

Which keyword prevents inheritance?

A) static

B) final

C) abstract

D) private

Answer: B

MCQ 12

finally is associated with

A) Inheritance

B) Exception Handling

C) Interfaces

D) Threads

Answer: B

MCQ 13

finalize() is called by

A) Compiler

B) JVM Garbage Collector

C) Constructor

D) Main Method

13
Answer: B

MCQ 14

Which is NOT a use of final ?

A) Variable

B) Method

C) Class

D) Package

Answer: D

MCQ 15

Which statement is FALSE?

A) String is a final class.

B) Final methods cannot be overridden.

C) Final variables can be modified multiple times.

D) Final classes cannot be inherited.

Answer: C

Common Mistakes Asked in TCS


❌ Wrong

```java id="h1n7q5" final int x = 10;

x = 30;

Compile-Time Error.

---

14
❌ Trying to extend String.

```java id="c4v2m8"
class MyString extends String{

Compile-Time Error.

❌ Writing

```java id="p7k5d3" abstract final void show();

Compile-Time Error.

---

# Memory Tricks

Remember

```text id="x5m8r1"
final Variable

Cannot Change Value

Remember

```text id="n9q2v6" final Method

Cannot Override

---

Remember

15
```text id="d3w7k4"
final Class

Cannot Inherit

Remember

```text id="b6r1p9" String

final Class

---

Remember

```text id="m8t5c2"
final

Keyword

finally

Exception Block

finalize()

Garbage Collection

One-Minute Revision
✔ final is used to restrict modification.

16
✔ final Variable → Value cannot be changed after initialization.

✔ final Method → Cannot be overridden (but can be overloaded).

✔ final Class → Cannot be inherited.

✔ String is a final class.

✔ Constructors cannot be final.

✔ abstract final methods are not allowed.

✔ Difference:

• final → Keyword
• finally → Exception Handling Block
• finalize() → Garbage Collection Method

🎯 TCS IPA Memory Shortcut

final Used With Meaning

Variable Cannot Change

Method Cannot Override

Class Cannot Inherit

⭐ Most Expected TCS MCQs

• What is the purpose of final ?


• Can a final variable be modified? → ❌ No
• Can a final method be overridden? → ❌ No
• Can a final method be overloaded? → ✅ Yes
• Can a final class be inherited? → ❌ No
• Which Java class is final? → String
• Difference between final, finally, and finalize()

17
CORE JAVA FOR TCS IPA – Chapter 18: Exception
Handling (Detailed Notes + MCQs)

What is Exception Handling?


An Exception is an unexpected event that occurs during program execution and interrupts the normal
flow of the program.

Exception Handling is the mechanism used to handle such errors so that the program can continue
executing normally.

Example:

int a = 10;
int b = 0;

[Link](a / b);

Output

ArithmeticException

Without exception handling, the program terminates abnormally.

Why Do We Need Exception Handling?


Without Exception Handling

✔ Program terminates unexpectedly.

With Exception Handling

✔ Program continues execution.

Advantages

• Prevents abnormal program termination.


• Makes programs robust.

1
• Improves readability.
• Helps in debugging.
• Maintains normal program flow.

Exception Hierarchy
One of the most important TCS IPA MCQs.

Object

Throwable

┌───────────────┐
│ │
Error Exception

RuntimeException

Memory Trick

Throwable

Exception

RuntimeException

Types of Exceptions
Java exceptions are mainly divided into:

1. Checked Exceptions
2. Unchecked Exceptions

2
1. Checked Exceptions
Checked exceptions are checked by the compiler during compilation.

Also called

✔ Compile-Time Exceptions

Program must either

• Handle them using try-catch , or


• Declare them using throws .

Examples

• IOException
• SQLException
• FileNotFoundException
• ClassNotFoundException

Example

FileReader fr = new FileReader("[Link]");

If the file does not exist,

Compile-Time Error occurs unless handled.

2. Unchecked Exceptions
Unchecked exceptions occur during runtime.

Also called

✔ Runtime Exceptions

Compiler does not check them.

Examples

• ArithmeticException
• NullPointerException
• ArrayIndexOutOfBoundsException

3
• NumberFormatException

Common Runtime Exceptions


ArithmeticException
Occurs during illegal arithmetic operations.

Example

int a = 10;

[Link](a / 0);

Output

ArithmeticException

NullPointerException
Occurs when a null reference accesses an object.

Example

String s = null;

[Link]([Link]());

Output

NullPointerException

ArrayIndexOutOfBoundsException
Occurs when an invalid array index is accessed.

4
Example

int arr[] = {10,20,30};

[Link](arr[5]);

Output

ArrayIndexOutOfBoundsException

NumberFormatException
Occurs when converting an invalid string into a number.

Example

[Link]("ABC");

Output

NumberFormatException

Exception Handling Keywords


Java provides 5 important keywords.

try

catch

finally

throw

throws

These are extremely important for TCS.

5
try Block
The code that may generate an exception is placed inside the try block.

Example

try{

int a = 10/0;

catch Block
The catch block handles the exception.

Example

try{

int a = 10/0;

catch(ArithmeticException e){

[Link]("Cannot Divide by Zero");

Output

Cannot Divide by Zero

6
finally Block
The finally block executes whether an exception occurs or not.

Example

try{

[Link]("Try");

finally{

[Link]("Finally");

Output

Try

Finally

Does finally Always Execute?


Almost Yes.

Exception

[Link](0);

Example

try{

[Link](0);

7
finally{

[Link]("Finally");

Output

(No Output)

Reason

The JVM terminates immediately.

TCS Favorite MCQ

Does finally always execute?

Answer: Almost Yes, except when the JVM exits (e.g., [Link]() ).

throw Keyword
Used to explicitly throw an exception.

Example

throw new ArithmeticException("Invalid Operation");

throws Keyword
Used in the method declaration to indicate that the method may throw an exception.

Example

8
void display() throws IOException{

Memory Trick

throw

Throws One Exception

throws

Declares Exceptions

throw vs throws
throw throws

Used inside a method Used in method declaration

Throws one exception Declares one or more exceptions

Followed by an exception object Followed by exception class names

Multiple catch Blocks


Example

try{

catch(ArithmeticException e){

9
catch(NullPointerException e){

catch(Exception e){

Always place

Specific Exception

General Exception

Otherwise,

Compile-Time Error.

Exception Propagation
If an exception is not handled,

it propagates to the calling method.

Example

method3()

method2()

method1()

main()

10
Checked vs Unchecked Exceptions
Checked Exception Unchecked Exception

Compile-Time Runtime

Checked by Compiler Not Checked by Compiler

Must Handle Optional to Handle

IOException ArithmeticException

SQLException NullPointerException

Error vs Exception
Error Exception

Serious problem Recoverable problem

JVM related Program related

StackOverflowError IOException

Frequently Asked TCS MCQs


MCQ 1

Exception Handling is used to

A) Speed up execution

B) Handle runtime errors

C) Increase memory

D) Create objects

Answer: B

11
MCQ 2

Root class of all exceptions is

A) Object

B) Throwable

C) Exception

D) Error

Answer: B

MCQ 3

Which is a Checked Exception?

A) ArithmeticException

B) NullPointerException

C) IOException

D) NumberFormatException

Answer: C

MCQ 4

Which is NOT a Checked Exception?

A) IOException

B) SQLException

C) ArithmeticException

D) FileNotFoundException

Answer: C

12
MCQ 5

ArithmeticException occurs when

A) Array index is invalid

B) Divide by zero

C) Null object access

D) Invalid string conversion

Answer: B

MCQ 6

NullPointerException occurs when

A) Array index exceeds size

B) Null object is accessed

C) File is missing

D) Invalid number conversion

Answer: B

MCQ 7

Which keyword is used to handle exceptions?

A) try

B) catch

C) Both A and B

D) throw

Answer: C

13
MCQ 8

Which block always executes?

A) try

B) catch

C) finally

D) throw

Answer: C

MCQ 9

Which keyword explicitly throws an exception?

A) throws

B) throw

C) finally

D) catch

Answer: B

MCQ 10

Which keyword declares an exception?

A) throw

B) throws

C) catch

D) try

Answer: B

14
MCQ 11

Which exception occurs here?

[Link]("ABC");

A) IOException

B) NumberFormatException

C) ArithmeticException

D) SQLException

Answer: B

MCQ 12

Which statement is TRUE?

A) finally never executes.

B) finally executes even if no exception occurs.

C) catch always executes.

D) throw declares an exception.

Answer: B

MCQ 13

When does finally NOT execute?

A) Divide by zero

B) NullPointerException

C) [Link]()

D) IOException

15
Answer: C

MCQ 14

Which exception occurs here?

String s = null;

[Link]([Link]());

A) IOException

B) NullPointerException

C) ArithmeticException

D) NumberFormatException

Answer: B

MCQ 15

Arrange the hierarchy correctly.

A)

Exception

Throwable

Object

B)

Object

16
Throwable

Exception

RuntimeException

C)

RuntimeException

Throwable

Object

D)

Object

Exception

Throwable

Answer: B

Common Mistakes Asked in TCS


❌ Thinking Checked Exceptions occur at runtime.

✔ Checked Exceptions are checked during compilation.

17
❌ Confusing throw and throws .

✔ throw → Throws an exception.

✔ throws → Declares exceptions.

❌ Thinking finally always executes.

✔ It does not execute after [Link]() .

Memory Tricks
Remember

Throwable

Exception

RuntimeException

Remember

Checked

Compile-Time

IOException

SQLException

18
Remember

Unchecked

Runtime

ArithmeticException

NullPointerException

ArrayIndexOutOfBoundsException

NumberFormatException

Remember

throw

Throw One

throws

Declare Many

Remember

finally

Almost Always Executes

19
Except [Link]()

One-Minute Revision
✔ Exception = Unexpected event during program execution.

✔ Root class = Throwable.

✔ Checked Exceptions → Compile-Time (IOException, SQLException).

✔ Unchecked Exceptions → Runtime (ArithmeticException, NullPointerException,


ArrayIndexOutOfBoundsException, NumberFormatException).

✔ Exception handling keywords:

• try
• catch
• finally
• throw
• throws

✔ throw → Explicitly throws an exception.

✔ throws → Declares exceptions.

✔ finally executes almost always, except when the JVM terminates using [Link]() .

🎯 TCS IPA Memory Shortcut

Keyword Purpose

try Risky Code

catch Handle Exception

finally Cleanup Code

throw Throw Exception

throws Declare Exception

⭐ Most Expected TCS MCQs

• Root class of exceptions → Throwable

20
• Checked vs Unchecked Exceptions
• Difference between throw and throws
• Common Runtime Exceptions
• Does finally always execute? → Almost Yes, except [Link]()
• Exception hierarchy
• Which exceptions are checked and unchecked?

21
CORE JAVA FOR TCS IPA – Chapter 19: Java
Collections Framework (Detailed Notes + MCQs)

What is the Java Collections Framework (JCF)?


The Java Collections Framework (JCF) is a set of classes and interfaces used to store, manipulate, and
process groups of objects efficiently.

Before Collections, Java used Arrays, which have a fixed size.

Collections provide:

• Dynamic Size
• Easy Searching
• Sorting
• Insertion
• Deletion
• Better Performance

Why Do We Need Collections?


Arrays have limitations:

❌ Fixed Size

❌ Difficult insertion/deletion

Collections solve these problems.

Advantages

✔ Dynamic Size

✔ Reusable Data Structures

✔ Built-in Algorithms

✔ Better Performance

✔ Easy Data Manipulation

1
Collection Framework Hierarchy
One of the most important TCS IPA MCQs.

```text id="7v2kp9" Iterable │ Collection │ ├── List ├── Set └── Queue

Map (Separate Interface)

Memory Trick

```text id="2m8cr4"
Collection

List

Set

Queue

Map (Separate)

Important: Map is not a child of the Collection interface.

List Interface
A List stores elements in insertion order.

Features

✔ Duplicates Allowed

✔ Order Maintained

✔ Index-Based Access

Example

```text id="8d4nh6" 10

2
20

20

30

Duplicates are allowed.

---

# ArrayList

Most commonly used List implementation.

Features

✔ Dynamic Array

✔ Fast Random Access

✔ Slow Insertion & Deletion (middle)

✔ Allows Duplicates

✔ Maintains Insertion Order

Example

```java id="4k5bz2"
ArrayList<String> list = new ArrayList<>();

[Link]("A");
[Link]("B");
[Link]("A");

[Link](list);

Output

```text id="3q7lw1" [A, B, A]

---

# LinkedList

3
Implemented using a doubly linked list.

Features

✔ Fast Insertion

✔ Fast Deletion

✔ Slow Random Access

✔ Maintains Order

✔ Allows Duplicates

---

# ArrayList vs LinkedList

| ArrayList | LinkedList |
|------------|------------|
| Dynamic Array | Doubly Linked List |
| Fast Random Access | Slow Random Access |
| Slow Insertion | Fast Insertion |
| Less Memory | More Memory |

**TCS MCQ Favorite**

---

# Vector

Vector is similar to ArrayList.

Features

✔ Thread Safe

✔ Synchronized

✔ Slower than ArrayList

---

# ArrayList vs Vector

| ArrayList | Vector |
|------------|--------|
| Not Thread Safe | Thread Safe |

4
| Faster | Slower |
| Not Synchronized | Synchronized |

---

# Stack

Stack follows

```text id="9t6fp3"
LIFO

Last In

First Out

Example

```text id="4g1yb7" Push

10

20

30

Pop

30

Applications

✔ Undo Operation

✔ Browser History

✔ Function Calls

---

# Queue

Queue follows

5
```text id="1z8vr5"
FIFO

First In

First Out

Example

```text id="5j3cw9" 10

20

30

Remove

10

Applications

✔ Printer Queue

✔ Ticket Booking

✔ Scheduling

---

# Set Interface

A Set stores **unique elements**.

Features

✔ No Duplicates

✔ No Index

---

# HashSet

6
Features

✔ No Duplicates

✔ Unordered

✔ Fast

✔ Internally Uses **HashMap**

Example

```java id="6r1tm8"
HashSet<Integer> set = new HashSet<>();

[Link](10);
[Link](20);
[Link](10);

[Link](set);

Output

```text id="8v2ln4" [10, 20]

Duplicate removed.

---

# LinkedHashSet

Features

✔ No Duplicates

✔ Maintains Insertion Order

---

# TreeSet

Features

✔ No Duplicates

7
✔ Sorted Order

✔ Implements NavigableSet

Example

```text id="7k5wp2"
10

20

Output

10

20

Automatically sorted.

Set Comparison
HashSet LinkedHashSet TreeSet

Unordered Ordered Sorted

Fastest Moderate Slower

Uses HashMap Uses HashMap Uses Tree Structure

Map Interface
A Map stores data in Key-Value Pairs.

Example

```text id="3p8vm6" 101 → Harshad

8
102 → Rahul

103 → Amit

Keys must be unique.

Values may repeat.

---

# HashMap

Most important TCS topic.

Features

✔ Key-Value Pair

✔ One Null Key

✔ Multiple Null Values

✔ Unordered

✔ Fast

Example

```java id="4d7kn1"
HashMap<Integer,String> map = new HashMap<>();

[Link](1,"A");

[Link](2,"B");

[Link](null,"C");

[Link](3,null);

Valid.

9
Hashtable
Features

✔ Thread Safe

✔ No Null Key

✔ No Null Value

✔ Synchronized

HashMap vs Hashtable
HashMap Hashtable

One Null Key No Null Key

Many Null Values No Null Values

Faster Slower

Not Synchronized Synchronized

TreeMap
Features

✔ Sorted Keys

✔ No Null Key

✔ Values may be null

✔ Uses Red-Black Tree

Example

```text id="5m7dz9" 5

10
8

Output

---

# LinkedHashMap

Features

✔ Maintains Insertion Order

✔ Faster than TreeMap

✔ One Null Key

✔ Multiple Null Values

---

# Collection Comparison Table

| Collection | Duplicates | Order | Null Allowed |


|-------------|------------|-------|--------------|
| ArrayList | Yes | Yes | Yes |
| LinkedList | Yes | Yes | Yes |
| Vector | Yes | Yes | Yes |
| Stack | Yes | LIFO | Yes |
| HashSet | No | No | One Null |
| LinkedHashSet | No | Yes | One Null |
| TreeSet | No | Sorted | No Null |
| HashMap | Keys No, Values Yes | No | One Null Key, Many Null Values |
| Hashtable | Keys No, Values Yes | No | No Null Key, No Null Value |
| TreeMap | Keys No | Sorted | No Null Key |
| LinkedHashMap | Keys No | Yes | One Null Key, Many Null Values |

---

11
# Frequently Asked TCS MCQs

### MCQ 1

Which interface allows duplicate elements?

A) Set

B) List

C) Map

D) Queue

**Answer:** B

---

### MCQ 2

Which collection does **NOT** allow duplicates?

A) ArrayList

B) LinkedList

C) HashSet

D) Vector

**Answer:** C

---

### MCQ 3

Which List implementation provides fast random access?

A) LinkedList

B) ArrayList

C) Stack

D) Vector

**Answer:** B

12
---

### MCQ 4

Which List implementation provides fast insertion and deletion?

A) ArrayList

B) LinkedList

C) Vector

D) Stack

**Answer:** B

---

### MCQ 5

Which collection follows LIFO?

A) Queue

B) Stack

C) LinkedList

D) TreeSet

**Answer:** B

---

### MCQ 6

Which collection follows FIFO?

A) Queue

B) Stack

C) Vector

D) TreeMap

**Answer:** A

13
---

### MCQ 7

Which Set maintains insertion order?

A) HashSet

B) LinkedHashSet

C) TreeSet

D) Vector

**Answer:** B

---

### MCQ 8

Which Set stores elements in sorted order?

A) HashSet

B) LinkedHashSet

C) TreeSet

D) Stack

**Answer:** C

---

### MCQ 9

HashSet internally uses

A) TreeMap

B) LinkedList

C) HashMap

D) Hashtable

**Answer:** C

14
---

### MCQ 10

HashMap allows

A) No Null Key

B) One Null Key

C) Two Null Keys

D) Unlimited Null Keys

**Answer:** B

---

### MCQ 11

HashMap allows

A) No Null Values

B) One Null Value

C) Many Null Values

D) Only Two Null Values

**Answer:** C

---

### MCQ 12

Hashtable allows

A) One Null Key

B) Many Null Values

C) No Null Key and No Null Value

D) One Null Key and One Null Value

**Answer:** C

15
---

### MCQ 13

Which Map stores keys in sorted order?

A) HashMap

B) Hashtable

C) LinkedHashMap

D) TreeMap

**Answer:** D

---

### MCQ 14

Which Map maintains insertion order?

A) HashMap

B) Hashtable

C) LinkedHashMap

D) TreeMap

**Answer:** C

---

### MCQ 15

Which statement is TRUE?

A) Map extends Collection.

B) TreeSet allows duplicate elements.

C) HashMap allows one null key.

D) Hashtable allows multiple null values.

**Answer:** C

16
---

# Common Mistakes Asked in TCS

❌ Thinking **Map** is a child of **Collection**.

✔ **Map is a separate interface.**

---

❌ Thinking HashSet maintains insertion order.

✔ Only **LinkedHashSet** maintains insertion order.

---

❌ Thinking Hashtable allows null.

✔ Hashtable allows **neither null keys nor null values**.

---

❌ Thinking TreeSet allows duplicates.

✔ TreeSet stores only **unique** elements in **sorted order**.

---

# Memory Tricks

Remember

```text id="6r4kb2"
List

Duplicates

Order

Remember

17
```text id="9v1tm7" Set

No Duplicates

---

Remember

```text id="4c8wp5"
Stack

LIFO

Remember

```text id="2n5dy8" Queue

FIFO

---

Remember

```text id="8m7qz1"
HashMap

1 Null Key

Many Null Values

Remember

18
```text id="5x3kl6" Hashtable

No Null Key

No Null Value

---

Remember

```text id="7j2pv9"
TreeMap

Sorted Keys

Remember

```text id="1d6rn4" HashSet

Uses HashMap ```

One-Minute Revision
✔ Collection Hierarchy → List, Set, Queue (Map is separate).

✔ List → Duplicates Allowed, Order Maintained.

✔ ArrayList → Fast Random Access.

✔ LinkedList → Fast Insertion & Deletion.

✔ Vector → Thread Safe, Synchronized.

19
✔ Stack → LIFO.

✔ Queue → FIFO.

✔ Set → No Duplicates.

✔ HashSet → Unordered, Uses HashMap.

✔ LinkedHashSet → Maintains Insertion Order.

✔ TreeSet → Sorted Order.

✔ HashMap → One Null Key, Many Null Values.

✔ Hashtable → No Null Key, No Null Value.

✔ TreeMap → Sorted Keys.

✔ LinkedHashMap → Maintains Insertion Order.

🎯 TCS IPA Memory Shortcut

Collection Key Feature

ArrayList Fast Random Access

LinkedList Fast Insertion

Vector Thread Safe

Stack LIFO

Queue FIFO

HashSet No Duplicates

LinkedHashSet Ordered

TreeSet Sorted

HashMap 1 Null Key, Many Null Values

Hashtable No Nulls

TreeMap Sorted Keys

LinkedHashMap Ordered Map

20
⭐ Most Expected TCS MCQs

• Does HashMap allow null keys? → ✅ One


• Does HashMap allow null values? → ✅ Many
• Does Hashtable allow null? → ❌ No
• Which collection follows LIFO? → Stack
• Which collection follows FIFO? → Queue
• Which Set maintains insertion order? → LinkedHashSet
• Which Set stores elements in sorted order? → TreeSet
• Which Map stores keys in sorted order? → TreeMap
• HashSet internally uses → HashMap
• Is Map a child of Collection? → ❌ No

21
CORE JAVA FOR TCS IPA – Chapter 20: Wrapper
Classes (Detailed Notes + MCQs)

What are Wrapper Classes?


A Wrapper Class is a class that wraps (converts) a primitive data type into an object.

Java provides wrapper classes because Collections Framework and many Java APIs work only with objects,
not primitive data types.

Example

```text id="9r2v7m" Primitive

Object

Wrapper Class

Example

```java id="6m8k1p"
int x = 10;

Integer obj = [Link](x);

Here,

int is converted into an Integer object.

Why Do We Need Wrapper Classes?


Primitive data types are not objects.

Collections like ArrayList can store only objects.

1
Wrong

```java id="3q5t8w" ArrayList<int> list = new ArrayList<>();

Compile-Time Error

Correct

```java id="2w7p4d"
ArrayList<Integer> list = new ArrayList<>();

Primitive Data Types and Wrapper Classes


Primitive Type Wrapper Class

byte Byte

short Short

int Integer

long Long

float Float

double Double

char Character

boolean Boolean

TCS Tip: Memorize this table.

Autoboxing
Autoboxing is the automatic conversion of a primitive data type into its corresponding wrapper
object.

Example

```java id="8x4m7q" int x = 100;

Integer obj = x;

2
Java automatically converts

```text id="1k9n5v"
int

Integer

Output

```text id="7c2r8p" 100

---

# Manual Boxing

Before Java 5,

boxing was done manually.

Example

```java id="4d6y2n"
int x = 100;

Integer obj = [Link](x);

Unboxing
Unboxing is the automatic conversion of a wrapper object into a primitive data type.

Example

```java id="5f8v3k" Integer obj = 200;

int x = obj;

Java automatically converts

```text id="6j1w4r"

3
Integer

int

Output

```text id="8p3q7m" 200

---

# Manual Unboxing

Example

```java id="2m9c5x"
Integer obj = [Link](200);

int x = [Link]();

Autoboxing vs Unboxing
Autoboxing Unboxing

Primitive → Object Object → Primitive

Automatic Automatic

int → Integer Integer → int

Memory Trick

```text id="5t7x2v" Autoboxing

Primitive

Object

4
```text id="8y4m1q"
Unboxing

Object

Primitive

Common Wrapper Class Methods


[Link]()
Converts a String into an int .

Example

```java id="3r6k8p" String s = "123";

int x = [Link](s);

[Link](x);

Output

```text id="9m1d7w"
123

[Link]()
Converts a primitive or String into an Integer object.

Example

```java id="6v3q8n" Integer obj = [Link](100);

5
---

## intValue()

Converts an `Integer` object into an `int`.

Example

```java id="1n4k9m"
Integer obj = 50;

int x = [Link]();

[Link]()
Checks whether a character is a digit.

Example

```java id="8w5t2q" [Link]('5');

Output

```text id="7x9m4p"
true

[Link]()
Checks whether a character is a letter.

Example

```java id="4q8v6d" [Link]('A');

Output

```text id="2k7n5r"
true

6
[Link]()
Checks whether a character is uppercase.

Example

```java id="5m1p8x" [Link]('A');

Output

```text id="6r3v9q"
true

[Link]()
Checks whether a character is lowercase.

Example

```java id="7p4k2n" [Link]('a');

Output

```text id="9t6w1m"
true

Wrapper Classes are Immutable


Wrapper objects cannot be modified after creation.

Example

```java id="2c7m4v" Integer x = 10;

x = 20;

Actually,

a **new object** is created.

7
---

# Wrapper Class Hierarchy

```text id="4x9k1p"
Object

Number

Byte

Short

Integer

Long

Float

Double

Character and Boolean do not extend Number .

Frequently Asked TCS MCQs


MCQ 1

Wrapper class for int is

A) Int

B) Integer

C) Number

D) Long

Answer: B

8
MCQ 2

Wrapper class for char is

A) Char

B) Character

C) String

D) CharacterWrapper

Answer: B

MCQ 3

Autoboxing converts

A) Object → Primitive

B) Primitive → Object

C) String → Integer

D) Object → String

Answer: B

MCQ 4

Unboxing converts

A) Primitive → Object

B) Object → Primitive

C) String → Integer

D) Object → Object

Answer: B

9
MCQ 5

Which method converts String to int?

A) valueOf()

B) parseInt()

C) intValue()

D) toInt()

Answer: B

MCQ 6

Which method returns an Integer object?

A) parseInt()

B) valueOf()

C) intValue()

D) parse()

Answer: B

MCQ 7

Which wrapper class is used for boolean ?

A) Bool

B) Boolean

C) Logical

D) Binary

Answer: B

10
MCQ 8

Which wrapper class is used for double ?

A) Decimal

B) Double

C) Float

D) Number

Answer: B

MCQ 9

Which wrapper class is used for long ?

A) Long

B) Integer

C) Double

D) Number

Answer: A

MCQ 10

Which wrapper class is used for float ?

A) Float

B) Double

C) Decimal

D) Number

Answer: A

11
MCQ 11

Which wrapper class is used for byte ?

A) Byte

B) Integer

C) Number

D) Character

Answer: A

MCQ 12

Which statement is TRUE?

A) Collections store primitive types directly.

B) Collections store objects.

C) Wrapper classes are mutable.

D) Integer is a primitive type.

Answer: B

MCQ 13

Which method converts an Integer object to int?

A) valueOf()

B) parseInt()

C) intValue()

D) toInteger()

Answer: C

12
MCQ 14

Which classes extend Number ?

A) Integer

B) Double

C) Float

D) All of the above

Answer: D

MCQ 15

Which statement is FALSE?

A) Integer is the wrapper class for int.

B) Character is the wrapper class for char.

C) Boolean is the wrapper class for boolean.

D) String is the wrapper class for char.

Answer: D

Common Mistakes Asked in TCS


❌ Thinking wrapper class for int is Int.

✔ Correct answer:

```text id="3v6q9p" Integer

---

❌ Thinking Collections store primitive data types.

✔ Collections store **objects**, so wrapper classes are used.

13
---

❌ Confusing `parseInt()` and `valueOf()`.

✔ `parseInt()` → Returns **int**

✔ `valueOf()` → Returns **Integer**

---

# Memory Tricks

Remember

```text id="7n2x5r"
Primitive

Wrapper

```text id="1k8m4q" int

Integer

---

```text id="5w9v2n"
char

Character

```text id="8r3p6m" boolean

Boolean

14
---

Remember

```text id="9q5t1v"
Autoboxing

Primitive

Object

Remember

```text id="2m7x4k" Unboxing

Object

Primitive ```

One-Minute Revision
✔ Wrapper classes convert primitive data types into objects.

✔ Java provides 8 wrapper classes for the 8 primitive types.

✔ Autoboxing → Primitive → Object.

✔ Unboxing → Object → Primitive.

✔ [Link]() → Returns int.

✔ [Link]() → Returns Integer object.

15
✔ Wrapper classes are immutable.

✔ Collections Framework works with objects, so wrapper classes are required.

🎯 TCS IPA Memory Shortcut

Primitive Wrapper Class

byte Byte

short Short

int Integer

long Long

float Float

double Double

char Character

boolean Boolean

⭐ Most Expected TCS MCQs

• Wrapper class for int → Integer


• Wrapper class for char → Character
• Wrapper class for boolean → Boolean
• Autoboxing → Primitive to Object
• Unboxing → Object to Primitive
• parseInt() returns → int
• valueOf() returns → Integer
• Why are wrapper classes used? → Collections store objects, not primitive types

16
CORE JAVA FOR TCS IPA – Chapter 21: Java
Packages (Detailed Notes + MCQs)

What is a Package?
A Package is a collection of related classes, interfaces, enums, and sub-packages.

Packages help organize Java programs and avoid naming conflicts.

Think of a package like a folder that contains related Java files.

Example

```text id="1q8r5m" Folder

Java Package

Classes

---

# Why Do We Need Packages?

Without packages,

All classes would be stored together, making programs difficult to manage.

Packages provide:

✔ Better Organization

✔ Avoid Naming Conflicts

✔ Easy Code Reuse

✔ Security

✔ Access Protection

1
---

# Types of Packages

Java has **two types of packages**.

## 1. Built-in Packages

Provided by Java.

Examples

- `[Link]`
- `[Link]`
- `[Link]`
- `[Link]`
- `[Link]`
- `[Link]`

---

## 2. User-Defined Packages

Created by programmers.

Example

```java id="2m4v7q"
package [Link];

Most Important Java Packages


These are frequently asked in TCS IPA.

1. [Link]
The most important package.

Contains commonly used classes.

2
Examples

• String
• Object
• System
• Math
• Integer
• Character
• Thread
• Exception

Example

```java id="4x6k1n" String name = "Harshad";

[Link](name);

No import statement is required.

---

# [Link] is Imported Automatically

This is one of the **most repeated TCS MCQs**.

Whenever a Java program runs,

the compiler automatically imports

```java id="9r3p8w"
[Link].*

Therefore,

you can directly use

• String
• System
• Math
• Object

without writing

```java id="7t2m6v" import [Link].*;

3
Memory Trick

```text id="6v9q2k"
Automatic Import

[Link]

2. [Link]
Contains utility classes.

Common Classes

• ArrayList
• LinkedList
• HashMap
• HashSet
• Scanner
• Collections
• Arrays
• Date
• Random

Example

```java id="3d7k9m" import [Link];

Scanner sc = new Scanner([Link]);

---

# 3. [Link]

Used for Input and Output operations.

Common Classes

- File
- FileReader
- FileWriter
- BufferedReader

4
- BufferedWriter
- PrintWriter

Example

```java id="5p8r2x"
import [Link];

Applications

✔ Reading Files

✔ Writing Files

4. [Link]
Used for database programming.

Common Classes

• Connection
• Statement
• PreparedStatement
• ResultSet
• DriverManager

Example

```java id="8n4w1q" import [Link];

Applications

✔ JDBC

✔ MySQL

✔ Oracle Database

---

# Other Important Packages

## [Link]

5
Used for networking.

Examples

- Socket
- URL
- ServerSocket

---

## [Link]

Introduced in Java 8.

Used for Date and Time.

Examples

- LocalDate
- LocalTime
- LocalDateTime

---

# Import Statement

Syntax

```java id="6m1q9v"
import [Link];

Example

```java id="4k7x3p" import [Link];

---

# Import All Classes

Syntax

```java id="1t8r5d"
import [Link].*;

6
Imports all classes from the package.

Fully Qualified Class Name


Instead of importing,

we can use the complete package name.

Example

```java id="9y2n6k" [Link] sc = new [Link]([Link]);

No import statement is needed.

---

# package Keyword

Used to create a user-defined package.

Example

```java id="2v5m8r"
package student;

public class Test{

This class belongs to the student package.

Accessing a User-Defined Package


Example

```java id="7k1q4m" import [Link];

---

# Package Naming Convention

7
Use lowercase letters.

Examples

```text id="3m8v2p"
[Link]

student

[Link]

[Link]

Commonly Used Classes by Package


Package Common Classes

[Link] String, System, Math, Object, Integer

[Link] Scanner, ArrayList, HashMap, Collections

[Link] File, BufferedReader, FileWriter

[Link] Connection, Statement, ResultSet

[Link] Socket, URL

[Link] LocalDate, LocalTime

Frequently Asked TCS MCQs


MCQ 1

A package is

A) A method

B) A folder containing related classes

C) A constructor

D) A variable

8
Answer: B

MCQ 2

Which package is imported automatically?

A) [Link]

B) [Link]

C) [Link]

D) [Link]

Answer: D

MCQ 3

Which package contains the Scanner class?

A) [Link]

B) [Link]

C) [Link]

D) [Link]

Answer: C

MCQ 4

Which package contains the String class?

A) [Link]

B) [Link]

C) [Link]

D) [Link]

9
Answer: B

MCQ 5

Which package is used for file handling?

A) [Link]

B) [Link]

C) [Link]

D) [Link]

Answer: C

MCQ 6

Which package is used for database programming?

A) [Link]

B) [Link]

C) [Link]

D) [Link]

Answer: B

MCQ 7

Which keyword is used to create a package?

A) import

B) package

C) class

D) new

10
Answer: B

MCQ 8

Which keyword is used to use classes from another package?

A) package

B) import

C) extends

D) implements

Answer: B

MCQ 9

Which package contains the Math class?

A) [Link]

B) [Link]

C) [Link]

D) [Link]

Answer: C

MCQ 10

Which package contains ArrayList ?

A) [Link]

B) [Link]

C) [Link]

D) [Link]

11
Answer: A

MCQ 11

Which package contains HashMap ?

A) [Link]

B) [Link]

C) [Link]

D) [Link]

Answer: C

MCQ 12

Which package contains Connection ?

A) [Link]

B) [Link]

C) [Link]

D) [Link]

Answer: A

MCQ 13

Which package contains BufferedReader ?

A) [Link]

B) [Link]

C) [Link]

D) [Link]

12
Answer: B

MCQ 14

Which statement is TRUE?

A) [Link] must always be imported manually.

B) [Link] is imported automatically.

C) Scanner belongs to [Link].

D) String belongs to [Link].

Answer: B

MCQ 15

Which package is introduced for modern Date and Time API?

A) [Link]

B) [Link]

C) [Link]

D) [Link]

Answer: B

Common Mistakes Asked in TCS


❌ Writing

```java id="6p3n8q" import [Link].*;

✔ Not required.

Java imports it automatically.

---

13
❌ Thinking `Scanner` belongs to `[Link]`.

✔ Correct package

```text id="8r5m1v"
[Link]

❌ Thinking String belongs to [Link] .

✔ Correct package

```text id="1k7x4p" [Link]

---

# Memory Tricks

Remember

```text id="2m9q6r"
[Link]

Automatic Import

Remember

```text id="5v3k8n" [Link]

Collections

Scanner

---

Remember

14
```text id="9p1r7m"
[Link]

File Handling

Remember

```text id="3x8w5q" [Link]

Database

---

Remember

```text id="7n2v4k"
package

Create Package

import

Use Package

One-Minute Revision
✔ A Package is a collection of related classes and interfaces.

✔ Java has Built-in Packages and User-Defined Packages.

✔ [Link] is automatically imported.

✔ [Link] contains Scanner, ArrayList, HashMap, and other utility classes.

15
✔ [Link] is used for file handling.

✔ [Link] is used for database programming (JDBC).

✔ Use the package keyword to create a package.

✔ Use the import keyword to use classes from another package.

🎯 TCS IPA Memory Shortcut

Package Purpose

[Link] Core Java Classes (Auto Imported)

[Link] Collections & Scanner

[Link] File Handling

[Link] Database (JDBC)

[Link] Networking

[Link] Date & Time API

⭐ Most Expected TCS MCQs

• Which package is imported automatically? → [Link]


• Which package contains Scanner ? → [Link]
• Which package contains String ? → [Link]
• Which package is used for file handling? → [Link]
• Which package is used for database connectivity? → [Link]
• Which keyword creates a package? → package
• Which keyword imports classes? → import

16
CORE JAVA FOR TCS IPA – Chapter 22:
Multithreading (Detailed Notes + MCQs)

What is Multithreading?
Multithreading is the process of executing multiple threads simultaneously within a single program.

A Thread is the smallest unit of execution in a process.

Example

While using Google Chrome:

• One thread downloads a file.


• Another thread plays a video.
• Another thread loads a webpage.

All tasks run simultaneously.

This is Multithreading.

Why Do We Need Multithreading?


Without multithreading,

Tasks execute one after another.

With multithreading,

Tasks execute concurrently.

Advantages

✔ Better Performance

✔ Efficient CPU Utilization

✔ Faster Execution

✔ Improved User Experience

1
✔ Background Processing

Process vs Thread
Process Thread

Heavyweight Lightweight

Own Memory Shares Process Memory

Slower Faster

Independent Dependent on Process

Life Cycle of a Thread


One of the favorite TCS MCQs.

```text id="6v2m8k" New

Runnable

Running

Waiting / Blocked

Terminated

---

# Ways to Create a Thread

Java provides **two ways**.

2
## 1. Extending the Thread Class

Example

```java id="5k8p2m"
class MyThread extends Thread{

public void run(){

[Link]("Thread Running");

public class Main{

public static void main(String[] args){

MyThread t = new MyThread();

[Link]();

Output

```text id="3r9w5n" Thread Running

---

## 2. Implementing Runnable Interface

Example

```java id="8m4q7v"
class MyThread implements Runnable{

public void run(){

[Link]("Thread Running");

3
}

public class Main{

public static void main(String[] args){

Thread t = new Thread(new MyThread());

[Link]();

Output

```text id="9x1k6p" Thread Running

---

# Thread vs Runnable

| Thread Class | Runnable Interface |


|---------------|-------------------|
| Extends Thread | Implements Runnable |
| Cannot extend another class | Can extend another class |
| Less Flexible | More Flexible |
| Less Preferred | More Preferred |

**Interview Tip:** Prefer **Runnable** because Java supports **single


inheritance**.

---

# Important Thread Methods

Java provides many methods.

Most important for TCS:

```text id="4p8m2r"
start()

run()

sleep()

4
join()

yield()

interrupt()

start()
Starts a new thread.

Example

```java id="7q3v8n" MyThread t = new MyThread();

[Link]();

Output

A new thread is created.

---

# run()

Contains the code executed by the thread.

Example

```java id="2m6k9w"
public void run(){

[Link]("Running");

Calling run() directly does not create a new thread.

It behaves like a normal method.

5
Difference Between start() and run()
This is one of the highest-weightage TCS MCQs.

start() run()

Creates a new thread Normal method call

JVM invokes run() internally Executes in the current thread

Multithreading occurs No multithreading

Example

```java id="5t9p1v" MyThread t = new MyThread();

[Link]();

Creates a new thread.

---

```java id="8w2m6q"
MyThread t = new MyThread();

[Link]();

No new thread.

Acts like a normal method.

sleep()
Pauses the current thread for a specified time.

Syntax

```java id="1r7x4n" [Link](1000);

Meaning

Pause for **1000 milliseconds (1 second).**

6
---

# join()

Makes one thread wait until another thread finishes.

Example

```java id="3v8k5m"
[Link]();

[Link]();

[Link]();

t2 starts only after t1 completes.

yield()
Temporarily pauses the current thread and gives other threads a chance to execute.

Example

```java id="6n2q9p" [Link]();

It is only a suggestion to the scheduler.

---

# interrupt()

Interrupts a sleeping or waiting thread.

Example

```java id="7m4v1k"
[Link]();

Usually results in

```text id="9k6r2p" InterruptedException

7
---

# Thread Scheduler

The JVM decides

- Which thread executes


- When it executes
- For how long it executes

This is handled by the **Thread Scheduler**.

---

# Thread Priority

Priority Range

```text id="5x8n3v"
1

10

Constants

```text id="2p7m5q" Thread.MIN_PRIORITY

Thread.NORM_PRIORITY

Thread.MAX_PRIORITY

10

8
Higher priority means a thread has a better chance of execution.

---

# Thread States

```text id="1k5v8r"
NEW

RUNNABLE

RUNNING

WAITING

TIMED_WAITING

BLOCKED

TERMINATED

Synchronization
Synchronization ensures

✔ Only one thread accesses a shared resource at a time.

Purpose

• Prevents Data Inconsistency


• Avoids Race Conditions

Daemon Thread
A daemon thread runs in the background.

Examples

✔ Garbage Collector

✔ Background Services

9
Main Thread
Every Java program starts with

```text id="8r4m2q" Main Thread

All user-created threads originate from it.

---

# Frequently Asked TCS MCQs

### MCQ 1

A thread is

A) A process

B) Smallest unit of execution

C) A package

D) An object

**Answer:** B

---

### MCQ 2

How many ways are there to create a thread?

A) One

B) Two

C) Three

D) Four

**Answer:** B

---

10
### MCQ 3

Which class can be extended to create a thread?

A) Object

B) Thread

C) Runnable

D) Process

**Answer:** B

---

### MCQ 4

Which interface can be implemented to create a thread?

A) Serializable

B) Runnable

C) Comparable

D) Cloneable

**Answer:** B

---

### MCQ 5

Which method starts a new thread?

A) run()

B) execute()

C) start()

D) begin()

**Answer:** C

---

11
### MCQ 6

Which method contains the code executed by the thread?

A) main()

B) start()

C) run()

D) sleep()

**Answer:** C

---

### MCQ 7

Which method pauses the current thread?

A) join()

B) sleep()

C) yield()

D) stop()

**Answer:** B

---

### MCQ 8

Which method waits for another thread to finish?

A) sleep()

B) yield()

C) join()

D) interrupt()

**Answer:** C

---

12
### MCQ 9

Which method interrupts a sleeping thread?

A) stop()

B) destroy()

C) interrupt()

D) notify()

**Answer:** C

---

### MCQ 10

Which method gives another thread a chance to execute?

A) join()

B) sleep()

C) yield()

D) start()

**Answer:** C

---

### MCQ 11

Which statement is TRUE?

A) `run()` creates a new thread.

B) `start()` creates a new thread.

C) Both create new threads.

D) Neither creates a thread.

**Answer:** B

---

13
### MCQ 12

Which thread starts every Java program?

A) Worker Thread

B) Daemon Thread

C) Main Thread

D) Child Thread

**Answer:** C

---

### MCQ 13

Which thread runs in the background?

A) Main Thread

B) Daemon Thread

C) Runnable Thread

D) Worker Thread

**Answer:** B

---

### MCQ 14

Normal thread priority is

A) 1

B) 5

C) 10

D) 0

**Answer:** B

---

14
### MCQ 15

Which statement is FALSE?

A) `start()` creates a new thread.

B) `run()` behaves like a normal method when called directly.

C) `sleep()` permanently stops a thread.

D) Java supports multithreading.

**Answer:** C

---

# Common Mistakes Asked in TCS

❌ Calling

```java id="7p3k8m"
run();

and expecting a new thread.

✔ Only

```java id="9m2v6q" start();

creates a new thread.

---

❌ Thinking `sleep()` stops a thread permanently.

✔ It only pauses the thread temporarily.

---

❌ Confusing `join()` and `yield()`.

✔ `join()` waits for another thread.

✔ `yield()` gives another thread a chance to execute.

---

15
# Memory Tricks

Remember

```text id="4x8n2p"
start()

New Thread

Remember

```text id="5r1m7v" run()

Normal Method

---

Remember

```text id="2k9q4w"
sleep()

Pause

Remember

```text id="6v3p8m" join()

Wait

---

16
Remember

```text id="1n5r2q"
yield()

Give Chance

Remember

```text id="8m7v4k" interrupt()

Stop Sleeping Thread ```

One-Minute Revision
✔ Multithreading means executing multiple threads simultaneously.

✔ Thread = Smallest unit of execution.

✔ Two ways to create threads:

• Extend Thread class.


• Implement Runnable interface.

✔ start() → Creates a new thread.

✔ run() → Normal method (if called directly).

✔ sleep() → Pauses the current thread.

✔ join() → Waits for another thread to complete.

✔ yield() → Gives another thread a chance to execute.

✔ interrupt() → Interrupts a sleeping/waiting thread.

✔ Every Java program starts with the Main Thread.

17
✔ Thread priority:

• MIN_PRIORITY = 1
• NORM_PRIORITY = 5
• MAX_PRIORITY = 10

🎯 TCS IPA Memory Shortcut

Method Purpose

start() Starts New Thread

run() Thread Code

sleep() Pause Thread

join() Wait for Another Thread

yield() Give CPU to Others

interrupt() Interrupt Thread

⭐ Most Expected TCS MCQs

• How many ways to create a thread? → 2


• Which method starts a new thread? → start()
• Difference between start() and run()
• Which method pauses a thread? → sleep()
• Which method waits for another thread? → join()
• Which method gives another thread a chance? → yield()
• Which thread starts every Java program? → Main Thread
• Preferred way to create threads? → Implement Runnable

18
CORE JAVA FOR TCS IPA – Chapter 23: File Handling
(Detailed Notes + MCQs)

What is File Handling?


File Handling is the process of creating, reading, writing, updating, and deleting files using Java.

Normally, data stored in variables is temporary (lost when the program ends).

File handling allows data to be stored permanently.

Example

```text id="6m2r8k" Program

File

Permanent Storage

---

# Why Do We Need File Handling?

Without File Handling

✔ Data is lost after program execution.

With File Handling

✔ Data is permanently stored.

Applications

- Student Records
- Banking Systems
- Employee Data
- Configuration Files
- Log Files

1
---

# Java File Handling Package

File handling classes belong to

```java id="8p5m2q"
[Link]

Example

```java id="4k7n9v" import [Link].*;

---

# Important File Handling Classes

The most important classes for TCS IPA are:

```text id="2v6r1m"
File

FileReader

BufferedReader

FileWriter

BufferedWriter

1. File Class
The File class is used to represent files and directories.

It can:

✔ Create a file

✔ Delete a file

✔ Check file existence

2
✔ Get file name

✔ Get file path

Example

```java id="9w3k6p" import [Link];

public class Main{

public static void main(String[] args){

File file = new File("[Link]");

---

# Common Methods of File Class

| Method | Purpose |
|---------|---------|
| createNewFile() | Creates a new file |
| exists() | Checks whether file exists |
| delete() | Deletes the file |
| getName() | Returns file name |
| getPath() | Returns file path |
| length() | Returns file size |
| mkdir() | Creates a directory |

Example

```java id="7x4m1q"
File file = new File("[Link]");

[Link]([Link]());

2. FileReader
Used to read character data from a file.

3
Example

```java id="3p8v5n" FileReader fr = new FileReader("[Link]");

Reads one character at a time.

Suitable for text files.

---

# 3. BufferedReader

Reads text efficiently using a buffer.

Advantages

✔ Faster than FileReader

✔ Can read an entire line

Example

```java id="6r2k9m"
BufferedReader br =
new BufferedReader(
new FileReader("[Link]"));

Read Line

```java id="5m7p4x" String line = [Link]();

---

# FileReader vs BufferedReader

| FileReader | BufferedReader |
|-------------|----------------|
| Reads character by character | Reads line by line |
| Slower | Faster |
| No Buffer | Uses Buffer |

---

# 4. FileWriter

4
Used to **write character data** into a file.

Example

```java id="2n5q8v"
FileWriter fw = new FileWriter("[Link]");

[Link]("Hello Java");

[Link]();

Output

```text id="8m1r6k" Hello Java

---

# Append Mode

To append data instead of overwriting,

use

```java id="7v3m2p"
FileWriter fw =
new FileWriter("[Link]", true);

5. BufferedWriter
Used to write text efficiently using a buffer.

Advantages

✔ Faster than FileWriter

✔ Less disk access

Example

```java id="9k6x1r" BufferedWriter bw = new BufferedWriter( new FileWriter("[Link]"));

[Link]("Welcome");

5
[Link]();

---

# FileWriter vs BufferedWriter

| FileWriter | BufferedWriter |
|-------------|----------------|
| Direct Writing | Buffered Writing |
| Slower | Faster |
| No Buffer | Uses Buffer |

---

# Reading a File

Example

```java id="4q8m7v"
BufferedReader br =
new BufferedReader(
new FileReader("[Link]"));

String line;

while((line = [Link]()) != null){

[Link](line);

[Link]();

Writing a File
Example

```java id="5w1k9p" BufferedWriter bw = new BufferedWriter( new FileWriter("[Link]"));

[Link]("Core Java");

[Link]();

6
---

# Closing Files

Always close a file after use.

Example

```java id="1m4v8q"
[Link]();

[Link]();

[Link]();

[Link]();

Reason

✔ Prevents memory leaks

✔ Releases system resources

Exception Handling in File Handling


File operations may throw checked exceptions.

Example

```java id="3x7n5m" try{

FileReader fr =
new FileReader("[Link]");

catch(IOException e){

[Link](e);

7
`IOException` is a **Checked Exception**.

---

# Frequently Used File Class Methods

| Method | Description |
|----------|-------------|
| exists() | Checks file existence |
| createNewFile() | Creates file |
| delete() | Deletes file |
| mkdir() | Creates directory |
| getName() | File name |
| getPath() | File path |
| length() | File size |

---

# Frequently Asked TCS MCQs

### MCQ 1

Which package contains file handling classes?

A) [Link]

B) [Link]

C) [Link]

D) [Link]

**Answer:** C

---

### MCQ 2

Which class is used to represent a file?

A) FileReader

B) FileWriter

C) File

D) BufferedReader

8
**Answer:** C

---

### MCQ 3

Which class reads characters from a file?

A) FileWriter

B) FileReader

C) BufferedWriter

D) Scanner

**Answer:** B

---

### MCQ 4

Which class writes characters into a file?

A) FileReader

B) BufferedReader

C) FileWriter

D) File

**Answer:** C

---

### MCQ 5

Which class reads text line by line?

A) FileReader

B) BufferedReader

C) Scanner

D) File

9
**Answer:** B

---

### MCQ 6

Which class writes text using a buffer?

A) FileWriter

B) BufferedWriter

C) FileReader

D) Scanner

**Answer:** B

---

### MCQ 7

Which method creates a new file?

A) newFile()

B) create()

C) createNewFile()

D) makeFile()

**Answer:** C

---

### MCQ 8

Which method checks whether a file exists?

A) check()

B) exists()

C) isFile()

D) available()

10
**Answer:** B

---

### MCQ 9

Which method deletes a file?

A) remove()

B) erase()

C) delete()

D) clear()

**Answer:** C

---

### MCQ 10

Which method returns the file name?

A) fileName()

B) getFile()

C) getName()

D) name()

**Answer:** C

---

### MCQ 11

Which method returns the file size?

A) size()

B) getSize()

C) length()

D) bytes()

11
**Answer:** C

---

### MCQ 12

Which exception is commonly thrown during file handling?

A) ArithmeticException

B) IOException

C) NullPointerException

D) SQLException

**Answer:** B

---

### MCQ 13

Which class is faster for reading text?

A) FileReader

B) BufferedReader

C) Scanner

D) File

**Answer:** B

---

### MCQ 14

Which class is faster for writing text?

A) FileWriter

B) BufferedWriter

C) File

D) Scanner

12
**Answer:** B

---

### MCQ 15

Which statement is TRUE?

A) FileReader writes data.

B) FileWriter reads data.

C) BufferedReader uses buffering and is faster.

D) File class reads file contents.

**Answer:** C

---

# Common Mistakes Asked in TCS

❌ Thinking `File` reads file contents.

✔ `File` only represents a file or directory.

---

❌ Forgetting to close files.

✔ Always call

```java id="7r3m8q"
close();

❌ Confusing FileReader and BufferedReader .

✔ FileReader → Character by character.

✔ BufferedReader → Line by line (faster).

13
Memory Tricks
Remember

```text id="8p4v2m" File

Represents File

---

Remember

```text id="6m7q1k"
FileReader

Read Characters

Remember

```text id="2x9r5n" BufferedReader

Read Lines

Fast

---

Remember

```text id="5v8m3q"
FileWriter

14
Write Characters

Remember

```text id="9k1p7r" BufferedWriter

Write Fast

---

Remember

```text id="4w6n2m"
[Link]

File Handling

One-Minute Revision
✔ File Handling is used to store data permanently.

✔ File handling classes belong to [Link] .

✔ File → Represents a file or directory.

✔ FileReader → Reads characters.

✔ BufferedReader → Reads lines (faster).

✔ FileWriter → Writes characters.

✔ BufferedWriter → Writes efficiently using a buffer.

✔ Always close files after use.

15
✔ File handling commonly throws IOException.

🎯 TCS IPA Memory Shortcut

Class Purpose

File Represents File/Directory

FileReader Read Characters

BufferedReader Read Lines (Fast)

FileWriter Write Characters

BufferedWriter Buffered Writing (Fast)

⭐ Most Expected TCS MCQs

• Which package contains file handling classes? → [Link]


• Which class represents a file? → File
• Which class reads characters? → FileReader
• Which class reads lines? → BufferedReader
• Which class writes characters? → FileWriter
• Which class writes faster? → BufferedWriter
• Which exception is common in file handling? → IOException
• Why should files be closed? → To release system resources and prevent memory leaks

16
CORE JAVA FOR TCS IPA – Chapter 24: Java 8
Features (Detailed Notes + MCQs)

Introduction to Java 8
Java 8 (released in 2014) is one of the most important versions of Java.

It introduced several powerful features that made Java programming:

• More concise
• Faster
• Functional
• Easy to read

TCS IPA frequently asks MCQs from Java 8 features.

Major Java 8 Features


```text id="5r8m2q" Java 8

Lambda Expression

Functional Interface

Stream API

Method Reference

Optional Class

Default Methods

Static Methods in Interface

New Date & Time API

---

1
# 1. Lambda Expression

A **Lambda Expression** is an **anonymous function** (a function without a


name).

It is used to write shorter and cleaner code.

**Syntax**

```java id="7n3v5m"
(parameters) -> expression

Example

Without Lambda

```java id="4p9x1k" Runnable r = new Runnable() {

public void run() {

[Link]("Hello");

};

With Lambda

```java id="9m6q2v"
Runnable r = () -> [Link]("Hello");

Advantages

✔ Less Code

✔ Better Readability

✔ Functional Programming

2
Lambda Expression Components
```text id="8w4r1p" (parameters)

->

Expression / Body

Example

```java id="3k7m8q"
(a, b) -> a + b

2. Functional Interface
One of the most important TCS MCQs.

A Functional Interface is an interface that contains exactly one abstract method.

It may also contain:

✔ Default Methods

✔ Static Methods

Example

```java id="2v5n9r" @FunctionalInterface

interface Test {

void display();

3
Valid

---

# Invalid Functional Interface

```java id="6q8m1k"
@FunctionalInterface

interface Test {

void show();

void display();

Compile-Time Error

Reason

A Functional Interface can have only one abstract method.

@FunctionalInterface Annotation
Used to indicate that an interface is a Functional Interface.

Example

```java id="4x2p7m" @FunctionalInterface

interface Demo {

void test();

If more than one abstract method is added,

the compiler generates an error.

4
---

# Common Functional Interfaces

Package

```java id="9k4r6v"
[Link]

Examples

• Predicate
• Function
• Consumer
• Supplier

3. Stream API
The Stream API is used to process collections efficiently.

It supports

✔ Filtering

✔ Sorting

✔ Mapping

✔ Counting

✔ Reducing

Example

```java id="7m5q1p" List<Integer> list = [Link](1,2,3,4,5);

[Link]()

.filter(x -> x > 2)

.forEach([Link]::println);

5
Output

```text id="5v8k2r"
3

Advantages

✔ Less Code

✔ Better Performance

✔ Parallel Processing

Common Stream Methods


Method Purpose

filter() Filters elements

map() Transforms elements

sorted() Sorts elements

distinct() Removes duplicates

count() Counts elements

forEach() Iterates through elements

collect() Collects results

4. Method Reference
A Method Reference is a shorter form of a Lambda Expression.

Syntax

```java id="8r1m6q" ClassName::methodName

6
Example

Lambda

```java id="2n7k4p"
[Link](x -> [Link](x));

Method Reference

```java id="6v3q9m" [Link]([Link]::println);

Advantages

✔ Cleaner Code

✔ Easy to Read

---

# Types of Method References

1. Static Method Reference

```java id="3m8v2k"
ClassName::staticMethod

1. Instance Method Reference

```java id="7p5q1n" object::method

---

3. Constructor Reference

```java id="4k9m6r"
ClassName::new

5. Optional Class
Introduced to avoid

7
```text id="9x2r5v" NullPointerException

Package

```java id="1m7k4q"
[Link]

Example

```java id="5v3p8n" Optional<String> name = [Link]("Harshad");

[Link]([Link]());

Advantages

✔ Better Null Handling

✔ Safer Code

---

# Common Optional Methods

| Method | Purpose |
|----------|----------|
| of() | Creates Optional |
| ofNullable() | Allows null |
| isPresent() | Checks value |
| get() | Returns value |
| orElse() | Default value |

---

# 6. Default Methods

Java 8 allows interfaces to contain **default methods**.

Example

```java id="2q8n5m"
interface Test {

default void show() {

[Link]("Default");

8
}

Purpose

Allows adding new methods to interfaces without breaking existing implementations.

7. Static Methods in Interface


Java 8 also introduced static methods inside interfaces.

Example

```java id="8m6r2p" interface Test {

static void display() {

[Link]("Hello");

Called using

```java id="4v9k1q"
[Link]();

Java 8 vs Java 7
Java 7 Java 8

No Lambda Lambda Expression

No Stream API Stream API

No Default Methods Default Methods

9
Java 7 Java 8

No Method Reference Method Reference

No Optional Optional Class

Frequently Asked TCS MCQs


MCQ 1

Lambda Expression was introduced in

A) Java 6

B) Java 7

C) Java 8

D) Java 9

Answer: C

MCQ 2

A Functional Interface contains

A) No abstract methods

B) One abstract method

C) Two abstract methods

D) Unlimited abstract methods

Answer: B

MCQ 3

Which annotation is used for a Functional Interface?

A) @Override

10
B) @FunctionalInterface

C) @Deprecated

D) @SafeVarargs

Answer: B

MCQ 4

Which Java 8 feature is used for functional programming?

A) Stream API

B) Lambda Expression

C) Optional

D) Method Reference

Answer: B

MCQ 5

Which API is used to process collections?

A) JDBC

B) Stream API

C) Reflection API

D) File API

Answer: B

MCQ 6

Method Reference uses

A) ::

11
B) ->

C) ::

D) =>

Answer: A

MCQ 7

Which class helps avoid NullPointerException?

A) Optional

B) Stream

C) String

D) Integer

Answer: A

MCQ 8

Which package contains Optional?

A) [Link]

B) [Link]

C) [Link]

D) [Link]

Answer: B

MCQ 9

Which interface method type was introduced in Java 8?

A) Abstract

12
B) Default

C) Final

D) Protected

Answer: B

MCQ 10

Java 8 introduced static methods in

A) Classes

B) Interfaces

C) Packages

D) Arrays

Answer: B

MCQ 11

Which symbol is used in Lambda Expressions?

A) ::

B) ->

C) =>

D) ==>

Answer: B

MCQ 12

Which statement is TRUE?

A) Functional Interface can have two abstract methods.

13
B) Functional Interface can have only one abstract method.

C) Functional Interface cannot have default methods.

D) Functional Interface cannot have static methods.

Answer: B

MCQ 13

Which Stream method removes duplicate elements?

A) sorted()

B) distinct()

C) count()

D) filter()

Answer: B

MCQ 14

Which Stream method filters elements?

A) map()

B) filter()

C) count()

D) collect()

Answer: B

MCQ 15

Which statement is FALSE?

A) Lambda Expressions reduce code.

14
B) Optional helps avoid NullPointerException.

C) Java 8 introduced Stream API.

D) Functional Interface contains multiple abstract methods.

Answer: D

Common Mistakes Asked in TCS


❌ Thinking a Functional Interface cannot have default methods.

✔ It can have default and static methods.

❌ Thinking Optional removes exceptions.

✔ It mainly helps avoid NullPointerException.

❌ Confusing Lambda ( -> ) and Method Reference ( :: ).

✔ Lambda → ->

✔ Method Reference → ::

Memory Tricks
Remember

```text id="5q9m2v" Lambda

->

Anonymous Function

15
---

Remember

```text id="2n6k8r"
Functional Interface

Exactly One

Abstract Method

Remember

```text id="7v4m1p" @FunctionalInterface

Annotation

---

Remember

```text id="4r8q5n"
Method Reference

::

Remember

```text id="8k2m7v" Optional

Avoid

NullPointerException

16
---

Remember

```text id="1p6v4q"
Stream API

Process Collections

One-Minute Revision
✔ Java 8 introduced Lambda Expressions, Functional Interfaces, Stream API, Method References,
Optional, Default Methods, and Static Methods in Interfaces.

✔ Lambda Expression uses -> .

✔ Method Reference uses :: .

✔ Functional Interface contains exactly one abstract method.

✔ @FunctionalInterface is used to declare a Functional Interface.

✔ Stream API is used to process collections efficiently.

✔ Optional helps avoid NullPointerException.

✔ Interfaces can have default and static methods from Java 8.

🎯 TCS IPA Memory Shortcut

Feature Purpose

Lambda Short Anonymous Function ( -> )

Functional Interface One Abstract Method

@FunctionalInterface Annotation

Stream API Process Collections

Method Reference ::

17
Feature Purpose

Optional Avoid NullPointerException

Default Method Interface Method with Body

Static Method Static Method in Interface

⭐ Most Expected TCS MCQs

• Java 8 introduced → Lambda Expressions


• Functional Interface → Exactly One Abstract Method
• Annotation for Functional Interface → @FunctionalInterface
• Lambda Operator → ->
• Method Reference Operator → ::
• Stream API is used for → Processing Collections
• Optional prevents → NullPointerException
• Java 8 interface features → Default & Static Methods

18
CORE JAVA FOR TCS IPA – Chapter 25: Important
Output-Based Questions (Detailed Notes + MCQs)

Introduction
Output-based questions are among the most frequently asked questions in the TCS IPA Java test.

These questions test your understanding of:

• Operators
• Strings
• StringBuilder
• Increment/Decrement
• Loops
• Arrays
• Method Calls
• Object References
• Wrapper Classes

Tip: Never guess the output. Execute the code step by step mentally.

1. Post Increment (x++)


Example

int x = 5;

[Link](x++);

[Link](x);

Output

1
Explanation

• x++ uses the current value first.


• Then it increments.

Memory Trick

Post Increment

Use

Increase

2. Pre Increment (++x)


Example

int x = 5;

[Link](++x);

[Link](x);

Output

Explanation

First increment,

then use the value.

Memory Trick

2
Pre Increment

Increase

Use

3. Combined Example

int x = 5;

[Link](x++);

[Link](++x);

Output

Explanation

Initially

x = 5

First line

Print 5

x becomes 6

Second line

3
Increment to 7

Print 7

4. String is Immutable
Example

String s = "Java";

[Link](" Programming");

[Link](s);

Output

Java

Explanation

concat() creates a new String.

Original string is unchanged.

Correct Way

s = [Link](" Programming");

[Link](s);

Output

Java Programming

4
5. StringBuilder is Mutable
Example

StringBuilder sb = new StringBuilder("Java");

[Link](" Programming");

[Link](sb);

Output

Java Programming

Explanation

append() modifies the existing object.

6. StringBuffer Example

StringBuffer sb = new StringBuffer("Hello");

[Link](" World");

[Link](sb);

Output

Hello World

7. Equality (==)
Example

String s1 = "Java";

5
String s2 = "Java";

[Link](s1 == s2);

Output

true

Reason

Both refer to the same object in the String Constant Pool (SCP).

8. equals()
Example

String s1 = new String("Java");

String s2 = new String("Java");

[Link]([Link](s2));

Output

true

Reason

equals() compares contents.

9. == with new String()

String s1 = new String("Java");

String s2 = new String("Java");

[Link](s1 == s2);

6
Output

false

Reason

Different heap objects.

10. Array Length

int arr[] = {1,2,3};

[Link]([Link]);

Output

Remember

Arrays use

length

NOT

length()

11. String Length

String s = "Java";

[Link]([Link]());

Output

7
4

Remember

Strings use

length()

12. charAt()

String s = "Java";

[Link]([Link](2));

Output

Index starts from 0.

13. substring()

String s = "Programming";

[Link]([Link](3,7));

Output

gram

End index is excluded.

8
14. [Link]()

[Link]([Link]("100")+20);

Output

120

15. String Concatenation

[Link](10+20+"Java");

Output

30Java

[Link]("Java"+10+20);

Output

Java1020

16. Boolean Expression

[Link](10>5 && 5>2);

Output

true

9
17. Short-Circuit

int x = 5;

[Link](x>10 && ++x>6);

[Link](x);

Output

false

Reason

Second condition is not executed.

18. Switch with String

String day = "MON";

switch(day){

case "MON":

[Link]("Monday");

Output

Monday

(Java 7 onwards)

10
19. Default Value

class Test{

int x;

public static void main(String args[]){

Test t = new Test();

[Link](t.x);

Output

Instance variables get default values.

20. Local Variable

public static void main(String args[]){

int x;

[Link](x);

Output

Compile-Time Error

Local variables have no default value.

11
Frequently Asked TCS MCQs
MCQ 1

Output

int x=5;

[Link](x++);

A) 5

B) 6

C) Error

D) 4

Answer: A

MCQ 2

Output

int x=5;

[Link](++x);

A) 5

B) 6

C) 7

D) Error

Answer: B

MCQ 3

Output

12
String s="Java";

[Link](" Programming");

[Link](s);

A) Java

B) Java Programming

C) Programming

D) Error

Answer: A

MCQ 4

Output

StringBuilder sb=new StringBuilder("Java");

[Link](" Programming");

[Link](sb);

A) Java

B) Java Programming

C) Programming

D) Error

Answer: B

MCQ 5

Which class is immutable?

A) StringBuilder

13
B) StringBuffer

C) String

D) ArrayList

Answer: C

MCQ 6

Which class is mutable?

A) String

B) StringBuilder

C) Integer

D) Character

Answer: B

MCQ 7

Which compares object content?

A) ==

B) equals()

C) compare()

D) compareTo()

Answer: B

MCQ 8

Arrays use

A) length()

14
B) size()

C) length

D) count()

Answer: C

MCQ 9

Strings use

A) length

B) size()

C) length()

D) count()

Answer: C

MCQ 10

Output

[Link](10+20+"Java");

A) Java30

B) 30Java

C) 1020Java

D) Error

Answer: B

MCQ 11

Output

15
[Link]("Java"+10+20);

A) Java30

B) Java1020

C) 30Java

D) Error

Answer: B

MCQ 12

Output

[Link]([Link]("50")+50);

A) 5050

B) 100

C) Error

D) 50

Answer: B

MCQ 13

Local variables

A) Have default values

B) Do not have default values

C) Are always 0

D) Are always null

Answer: B

16
MCQ 14

Instance variables

A) Have no default values

B) Have default values

C) Must be initialized

D) Cannot be initialized

Answer: B

MCQ 15

Which statement is TRUE?

A) StringBuilder is immutable.

B) String is mutable.

C) StringBuilder is mutable.

D) StringBuffer is immutable.

Answer: C

Common TCS Traps


❌ [Link]() changes the original string.

✔ False — String is immutable.

❌ Arrays use length() .

✔ False — Arrays use length .

❌ == compares String content.

17
✔ False — == compares references.

❌ Local variables get default values.

✔ False — They must be initialized before use.

Memory Tricks
Remember

x++

Use

Increase

++x

Increase

Use

String

Immutable

18
StringBuilder

Mutable

==

Reference

equals()

Content

Array

length

String

length()

One-Minute Revision
✔ x++ → Use first, then increment.

19
✔ ++x → Increment first, then use.

✔ String is immutable.

✔ StringBuilder and StringBuffer are mutable.

✔ == compares references.

✔ equals() compares contents.

✔ Arrays use length .

✔ Strings use length() .

✔ Local variables have no default value.

✔ Instance variables have default values.

🎯 TCS IPA Memory Shortcut

Topic Remember

x++ Use → Increase

++x Increase → Use

String Immutable

StringBuilder Mutable

== Reference Comparison

equals() Content Comparison

Array length

String length()

⭐ Most Expected TCS Output Questions

• Output of x++ and ++x


• [Link]() vs [Link]()
• == vs equals()
• length vs length()
• [Link]()
• String concatenation with numbers
• Default values of variables
• Local variable initialization errors

20
CORE JAVA FOR TCS IPA – Chapter 26: Frequently
Asked Java Exceptions (Detailed Notes + MCQs)

What is an Exception?
An Exception is an unexpected event that occurs during the execution of a program and disrupts its
normal flow.

Java provides many built-in exception classes.

For the TCS IPA Exam, these exceptions are asked repeatedly:

• ArithmeticException
• NullPointerException
• ArrayIndexOutOfBoundsException
• ClassCastException
• NumberFormatException
• IOException
• SQLException

Exception Hierarchy
```text id="2m8q4v" Object

Throwable

Exception

RuntimeException

Memory Trick

```text id="8k3r1m"
Throwable

1

Exception

RuntimeException

Types of Exceptions
Java exceptions are divided into two categories.

Checked Exceptions
✔ Checked during compilation.

Examples

• IOException
• SQLException
• FileNotFoundException

Unchecked Exceptions
✔ Occur during runtime.

Examples

• ArithmeticException
• NullPointerException
• ArrayIndexOutOfBoundsException
• NumberFormatException
• ClassCastException

1. ArithmeticException
Occurs during illegal arithmetic operations.

Most common reason

2
✔ Divide by zero.

Example

```java id="6v2m9k" int a = 10;

[Link](a / 0);

Output

```text id="4p7x1q"
ArithmeticException

Reason

Division by zero is not allowed.

2. NullPointerException
Occurs when a null reference is used to access an object.

Example

```java id="3r8n5v" String s = null;

[Link]([Link]());

Output

```text id="9m4q2k"
NullPointerException

Reason

s does not reference any object.

3. ArrayIndexOutOfBoundsException
Occurs when an invalid array index is accessed.

3
Example

```java id="8p1v7m" int arr[] = {10,20,30};

[Link](arr[5]);

Output

```text id="1k5r8q"
ArrayIndexOutOfBoundsException

Reason

Array size is 3, but index 5 is accessed.

4. ClassCastException
Occurs when an object is cast to an incompatible type.

Example

```java id="5n3q8v" Object obj = "Java";

Integer x = (Integer)obj;

Output

```text id="2v7m1k"
ClassCastException

Reason

A String object cannot be cast to Integer .

5. NumberFormatException
Occurs when converting an invalid string into a number.

Example

4
```java id="7m2p4q" [Link]("ABC");

Output

```text id="9r6k3v"
NumberFormatException

Reason

"ABC" is not a valid integer.

6. IOException
A Checked Exception.

Occurs during Input/Output operations.

Examples

• File not found


• File read/write errors

Example

```java id="4x9m2p" FileReader fr = new FileReader("[Link]");

If the file does not exist,

`IOException` (or its subclass `FileNotFoundException`) is thrown.

---

# 7. SQLException

A **Checked Exception**.

Occurs during **database operations**.

Examples

- Invalid SQL Query


- Database Connection Failure
- Wrong Table Name

5
Example

```java id="6q1v8k"
Connection con = [Link](...);

If the database connection fails,

SQLException is thrown.

Checked vs Unchecked Exceptions


Checked Exception Unchecked Exception

Compile-Time Runtime

Must Handle Optional to Handle

IOException ArithmeticException

SQLException NullPointerException

FileNotFoundException NumberFormatException

Exception Summary Table


Exception Cause Type

ArithmeticException Divide by Zero Unchecked

NullPointerException Null Object Access Unchecked

ArrayIndexOutOfBoundsException Invalid Array Index Unchecked

ClassCastException Invalid Type Casting Unchecked

NumberFormatException Invalid Number Conversion Unchecked

IOException File/Input-Output Error Checked

SQLException Database Error Checked

6
How to Handle Exceptions
Example

```java id="8n4q7m" try{

int a = 10 / 0;

catch(ArithmeticException e){

[Link]("Cannot divide by zero");

Output

```text id="5k2m9r"
Cannot divide by zero

Frequently Asked TCS MCQs


MCQ 1

Which exception occurs when dividing by zero?

A) IOException

B) NullPointerException

C) ArithmeticException

D) SQLException

Answer: C

7
MCQ 2

Which exception occurs when accessing a null object?

A) ArithmeticException

B) NumberFormatException

C) NullPointerException

D) IOException

Answer: C

MCQ 3

Which exception occurs when an invalid array index is accessed?

A) ClassCastException

B) ArrayIndexOutOfBoundsException

C) IOException

D) SQLException

Answer: B

MCQ 4

Which exception occurs during invalid type casting?

A) NumberFormatException

B) ClassCastException

C) ArithmeticException

D) IOException

Answer: B

8
MCQ 5

Which exception occurs when parsing "ABC" using [Link]() ?

A) IOException

B) NumberFormatException

C) ArithmeticException

D) SQLException

Answer: B

MCQ 6

Which exception is related to file handling?

A) SQLException

B) IOException

C) ArithmeticException

D) NullPointerException

Answer: B

MCQ 7

Which exception is related to database programming?

A) IOException

B) ArithmeticException

C) SQLException

D) NumberFormatException

Answer: C

9
MCQ 8

Which of the following is a Checked Exception?

A) ArithmeticException

B) NullPointerException

C) IOException

D) ClassCastException

Answer: C

MCQ 9

Which of the following is an Unchecked Exception?

A) IOException

B) SQLException

C) NumberFormatException

D) FileNotFoundException

Answer: C

MCQ 10

Which statement is TRUE?

A) IOException is unchecked.

B) SQLException is unchecked.

C) ArithmeticException is checked.

D) IOException is checked.

Answer: D

10
MCQ 11

Which exception occurs when reading a non-existing file?

A) NumberFormatException

B) IOException

C) NullPointerException

D) ArithmeticException

Answer: B

MCQ 12

Which exception occurs here?

```java id="9w6k2m" Object obj = "Java";

Integer i = (Integer)obj;

A) NullPointerException

B) ArithmeticException

C) ClassCastException

D) IOException

**Answer:** C

---

### MCQ 13

Root class of all exceptions is

A) Exception

B) Object

C) Throwable

D) RuntimeException

11
**Answer:** C

---

### MCQ 14

Which statement is FALSE?

A) SQLException is a Checked Exception.

B) ArithmeticException is an Unchecked Exception.

C) NullPointerException is a Checked Exception.

D) IOException is a Checked Exception.

**Answer:** C

---

### MCQ 15

Which exception occurs most commonly in JDBC?

A) SQLException

B) IOException

C) ArithmeticException

D) ClassCastException

**Answer:** A

---

# Common Mistakes Asked in TCS

❌ Thinking `IOException` is a Runtime Exception.

✔ It is a **Checked Exception**.

---

❌ Confusing `NumberFormatException` with `ClassCastException`.

12
✔ `NumberFormatException` → Invalid String to Number Conversion.

✔ `ClassCastException` → Invalid Object Type Casting.

---

❌ Thinking `NullPointerException` occurs because of arrays.

✔ It occurs due to **null object references**.

---

# Memory Tricks

Remember

```text id="7p3m9k"
ArithmeticException

Divide by Zero

```text id="5v8r2q" NullPointerException

Null Object

---

```text id="1m4k7v"
ArrayIndexOutOfBoundsException

Wrong Index

```text id="9x2q5n" ClassCastException

13
Wrong Casting

---

```text id="4r6m8p"
NumberFormatException

Invalid Number

```text id="6k1v3q" IOException

File Handling

---

```text id="2n8m5r"
SQLException

Database

One-Minute Revision
✔ ArithmeticException → Divide by zero.

✔ NullPointerException → Accessing a null object.

✔ ArrayIndexOutOfBoundsException → Invalid array index.

✔ ClassCastException → Invalid object type casting.

✔ NumberFormatException → Invalid string to number conversion.

✔ IOException → File/Input-Output errors (Checked).

14
✔ SQLException → Database errors (Checked).

✔ Root class of all exceptions → Throwable.

🎯 TCS IPA Memory Shortcut

Exception Cause

ArithmeticException Divide by Zero

NullPointerException Null Object

ArrayIndexOutOfBoundsException Invalid Array Index

ClassCastException Wrong Type Casting

NumberFormatException Invalid Number Conversion

IOException File Handling

SQLException Database Error

⭐ Most Expected TCS MCQs

• Which exception occurs when dividing by zero? → ArithmeticException


• Which exception occurs on null object access? → NullPointerException
• Which exception occurs on invalid array index? → ArrayIndexOutOfBoundsException
• Which exception occurs during invalid type casting? → ClassCastException
• Which exception occurs with [Link]("ABC") ? → NumberFormatException
• Which exception is related to file handling? → IOException
• Which exception is related to JDBC? → SQLException
• Which are Checked Exceptions? → IOException, SQLException

15
CORE JAVA FOR TCS IPA – Chapter 27: Java
Keywords (Must Memorize) – Detailed Notes +
MCQs

What are Java Keywords?


Keywords are reserved words in Java that have predefined meanings.

They cannot be used as identifiers (such as variable names, method names, or class names).

Example (Invalid)

int class = 10;

Output

Compile-Time Error

Reason: class is a Java keyword.

Most Important Java Keywords for TCS IPA

this

super

static

final

abstract

synchronized

volatile

transient

1
native

strictfp

instanceof

These keywords are frequently asked in TCS IPA MCQs.

1. this Keyword
this refers to the current object.

Uses

✔ Current object

✔ Current instance variable

✔ Current constructor ( this() )

Example

class Student{

int age;

Student(int age){

[Link] = age;

Cannot be used inside a static method.

2. super Keyword
super refers to the parent class object.

2
Uses

✔ Access parent variables

✔ Access parent methods

✔ Call parent constructor

Example

class Animal{

void sound(){

[Link]("Animal");

class Dog extends Animal{

void display(){

[Link]();

this vs super
this super

Current Class Parent Class

Current Object Parent Object

this() calls current constructor super() calls parent constructor

3
3. static Keyword
Belongs to the class, not objects.

Uses

✔ Static Variables

✔ Static Methods

✔ Static Block

✔ Static Nested Class

Example

class Test{

static int count = 0;

Memory

Class

Static

4. final Keyword
Used to restrict modification.

Used With Meaning

Variable Cannot change value

Method Cannot override

Class Cannot inherit

4
Example

final int x = 100;

5. abstract Keyword
Used to achieve abstraction.

Can be used with

✔ Classes

✔ Methods

Example

abstract class Animal{

abstract void sound();

Cannot create an object of an abstract class.

6. synchronized Keyword
Used in Multithreading.

Purpose

✔ Prevents multiple threads from accessing the same resource simultaneously.

Example

synchronized void display(){

5
Advantages

✔ Thread Safety

✔ Prevents Race Conditions

7. volatile Keyword
Used with variables.

Purpose

Ensures that every thread reads the latest value of the variable from main memory.

Example

volatile boolean flag = true;

Important

Used in multithreading.

8. transient Keyword
Used during Serialization.

A transient variable is not serialized.

Example

transient int password;

Memory Trick

transient

Temporary

6

Not Saved

9. native Keyword
Indicates that a method is implemented in a language other than Java (usually C/C++).

Example

public native void display();

Commonly used in JNI (Java Native Interface).

10. strictfp Keyword


Ensures consistent floating-point calculations across different platforms.

Example

strictfp class Test{

Used to maintain platform-independent floating-point results.

11. instanceof Operator


Checks whether an object belongs to a particular class or interface.

Example

7
String s = "Java";

[Link](s instanceof String);

Output

true

Example

Object obj = "Java";

[Link](obj instanceof String);

Output

true

Summary Table
Keyword Purpose

this Current Object

super Parent Object

static Belongs to Class

final Restrict Modification

abstract Abstraction

synchronized Thread Safety

volatile Latest Variable Value

transient Not Serialized

native Non-Java Method

strictfp Floating Point Consistency

instanceof Checks Object Type

8
Frequently Asked TCS MCQs
MCQ 1

this keyword refers to

A) Parent Class

B) Current Object

C) Current Package

D) Interface

Answer: B

MCQ 2

super keyword refers to

A) Current Class

B) Parent Class

C) Current Method

D) Interface

Answer: B

MCQ 3

Which keyword belongs to the class?

A) final

B) static

C) this

D) super

9
Answer: B

MCQ 4

Which keyword prevents inheritance?

A) static

B) final

C) abstract

D) native

Answer: B

MCQ 5

Which keyword is used to create an abstract class?

A) interface

B) abstract

C) static

D) final

Answer: B

MCQ 6

Which keyword provides thread safety?

A) volatile

B) synchronized

C) native

D) transient

10
Answer: B

MCQ 7

Which keyword ensures visibility of variables across threads?

A) final

B) volatile

C) synchronized

D) native

Answer: B

MCQ 8

Which keyword prevents a variable from being serialized?

A) native

B) transient

C) volatile

D) strictfp

Answer: B

MCQ 9

Which keyword indicates a method is implemented in C/C++?

A) transient

B) strictfp

C) native

D) synchronized

11
Answer: C

MCQ 10

Which keyword ensures platform-independent floating-point calculations?

A) final

B) volatile

C) strictfp

D) native

Answer: C

MCQ 11

Which operator checks an object's type?

A) typeof

B) instanceof

C) is

D) classof

Answer: B

MCQ 12

Which statement is TRUE?

A) this refers to the parent object.

B) super refers to the current object.

C) instanceof checks an object's type.

D) final allows inheritance.

12
Answer: C

MCQ 13

Which keyword cannot be used inside a static method?

A) super

B) this

C) Both A and B

D) static

Answer: C

MCQ 14

Which keyword is related to serialization?

A) transient

B) native

C) strictfp

D) volatile

Answer: A

MCQ 15

Which statement is FALSE?

A) final prevents overriding.

B) volatile is used in multithreading.

C) native methods are written in Java.

D) instanceof returns true or false .

13
Answer: C

Common Mistakes Asked in TCS


❌ Thinking this refers to the parent class.

✔ this refers to the current object.

❌ Thinking volatile provides thread synchronization.

✔ volatile provides visibility, not synchronization.

❌ Thinking transient means temporary variable.

✔ It means the variable is not serialized.

❌ Confusing this() and super() .

✔ this() → Calls current class constructor.

✔ super() → Calls parent class constructor.

Memory Tricks
Remember

this

Current Object

super

14
Parent Object

static

Class

final

Cannot Change

abstract

Incomplete

synchronized

Thread Safety

volatile

Latest Value

15
transient

Not Serialized

native

C / C++

strictfp

Floating Point

instanceof

Type Check

One-Minute Revision
✔ this → Current Object.

✔ super → Parent Object.

✔ static → Belongs to Class.

✔ final → Prevents modification.

✔ abstract → Used for abstraction.

16
✔ synchronized → Thread safety.

✔ volatile → Ensures latest variable value is visible to all threads.

✔ transient → Variable is not serialized.

✔ native → Method implemented in C/C++.

✔ strictfp → Platform-independent floating-point calculations.

✔ instanceof → Checks whether an object belongs to a class/interface.

🎯 TCS IPA Memory Shortcut

Keyword Remember

this Current Object

super Parent Object

static Class Member

final Cannot Change

abstract Incomplete Class/Method

synchronized Thread Safety

volatile Latest Value

transient Not Serialized

native C/C++ Method

strictfp Floating Point Consistency

instanceof Type Checking

⭐ Most Expected TCS MCQs

• this refers to → Current Object


• super refers to → Parent Object
• static belongs to → Class
• final prevents → Modification
• abstract is used for → Abstraction
• synchronized provides → Thread Safety
• volatile ensures → Variable Visibility
• transient is related to → Serialization
• native methods are written in → C/C++

17
• strictfp ensures → Floating-Point Consistency
• instanceof checks → Object Type

18
CORE JAVA FOR TCS IPA – Chapter 28: Frequently
Asked Java Differences (Detailed Notes + MCQs)

Introduction
Difference-based MCQs are among the most frequently asked questions in the TCS IPA Java Exam.

Instead of asking definitions, TCS often asks:

• Which statement is TRUE?


• Which feature belongs to which concept?
• Compare two Java concepts.

This chapter covers all the high-frequency Java differences.

1. JDK vs JRE vs JVM


Feature JDK JRE JVM

Full Form Java Development Kit Java Runtime Environment Java Virtual Machine

Purpose Develop + Compile + Run Run Java Programs Execute Bytecode

Compiler ( javac ) ✅ Yes ❌ No ❌ No

JVM Included ✅ Yes ✅ Yes —

Used By Developers End Users Java Runtime

Memory Trick

```text id="7d1m4p" JDK

JRE

JVM

1
**Most Expected MCQ**

Which contains the Java Compiler?

✅ **JDK**

---

# 2. String vs StringBuilder

| String | StringBuilder |
|----------|---------------|
| Immutable | Mutable |
| Slower | Faster |
| Thread Safe | Not Thread Safe |
| Creates New Object | Modifies Existing Object |

Example

```java id="2r8v5n"
String s = "Java";

[Link](" Programming");

[Link](s);

Output

```text id="8m1q6k" Java

---

```java id="4p7x2m"
StringBuilder sb = new StringBuilder("Java");

[Link](" Programming");

[Link](sb);

Output

```text id="6v9k3r" Java Programming

2
---

# 3. StringBuffer vs StringBuilder

| StringBuffer | StringBuilder |
|---------------|---------------|
| Thread Safe | Not Thread Safe |
| Synchronized | Not Synchronized |
| Slower | Faster |
| Mutable | Mutable |

### Memory Trick

```text id="5n2q7v"
Buffer

Safe

```text id="1m8r4k" Builder

Fast

---

# 4. ArrayList vs LinkedList

| ArrayList | LinkedList |
|------------|------------|
| Dynamic Array | Doubly Linked List |
| Fast Random Access | Slow Random Access |
| Slow Insertion | Fast Insertion |
| Less Memory | More Memory |

### Most Expected MCQ

Which provides fast random access?

✅ **ArrayList**

---

3
# 5. HashMap vs Hashtable

| HashMap | Hashtable |
|----------|-----------|
| One Null Key | No Null Key |
| Many Null Values | No Null Values |
| Not Synchronized | Synchronized |
| Faster | Slower |

### Memory Trick

```text id="9v5m1q"
HashMap

1 Null Key

Many Null Values

```text id="3k7r2p" Hashtable

No Null

---

# 6. HashSet vs TreeSet

| HashSet | TreeSet |
|----------|---------|
| Unordered | Sorted |
| Uses HashMap | Uses Tree Structure |
| Faster | Slower |
| One Null Allowed | No Null Allowed |

### Most Expected MCQ

Which collection stores elements in sorted order?

✅ **TreeSet**

---

4
# 7. == vs equals()

| == | equals() |
|----|-----------|
| Reference Comparison | Content Comparison |
| Compares Memory Address | Compares Object Data |
| Used with Objects | Overridden by Many Classes |

Example

```java id="4n8q5m"
String s1 = new String("Java");

String s2 = new String("Java");

[Link](s1 == s2);

Output

```text id="2p7v1k" false

---

```java id="6m3r8q"
[Link]([Link](s2));

Output

```text id="9k4x2v" true

---

# 8. throw vs throws

| throw | throws |
|--------|---------|
| Throws an exception | Declares exceptions |
| Used Inside Method | Used in Method Declaration |
| Throws One Exception | Declares One or More Exceptions |

Example

5
```java id="7x5m2p"
throw new ArithmeticException();

```java id="5r9k1v" void display() throws IOException{

### Memory Trick

```text id="1n6q4m"
throw

Throw

```text id="8v3p7k" throws

Declare

---

# 9. Method Overloading vs Method Overriding

| Overloading | Overriding |
|--------------|------------|
| Same Method Name | Same Method Signature |
| Different Parameters | Same Parameters |
| Compile-Time Polymorphism | Run-Time Polymorphism |
| No Inheritance Required | Inheritance Required |
| Compiler Decides | JVM Decides |

### Memory Trick

```text id="2m7r5q"
Overloading

6
Compile-Time

```text id="6k1v9p" Overriding

Run-Time

---

# 10. Interface vs Abstract Class

| Interface | Abstract Class |


|------------|----------------|
| Multiple Inheritance | Partial Implementation |
| No Constructor | Constructor Allowed |
| Methods Public & Abstract (by default) | Abstract + Normal Methods |
| Variables are Public Static Final | Instance Variables Allowed |
| Uses `implements` | Uses `extends` |

### Most Expected MCQ

Which supports multiple inheritance?

✅ **Interface**

---

# Bonus High-Frequency Differences

## List vs Set

| List | Set |
|------|-----|
| Duplicates Allowed | No Duplicates |
| Ordered | Usually Unordered |

---

## Checked vs Unchecked Exceptions

| Checked | Unchecked |
|----------|-----------|
| Compile-Time | Runtime |
| IOException | ArithmeticException |

7
| SQLException | NullPointerException |

---

## start() vs run()

| start() | run() |
|----------|-------|
| Creates New Thread | Normal Method |
| Calls run() Internally | No New Thread |

---

## length vs length()

| length | length() |
|----------|----------|
| Arrays | String |

---

## final vs finally vs finalize()

| final | finally | finalize() |


|--------|----------|------------|
| Keyword | Exception Block | Garbage Collection Method |

---

# Frequently Asked TCS MCQs

### MCQ 1

Which contains the Java Compiler?

A) JVM

B) JRE

C) JDK

D) Bytecode

**Answer:** C

---

### MCQ 2

8
Which class is immutable?

A) StringBuilder

B) StringBuffer

C) String

D) ArrayList

**Answer:** C

---

### MCQ 3

Which class is thread-safe?

A) StringBuilder

B) StringBuffer

C) ArrayList

D) LinkedList

**Answer:** B

---

### MCQ 4

Which collection provides fast random access?

A) LinkedList

B) ArrayList

C) HashSet

D) TreeSet

**Answer:** B

---

### MCQ 5

9
HashMap allows

A) No Null Key

B) One Null Key

C) Two Null Keys

D) Unlimited Null Keys

**Answer:** B

---

### MCQ 6

Hashtable allows

A) One Null Key

B) Many Null Values

C) No Null Key and No Null Value

D) One Null Value

**Answer:** C

---

### MCQ 7

Which collection stores elements in sorted order?

A) HashSet

B) TreeSet

C) LinkedHashSet

D) ArrayList

**Answer:** B

---

### MCQ 8

10
`==` compares

A) Content

B) Memory Reference

C) Length

D) Characters

**Answer:** B

---

### MCQ 9

`equals()` compares

A) References

B) Contents

C) Memory Address

D) Objects Only

**Answer:** B

---

### MCQ 10

Which keyword declares an exception?

A) throw

B) throws

C) catch

D) finally

**Answer:** B

---

### MCQ 11

11
Method Overloading is

A) Run-Time Polymorphism

B) Compile-Time Polymorphism

C) Dynamic Binding

D) Inheritance

**Answer:** B

---

### MCQ 12

Method Overriding is

A) Compile-Time Polymorphism

B) Run-Time Polymorphism

C) Constructor Overloading

D) Static Binding

**Answer:** B

---

### MCQ 13

Which supports multiple inheritance?

A) Abstract Class

B) Interface

C) Final Class

D) Thread Class

**Answer:** B

---

### MCQ 14

12
Which statement is TRUE?

A) Abstract Class supports multiple inheritance.

B) Interface can have constructors.

C) Interface supports multiple inheritance.

D) HashMap does not allow null values.

**Answer:** C

---

### MCQ 15

Which statement is FALSE?

A) ArrayList provides fast random access.

B) TreeSet stores sorted elements.

C) StringBuilder is immutable.

D) `throw` throws an exception.

**Answer:** C

---

# Common Mistakes Asked in TCS

❌ Thinking **JRE contains the compiler**.

✔ Only **JDK** contains `javac`.

---

❌ Thinking **StringBuilder is thread-safe**.

✔ **StringBuffer** is thread-safe.

---

❌ Thinking **HashMap** does not allow null.

✔ HashMap allows **one null key** and **multiple null values**.

13
---

❌ Confusing **throw** and **throws**.

✔ `throw` → Throws an exception.

✔ `throws` → Declares exceptions.

---

# Memory Tricks

Remember

```text id="3r7m1k"
JDK

Compiler

```text id="9v2q6p" String

Immutable

---

```text id="6m4k8r"
StringBuilder

Fast

```text id="1x5p9n" HashMap

1 Null Key

14
---

```text id="8q3v7m"
Hashtable

No Null

```text id="4n8r2k" Overloading

Compile-Time

---

```text id="5p1m6q"
Overriding

Run-Time

```text id="2v9k4r" Interface

Multiple Inheritance ```

One-Minute Revision
✔ JDK → Development (Compiler Included)

✔ JRE → Runtime Environment

✔ JVM → Executes Bytecode

✔ String → Immutable

15
✔ StringBuilder → Mutable & Fast

✔ StringBuffer → Thread Safe

✔ ArrayList → Fast Random Access

✔ LinkedList → Fast Insertion

✔ HashMap → One Null Key, Many Null Values

✔ Hashtable → No Null Key, No Null Value

✔ HashSet → Unordered

✔ TreeSet → Sorted

✔ == → Reference Comparison

✔ equals() → Content Comparison

✔ throw → Throw Exception

✔ throws → Declare Exception

✔ Overloading → Compile-Time

✔ Overriding → Run-Time

✔ Interface → Multiple Inheritance

✔ Abstract Class → Partial Implementation

🎯 Ultimate TCS IPA Difference Chart

Topic Remember

JDK vs JRE Compiler only in JDK

String vs StringBuilder Immutable vs Mutable

StringBuffer vs StringBuilder Thread Safe vs Not Thread Safe

ArrayList vs LinkedList Random Access vs Fast Insertion

HashMap vs Hashtable Null Allowed vs No Null

16
Topic Remember

HashSet vs TreeSet Unordered vs Sorted

== vs equals() Reference vs Content

throw vs throws Throw vs Declare

Overloading vs Overriding Compile-Time vs Run-Time

Interface vs Abstract Class Multiple Inheritance vs Partial Implementation

⭐ Highest Probability TCS MCQs

• Compiler is available in → JDK


• Immutable class → String
• Thread-safe string class → StringBuffer
• Fast random access → ArrayList
• HashMap allows → One Null Key & Many Null Values
• Hashtable allows → No Null Key & No Null Value
• Sorted Set → TreeSet
• == compares → Reference
• equals() compares → Content
• throw vs throws
• Overloading vs Overriding
• Interface vs Abstract Class

17
CORE JAVA FOR TCS IPA – Chapter 29: Must Know
Java APIs (Detailed Notes + MCQs)

Introduction
Java provides a large number of built-in classes known as Java APIs (Application Programming
Interfaces).

For the TCS IPA Exam, you are not expected to memorize every API, but you must know the most
commonly used classes and their methods.

The APIs most frequently asked in TCS are:

• Scanner
• Arrays
• Collections
• Math
• Character
• String
• StringBuilder
• ArrayList
• HashMap
• HashSet
• LinkedList
• Queue
• Stack

1. Scanner Class
Package

```java id="4r9k2m" [Link]

Used to take user input.

Example

```java id="6m1v8q"
Scanner sc = new Scanner([Link]);

1
Important Methods

Method Purpose

nextInt() Reads integer

nextDouble() Reads double

nextFloat() Reads float

nextLong() Reads long

next() Reads one word

nextLine() Reads entire line

nextBoolean() Reads boolean

Example

```java id="3p7m4k" int age = [Link]();

String name = [Link]();

**TCS MCQ**

Which method reads an entire line?

✅ **nextLine()**

---

# 2. Arrays Class

**Package**

```java id="9v5r2q"
[Link]

Provides utility methods for arrays.

Important Methods

Method Purpose

sort() Sort array

2
Method Purpose

binarySearch() Search element

equals() Compare arrays

fill() Fill array

toString() Convert array to string

Example

```java id="2k8m5v" int arr[] = {5,2,4};

[Link](arr);

Output

```text id="7n3q1p"
2 4 5

[Link]()
Example

```java id="5x9k2m" int arr[] = {10,20,30,40};

[Link]([Link](arr,30));

Output

```text id="8p4v7r"
2

Note: Array must be sorted before using binarySearch() .

3. Collections Class
Package

```java id="6m2q8v" [Link]

3
Provides utility methods for collections.

## Important Methods

| Method | Purpose |
|----------|---------|
| sort() | Sort List |
| reverse() | Reverse List |
| max() | Maximum Element |
| min() | Minimum Element |
| shuffle() | Random Order |

Example

```java id="1v7k4m"
[Link](list);

4. Math Class
Package

```java id="5q9m3r" [Link]

Automatically imported.

## Important Methods

| Method | Purpose |
|----------|---------|
| abs() | Absolute value |
| sqrt() | Square root |
| pow() | Power |
| max() | Maximum |
| min() | Minimum |
| random() | Random number |
| ceil() | Round up |
| floor() | Round down |

Example

```java id="9m1k7v"
[Link]([Link](25));

4
Output

```text id="3r6q2p" 5.0

---

# 5. Character Class

**Package**

```java id="2n8v5m"
[Link]

Important Methods

Method Purpose

isDigit() Checks digit

isLetter() Checks letter

isUpperCase() Uppercase check

isLowerCase() Lowercase check

toUpperCase() Convert to uppercase

toLowerCase() Convert to lowercase

Example

```java id="7k3m9q" [Link]('5');

Output

```text id="4p8v1r"
true

6. String Class
Most important Java API.

5
Important Methods

Method Purpose

length() String length

charAt() Character at index

substring() Substring

contains() Contains text

equals() Content comparison

equalsIgnoreCase() Ignore case

indexOf() First occurrence

lastIndexOf() Last occurrence

replace() Replace text

trim() Remove spaces

split() Split string

toUpperCase() Uppercase

toLowerCase() Lowercase

startsWith() Prefix check

endsWith() Suffix check

isEmpty() Empty string check

concat() Join strings

7. StringBuilder Class
Mutable string class.

Important Methods

Method Purpose

append() Add text

insert() Insert text

delete() Delete characters

6
Method Purpose

reverse() Reverse string

replace() Replace characters

length() Length

charAt() Character at index

Example

```java id="4v6m2p" StringBuilder sb = new StringBuilder("Java");

[Link](" Programming");

---

# 8. ArrayList Class

Dynamic array implementation.

## Important Methods

| Method | Purpose |
|----------|---------|
| add() | Insert element |
| remove() | Delete element |
| get() | Access element |
| set() | Update element |
| contains() | Check existence |
| size() | Number of elements |
| clear() | Remove all |
| isEmpty() | Empty check |

Example

```java id="1m5q8v"
[Link](10);

[Link](0);

[Link](0);

7
9. HashMap Class
Stores key-value pairs.

Important Methods

Method Purpose

put() Insert key-value

get() Get value

remove() Delete key

containsKey() Key exists

containsValue() Value exists

keySet() All keys

values() All values

size() Number of entries

clear() Remove all

Example

```java id="8p2r7m" [Link](1,"Java");

[Link](1);

---

# 10. HashSet Class

Stores unique elements.

## Important Methods

| Method | Purpose |
|----------|---------|
| add() | Add element |
| remove() | Remove element |
| contains() | Check existence |
| size() | Number of elements |
| clear() | Remove all |

8
---

# 11. LinkedList Class

Implements List and Queue.

## Important Methods

| Method | Purpose |
|----------|---------|
| add() | Insert |
| remove() | Delete |
| get() | Access |
| addFirst() | Insert at beginning |
| addLast() | Insert at end |
| removeFirst() | Remove first |
| removeLast() | Remove last |

---

# 12. Queue Interface

FIFO structure.

## Important Methods

| Method | Purpose |
|----------|---------|
| offer() | Insert |
| add() | Insert |
| peek() | View first element |
| poll() | Remove first element |
| remove() | Remove first |

Example

```java id="5r9m3q"
[Link](10);

[Link]();

[Link]();

9
13. Stack Class
LIFO structure.

Important Methods

Method Purpose

push() Insert

pop() Remove top

peek() View top

empty() Check empty

search() Find element

Example

```java id="2v6k1m" [Link](10);

[Link]();

[Link]();

---

# API Summary Table

| API | Frequently Used Methods |


|------|-------------------------|
| Scanner | nextInt(), next(), nextLine() |
| Arrays | sort(), binarySearch(), equals() |
| Collections | sort(), reverse(), max(), min() |
| Math | sqrt(), pow(), abs(), max(), min() |
| Character | isDigit(), isLetter(), isUpperCase() |
| String | length(), charAt(), substring(), split(), contains() |
| StringBuilder | append(), insert(), delete(), reverse() |
| ArrayList | add(), remove(), get(), contains() |
| HashMap | put(), get(), keySet(), values() |
| HashSet | add(), remove(), contains() |
| LinkedList | addFirst(), addLast(), removeFirst() |
| Queue | offer(), peek(), poll() |
| Stack | push(), pop(), peek() |

---

10
# Frequently Asked TCS MCQs

### MCQ 1

Which method reads an integer?

A) next()

B) nextLine()

C) nextInt()

D) nextDouble()

**Answer:** C

---

### MCQ 2

Which method sorts an array?

A) [Link]()

B) [Link]()

C) sort()

D) [Link]()

**Answer:** B

---

### MCQ 3

Which method searches a sorted array?

A) [Link]()

B) [Link]()

C) [Link]()

D) [Link]()

**Answer:** B

11
---

### MCQ 4

Which method sorts an ArrayList?

A) [Link]()

B) [Link]()

C) [Link]()

D) [Link]()

**Answer:** B

---

### MCQ 5

Which class contains `sqrt()`?

A) Arrays

B) Math

C) Character

D) String

**Answer:** B

---

### MCQ 6

Which method checks whether a character is a digit?

A) isDigit()

B) isNumber()

C) digit()

D) isInteger()

**Answer:** A

12
---

### MCQ 7

Which method appends text to a `StringBuilder`?

A) concat()

B) append()

C) add()

D) insert()

**Answer:** B

---

### MCQ 8

Which method inserts a key-value pair into a `HashMap`?

A) add()

B) insert()

C) put()

D) set()

**Answer:** C

---

### MCQ 9

Which method returns all keys from a `HashMap`?

A) values()

B) keys()

C) keySet()

D) getKeys()

**Answer:** C

13
---

### MCQ 10

Which method returns all values from a `HashMap`?

A) keySet()

B) values()

C) valueSet()

D) getValues()

**Answer:** B

---

### MCQ 11

Which Queue method removes and returns the first element?

A) peek()

B) poll()

C) push()

D) offer()

**Answer:** B

---

### MCQ 12

Which Stack method removes the top element?

A) push()

B) peek()

C) pop()

D) remove()

**Answer:** C

14
---

### MCQ 13

Which method checks whether an `ArrayList` contains an element?

A) search()

B) contains()

C) exists()

D) find()

**Answer:** B

---

### MCQ 14

Which statement is TRUE?

A) `peek()` removes an element.

B) `poll()` removes and returns the first Queue element.

C) `push()` is used in Queue.

D) `pop()` inserts into Stack.

**Answer:** B

---

### MCQ 15

Which statement is FALSE?

A) `[Link]()` works correctly on a sorted array.

B) `[Link]()` returns a random number.

C) `[Link]()` inserts key-value pairs.

D) `[Link]()` removes the top element.

**Answer:** D

15
---

# Common Mistakes Asked in TCS

❌ Using `[Link]()` for an `ArrayList`.

✔ Use **`[Link]()`** for lists.

---

❌ Using `length()` for arrays.

✔ Arrays use **`length`** (property).

---

❌ Thinking `peek()` removes an element.

✔ `peek()` only **views** the element.

✔ `poll()` removes it.

---

❌ Using `concat()` with `StringBuilder`.

✔ `StringBuilder` uses **`append()`**.

---

# Memory Tricks

Remember

```text id="7m4q1p"
Scanner

nextInt()

Input

16
```text id="3k9v5r" Arrays

sort()

---

```text id="1n8m2q"
Collections

sort(List)

```text id="6v2r7m" Math

sqrt()

pow()

---

```text id="4p5k8n"
Character

isDigit()

isLetter()

```text id="9q1m6v" HashMap

put()

get()

17
---

```text id="2r8k3p"
Queue

peek()

poll()

```text id="5m7v1q" Stack

push()

pop() ```

One-Minute Revision
✔ Scanner → nextInt() , next() , nextLine()

✔ Arrays → sort() , binarySearch()

✔ Collections → sort() , reverse()

✔ Math → sqrt() , pow() , abs() , random()

✔ Character → isDigit() , isLetter()

✔ String → length() , charAt() , substring() , split()

✔ StringBuilder → append() , insert() , reverse()

✔ ArrayList → add() , remove() , get() , contains()

✔ HashMap → put() , get() , keySet() , values()

✔ HashSet → add() , remove() , contains()

18
✔ LinkedList → addFirst() , removeFirst()

✔ Queue → offer() , peek() , poll()

✔ Stack → push() , pop() , peek()

🎯 TCS IPA API Quick Reference

API Must-Know Methods

Scanner nextInt() , next() , nextLine()

Arrays sort() , binarySearch()

Collections sort() , reverse()

Math sqrt() , pow() , abs() , random()

Character isDigit() , isLetter()

String length() , charAt() , substring()

StringBuilder append() , reverse()

ArrayList add() , remove() , get()

HashMap put() , get() , keySet() , values()

HashSet add() , contains()

LinkedList addFirst() , removeFirst()

Queue offer() , peek() , poll()

Stack push() , pop() , peek()

⭐ Highest Probability TCS MCQs

• Scanner reads integer → nextInt()


• Sort an array → [Link]()
• Sort an ArrayList → [Link]()
• Search a sorted array → [Link]()
• Add element to ArrayList → add()
• Insert into HashMap → put()
• Get all keys → keySet()
• Get all values → values()
• Queue view first element → peek()
• Queue remove first element → poll()
• Stack insert → push()
• Stack remove → pop()

19

You might also like