0% found this document useful (0 votes)
20 views10 pages

? Java Exam

The document serves as a comprehensive guide on Java programming concepts, covering OOP fundamentals, data types, variable scope, access modifiers, methods, constructors, and more. It includes exam lines for quick reference, sample code output questions, and common mistakes to avoid. Key topics include the use of the 'this' keyword, static vs dynamic binding, and garbage collection in Java.

Uploaded by

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

? Java Exam

The document serves as a comprehensive guide on Java programming concepts, covering OOP fundamentals, data types, variable scope, access modifiers, methods, constructors, and more. It includes exam lines for quick reference, sample code output questions, and common mistakes to avoid. Key topics include the use of the 'this' keyword, static vs dynamic binding, and garbage collection in Java.

Uploaded by

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

📘 Java Exam – Section A Personal Textbook

🔹 1. OOP Fundamentals

✅ Class

 Definition: A class is a user-defined blueprint that groups data (fields) and methods.

 Contains: Fields, methods, constructors, nested classes, static members, initialization blocks.

 Purpose: Organizes code, models real-world entities, enables encapsulation and reusability.

✅ Object

 Definition: A concrete instance of a class with its own copy of instance fields.

 Components:

o Identity: Memory reference

o State: Field values

o Behaviour: Methods it can perform

 Example:

 class Car {

 String color;

 void move() { }

 }

 Car c = new Car();

 [Link] = "Red";

 [Link]();

📝 Exam-line:

Class = blueprint; Object = instance with state & behaviour.

🔹 2. Data Types, Sizes & Ranges

Type Size Range / Notes

byte 1 byte -128 to 127

short 2 bytes -32,768 to 32,767

-2,147,483,648 to
int 4 bytes
2,147,483,647

long 8 bytes ±9.2 quintillion

~7 decimal digits (use


float 4 bytes
suffix f)

double 8 bytes ~15 decimal digits

char 2 bytes Unicode 0 to 65,535

boolea JVM- Only true or false


Type Size Range / Notes

n dependent

📝 Exam-line:

Give sizes and typical ranges; boolean is JVM-dependent but stores true/false.

🔹 3. Scope & Lifetime of Variables

Type Scope Lifetime

During method/block
Local Variable Inside method/block
execution

Method
Method body During method execution
Parameter

Instance Whole class (non- As long as object is


Variable static) referenced

From class load to


Static Variable Whole application
termination

📝 Exam-line:

Local = block; Instance = per-object; Static = per-class program lifetime.

✨ Section 4: Syntax for Referencing Class Members

🔹 Accessing Members

Context Syntax Example

Inside same class (non- fieldName or


static) methodName()

Using this keyword [Link]

[Link] or
From another object
[Link]()

Static member access [Link]

🔹 Using this

 Refers to the current object.

 Valid in instance methods, constructors, and instance blocks.

 Used to:

o Disambiguate field vs parameter: [Link] = name;

o Call another constructor: this(args); (must be first line)

o Pass current object: someMethod(this);

📝 Exam-line:

Use this to refer to current object; access fields, resolve naming conflicts, call constructors.
✨ Section 5: Access Modifiers

Modifie
Access Level
r

public Accessible from any class

protecte Same package + subclasses (even


d outside)

default Package-private (no keyword used)

Accessible only within the same


private
class

🔸 Key Notes

 protected allows package access and subclass access.

 You cannot reduce access when overriding methods.

 Use private for fields and expose them via getters/setters.

📝 Exam-line:

public = everywhere; protected = package + subclass; default = package-only; private = class-only.

✨ Section 6: Methods vs Objects

🔹 Methods

 Named blocks of code that perform actions.

 Can be:

o Instance methods: require an object

o Static methods: belong to class, no object needed

🔹 Objects

 Represent real entities.

 Required to access instance fields and methods.

🔸 Examples

class Car {

void drive() { } // instance method

static void printVersion() { } // static method

Car c = new Car();

[Link](); // instance method call

[Link](); // static method call

📝 Exam-line:

Static methods = no object needed; instance methods = need object.


✨ Section 7: Constructors

🔹 What Happens When You Call new

1. Memory allocated for object

2. Default values assigned to fields

3. Instance initializer blocks run

4. Constructor body executes

5. Reference returned

🔹 Rules

 No return type

 Cannot be static or final

 Can be overloaded

 If no constructor is defined, compiler adds default no-arg constructor

🔹 Constructor Chaining

class A {

A() { ... }

A(int x) { this(); ... } // calls A()

🔹 Final Fields

 Must be initialized in declaration or every constructor

📝 Exam-line:

Constructor = special method for initialization; no return type; called by new.

_________________________________________________________________________________

✨ Section 8: Copy Constructor – Shallow vs Deep Copy

🔹 Copy Constructor

 A constructor that creates a new object by copying fields from another object of the same class.

 Java doesn’t have built-in syntax—you write it manually.

🔹 Shallow Copy

 Copies primitive fields and references to objects.

 Both objects share the same sub-objects.

🔹 Deep Copy

 Recursively creates new copies of referenced objects.

 Ensures full independence between original and copy.

🔸 Example Problem

class Person {

String name;

Address addr;
}

 Shallow copy: addr is shared.

 Deep copy: addr is cloned.

📝 Exam-line:

Copy constructor copies values; deep copy duplicates objects; shallow copy shares references.

✨ Section 9: The this Keyword

🔹 Valid Contexts

 Instance methods

 Constructors

