0% found this document useful (0 votes)
3 views20 pages

Variables

The document provides a comprehensive overview of Java variables, operators, and control statements. It explains variable types, naming conventions, memory allocation, and the differences between instance and static variables. Additionally, it covers operator classifications, control flow mechanisms, and common errors, emphasizing the importance of proper usage for effective programming.

Uploaded by

23wh1a0228
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)
3 views20 pages

Variables

The document provides a comprehensive overview of Java variables, operators, and control statements. It explains variable types, naming conventions, memory allocation, and the differences between instance and static variables. Additionally, it covers operator classifications, control flow mechanisms, and common errors, emphasizing the importance of proper usage for effective programming.

Uploaded by

23wh1a0228
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 Variables

1. What is a Variable?
A variable is a named memory location used to store data during program execution.
The value of a variable can change while the program is running.

int x = 10;

 int → data type


 x → variable name
 10 → value

2. Syntax of Variable Declaration


dataType variableName;
dataType variableName = value;

Examples:

int a;
int b = 20;

3. Rules for Naming Variables (Identifiers)


✔ Must start with a letter, _, or $
✔ Cannot start with a digit
✔ Cannot use Java keywords
✔ Case-sensitive
✔ No spaces allowed

Valid:

int totalMarks;
int _count;
int $price;

Invalid:

int 2num; // starts with digit


int class; // keyword
int total marks; // space

4. Types of Variables in Java


Java variables are classified based on scope and lifetime.

Type Also Called Where Declared


Instance Variable Object variable Inside class, outside methods
Static Variable Class variable Inside class with static
Local Variable Method variable Inside methods/blocks

5. Instance Variables
�Definition

Variables declared inside a class but outside any method, without static.

class Student {
int id;
String name;
}

�Characteristics

✔ Created when object is created


✔ Each object gets its own copy
✔ Stored in heap memory
✔ Automatically assigned default values

6. Static Variables (Class Variables)


�Definition

Variables declared using the static keyword.

class Student {
static String college = "ABC";
}
�Characteristics

✔ Belongs to class, not object


✔ Only one copy shared by all objects
✔ Stored in method area
✔ Can be accessed using class name

[Link]([Link]);

7. Local Variables
�Definition

Variables declared inside methods, constructors, or blocks.

void show() {
int x = 10;
}

�Characteristics

✔ Scope limited to the block


✔ Stored in stack memory
✔ No default values
✔ Must be initialized before use

int x;
[Link](x); // Compile-time error

8. Default Values of Variables


Variable Type Default Value
Instance Depends on data type
Static Depends on data type
Local ❌ No default value

Primitive defaults:

 int → 0
 float → 0.0
 boolean → false
 char → '\u0000'
 Reference → null

9. Scope of Variables
Variable Scope
Instance Entire object
Static Entire class
Local Block or method only

� Lifetime of Variables
Variable Lifetime
Instance As long as object exists
Static Until class is unloaded
Local Until method/block execution ends

11. Accessing Variables


class Test {
int a = 10; // instance
static int b = 20; // static

void display() {
int c = 30; // local
[Link](a + b + c);
}
}

12. Difference Between Static and Instance Variables


Feature Instance Static
Keyword No static
Object Dependency Yes No
Memory Allocation Per object One time
Access Object reference Class name
13. Variable Shadowing
When a local variable hides an instance variable.

class Test {
int x = 10;

void show(int x) {
[Link](x); // local
[Link](this.x); // instance
}
}

14. Final Variables


�Meaning

A variable declared as final cannot be changed.

final int MAX = 100;

✔ Must be initialized once


✔ Used for constants

15. Static Final Variables (Constants)


class Test {
static final double PI = 3.14;
}

✔ Common naming convention → UPPERCASE


✔ One copy shared
✔ Value cannot change

16. Initialization of Variables


�Instance & Static Initialization

 Using declaration
 Using constructor
 Using initialization blocks

class Test {
int x = 10;
}

17. Parameter Variables


void add(int a, int b) {
int sum = a + b;
}

✔ Parameters are local variables

18. Variables and Memory Areas


