0% found this document useful (0 votes)
12 views29 pages

Java Unit1 ExamNotes

This document provides comprehensive exam notes on Java programming, covering topics such as the history of Java, object-oriented programming features, classes and objects, data types, and variable scope. Key concepts include the four pillars of OOP (encapsulation, inheritance, polymorphism, and abstraction), the structure of classes and objects, and the differences between JDK, JRE, and JVM. It also includes quick revision summaries and common exam questions for effective preparation.

Uploaded by

Avdhesh Dadhich
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)
12 views29 pages

Java Unit1 ExamNotes

This document provides comprehensive exam notes on Java programming, covering topics such as the history of Java, object-oriented programming features, classes and objects, data types, and variable scope. Key concepts include the four pillars of OOP (encapsulation, inheritance, polymorphism, and abstraction), the structure of classes and objects, and the differences between JDK, JRE, and JVM. It also includes quick revision summaries and common exam questions for effective preparation.

Uploaded by

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

JAVA PROGRAMMING

Unit 1 — Complete Exam Notes

Introduction • OOP • Classes • Data Types • Operators

Prepared for: End Semester Examination Preparation

■ QUICK REVISION SUMMARY — All Topics at a Glance


Topic Core Idea / Key Facts

History of Java 1991 Oak → 1995 Java by Sun; WORA principle; JVM magic

OOP Features 4 Pillars: Encapsulation, Inheritance, Polymorphism, Abstraction

Class & Object Class = blueprint; Object = real instance; new keyword creates object

Variables & Scope Local (method), Instance (class), Static (class-level shared)

Data Types 8 primitives: byte,short,int,long,float,double,char,boolean

Type Casting Widening (auto) vs Narrowing (explicit); (int)3.14 → 3

Operators Arithmetic+-*/%, Bitwise&|^~<<>>, Relational==!=<>, Logical&&||!

Postfix → Unary → * / → + - → Shift → Relational → Equality → Bitwise → Logical


Operator Precedence → Ternary → Assignment
1. History and Overview of Java

1.1 Formal Definition


■ Formal Definition

Java is a high-level, object-oriented, platform-independent, compiled-and-interpreted programming


language developed by Sun Microsystems in 1995. It follows the principle "Write Once, Run Anywhere"
(WORA), meaning Java code compiled into bytecode can run on any device that has a Java Virtual
Machine (JVM) installed, regardless of the underlying operating system or hardware.

1.2 Timeline & Key Events


Year Event

1991 James Gosling at Sun Microsystems starts 'Green Project'. Language first called Oak.

1992 Oak is designed for embedded systems (set-top boxes, PDAs).

1995 Oak renamed Java (inspired by Java coffee). Publicly released. Applets debut in browsers.

1996 JDK 1.0 released — first official SDK.

2004 Java 5 — Generics, Enhanced for-loop, Autoboxing introduced.

2010 Oracle acquires Sun Microsystems. Stewardship of Java shifts.

2014 Java 8 — Lambda expressions, Streams API (major revolution).

2023+ Java 21 LTS — Virtual Threads (Project Loom), Pattern Matching.

1.3 Java's Architecture — JDK / JRE / JVM


Understanding the difference between JDK, JRE, and JVM is a very common exam question.

Component Role & Description

Complete development environment. Contains JRE + compiler (javac)


JDK (Java Development Kit) + debugger + tools. Used by developers.

Environment to run Java programs. Contains JVM + standard libraries.


JRE (Java Runtime Environment) Used by end users.

Abstract machine that executes Java bytecode. Makes Java


JVM (Java Virtual Machine) platform-independent. Different JVM for each OS.

ASCII Diagram — Compilation and Execution Flow:


Java Source Code (.java file)

v [javac compiler]

Bytecode (.class file) <-- Platform-independent

|
v [JVM on Windows / Linux / Mac]

Machine Code (native) <-- Platform-specific execution

Program Output

JDK ⊃ JRE ⊃ JVM (Containment)

JDK is the outermost container. JRE is inside JDK. JVM is inside JRE.

Memory Trick: D(evelop) > R(un) > V(irtualize) — DRV → Developer Runs Virtually.

1.4 Features of Java (Exam Favourite!)


Feature What It Means

Syntax derived from C/C++ but without complex features like pointers, operator
Simple overloading, multiple inheritance.

Object-Oriented Everything is modelled as objects. Supports all 4 OOP pillars.

Platform-Independent WORA — bytecode runs on any JVM. Achieved via intermediate bytecode.

Secure No explicit pointers. Bytecode verifier, Security Manager, sandboxed execution.