 Instance initializer blocks

🔹 Uses

1. Access current object's fields: [Link]

2. Resolve naming conflicts: [Link] = name

3. Call another constructor: this(args) (must be first line)

4. Pass current object: someMethod(this)

5. Return current object: return this (useful for chaining)

🔸 Restrictions

 Not allowed in static methods or static blocks.

📝 Exam-line:

this = current object reference; used for field access, constructor chaining, and disambiguation.

✨ Section 10: Accessor & Mutator Methods (Getters/Setters)

🔹 Purpose

 Encapsulation: hide internal data

 Validation: check input before assignment

🔹 Pattern

private int age;

public int getAge() {

return age;

public void setAge(int age) {

if (age >= 0) [Link] = age;

}
🔸 Read-only / Write-only

 Getter only → read-only

 Setter only → write-only (rare)

📝 Exam-line:

Accessor = reads value; Mutator = modifies value; used for encapsulation and validation.

✨ Section 11: Static vs Dynamic Binding

🔹 Static Binding (Compile-time)

 Applies to:

o static methods

o private methods

o final methods

o Overloaded methods

🔹 Dynamic Binding (Runtime)

 Applies to overridden methods.

 Enables polymorphism.

🔸 Example

class A {

void show() { [Link]("A"); }

class B extends A {

void show() { [Link]("B"); }

A a = new B();

[Link](); // prints "B" → dynamic binding

📝 Exam-line:

Static = compile-time; dynamic = runtime (overriding).

✨ Section 12: For Loops

🔹 Standard Syntax

for (initialization; condition; update) {

// body

🔹 Control Statements

 break: exits loop immediately

 continue: skips current iteration


🔸 Example

for (int i = 0; i < 10; i++) {

if (i == 5) break;

if (i % 2 == 0) continue;

[Link](i); // prints odd numbers < 5

🔹 Enhanced For Loop (For-each)

for (Type var : collection) {

// read-only access

📝 Exam-line:

Standard for = index loop; nested for = grids; enhanced for = for-each over arrays/collections.

✨ Section 13: Operator Precedence

🔹 Precedence Order (High → Low)

Lev
Operators
el

1 () . []

2 expr++ expr--

++expr --expr +
3
-!

4 */%

5 +-

6 << >> >>>

< > <= >=


7
instanceof

8 == !=

9 &

10 ^

11 |

12 &&

13 ||

14 ?:

= += -= *= /=
15
etc.

🔸 Examples
5+2*3 // 2*3 = 6 → 5 + 6 = 11

(5 + 2) * 3 // 7 * 3 = 21

int a = 10;

[Link](a++ + ++a); // 10 + 12 = 22

📝 Exam-line:

Use parentheses to clarify precedence; multiplication/division > addition/subtraction.

✨ Section 14: Garbage Collection & Destructors

🔹 Why No Destructors in Java

 Java uses automatic garbage collection.

 Destructors (like in C++) are unpredictable in Java.

🔹 Safe Resource Management

1. try-with-resources (preferred)

2. try (BufferedReader br = new BufferedReader(new FileReader("[Link]"))) {

3. // use br

4. } // [Link]() auto-called

5. finally block

6. BufferedReader br = null;

7. try {

8. br = new BufferedReader(...);

9. } finally {

10. if (br != null) [Link]();

11. }

12. Avoid finalize()

o Deprecated and unreliable.

📝 Exam-line:

Java uses garbage collection; use try-with-resources or finally for cleanup.

✨ Section 15: Sample Code Output Questions

🔹 Quick Traces

[Link]([Link](4.9)); // 4.0

int x = 5; [Link](++x); // 6

char ch = (char)67; [Link](ch); // C

[Link](5 + 2 * 3); // 11

int a = 10; [Link](a++ + ++a); // 22


📝 Exam-tip:

Show step-by-step variable changes for full marks.

✨ Section 16: Common 2-Mark Questions

Question Short Answer

Define class and Class = blueprint; Object =


object instance

Primitive vs reference Primitive = value; Reference =


type address

What is a constructor? Special method for initialization

Purpose of this
Refers to current object
keyword

int→0, boolean→false,
Default field values
reference→null

What is a static field? Shared by all objects

== = reference; .equals() = logical


== vs .equals()
equality

Method overloading Same name, different parameters

Subclass redefines inherited


Method overriding
method

Garbage Collector reclaims


What is GC?
memory

✨ Section 17: Sample MCQs

Question Answer

byte max value 127

int size in bytes 4

Keyword for inheritance extends

Entry method for Java


main()
program

[Link](2,3) 8.0

Logical AND operator &&

Result of 5/2 (int division) 2

Data type for Unicode char char

Package-private modifier default

Stops a loop break

Enhanced for loop Cannot modify


Question Answer

limitation size

[Link]
Static method call
d()

True about constructors No return type

this calls which


this(args)
constructor?

Deprecated cleanup
finalize()
method

Higher precedence: * or +? *

Purpose of new Allocates memory

Correct array iteration for(int x : arr)

Binding for overridden


Dynamic binding
methods

✨ Section 18: Practical Tips & Mistakes to Avoid

 ✅ Always initialize local variables.

 ✅ Default constructors are only auto-created if no other constructor is defined.

 ✅ Use parentheses for clarity in expressions.

 ✅ Prefer int for counters; use long for large ranges.

 ✅ Keep fields private; use getters/setters.

 ❌ Don’t rely on finalize()—use try-with-resources.

 ✅ Use .equals() for object comparison (e.g., Strings), not ==.

You might also like