Variable Memory
Local Stack
Instance Heap
Static Method Area

19. Common Compile-Time Errors


❌ Using uninitialized local variable
❌ Duplicate local variable names
❌ Accessing instance variable from static context without object

static void show() {


[Link](x); // Error if x is instance
}

20. Interview & Exam Important Points


✔ Java is strongly typed
✔ Local variables have no default values
✔ Static variables are shared
✔ this refers to current object
✔ final prevents reassignment
� Final Summary
 Variables store data
 Type decides memory and range
 Scope defines visibility
 Lifetime defines existence
 Correct usage avoids memory and logic errors
Operators in Java

1What is an Operator?
An operator is a symbol that performs a specific operation on one or more operands.

int c = a + b;

 + → operator
 a, b → operands

2. Classification of Operators in Java


Java operators are classified into the following categories:

Category Operators
Arithmetic + - * / %
Unary ++ -- + - !
Relational (Comparison) < > <= >= == !=
Logical `&&
Bitwise `&
Shift << >> >>>
Assignment = += -= *= /= %=
Conditional (Ternary) ?:
Type Comparison instanceof

3. Arithmetic Operators
Used to perform basic mathematical operations.

Operator Meaning Example


+ Addition a + b
- Subtraction a - b
* Multiplication a * b
Operator Meaning Example
/ Division a / b
% Modulus (remainder) a % b

Example:

int a = 10, b = 3;
[Link](a + b); // 13
[Link](a / b); // 3
[Link](a % b); // 1

❌ Division by zero causes:

ArithmeticException

4. Unary Operators
Operate on single operand.

Operator Meaning
++ Increment
-- Decrement
+ Unary plus
- Unary minus
! Logical NOT

Pre-increment vs Post-increment
int x = 5;
[Link](++x); // 6
[Link](x++); // 6, then x becomes 7

5. Relational (Comparison) Operators


Used to compare two values.
Result is always boolean.

Operator Meaning
< Less than
> Greater than
Operator Meaning
<= Less than or equal
>= Greater than or equal
== Equal to
!= Not equal

Example:

int a = 10, b = 20;


[Link](a < b); // true

❌== compares values for primitives and references for objects

6. Logical Operators
Used with boolean expressions.