Strong type checking, exception handling, automatic garbage collection prevent


Robust crashes.

Multithreaded Built-in support for concurrent programming using Thread class / Runnable interface.

Architecture-Neutral Bytecode format is the same regardless of underlying processor.

High Performance JIT (Just-In-Time) compiler converts bytecode to native code at runtime for speed.

Distributed Built-in networking ([Link]) supports TCP/IP, RMI, socket programming.

Dynamic Classes loaded at runtime. Supports reflection. Programs can adapt at run time.

■ Memory Trick

Simple Secure Robust Object Platform Multithreaded Architecture High Dynamic = SSROPMAHD → 'Some
Students Run On Platforms Making Amazing High-quality Degrees'

■ EXAM Q: What is WORA? How does JVM achieve platform independence?


■ EXAM Q: Differentiate between JDK, JRE, and JVM with diagram.
■ EXAM Q: List and explain any 5 features of Java.
2. Object-Oriented Programming (OOP) Features

2.1 What is OOP?


■ Formal Definition

Object-Oriented Programming (OOP) is a programming paradigm that organises software design around
data (objects) rather than functions and logic. It models real-world entities as objects that have state
(attributes/fields) and behaviour (methods). Java is a purely object-oriented language (except for its 8
primitive data types).

2.2 The Four Pillars of OOP


Pillar 1 — Encapsulation
Definition: Wrapping data (variables) and the methods that operate on that data into a single unit called a class,
and restricting direct access to the data from outside the class. This is achieved using access modifiers (private,
public, protected).

Real-world analogy: A capsule tablet — the medicine is inside, protected. You only interact via the outer shell
(methods like setName, getName).

// Encapsulation Example