Operator Meaning
&& Logical AND
`
! Logical NOT

Example:

int age = 20;


[Link](age > 18 && age < 60); // true

Short-Circuit Behavior
false && method(); // method() not executed
true || method(); // method() not executed

7. Bitwise Operators
Operate on bits.

Operator Name
& AND
` `
^ XOR
Operator Name
~ NOT

Example:

int a = 5; // 0101
int b = 3; // 0011
[Link](a & b); // 1

8. Shift Operators
Used to shift bits left or right.

Operator Meaning
<< Left shift
>> Right shift (signed)
>>> Right shift (unsigned)

Example:

int a = 8;
[Link](a << 1); // 16

9. Assignment Operators
Used to assign values.

Operator Meaning
= Assignment
+= Add & assign
-= Subtract & assign
*= Multiply & assign
/= Divide & assign
%= Modulus & assign

Example:

int x = 10;
x += 5; // x = 15
� Conditional (Ternary) Operator
Only operator that takes three operands.

condition ? value1 : value2;

Example:

int max = (a > b) ? a : b;

✔ Replacement for simple if-else

11. instanceof Operator


Used to check object type.

String s = "Java";
[Link](s instanceof String); // true

✔ Prevents ClassCastException

12. Operator Precedence (High → Low)


1. Unary (++ -- !)
2. Arithmetic (* / %)
3. Arithmetic (+ -)
4. Relational (< > <= >=)
5. Equality (== !=)
6. Logical (&& ||)
7. Ternary (?:)
8. Assignment (=)

Example:

int x = 10 + 5 * 2; // 20

13. Type Promotion in Expressions


 byte, short, char → promoted to int
 If one operand is long → result is long
 If one operand is float/double → result is float/double

Example:

byte a = 10, b = 20;


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

14. Common Errors & Traps


❌ Using== instead of equals() for Strings
❌ Division by zero
❌ Confusing& and &&
❌ Overflow in arithmetic operations

15. Exam & Interview Key Points


✔ Java does not support operator overloading (except + for String)
✔ Relational operators return boolean
✔ Logical operators work only on boolean
✔ instanceof works only with objects
✔ Ternary operator is faster than if-else

� Final Summary
 Operators manipulate data
 Java provides rich operator set
 Strong typing prevents misuse
 Operator precedence is crucial
 Mastery of operators improves logic & performance
Control Statements in Java

1. What are Control Statements?


Control statements control the flow of execution of a program based on conditions or
repetition.

They decide:
✔ which statement executes
✔ how many times it executes

2. Classification of Control Statements


Category Statements
Selection (Decision Making) if, if-else, else-if, switch
Iteration (Looping) for, while, do-while, for-each
Jump (Branching) break, continue, return

� SELECTION STATEMENTS

3. if Statement
Executes a block only if condition is true.

Syntax:
if(condition) {
statements;
}

Example:

int age = 20;


if(age >= 18) {
[Link]("Eligible to vote");
}
✔ Condition must be boolean

4. if-else Statement
Executes one block if condition is true, otherwise another.

if(condition) {
statements;
} else {
statements;
}

Example:

if(age >= 18)


[Link]("Eligible");
else
[Link]("Not Eligible");

5. else-if Ladder
Used to check multiple conditions.

if(marks >= 90)


grade = 'A';
else if(marks >= 75)
grade = 'B';
else if(marks >= 60)
grade = 'C';
else
grade = 'D';

✔ Evaluated from top to bottom


✔ First true condition executes

6. Nested if
An if inside another if.

if(age >= 18) {


if(hasVoterId) {
[Link]("Can Vote");
}
}

� switch STATEMENT

7. switch Statement
Used when multiple choices depend on single variable.

Syntax:
switch(expression) {
case value1:
statements;
break;
case value2:
statements;
break;
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 Day");
}

8. Rules of switch
✔ Expression must be byte, short, char, int, enum, String
✔ case values must be constant
✔ Duplicate cases not allowed
✔ break prevents fall-through
9. switch vs if-else
Feature if-else switch
Condition Multiple expressions Single variable
Range Supported Not supported
Performance Slower Faster
Readability Less Better for menus

� ITERATION (LOOPS)

� for Loop
Used when number of iterations is known.

Syntax:
for(initialization; condition; increment/decrement) {
statements;
}

Example:

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


[Link](i);
}

11. while Loop


Used when iterations are unknown.

while(condition) {
statements;
}

Example:

int i = 1;
while(i <= 5) {
[Link](i);
i++;
}
12. do-while Loop
Executes at least once, condition checked later.

do {
statements;
} while(condition);

Example:

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

13. for-each Loop (Enhanced for)


Used to traverse arrays and collections.

for(int x : arr) {
[Link](x);
}

✔ No index access
✔ Read-only loop

� JUMP STATEMENTS

14. break Statement


Used to terminate loop or switch.

for(int i=1;i<=5;i++) {
if(i==3) break;
[Link](i);
}
15. continue Statement
Skips current iteration and continues loop.

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

16. return Statement


Used to exit method and optionally return value.

return x;

� LABELLED STATEMENTS

17. Labelled break & continue


outer:
for(int i=1;i<=3;i++) {
for(int j=1;j<=3;j++) {
if(i==2) break outer;
}
}

✔ Used to control nested loops

18. Common Errors


❌ Using non-boolean condition in if
❌ Missingbreak in switch
❌ Infinite loops
❌ Off-by-one errors

19. Performance & Usage Tips


✔ Use switch for menu-driven programs
✔ Use for when iteration count known
✔ Use while for input-based loops
✔ Avoid deep nesting

20. Exam & Interview Key Points


✔ Java does not allow if(1) or while(0)
✔ do-while executes at least once
✔ switch supports String (Java 7+)
✔ break exits loop, continue skips iteration
✔ Enhanced for loop is read-only

� Final Summary
 Control statements direct program flow
 if handles conditions
 switch handles choices
 Loops handle repetition
 Jump statements alter execution

You might also like