public class Student {

private String name; // private = hidden from outside

private int age;

// Public getter method — controlled access

public String getName() { return name; }

// Public setter method — validation possible

public void setAge(int age) {

if (age > 0) [Link] = age; // validation!

Pillar 2 — Inheritance
Definition: The mechanism by which one class (child/subclass) acquires the properties and behaviours (fields and
methods) of another class (parent/superclass) using the extends keyword. Promotes code reusability.

Types of Inheritance in Java:

Type Description

Single One child, one parent. A extends B.

Multilevel A → B → C (chain). C gets all from B and A.

Hierarchical Multiple children from one parent. B extends A, C extends A.


NOT supported directly in Java (to avoid Diamond Problem). Achieved
Multiple via interfaces.

// Inheritance Example

class Animal {

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

class Dog extends Animal { // Dog inherits Animal

void bark() { [Link]("Dog barks"); }

// Usage:

Dog d = new Dog();

[Link](); // Inherited method

[Link](); // Own method

Pillar 3 — Polymorphism
Definition: The ability of an object to take many forms. A single interface can represent different underlying forms
(data types/classes). Comes in two types: Compile-time (Method Overloading) and Runtime (Method Overriding).

Type How It Works

Method Overloading (Compile-time Same method name, different parameter lists in the SAME class.
Polymorphism) Resolved at compile time.

Method Overriding (Runtime Same method name + same parameters in PARENT and CHILD class.
Polymorphism) Child overrides parent. Resolved at runtime via dynamic dispatch.

Pillar 4 — Abstraction
Definition: Hiding the internal implementation details and showing only the essential features to the user.
Achieved in Java using abstract classes and interfaces.

Real-world analogy: You drive a car without knowing how the engine works internally — you only interact with the
steering wheel and pedals (the interface).

■ Memory Trick

EPIC = Encapsulation, Polymorphism, Inheritance, (Abstr)Action. Remember: OOP is EPIC!

■ EXAM Q: Explain the four pillars of OOP with real-life examples.


■ EXAM Q: Why does Java not support multiple inheritance? How is it handled?
■ EXAM Q: What is the difference between method overloading and overriding?
3. Class Fundamentals — Classes & Objects

3.1 What is a Class?


■ Formal Definition

A class in Java is a user-defined blueprint or template that defines the structure and behaviour of objects. It
is a logical construct that encapsulates data members (fields/variables) and member functions (methods)
into a single unit. A class does not occupy memory by itself — memory is allocated only when an object is
created.

Syntax of a Class:
class ClassName {

// 1. Fields (instance variables) — state

dataType fieldName;

// 2. Constructor — special method to initialize

ClassName(parameters) {

// initialization code

// 3. Methods — behaviour

returnType methodName(parameters) {

// method body

3.2 What is an Object?


■ Formal Definition

An object is a runtime instance of a class. It is a real entity that has: (1) State — represented by its instance
variables; (2) Behaviour — defined by its methods; (3) Identity — a unique reference in memory (handled
by the JVM). Objects are created using the new keyword, which allocates memory on the heap.

Complete Example: Class + Object + Constructor:


// CLASS DEFINITION

class Box {

double width; // instance variable (state)

double height;

double depth;

// Constructor — called automatically when object is created


Box(double w, double h, double d) {

width = w;

height = h;

depth = d;

// Method — behaviour

double volume() {

return width * height * depth;

// MAIN CLASS — where execution starts

class Main {

public static void main(String[] args) {

// Creating an object using 'new'

Box myBox = new Box(10, 5, 3); // memory allocated on heap

// Accessing method via object reference

[Link]("Volume = " + [Link]());

Volume = 150.0

3.3 Declaring Objects and Object Reference Variables


In Java, object creation is a two-step process:

// Step 1: Declare a reference variable (stored in STACK)

Box b1; // b1 is just a reference, points to null

// Step 2: Instantiate (allocate memory on HEAP)

b1 = new Box(3, 4, 5);

// Or combined in one line:

Box b2 = new Box(2, 2, 2);

// ASSIGNING REFERENCE VARIABLES

Box b3 = b1; // b3 and b1 now point to the SAME object in heap!

// Changing b3 changes b1's object too


Memory Diagram — Stack vs Heap:
STACK (References) HEAP (Actual Objects)

■■■■■■■■■■■■■■■ ■■■■■■■■■■■■■■■■■■■■■■■■■■■■

■ b1 ■■■■■■■■■■■■■■■■■ ■ Box { w=3, h=4, d=5 } ■ ← address 1001

■ b3 ■■■■■■■■■■■■■■■■■ ■ (same object!) ■

■ b2 ■■■■■■■■■■■■■■■■■ ■ Box { w=2, h=2, d=2 } ■ ← address 1055

■■■■■■■■■■■■■■■ ■■■■■■■■■■■■■■■■■■■■■■■■■■■■

■■ Common Exam Trap

When you do Box b3 = b1; both b3 and b1 refer to the same object. This is NOT copying the object — it is
copying the reference (address). So [Link] = 99 will also change b1's width!

■ EXAM Q: What is the difference between a class and an object?


■ EXAM Q: What happens when you assign one object reference to another?
4. Literals, Variables, Comments & Separators

4.1 Literals
■ Formal Definition

A literal is a fixed, constant value that appears directly in the source code. Literals represent the raw data
values and are assigned directly to variables. Java supports six types of literals: Integer, Floating-point,
Character, String, Boolean, and Null.

Type Example Note

int a = 42;<br/>int
hex = 0xFF;<br/>int
bin = 0b1010;<br/>int Decimal, Hexadecimal (0x), Binary (0b), Octal (0)
Integer Literal oct = 017; — Java supports all 4!

double d =
3.14;<br/>float f =
Floating-point Literal 2.5f; Default is double. Use 'f' suffix for float.

char c =
'A';<br/>char n = Enclosed in single quotes. \n, \t are escape
Character Literal '\n'; sequences.

String Literal String s = "Hello"; Enclosed in double quotes. Stored in String Pool.

Boolean Literal boolean b = true; Only true or false — nothing else!

Null Literal Object o = null; Represents absence of object reference.

4.2 Variables
■ Formal Definition

A variable is a named memory location that stores a value which can change during program execution. In
Java, every variable must be declared with a data type before use. Variables have a name (identifier), a
type, and a value.

Variable Type Description & Default Example

Declared inside a method/block. Scope = within that


method/block only. Must be initialized before use. NOT
Local Variable given default values. int x = 10; inside main()

Declared inside a class but outside any method. Each


object has its own copy. Gets default values (0, null,
Instance Variable false). class Dog { String name; }

Declared with 'static' keyword. Shared by ALL objects of


Static (Class) Variable the class. Only one copy exists. Belongs to the class. static int count = 0;

4.3 Comments
// 1. Single-line Comment — anything after // is ignored by compiler
int x = 10; // This is a single-line comment

/* 2. Multi-line Comment — spans multiple lines

Used for longer explanations

Everything between /* and */ is ignored */

/**

* 3. Documentation Comment (Javadoc)

* Used by the javadoc tool to generate HTML API docs

* @param name the name of the person

* @return a greeting string

*/

public String greet(String name) { return "Hello " + name; }

4.4 Separators
Separators are symbols that define the structure of the code:

Separator Usage

() Method calls, parameter lists, expressions: add(a, b)

{} Class body, method body, block of code

[] Array declarations and access: int[] arr = new int[5];

; Statement terminator — every statement ends with semicolon

, Separates multiple variables, parameters: int a, b, c;

. Member access operator: [Link](), [Link]

... Varargs (variable arguments): void print(int... nums)


5. Scope and Lifetime of Variables
■ Formal Definition

Scope refers to the region of a program where a variable is accessible (can be read or written). Lifetime
refers to the duration for which a variable exists in memory. These two concepts are closely linked — a
variable is allocated memory when it comes into scope and is destroyed (garbage collected or popped from
stack) when it goes out of scope.

class ScopeDemo {

static int classVar = 100; // CLASS scope — exists as long as class is loaded

int instanceVar = 50; // OBJECT scope — exists as long as object lives

void method() {

int localVar = 10; // METHOD scope — exists only during method execution

int blockVar = 5; // BLOCK scope — exists only inside this {}

[Link](blockVar); // OK

// [Link](blockVar); // ERROR! blockVar out of scope

[Link](localVar); // OK

[Link](instanceVar); // OK — object-level access

[Link](classVar); // OK — class-level access

Scope Hierarchy Diagram:


■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■

■ CLASS SCOPE (static variables) ■

■ ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ ■

■ ■ OBJECT SCOPE (instance variables) ■ ■

■ ■ ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ ■ ■

■ ■ ■ METHOD SCOPE (local variables) ■ ■ ■

■ ■ ■ ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ ■ ■ ■

■ ■ ■ ■ BLOCK SCOPE (for, if, {}) ■ ■ ■ ■

■ ■ ■ ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ ■ ■ ■

■ ■ ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ ■ ■
■ ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ ■

■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■

■■ Exam Trap

Local variables in Java do NOT get default values. If you declare int x; inside a method and use it without
initializing, you get a compile-time error: 'variable x might not have been initialized'.

■ EXAM Q: Explain variable scope with a code example showing all three types.
6. Data Types in Java
■ Formal Definition

A data type in Java specifies the type of data that a variable can store, the size of memory it occupies, and
the range of valid values it can hold. Java is a statically typed language — every variable must be declared
with a type before use. Data types are divided into two categories: Primitive (8 types) and
Non-Primitive/Reference (objects, arrays, strings).

6.1 The 8 Primitive Data Types


Type Size Range Default Example

8 bits
byte 1 byte -128 to 127 0 byte b = 100;
16 bits
short 2 bytes -32,768 to 32,767 0 short s = 1000;
32 bits
int 4 bytes -2,147,483,648 to 2,147,483,647 0 int i = 42;
64 bits
long 8 bytes -9.2×10^18 to 9.2×10^18 0L long l = 100L;
32 bits
float 4 bytes ~6-7 decimal digits 0.0f float f = 3.14f;
64 bits
double 8 bytes ~15-16 decimal digits 0.0d double d = 3.14;
16 bits
char 2 bytes 0 to 65,535 (Unicode) '\u0000' char c = 'A';
boolean ok =
boolean 1 bit true or false false true;

■ Memory Trick

'B S I L F D C B' → 'Big Students In Lab Find Data Crunching Boring' (byte, short, int, long, float, double, char,
boolean)

6.2 Integer Types — Detailed


All integer types (byte, short, int, long) are signed in Java, meaning they can hold both positive and negative
values. The int type is the most commonly used. For very large numbers, use long with the 'L' suffix.

int decimal = 100; // Base-10

int hex = 0x64; // Hexadecimal (0x prefix) → 100

int octal = 0144; // Octal (0 prefix) → 100

int binary = 0b1100100; // Binary (0b prefix) → 100

long big = 9876543210L;// Long — note the 'L' suffix

// Underscore in literals (Java 7+) for readability

int million = 1_000_000; // Same as 1000000


6.3 Floating Point Types
float uses 32-bit IEEE 754 standard (single precision). double uses 64-bit IEEE 754 (double precision). Always
prefer double for precision-sensitive calculations.

float f = 3.14f; // Must use 'f' suffix

double d = 3.14159265358979; // Default type for decimal literals

// Special float/double values:

double inf = 1.0 / 0.0; // Infinity

double nan = 0.0 / 0.0; // NaN (Not a Number)

[Link](inf); // Output: Infinity

[Link](nan); // Output: NaN

6.4 char Type


Java uses 16-bit Unicode for char (not 8-bit ASCII like C/C++). This allows Java to handle international characters
natively.

char c1 = 'A'; // Direct character

char c2 = 65; // ASCII/Unicode value → 'A'

char c3 = '\u0041'; // Unicode escape → 'A'

char c4 = '\n'; // Escape sequence (newline)

// char arithmetic is allowed!

char c5 = (char)('A' + 1); // → 'B'

[Link]((int)'A'); // Output: 65

6.5 boolean Type


Java's boolean is strict — only true or false. Unlike C, you CANNOT use 0 for false or 1 for true. This prevents
many bugs.

■■ Common Mistake

In Java: if (1) { } → COMPILE ERROR! Use if (true) { } or a proper boolean expression.

■ EXAM Q: List all 8 primitive data types with their sizes and ranges.
■ EXAM Q: What is the difference between float and double?
7. Type Conversion and Casting
■ Formal Definition

Type Conversion is the process of converting a value from one data type to another. In Java, there are two
kinds: Widening Conversion (automatic/implicit, from smaller to larger type, no data loss) and Narrowing
Conversion (explicit/casting, from larger to smaller type, possible data loss).

7.1 Widening Conversion (Automatic / Implicit)


Widening happens automatically when you assign a smaller type to a larger type. No explicit cast is needed
because there is no risk of losing data.

// Widening Conversion — automatic

byte b = 10;

short s = b; // byte → short (auto)

int i = s; // short → int (auto)

long l = i; // int → long (auto)

float f = l; // long → float (auto)

double d = f; // float → double (auto)

[Link](d); // Output: 10.0

Widening order (memory hierarchy — smallest to largest):


byte → short → int → long → float → double

char → int (char is also widened to int)

7.2 Narrowing Conversion (Explicit / Casting)


Narrowing requires an explicit cast operator in parentheses. You are telling the compiler: 'I know data loss may
happen — do it anyway.' Useful when you are certain the value fits in the smaller type.

// Narrowing Conversion — explicit cast required

double d = 9.99;

int i = (int) d; // Truncates decimal part → 9 (NOT rounded!)

[Link](i); // Output: 9

// Larger int to byte — possible overflow

int big = 300;

byte small = (byte) big; // 300 % 256 = 44 (overflow!)

[Link](small); // Output: 44

// double to float

double pi = 3.141592653589793;
float pf = (float) pi; // precision lost

[Link](pf); // Output: 3.1415927

44

3.1415927

7.3 Type Promotion in Expressions


Java automatically promotes smaller types (byte, short, char) to int in arithmetic expressions. This is called
automatic type promotion.

byte a = 40, b = 50;

// byte result = a + b; // ERROR! a+b becomes int automatically

int result = a + b; // Correct: result is int (90)

byte c = (byte)(a + b); // OK with explicit cast

■■ Exam Trap — Casting does NOT round

(int)3.99 gives 3, NOT 4. Casting truncates (chops off) the decimal part. To round, use [Link]().

■ EXAM Q: What is the difference between widening and narrowing conversion? Give examples.
■ EXAM Q: What is the output of: int x = (int)3.99; [Link](x);
8. Operators in Java
■ Formal Definition

An operator is a special symbol or keyword that instructs the compiler to perform a specific mathematical,
logical, bitwise, or relational operation on one or more operands (values/variables) and produce a result.
Java provides a rich set of operators organized into distinct categories.

8.1 Arithmetic Operators


Op Name Example Note

Also used for String concatenation: "Hi" + "!" =


+ Addition 5 + 3 = 8 "Hi!"

- Subtraction 5 - 3 = 2 Unary minus: -5

* Multiplication 5 * 3 = 15 —

5 / 2 = 2 (int), Integer division truncates. Use float/double for


/ Division 5.0/2 = 2.5 decimal result

Modulus
% (Remainder) 5 % 3 = 2 Useful for even/odd check: if(n%2==0)

Post: use then increment. Pre: increment then


++ Increment x++ (post), ++x (pre) use.

-- Decrement x-- (post), --x (pre) Same logic as ++

// Pre vs Post Increment — Classic Exam Question!

int a = 5;

[Link](a++); // Output: 5 (print THEN increment)

[Link](a); // Output: 6

int b = 5;

[Link](++b); // Output: 6 (increment THEN print)

[Link](b); // Output: 6

8.2 Bitwise Operators


Bitwise operators work on individual bits of integer types. Extremely important in systems programming,
encryption, and flags.

Op Name Rule Example


5 & 3 = 1 (101 &
& Bitwise AND Both bits must be 1 → result is 1 011 = 001)

5 | 3 = 7 (101 |
| Bitwise OR At least one bit is 1 → result is 1 011 = 111)

5 ^ 3 = 6 (101 ^
^ Bitwise XOR Bits differ → result is 1 011 = 110)

~5 = -6 (flips all
Bitwise NOT bits + two's
~ (complement) Inverts all bits complement)

5 << 1 = 10
<< Left Shift Shifts bits left, fills 0 on right (equivalent to ×2)

20 >> 2 = 5
>> Right Shift (signed) Shifts bits right, preserves sign bit (equivalent to ÷4)

>>> Unsigned Right Shift Shifts right, fills 0 (ignores sign) -1 >>> 28 = 15

// Bitwise Example — Step by Step

int a = 5; // binary: 0000 0101

int b = 3; // binary: 0000 0011

[Link](a & b); // 0000 0001 = 1

[Link](a | b); // 0000 0111 = 7

[Link](a ^ b); // 0000 0110 = 6

[Link](~a); // 1111 1010 = -6 (two's complement)

[Link](a << 1); // 0000 1010 = 10

[Link](a >> 1); // 0000 0010 = 2

-6

10

8.3 Relational (Comparison) Operators


Relational operators compare two values and return a boolean result (true or false). Used extensively in
conditions.

Op Name Example Exam Note

5 == 5 → true; 5 == 3 Do NOT confuse with =


== Equal to → false (assignment)!

!= Not equal to 5 != 3 → true —


> Greater than 5 > 3 → true —

< Less than 5 < 3 → false —

>= Greater than or equal 5 >= 5 → true —

<= Less than or equal 3 <= 5 → true —

8.4 Boolean Logical Operators


These operators work on boolean expressions and return boolean results. Critical for conditions and control flow.

Op Name Rule Key Point

Short-circuit: if left is false, right is NOT


&& Logical AND true only if BOTH are true evaluated!

Short-circuit: if left is true, right is NOT


|| Logical OR true if AT LEAST ONE is true evaluated!

! Logical NOT Inverts boolean !true = false; !false = true

Boolean AND Same as && but evaluates BOTH


& (non-short-circuit) sides always Rarely used; mainly for side effects

Boolean OR Same as || but evaluates BOTH


| (non-short-circuit) sides always Rarely used

^ Boolean XOR true if operands are DIFFERENT true ^ false = true; true ^ true = false

// Short-circuit evaluation example

int x = 10;

boolean result = (x > 5) || (++x > 0); // right side NOT evaluated!

[Link](x); // Output: 10 (not 11!)

boolean r2 = (x < 5) && (++x > 0); // right side NOT evaluated!

[Link](x); // Output: 10 (not 11!)

10

10

8.5 Assignment Operators


The basic assignment operator is =. Java also provides compound assignment operators that combine an
arithmetic/bitwise operation with assignment.

Op Name Example Equivalent

= Simple assignment x = 5 x is now 5

+= Add and assign x += 3 Same as x = x + 3

-= Subtract and assign x -= 2 Same as x = x - 2

*= Multiply and assign x *= 4 Same as x = x * 4

/= Divide and assign x /= 2 Same as x = x / 2


%= Modulus and assign x %= 3 Same as x = x % 3

&= Bitwise AND and assign x &= 0xFF Same as x = x & 0xFF

|= Bitwise OR and assign x |= mask —

^= Bitwise XOR and assign x ^= bits —

<<= Left shift and assign x <<= 2 Same as x = x << 2

>>= Right shift and assign x >>= 1 Same as x = x >> 1


9. Operator Precedence — Complete Table
■ What is Operator Precedence?

Operator Precedence defines the order in which operators are evaluated in an expression that has multiple
operators. Higher precedence operators are evaluated first. When two operators have the same
precedence, associativity determines the order (left-to-right or right-to-left).

Precedence Category Operators Associativity

1 (Highest) Postfix expr++ expr-- Left → Right

2 Unary ++expr --expr +expr -expr ~ ! Right → Left

3 Multiplicative * / % Left → Right

4 Additive + - Left → Right

5 Shift << >> >>> Left → Right

6 Relational < > <= >= instanceof Left → Right

7 Equality == != Left → Right

8 Bitwise AND & Left → Right

9 Bitwise XOR ^ Left → Right

10 Bitwise OR | Left → Right

11 Logical AND && Left → Right

12 Logical OR || Left → Right

13 Ternary ? : Right → Left

= += -= *= /= %= &= ^= |= <<=
14 (Lowest) Assignment >>= >>>= Right → Left

Precedence — Solved Example:


// What is the value of result?

int result = 2 + 3 * 4 - 1;

// Step 1: * has higher precedence than + and -

// 3 * 4 = 12

// Step 2: left-to-right: 2 + 12 = 14

// Step 3: 14 - 1 = 13

[Link](result); // Output: 13

// Another example:

int x = 10, y = 5, z = 2;

boolean b = x > y && y > z;


// Step 1: x > y → true

// Step 2: y > z → true

// Step 3: true && true → true

[Link](b); // Output: true

13

true

■ Memory Trick

P-U-M-A-S-R-E-B-X-O-A-O-T-A → 'Postfix Unary Mult Add Shift Relational Equality Bitwise(&) Xor bitOr
And(&&) Or(||) Ternary Assignment'

■ EXAM Q: Evaluate: 5 + 3 * 2 - 8 / 4 + 1. Show step by step working.


■ EXAM Q: What is operator associativity? Give examples of left-to-right and right-to-left.
10. Complete Working Java Program — Unit 1 Concepts
This single program demonstrates ALL major Unit 1 concepts:

// ============================================================

// [Link] — Demonstrates ALL Unit 1 Concepts

// ============================================================

public class JavaUnit1Demo {

// --- Instance variable (Object scope) ---

int instanceVar = 100;

// --- Static variable (Class scope) ---

static int staticVar = 200;

// --- Constructor ---

JavaUnit1Demo(int val) {

[Link] = val; // 'this' refers to current object

// --- Method showing data types and operators ---

static void dataTypesDemo() {

[Link]("=== DATA TYPES ===");

byte b = 127; // max byte value

short s = 32000;

int i = 2_000_000; // underscore for readability

long l = 9_000_000_000L;

float f = 3.14f;

double d = 3.141592653589793;

char c = 'J';

boolean ok = true;

[Link]("byte=" + b + " short=" + s + " int=" + i);

[Link]("long=" + l + " float=" + f + " double=" + d);

[Link]("char=" + c + " boolean=" + ok);

static void castingDemo() {

[Link]("\n=== TYPE CASTING ===");


// Widening (automatic)

int x = 42;

double xd = x; // int → double (widening)

[Link]("Widening: int " + x + " → double " + xd);

// Narrowing (explicit)

double pi = 3.99;

int ipi = (int) pi; // truncates → 3, NOT 4!

[Link]("Narrowing: double " + pi + " → int " + ipi);

static void operatorsDemo() {

[Link]("\n=== OPERATORS ===");

int a = 10, b = 3;

// Arithmetic

[Link]("Arithmetic: " + a + "/" + b + " = " + (a/b)

+ " remainder " + (a%b));

// Bitwise

[Link]("Bitwise AND: 10 & 3 = " + (a & b));

[Link]("Left Shift: 10 << 1 = " + (a << 1));

// Relational

[Link]("Relational: 10 > 3 is " + (a > b));

// Logical with short-circuit

int counter = 0;

boolean res = (a > 5) || (++counter > 0);

[Link]("Short-circuit ||: counter = " + counter); // 0!

// Ternary operator

String msg = (a > b) ? "a is bigger" : "b is bigger";

[Link]("Ternary: " + msg);

// Compound assignment

a += 5;

[Link]("After a += 5: a = " + a);


}

public static void main(String[] args) {

dataTypesDemo();

castingDemo();

operatorsDemo();

// OOP — creating objects

[Link]("\n=== OBJECTS ===");

JavaUnit1Demo obj1 = new JavaUnit1Demo(500);

JavaUnit1Demo obj2 = new JavaUnit1Demo(999);

[Link]("[Link] = " + [Link]);

[Link]("[Link] = " + [Link]);

[Link]("staticVar (shared) = " + staticVar);

// Object reference assignment

JavaUnit1Demo obj3 = obj1; // obj3 points to same as obj1

[Link] = 777;

[Link]("After obj3=obj1, [Link]=777:");

[Link]("[Link] = " + [Link]); // 777!

=== DATA TYPES ===

byte=127 short=32000 int=2000000

long=9000000000 float=3.14 double=3.141592653589793

char=J boolean=true

=== TYPE CASTING ===

Widening: int 42 → double 42.0

Narrowing: double 3.99 → int 3

=== OPERATORS ===

Arithmetic: 10/3 = 3 remainder 1

Bitwise AND: 10 & 3 = 2

Left Shift: 10 << 1 = 20

Relational: 10 > 3 is true

Short-circuit ||: counter = 0


Ternary: a is bigger

After a += 5: a = 15

=== OBJECTS ===

[Link] = 500

[Link] = 999

staticVar (shared) = 200

After obj3=obj1, [Link]=777:

[Link] = 777
11. Common Mistakes & Exam Traps
Trap 1: Using = instead of == if (x = 5) — COMPILE ERROR in Java (unlike C, where it runs silently)

Trap 2: Integer division truncation int x = 7/2; → x = 3, NOT 3.5. Use double d = 7.0/2;

Trap 3: Casting truncates, does NOT


round (int)3.99 = 3, NOT 4. Use [Link]() for rounding.

Trap 4: float needs 'f' suffix float f = 3.14; → ERROR. Must be float f = 3.14f;

Trap 5: long needs 'L' suffix long l = 9999999999; → ERROR. Must be 9999999999L

Trap 6: Local variables have no


default int x; [Link](x); → COMPILE ERROR

Trap 7: Object reference ≠ Object


copy Box b2 = b1; makes b2 point to same object. Modifying b2 modifies b1.

Trap 8: ++ pre vs post int a=5; int b=a++; → b=5, a=6. int c=++a; → a=7, c=7.

Trap 9: Short-circuit &&/|| If left side of && is false, right side is NEVER evaluated.

Trap 10: boolean ≠ integer Java boolean cannot be used as int. if(1){} → COMPILE ERROR.

Trap 11: char is unsigned char range is 0–65535, not negative. It's actually uint16 internally.

Trap 12: Multiple inheritance Java classes cannot extend multiple classes. Use interfaces instead.
12. Top Exam Questions — Unit 1

2-Mark Questions
Q1. Define Java. What does WORA mean?
Q2. What is a JVM? What is its role?
Q3. Differentiate between JDK, JRE, and JVM.
Q4. List any 5 features of Java.
Q5. What is an object? What are its three characteristics?
Q6. What is the difference between a class and an object?
Q7. Define encapsulation with an example.
Q8. What is the default value of int, float, boolean, char?
Q9. What is a literal? Give 3 types with examples.
Q10. What is type casting? Give one example.
Q11. What is the difference between == and = operators?
Q12. What is the difference between & and && operators?
Q13. What is operator precedence? Give an example.
Q14. What is the scope of a local variable?
Q15. Define widening and narrowing conversion.

5-Mark Questions
Q1. Explain the history and evolution of Java with a timeline.
Q2. Explain all 4 pillars of OOP with real-life examples and Java code.
Q3. Write a Java program to demonstrate all 8 primitive data types.
Q4. Explain the difference between method overloading and method overriding with examples.
Q5. Describe all types of variables in Java with scope and lifetime.
Q6. Explain all arithmetic operators with examples and a working Java program.
Q7. Describe all bitwise operators with truth tables and examples.
Q8. Explain type conversion (widening and narrowing) with examples and potential issues.
Q9. Write a note on comments and separators in Java with examples.
Q10. Explain operator precedence with a table and worked example.

10-Mark Questions (Long Answer)


Q1. Write a Java program demonstrating OOP concepts: encapsulation, inheritance, and polymorphism.
Q2. Explain Java's architecture (JDK/JRE/JVM) with diagram. How does Java achieve platform independence?
Q3. Explain all operators in Java (arithmetic, bitwise, relational, logical, assignment) with examples and a
complete program.
Q4. Discuss classes and objects in Java. Explain object creation, reference variables, and memory allocation
with diagrams.
Q5. Write a comprehensive note on Java data types, type casting, and type promotion in expressions with
examples.
■ All Memory Tricks — Last-Minute Revision
'SSROPMAHD' — Some Students Run On Platforms Making Amazing High-quality
Degrees (Simple, Secure, Robust, Object-Oriented, Platform-independent,
Java Features Multithreaded, Architecture-neutral, High-performance, Dynamic)

DRV = Developer Runs Virtually. JDK for Developing, JRE for Running, JVM for
JDK ⊃ JRE ⊃ JVM Virtualizing.

OOP Pillars EPIC = Encapsulation, Polymorphism, Inheritance, (abstr)Action. OOP is EPIC!

'B S I L F D C B' → 'Big Students In Lab Find Data Crunching Boring' (byte, short, int,
8 Primitive Types long, float, double, char, boolean)

Bigger → Smaller = NARROWING needs CASTING. Small → Big = WIDENING


Widening Order (auto). Think: widening a road = safe, no problem.

'PUMPS RE-BXOA-TA' → Postfix, Unary, Mult, Plus(additive), Shift, Relational,


Operator Precedence Equality, Bitwise(&), Xor, bitOr, And(&&), Or(||), Ternary, Assignment

Pre vs Post ++ 'POST = Print THEN tick. PRE = tick THEN Print.' (tick = increment)

Short-circuit 'Short means STOP early.' && stops on first FALSE. || stops on first TRUE.

Float vs Double F = Fewer digits (6-7). D = Double the digits (15-16). Always double for precision.

■ All the best for your exams! Revise this sheet 24 hours before the exam.
Focus: OOP pillars + Data types table + Operator precedence + Type casting rules + Pre/Post increment.

You might also like