0% found this document useful (0 votes)
1 views68 pages

Java (Q Spider)

Java is a high-level, object-oriented programming language that is platform-independent and secure, featuring garbage collection and multi-threading capabilities. The document covers various aspects of Java, including its file types, historical context, programming structure, data types, operators, and key concepts such as variables and comments. It also highlights the importance of Java's long-term support and provides examples of syntax and usage.

Uploaded by

kavinlmcsk2k3
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)
1 views68 pages

Java (Q Spider)

Java is a high-level, object-oriented programming language that is platform-independent and secure, featuring garbage collection and multi-threading capabilities. The document covers various aspects of Java, including its file types, historical context, programming structure, data types, operators, and key concepts such as variables and comments. It also highlights the importance of Java's long-term support and provides examples of syntax and usage.

Uploaded by

kavinlmcsk2k3
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
You are on page 1/ 68

Introduction to Java

General Information

● Java is a programming language.


● Java is a high-level language.
● Java is an Object-Oriented Programming (OOP) language.
● Java provides a virtual representation of real-world entities.
● Java is platform-independent (Write Once, Run Anywhere - WORA).
● Java is secure (bytecode is shared, not source files).
● Multi-threaded (e.g., watching a video and commenting simultaneously on YouTube).
● Garbage collection (automatically collects unused references, saving memory and
preventing memory leaks).

File Types

● Common file types: .exe, .ios, .apk.


● Other related languages: Kotlin (Android), Swift (iOS), C, .NET, Rust (C, C++, Java).
● .pdf - Portable Document Format
● .exe - Executable File
● .dmg - Disk Image File (MacOS)
● .gif - Graphics Interchange Format Image
● .jpg - Joint Photographic Experts Group Image
● .png - Portable Network Graphics Image

Historical Context

● Older procedural languages: FORTRAN, COBOL, VB, PASCAL, C.

Windows Operating System:

● Built primarily using C, C++, and Assembly language.


● Kernel and core components are mainly written in C and C++.
● Low-level system components and device drivers are often written in Assembly
language for performance optimization.

macOS (Mac Operating System):

● Based on the Unix-like Darwin operating system.


● Core components, including the kernel and many system utilities, are written in C,
C++, and Objective-C.
● Incorporates components written in other languages like Swift and Assembly
language for specific tasks and optimizations.
Programming in Java
Long Term Service (LTS)

● Java provides long-term support for certain versions.

Compiler

● Checks syntax and order.


● Generates a .class file.

Interpreter

● Converts bytecode to machine code.


● Executes code line by line.

Executing a Java File

Compilation:

javac sourcefilename.java

1. (compiles and generates bytecode)

Execution:

java classname

2. (executes the Java class file)

Note: The class name may or may not be the same as the source filename, but the class file
should exist.

Structure of a Java Class

class ClassName {
// Inside class block

// Declaration statements
int variable;
ClassName() { // Constructor
}
void method() { // Method
}

// Initialization statements
static int staticVar; // Static
int nonStaticVar; // Non-static

// Enums/class declaration statements


}

Note: An empty System.out.print() will give an error.

Tokens in Java
● Definition: Smallest building blocks of any language.
● Keywords: Reserved words with specific meanings/functionality in Java (always
lowercase, 50+).
● Identifiers: Names for components in Java.
● Literals: Values assigned to variables (cannot use keywords, numbers, symbols
except _ and $, no spaces).
● Operators : Operators are symbols that perform operations .
● Separators:Separators (also known as delimiters) are symbols that are used to
separate code elements and help define the structure of Java programs.
● Comments :( ignored by computer )

Separators in Java

Separators (also known as delimiters) are symbols that are used to separate code elements
and help define the structure of Java programs. Common separators in Java include:

1. Parentheses ():
○ Used for method calls and to define precedence in expressions.
System.out.println("Hello, World!"); // method call

int result = (10 + 5) * 2; // precedence

2. Braces {}:
○ Used to define a block of code, such as in classes, methods, and loops.
if (a > b) {

// block of code
}

3. Brackets []:
○ Used for array declarations and accessing array elements.

int[] numbers = {1, 2, 3};

int firstNumber = numbers[0];

4. Semicolon ;:
○ Used to terminate statements.
int a = 10;

System.out.println(a);

5. Comma ,:
○ Used to separate elements in a list, such as in variable declarations and
method arguments.
int a = 10, b = 20;

void myMethod(int x, int y) { }

6. Dot .:
○ Used to access members of classes and objects.
System.out.println("Hello, World!");

Comments in Java

Comments are used to explain code and make it more readable. They are ignored by the
compiler.

Types of Comments

1. Single-line Comments:
○ Start with // and continue to the end of the line.
// This is a single-line comment

int a = 10; // This is another single-line comment

2. Multi-line Comments:
○ Start with /* and end with */. Can span multiple lines.
/*

* This is a multi-line comment.

*/
int a = 10;

3. Documentation Comments:
○ Start with /** and end with */. Used to generate documentation using tools
like Javadoc.
/**

* This is a documentation comment.

* It provides information about the method

* @param args command line arguments

*/

Common Keywords

(50 + keywords in java )

● abstract: Declares abstract ● double: Declares double


classes/methods; must be variables; 64-bit floating-point
subclassed. number.
● assert: Used for debugging; tests ● else: Specifies code if a condition
assumptions. is false.
● boolean: Declares boolean ● enum: Declares enumerated types.
variables; holds true or false. ● extends: Indicates inheritance
● break: Exits loops or switch from a class.
statements. ● final: Declares constants,
● byte: Declares byte variables; prevents inheritance or method
8-bit signed integer. overriding.
● case: Defines branches in switch ● finally: Block of code, always
statements. executed after try/catch.
● catch: Catches exceptions from ● float: Declares float variables;
try blocks. 32-bit floating-point number.
● char: Declares char variables; ● for: Begins a for loop.
16-bit Unicode character. ● goto: Reserved but not used.
● class: Declares a class. ● if: Tests a condition.
● const: Reserved but not used. ● implements: Implements an
● continue: Skips the current loop interface.
iteration. ● import: Imports
● default: Default case in switch packages/classes.
statements. ● instanceof: Tests if an object is
● do: Begins a do-while loop. an instance of a class/interface.
● int: Declares int variables; 32-bit
signed integer.
● interface: Declares an ● strictfp: Restricts floating-point
interface. calculations for portability.
● long: Declares long variables; ● super: Refers to superclass
64-bit signed integer. methods/constructors.
● native: Declares a method ● switch: Begins a switch
implemented in native code. statement.
● new: Creates new objects. ● synchronized: Ensures that a
● null: Represents a null reference. method or block is thread-safe.
● package: Declares a package. ● this: Refers to the current object.
● private: Access modifier; visible ● throw: Throws an exception.
only within the class. ● throws: Declares exceptions
● protected: Access modifier; thrown by a method.
visible within the package and ● transient: Excludes fields from
subclasses. serialization.
● public: Access modifier; visible ● try: Begins a block of code that
everywhere. may throw exceptions.
● return: Exits from a method, ● void: Specifies that a method
optionally returning a value. does not return a value.
● short: Declares short variables; ● volatile: Declares variables
16-bit signed integer. modified asynchronously.
● static: Declares class-level ● while: Begins a while loop.
fields and methods.

Data Types in Java


Types of Data

1. Primitive Type: Can be stored inside a single memory block.


2. Non-Primitive Type: Cannot fit inside one memory block, uses multiple blocks (e.g.,
String, array, class).

Primitive Data Types

● 8 types:
○ byte (8-bit)
○ short (16-bit)
○ int (32-bit)
○ long (64-bit)
○ float (32-bit)
○ double (64-bit)
○ char (16-bit)
○ boolean (1-bit)
Value Ranges

● Byte.MIN_VALUE ==> -128


● Byte.MAX_VALUE ==> 127
● Integer.MIN_VALUE ==> -2147483648
● Integer.MAX_VALUE ==> 2147483647
● Short.MIN_VALUE ==> -32768
● Short.MAX_VALUE ==> 32767
● Long.MIN_VALUE ==> -9223372036854775808
● Long.MAX_VALUE ==> 9223372036854775807
● Float.MIN_VALUE ==> 1.4E-45
● Float.MAX_VALUE ==> 3.4028235E38
● Double.MIN_VALUE ==> 4.9E-324
● Double.MAX_VALUE ==> 1.7976931348623157E308
● Character.MIN_VALUE ==> '\u0000'
● Character.MAX_VALUE ==> '\uffff'

Number Systems
● Binary: Base 2.
● Decimal: Base 10.
● Octal: Base 8.
● Hexadecimal: Base 16.

Variables in Java
● variable == container (data / literals )
● declaration == creation of memory location(SYNTAX : int a ; datatype identifier )
● all rules of identifier (snake case)

Characteristics

● Named block of memory.


● Temporary storage that can be updated.
● Scope and lifetime are determined by where the variable is declared.
● have name
● call name to fetch data
● temporary ( can change)
● updataion (easy )
● scope (visibility)
● lifetime ( intilization ,entering into memory to deleted from memory ,during execution

"all is stored in RAM", "65000 times faster than python"


Declaration

● Syntax: int a; (datatype identifier).

Types of Variables

1. Primitive Variable: Stores primitive data types.


○ Static
○ Non-static
2. Non-Primitive Variable: Stores references to objects (reference variables).
○ Static
○ Non-static
○ Example: name[0x1] -----> [j, a, n, a]
3. Local Variables: Declared inside methods or blocks.
○ Syntax: { a { b } }

Operators in Java:
Characteristics

● Perform operations and manipulate data.


● Require operands to perform actions.
● Return a value.

Precedence and Associativity

● Determines the order of execution when multiple operators are present in an


expression.

Types of Operators

Based on Number of Operands

1. Unary: Single operand.


2. Binary: Two operands.
3. Ternary: Three operands.

Based on Task

1. Arithmetic: +, -, *, /, % (perform arithmetic operations, binary in nature).


2. Relational: >, <, <=, >=, ==, != (return boolean, check relationships, binary in
nature).
3. Logical: &&, ||, ! (return boolean).
○ AND: boolean && boolean (short-circuit if false).
○ OR: boolean || boolean (short-circuit if true).
○ NOT: !boolean (unary operator).
4. Compound Assignments: +=, -=, *=, /=, %=.
5. Increment and Decrement: ++, --.
6. Conditional: ? :.
7. Bitwise: &, |, ^, ~, <<, >>, >>>.

Precedence Table
Precedence Operators Associativity

Postfix expr++, expr-- Left to right

Unary ++expr, --expr, +, -, Right to left


~, !

Multiplicative *, /, % Left to right

Additive +, - Left to right

Shift <<, >>, >>> Left to right

Relational <, <=, >, >=, Left to right


instanceof

Equality ==, != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR ` `

Logical AND && Left to right

Logical OR `

Ternary ? : Right to left

Assignment =, +=, -=, *=, /=, %= Right to left

&=, ^=, ` =, <<=, >>=,


>>>=`

Comma , Left to right


Examples

int res = 10 + 5 * 10 - 1 / 5;
res = 10 + 50 - 0;
res = 60;

double resDouble = 10 + 5 * 10 - 1 / 5;
resDouble = 60.0;

int resComplex = 10 - 5 + 2 - 5 - 12 + 5;
resComplex = -5;

String Concatenation

"Hi" + true; // Results in "Hitrue"


● Concatenation: The process of joining strings.
● Polymorphism: The + operator can concatenate strings or add numbers.
● Errors: Concatenation with keywords results in syntax errors.
● Conversion: Non-string operands are converted to their string representation when
concatenated with strings.

Automatic Promotion

double i = 10, j = 20;


i / j; // Results in 0.5
i / 20; // Results in 0.5
10 / j; // Results in 0.5
10 / 20; // Results in 0
10.0 / 20.0; // Results in 0.5

String Pool

"hi" == "HI"; // Results in false


"hi" + "HI" == "hiHI"; // Results in true
"hi" + 10 + 20 == "hi1020"; // Results in true

== Operator:

● For objects: Checks the reference (i.e., memory address).


● For primitives: Checks the actual value.
.equals():

● For objects: Checks the actual value (content) of the objects, provided the method is
overridden appropriately in the class

Logical AND (&&)

The && operator returns true if both operands are true. If the first operand is false, the
second operand is not evaluated (short-circuit evaluation).

Operand 1 Operand 2 Result (Operand 1 && Operand 2)

true true true

true false false

false true false

false false false


Logical NOT (!)

The ! operator returns the opposite boolean value of its operand. It is a unary operator.

Operand Result (! Operand)

true false

false true

Logical OR (||)

● Purpose: Returns true if at least one of the operands is true; otherwise, returns
false.
● Short-Circuiting: If the first operand is true, the second operand is not evaluated.

Operand 1 Operand 2 Result (Operand 1 | | Operand 2)

true true true

true false true

false true true

false false false

Conversion Methods in Java: .valueOf() and .parseInt()


.valueOf() Method:

● Definition: A static method defined in wrapper classes like Integer, Double, Boolean,
etc.
● Return Type: Returns an instance of the wrapper class.
● Null Handling: Can handle null input, returning a corresponding wrapper class object
with the value set to the specified string.
● Usage: Generally used for converting string representations of data into their
wrapper types.

Example:

String str = "123";


Integer intValue = Integer.valueOf(str); // returns an Integer
object with value 123
.parseInt() Method:

● Definition: A static method defined in wrapper classes like Integer.


● Return Type: Directly returns primitive data types, not wrapper objects.
● Null Handling: Does not handle null input; passing null will result in a
NullPointerException.
● Usage: Commonly used for converting string representations of data into their
primitive types.

String str = "123";


int intValue = Integer.parseInt(str); // returns int value 123

Similar Methods:

● parseInt() and valueOf() for Integer:


○ Function: Both methods can convert a string to an integer.
○ Differences:
■ Return type: parseInt() returns an int, while valueOf() returns an
Integer.
■ Null Handling: parseInt() does not handle null values, while
valueOf() can handle null inputs.

Example:

String str = "123";


int intValue1 = Integer.parseInt(str); // returns int value 123
Integer intValue2 = Integer.valueOf(str); // returns Integer object
with value 123

● parseDouble() and valueOf() for Double:


○ Function: Both methods convert strings to double values.
○ Differences:
■ Return type: parseDouble() returns a double, while valueOf()
returns a Double.
■ Null Handling: parseDouble() does not handle null values, while
valueOf() can handle null inputs.

String str = "3.14";


double doubleValue1 = Double.parseDouble(str); // returns double
value 3.14
Double doubleValue2 = Double.valueOf(str); // returns Double object
with value 3.14
Summary:

● .valueOf() Method:
○ Converts string representations to wrapper types.
○ Returns a wrapper object.
○ Can handle null inputs.
● .parseInt() Method:
○ Converts string representations to primitive types.
○ Returns a primitive value.
○ Cannot handle null inputs.

Converting an Integer to a String in Java

In Java, there are several ways to convert an integer to its string representation. Here are
three common methods:

1. Using String.valueOf(int i) Method

● Description: Converts the integer to a string representation.


int number = 123;

String str = String.valueOf(number);


System.out.println(str); // Output: "123"

2. Using Integer.toString(int i) Method

● Description: Also converts the integer to a string representation.

int number = 123;


String str = Integer.toString(number);
System.out.println(str); // Output: "123"

3. Using Concatenation with an Empty String

● Description: Converts the integer to a string by concatenating it with an empty


string.
int number = 123;

String str = number + "";

● System.out.println(str); // Output: "123"


Compound Assignment Operator

● Types: +=, -=, *=, /=, %=


● Function: Faster than standard arithmetic assignment (e.g., a = a + 1) because it
directly updates the variable.

int a = 10;
a += 5; // equivalent to a = a + 5; a becomes 15

Literal Types
● Integer Literals: By default, int type.
● Decimal Literals: By default, double type.

// Case 1: Widening
byte b1 = 100;
int i1 = b1; // implicit type casting

// Case 2: Narrowing
int i2 = 100;
byte b2 = (byte) i2; // explicit type casting

Conditional (Ternary) Operator

● Syntax: condition ? expression1 : expression2;


● Function: Evaluates a boolean expression (condition) and returns one of two values
depending on whether the condition is true or false.
● Usage: Often used to replace simple if-else statements.

Structure

● General Form: booleanExpression ? valueIfTrue : valueIfFalse;

int a = 5;
int b = 10;
int max = (a > b) ? a : b; // max will be 10 because a is not
greater than b

Finding the Greatest of Three Numbers:


int a = 10;
int b = 20;
int c = 30;
// Using nested ternary operators
int greatest = (a > b) ? (a > c ? a : c) : (b > c ? b : c);
// Explanation:
// If a > b is true, check if a > c. If true, a is the greatest;
otherwise, c is.
// If a > b is false, check if b > c. If true, b is the greatest;
otherwise, c is.

System.out.println(greatest); // Output: 30

Decision Making Statements in Java


Purpose

● Decision making statements help programmers to either execute or skip a set of


instructions based on certain conditions.

Types of Decision Making Statements (4 Types)


1. if Statement
2. if-else Statement
3. else-if Ladder
4. switch Statement

if Statement

Syntax:

if (condition) { // code to execute if condition is true }

if (true) {

System.out.println("Hello");
}
if (false) {
System.out.println("Hello"); // This statement is unreachable
}

if-else Statement
Syntax:

if (condition) {
// code to execute if condition is true
} else {
// code to execute if condition is false
}

int number = 10;


if (number < 20) {
System.out.println("The number is less than 20.");
} else {
System.out.println("The number is 20 or greater.");
}

if-else-if Ladder
Syntax:

if (condition1) {
// code to execute if condition1 is true
} else if (condition2) {
// code to execute if condition2 is true
} else if (condition3) {
// code to execute if condition3 is true
} else {
// code to execute if none of the above conditions are true
}

public class IfElseIfExample {


public static void main(String[] args) {
int score = 85;

if (score >= 90) {


System.out.println("Grade: A");
} else if (score >= 80) {
System.out.println("Grade: B");
} else if (score >= 70) {
System.out.println("Grade: C");
} else if (score >= 60) {
System.out.println("Grade: D");
} else {
System.out.println("Grade: F");
}
}
}

switch Statement
Syntax:

switch (expression) {
case value1:
// code to execute if expression equals value1
break;
case value2:
// code to execute if expression equals value2
break;
// more cases
default:
// code to execute if expression doesn't match any case
}

● Notes:
○ Menu-driven programs often use switch statements.
○ Without a break, execution "falls through" to subsequent cases.
○ The default case executes if no other case matches.
○ long, double, float, and boolean can't be used in switch expressions.
○ byte, short, int, enum, char, and String can be used in switch
expressions.

int day = 3;

switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
}

Increment/Decrement Operator (Unary Operators)


● Purpose: Increments or decrements a value by 1.
● Types:
○ Postfix: a++ (use first, then update)
○ Prefix: ++a (update first, then use)

int a = 10;
System.out.println(a++); // Output: 10 (postfix: use first, then
increment)
System.out.println(a); // Output: 11

a = 10;
System.out.println(++a); // Output: 11 (prefix: increment first,
then use)
System.out.println(a); // Output: 11

Compound Assignment Operator (+=, -=, *=, /=, %=)


● Purpose: Efficiently updates a variable's value by performing an operation and
assignment in one step.

int a = 10;
a += 1; // equivalent to a = a + 1;
System.out.println(a); // Output: 11

Typecast Operator

● Purpose: Converts data from one type to another.


● Types:
○ Primitives:
■ Narrowing (explicit by programmer): int i = 100; byte b =
(byte) i;
■ Widening:
■ Explicit: byte b = 10; int i = (int) b;
■ Implicit: byte b = 10; int i = b;
○ Non-Primitives:
■ Upcasting:
■ Explicit: SubClass obj = new SubClass();
SuperClass sup = (SuperClass) obj;
■ Implicit: SubClass obj = new SubClass();
SuperClass sup = obj;
■ Downcasting: SuperClass sup = new SubClass();
SubClass obj = (SubClass) sup;

>> TYPE CASTING ( converting data from one type to another )

>>Primitives

>> narrowing (1 ways )

> explicitly (by programmer )

>> widening (2 ways )

> explicitly (by programmer )

> implicitly ( by compiler )

>> Non -primitive

>> upcasting (2 ways )

> explicitly (by programmer )

> implicitly ( by compiler )zassss

>>downcasting (1 ways )

> explicitly (by programmer )

// Widening
byte b1 = 100;
int i1 = b1; // implicit type casting

// Narrowing
int i2 = 100;
byte b2 = (byte) i2; // explicit type casting
Scanner Class

● Purpose: Parses and reads input from various sources like keyboard, files, etc.
● Common Methods:
○ next(): Finds and returns the next complete token.
○ nextLine(): Advances the scanner past the current line.
○ nextInt(): Scans the next token as an int.
○ nextDouble(): Scans the next token as a double.
○ hasNext(): Returns true if the scanner has another token.
○ hasNextLine(): Returns true if the scanner has another line.
○ useDelimiter(String pattern): Sets the scanner's delimiting pattern.

Anatomy of the Syntax

● Scanner:
○ This is the class/type we are using.
● sc:
○ This is the name of the Scanner object we are creating.
● new Scanner(System.in):
○ new is a keyword/operator that creates a new instance of the Scanner class.
○ Scanner(System.in) is the constructor call that initializes the Scanner
object to read input from the standard input stream (keyboard).

How the Scanner Class Works

● The Scanner object accesses the buffer file in the operating system to read input.
● It converts the binary input from the keyboard (or other input sources) into high-level
language constructs that can be used in a Java program.
● contain access to the buffer file in the os which can convert the hl to ll and ll to hl
● these convert s the input of the keyboard (binary to hl language)

import java.util.Scanner;

public class ScannerExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Reading a string
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Name: " + name);

// Reading an integer
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.println("Age: " + age);

// Reading a double
System.out.print("Enter your GPA: ");
double gpa = scanner.nextDouble();
System.out.println("GPA: " + gpa);

scanner.close();
}
}

Looping Statements in Java

Purpose
● Looping statements in Java are used to repeat the execution of a block of code until
a specific condition is met or for a specified number of times.

Types of Looping Statements (4 Types)


1. while Loop
2. do-while Loop
3. for Loop
4. enhanced for Loop (for-each Loop)

while Loop
● Purpose: Executes a block of code repeatedly as long as a specified condition is
true.

while (condition) {

// code to execute
// increment / decrement
}
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}

● Execution Flow: Checks the condition before entering the loop body.

do-while Loop

● Purpose: Similar to while loop but guarantees that the loop body executes at least
once.

do {
// code to execute
// increment / decrement
} while (condition);

int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 5);

● Execution Flow: Executes the loop body first, then checks the condition.

for Loop
● Purpose: Used when the number of iterations is known and finite.

Syntax:

for (initialization; condition; increment/decrement) {


// code to execute
}
Example:
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
● Execution Flow: Executes initialization, checks condition, executes loop body,
increments/decrements, and repeats.

Enhanced for Loop (for-each Loop)


● Purpose: Simplifies iteration over collections and arrays.

Syntax:

for (type variable : collection) {


// code to execute
}

Example:

int[] numbers = {1, 2, 3, 4, 5};


for (int number : numbers) {
System.out.println(number);
}

● Execution Flow: Iterates through each element of the collection.

Differences between while and do-while Loops


● while Loop:
○ Checks the condition before executing the loop body.
○ May never execute if the condition is false initially.
○ Ideal for pre-check loops when the number of iterations is uncertain.
● do-while Loop:
○ Executes the loop body at least once before checking the condition.
○ Guarantees at least one execution of the loop body.
○ Ideal for post-check loops when the loop must execute at least once.

Nested Looping Statements

● Purpose: Loops inside another loop to create complex patterns or process


multi-dimensional data.

Example:

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


for (int j = 1; j <= 3; j++) {
System.out.println("i = " + i + ", j = " + j);
}
}

● Execution Flow: Outer loop executes once for each iteration of the inner loop.
Problem Solving Techniques

● Last Digit: Extracts the last digit of a number using n = n % 10;.


● Reverse: Reverses a number by accumulating digits using rev = rev * 10 +
lastDigit;.
● Last Before Digit: Retrieves the second last digit of a number using (n % 100) /
10;.

METHODS :

>> CONTAINER TO STORE (ACTION / TASKS /BEHAVIOUR)


>> LOGIN METHOD (INSTAGRAM)
>> TO AUTOMATE REPEATED TASKS
>> BLOCK OF INSTRUCTIONS WHICH USED TO PERFORM A SPECIFIC TASK
>> SET OF INSTRUCTIONS
>> NOT RUN UNLESS CALLED IN PROGRAM
>> GIVE SOMETHING TO THE CALLER
>> outside main method

Purpose

● Methods are blocks of code designed to perform specific tasks, automate repeated
actions, and organize code into manageable units.
● Methods store actions or behaviors, such as a login function in an application.

Key Features
● Not executed unless called: Methods must be explicitly invoked to run.
● Can return data: Methods can return values to the caller.
● Defined outside the main method: Methods are defined within a class but outside
the main method.

Syntax

[MODIFIER] returnType methodName([int a, int b]) {


// Method body
[return statement;]
}

● Method signature: methodName(int, int) - method name with arguments.


● Method declaration: public int methodName(int a, int b) { ... } -
method signature with modifiers and return type.
● Method definition: Includes the method body with code to execute.
● Formal arguments: Variables declared in the method declaration (e.g., int a,
int b).

public int calculateSum(int a, int b) {


return a + b;
}

Modifiers

● Access Modifiers: public, private, protected, <default>.


● Non-Access Modifiers: abstract, static, final, native, volatile,
transient.

Return Types

● void: Indicates no return value.


● Data types: Specifies the type of data the method will return (e.g., int, String).

Method Workflow

1. Method is called.
2. Caller execution is stopped.
3. Method execution starts.
4. After performing its task, control returns to the caller with the data (if any).

Characteristics of Methods

● Block of instructions: A method is a set of instructions grouped together.


● Not executed unless invoked.
● No nested methods: Methods cannot be defined inside other methods.
● Reusable: Methods can be called multiple times.
● Unlimited methods: A class can contain any number of methods.

Main Method

● Not built-in: The JVM calls the main method to start the program.

Types of Methods

1. Based on Arguments
○ No Argument: No parameters declared.
○ Parameterized: Declares formal arguments and can receive data during
execution.
○ Var Args: Allows variable number of arguments.
2. Based on Modifiers
○ Public
○ Protected
○ Static
○ Non-static
○ Final

Actual Arguments

● Actual arguments: The data passed to the method in the invocation statement.

No-Argument Method

public static void greet() {


System.out.println("Hello, World!");
}

// Invocation
greet(); // Outputs: Hello, World!

Parameterized Method

public static void greet(String name) {


System.out.println("Hello, " + name + "!");
}

// Invocation
greet("Alice"); // Outputs: Hello, Alice!

● The greet() method prints a general greeting.


● The greet(String name) method prints a personalized greeting using the
provided name.

Rules of Return Types in Methods

● Return Statement Position: The return statement should be the last statement in
the method body.
● Mandatory Return Statement: If the return type of the method is anything other than
void, a return statement is mandatory.
● Void Return Type: If the return type is void, a return; statement is optional but
not mandatory.
● Type Casting: Rules of type casting also apply to return types.
Calling Static Methods from Other Classes
Class Definition:

class A {
public static void M1() {
// Method of Class A
}
}

class B {
public static void main(String[] args) {
A.M1(); // Calling method from Class A
// M1(); // This will not work as it only looks within Class
B
}
}

Syntax:

ClassName.methodName();

Built-in Classes in Java

● java.lang Package: This package is imported by default in every Java program and
includes commonly used classes such as Math, String, Integer, etc.

Math Class Examples


Math Methods:

int max = Math.max(1, 2);


double ceilValue = Math.ceil(-1.88);
long roundedValue = Math.round(1.89);
double sqrtValue = Math.sqrt(100.1234);

System.out.println(max); // Output: 2
System.out.println(ceilValue); // Output: -1.0
System.out.println(roundedValue); // Output: 2
System.out.println(sqrtValue); // Output: 10.006168097728521


Example Programs

1. Calculate the Area of a Circle Using Methods

public class CircleArea {


public static void main(String[] args) {
double radius = 5.0;
double area = calculateArea(radius);
System.out.println("The area of the circle is: " + area);
}

public static double calculateArea(double radius) {


return Math.PI * Math.pow(radius, 2);
}
}

2. Convert INR to USD Using Methods

public class CurrencyConverter {


public static void main(String[] args) {
double inr = 1000.0;
double usd = convertINRtoUSD(inr);
System.out.println(inr + " INR is " + usd + " USD");
}

public static double convertINRtoUSD(double inr) {


double conversionRate = 0.013; // Example conversion rate
return inr * conversionRate;
}
}

3. Convert an Angle from Degrees to Radians

public class AngleConverter {


public static void main(String[] args) {
double degrees = 45.0;
double radians = convertDegreesToRadians(degrees);
System.out.println(degrees + " degrees is " + radians + "
radians");
}
public static double convertDegreesToRadians(double degrees) {
return Math.toRadians(degrees);
}
}

METHOD OVERLOADING:

>> declaring more than one mehod with same name but with different signature
(method overloading )
>> add(int a ,int b)
>> add(int a ,int b ,int c )

RULES FOR OVERLOADING :

>> diff no.of. arguments


>> diff types of data
>> diff sequence of parameter
>> same return type

length of argument:
>> m1 (int )
>> m1 (int ,int )
>> m1 (int ,int ,int )

length of formal arguments is same :

By changing the type of arguments:


>> m1 (int,int )
>> m1 (double,double)
>> m1 (char,char)

By changing the sequence:


>> m1(int ,double)
>> m1(double , int )
>> m1 (float ,int )
>> m1 (int ,float)

Arrays in Java
Definition and Characteristics

● Continuous Block of Memory: Arrays are stored in contiguous memory locations.


● Homogeneous Data: Arrays can store only elements of the same data type.
○ Valid examples: {1, 23, 3}, {"hi", "hii"}
○ Invalid example: {"hi", 12, true} (mix of different data types)
● Fixed Size: The size of an array is defined at the time of creation and cannot be
changed.
● Length Property: Use .length to get the length of the array (e.g., arr.length).

Purpose

● Store Multiple Values: Arrays are used to store multiple values of the same type
together.

Creation and Initialization

● Syntax:
○ Declaration and Instantiation: datatype[] variable = new
datatype[size];
■ Example: int[] arr = new int[7];
○ Separate Declaration and Instantiation:
■ Declaration: int arr[];
■ Instantiation: arr = new int[5];
○ Initialization with Values: int[] arr = {10, 20, 30};

Array Index

● Indexing: Arrays are indexed starting from 0.


● Array Elements: Accessed using indices, e.g., arr[0], arr[1].

Default Values

● Default Initialization: If an array is created without initialization, it is filled with default


values (e.g., 0 for integers).

Exception Handling

● ArrayIndexOutOfBoundsException: Occurs if you try to access an index less than


0 or greater than or equal to the length of the array.

Accessing Array Elements Using Loops


Example Using While Loop:

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


int i = 0;
while (i < arr.length) {
System.out.println(arr[i]);
i++;
}

Initialization Methods
Assigning Values to Indices:

int[] arr = new int[5];


arr[0] = 1;
arr[1] = 2;

Direct Initialization:

int[] arr = {1, 2, 3, 4, 5};

Example of Array Creation and Initialization


Declaration and Initialization:
int[] numbers = new int[5]; // Declaration and instantiation
numbers[0] = 10; // Initialization
numbers[1] = 20;

Direct Initialization:
int[] numbers = {10, 20, 30, 40, 50};

Common Use Cases

● Storing Homogeneous Data: Arrays are ideal for storing lists of items of the same
type.
● Iteration: Arrays are commonly used with loops to perform operations on each
element.

Linear Search
Definition

● Uni-directional Search: A method that sequentially checks each element in a list


until the desired element is found or the list ends.

Characteristics

● Return Value:
○ Index of Element: Returns the index of the element if found.
○ -1 if Not Found: Returns -1 if the element is not found.
■ Reason: Indices start from 0, so -1 is used to indicate absence.
Usage

● Finding Elements: Suitable for small to moderately sized arrays where ease of
implementation is prioritized over performance.
● Performance: O(n) time complexity, where n is the number of elements in the array.

Objects in Java
Definition

● Object: A block of memory that can store heterogeneous data (properties) and
methods (behaviors) to represent a real-world entity.

Key Characteristics

● Block of Memory: Reserved space in memory.


● Heterogeneous Data: Can store various types of data.
● Methods: Behaviors or functions associated with the object.
● State: Combination of properties and behaviors.

Advantages

● Real-world Representation: Models real-world entities.


● Flexible Size: Size is not fixed, adaptable based on properties and behaviors.
● Instance of a Class: Specific realization of a class.
● User-defined Datatype: Overcomes the limitations of primitive data types.
● Supports Methods: Unlike C structs, Java objects support methods.

Steps to Create an Object

Step 1: Create a Blueprint (Class)

1. Analyze Real-world Objects: Understand the entity to be modeled.


2. Identify Properties and Behaviors: Determine attributes and methods.
3. Check for Existing Blueprints: Use existing classes if available.
4. Create New Blueprint: Define a new class if no suitable blueprint exists.

Step 2: Instantiate the Object

1. Class Definition: Define the class with properties and methods.


2. Object Creation: Instantiate the class using the new keyword.

Example Code
class Student {
String name;
int age;
int rollNo;
public static void main(String[] args) {
// Step 2: Create an Object
Student s = new Student();
}
}

● Student s: Variable of type Student.


● new Student(): Creates a new memory location in the heap and returns its address.

Key Concepts

● new Keyword:
1. Memory Allocation: Allocates memory in the heap.
2. Type Matching: Returns the same type as the class.

Variables in Java

Types of Variables:

1. Static Variables:
○ Declared with the static keyword inside a class.
○ Initialized with default values if not explicitly initialized.
○ Can be accessed using the class name.

Characteristics:

■ Shared among all instances of the class.


■ Accessed using ClassName.variableName.
2. Non-Static Variables (Instance Variables):
○ Declared inside a class without the static keyword.
○ Memory allocated inside the object.
○ Used to store properties of real-world objects.
○ Accessed through object references.

Purpose:

● To store properties of real-world objects.


● Each instance of a class (object) has its own copy of non-static variables.

Accessing Non-Static Variables:

● Can only be accessed through object references.


● Each object has its own copy of the non-static variables, thus each object can have
different values for these variables.

3. Local Variables:
○ Declared inside methods, constructors, or blocks.
○ No default value; must be initialized before use.
○ Have precedence over global variables with the same name.

Class Variable Example

public class VariableExample {


// Global instance variable
int instanceVar = 10;

// Global static variable


static double staticVar = 3.14;

// Global final variable


final String finalVar = "FinalVariable";

public void myMethod(int parameter) {


// Local variable
int localVar = 20;

// Usage of instance, static, local, parameter, and final


variables
System.out.println("Instance variable: " + instanceVar);
System.out.println("Static variable: " + staticVar);
System.out.println("Local variable: " + localVar);
System.out.println("Parameter variable: " + parameter);
System.out.println("Final variable: " + finalVar);
}

public static void main(String[] args) {


VariableExample obj = new VariableExample();
obj.myMethod(30); // Passing a parameter to the method

// Accessing static variable directly from main method


System.out.println("Accessing static variable from main
method: " + staticVar);
}
}
Exceptions in Java

1. Error:

● Errors are serious problems that a reasonable application should not try to catch.
● They typically represent fatal problems that the application cannot recover from.
● Examples include:
○ StackOverflowError: Thrown when a stack overflow occurs because an
application recurses too deeply.
○ OutOfMemoryError: Thrown when the Java Virtual Machine (JVM) cannot
allocate an object because it is out of memory.
○ VirtualMachineError: A superclass of all the errors that occur within the
JVM.

2. Exception:

● Exceptions are conditions that an application might want to catch.


● They represent problems that can occur during the execution of a program.

2.1. Checked Exceptions:

● Checked exceptions are exceptions that are checked at compile-time.


● They must be either caught or declared in the method's throws clause.
● Examples include:
○ IOException
○ SQLException

2.2. Unchecked Exceptions (Runtime Exceptions):

● Unchecked exceptions are exceptions that occur at runtime.


● They are not checked at compile-time, meaning they do not need to be declared in a
method's throws clause or caught explicitly.
● Examples include:
○ NullPointerException: Thrown when an application attempts to use
null in a case where an object is required.
○ ArrayIndexOutOfBoundsException: Thrown to indicate that an array
has been accessed with an illegal index.
○ ArithmeticException: Thrown when an exceptional arithmetic condition
has occurred, like division by zero.
○ ClassCastException: Thrown to indicate that the code has attempted to
cast an object to a subclass of which it is not an instance.

Handling Exceptions:

● Java provides the try, catch, finally, and throw keywords for handling
exceptions.
Constructor in Java

A constructor is a special method used to initialize objects in Java. It has the same name as
the class and does not have a return type. Constructors are invoked automatically when an
object is created.

Characteristics of Constructors:

● Special Member: A constructor is a non-static member of a class.


● Same Name as Class: The name of the constructor must match the class name.
● No Return Type: Constructors do not have a return type, not even void.
● Initialization: They initialize object properties and allocate resources.

Syntax

[Modifier] ClassName(arguments) {

// Constructor body

Example:

public class Person {

String name;

int age;

// Constructor

Person(String name, int age) {

this.name = name;

this.age = age;

}
Types of Constructors

1. Built-In Constructor

Default Constructor:

● If no constructor is defined, the compiler adds a default constructor that


initializes the object with default values.

Example of Default Constructor:

public class Car {

String model;

// Default Constructor

Car() {

this.model = "Unknown";

Car myCar = new Car(); // Calls the default constructor

System.out.println(myCar.model); // Outputs: Unknown

2. Custom / User-Defined Constructors

No-Args Constructor:

● A constructor with no parameters.

public class Book {

String title;

// No-Args Constructor
Book() {

this.title = "Untitled";

Parameterized Constructor:

● A constructor that takes arguments to initialize object properties.

Example:

public class Book {

String title;

String author;

// Parameterized Constructor

Book(String title, String author) {

this.title = title;

this.author = author;

Usage:

Book myBook = new Book("1984", "George Orwell"); // Calls the


parameterized constructor

System.out.println(myBook.title); // Outputs: 1984

System.out.println(myBook.author); // Outputs: George Orwell


Purpose of Constructors

● Initialize Objects: Constructors provide initial values to the object’s attributes.


● Increases Readability: A parameterized constructor improves code readability by
allowing object initialization in one line.
● Encapsulation: Constructors help in encapsulating the initialization logic.

Constructor vs. Method

Notes on Constructors

● Implicit vs. Explicit Calls: While you can’t call a constructor directly, you can
instantiate an object using the new keyword, which implicitly calls the constructor.
● Constructor Overloading: Multiple constructors can be defined in a class with
different parameters.

this Keyword

Definition:

● this is a Java keyword that refers to the current object instance within a class.
● It is a non-static variable that holds a reference to the current object.

Uses of this:
1. Distinguishing Instance Variables from Local Variables:
○ this is used to differentiate between instance variables and local
variables or method parameters when they have the same name.

Example:

public class Book {

String title;

// Constructor with parameter

Book(String title) {

this.title = title; // `this.title` refers to the instance


variable, `title` refers to the parameter

2. In the Book class, this.title refers to the instance variable title, while
title refers to the constructor parameter.
3. Calling Other Constructors:
○ this() can be used to call another constructor in the same class
(constructor chaining).

Example:

public class Book {

String title;

String author;

// No-Args Constructor

Book() {

this("Unknown", "Unknown"); // Calls the parameterized


constructor

}
// Parameterized Constructor

Book(String title, String author) {

this.title = title;

this.author = author;

4. Here, the no-args constructor uses this() to call the parameterized


constructor.
5. Returning the Current Instance:
○ this can be used to return the current object instance from a method.

Example:

public class Book {

String title;

Book setTitle(String title) {

this.title = title;

return this; // Return the current instance

6. This allows method chaining: book.setTitle("New


Title").someOtherMethod();
7. Passing the Current Instance to Another Method:
○ this can be passed as an argument to other methods or constructors.

Example:

public class Book {

String title;
void printBook(Book b) {

System.out.println(b.title);

void print() {

printBook(this); // Passing the current instance to the


method

Constructor Overloading

Definition:

● Constructor overloading is a feature that allows a class to have more than one
constructor with different parameter lists.

Rules for Constructor Overloading:

1. Different Number of Parameters: Constructors must have a different number of


parameters.
2. Different Types of Parameters: Constructors must have different types of parameters.
3. Different Sequence of Parameters: Constructors must have different sequences of
parameters.

Constructor Overloading Characteristics:

● Multiple Constructors: Allows defining multiple constructors with different parameters.


● Increased Flexibility: Provides different ways to initialize objects.
● Readability: Improves code readability by offering multiple ways to create objects with
various initial states.

Constructor Overloading Rules Summary:Key Points for Constructor Overloading:

● Same Name: All overloaded constructors must have the same name as the class.
● Different Signatures: Each constructor must have a different parameter list.
Conclusion

Understanding the this keyword and constructor overloading are essential for effective
object-oriented programming in Java. They help manage object state and provide flexibility
in object creation.

Constructor Chaining in Java

Constructor Chaining refers to calling one constructor from another within the same class
or from a parent class constructor. It is a technique to reuse code and manage object
initialization more effectively.

Types of Constructor Chaining

1. Within the Same Class Using this() Statement


○ What It Does: Calls another constructor in the same class.
○ Syntax: this(arguments);

public class Book {


String title;
String author;
// No-args Constructor
Book() {
this("Unknown Title", "Unknown Author"); // Calls the
parameterized constructor
}

// Parameterized Constructor
Book(String title, String author) {
this.title = title;
this.author = author;
System.out.println("Title: " + title + ", Author: " +
author);
}

public static void main(String[] args) {


Book b1 = new Book(); // Calls no-args
constructor, which in turn calls the parameterized constructor
Book b2 = new Book("Java Basics", "John Doe"); // Calls
parameterized constructor directly
}
}

Output:
Title: Java Basics, Author: John Doe
Title: Unknown Title, Author: Unknown Author

○ Characteristics: this() must be the first statement in a constructor, only


one this() call is allowed, and recursive constructor calls are not permitted.
2. From Parent Class Using super() Statement
○ What It Does: Calls a constructor from the parent class.
○ Syntax: super(arguments);

public class Vehicle {

String type;

// Parent Class Constructor


Vehicle(String type) {
this.type = type;
System.out.println("Vehicle Type: " + type);
}
}

public class Car extends Vehicle {


String model;

// Child Class Constructor


Car(String model) {
super("Car"); // Calls the parent class constructor
this.model = model;
System.out.println("Car Model: " + model);
}

public static void main(String[] args) {


Car myCar = new Car("Sedan");
}
}
Output:
Vehicle Type: Car
Car Model: Sedan

○ Characteristics: super() must be the first statement in a constructor, only


one super() call is allowed, and it initializes the parent class before the child
class constructor executes.

Rules of Constructor Chaining

1. this() Usage:
○ this() can only be used to call another constructor in the same class.
○ It must be the first line in the constructor.
○ You can only have one this() call per constructor.
○ Recursive constructor calls (where a constructor calls itself directly or
indirectly) are not allowed.
○ If you have N constructors in a class, you can only have (N-1) this() calls.
2. super() Usage:
○ super() can be used to call a constructor from the parent class.
○ It must be the first line in the constructor.
○ You can only have one super() call per constructor.
○ It initializes the parent class before the child class constructor executes.
Constructor Overloading

Constructor overloading is a concept where you have more than one constructor in a class
with different parameters. This allows you to create objects in different ways depending on
the arguments provided.

Constructor Chaining Example

public class Example {


Example() {
this(10); // Calls the constructor with one int argument
System.out.println("No-arg Constructor");
}

Example(int i) {
this(i, "Hello"); // Calls the constructor with two
arguments
System.out.println("Single int Constructor: " + i);
}

Example(int i, String s) {
System.out.println("Two-arg Constructor: " + i + ", " + s);
}

public static void main(String[] args) {


Example ex = new Example(); // This calls the no-arg
constructor
}
}

Output:

Two-arg Constructor: 10, Hello


Single int Constructor: 10
No-arg Constructor

Conclusion

Constructor chaining is a powerful feature in Java for initializing objects. It uses this() for
constructors within the same class and super() for constructors in a parent class.
Understanding these concepts helps manage object creation and inheritance effectively.

Key Takeaways:

● this(): Use it to call another constructor in the same class.


● super(): Use it to call a constructor in the parent class.
● Constructor Overloading: Allows multiple constructors with different parameters.
● Constructor Chaining Rules: this() and super() must be the first line in a
constructor and can only be used once.
Non-Static Methods
Definition:

● A method that belongs to an object is known as a non-static method.


● Also known as an instance method or object method.
● Used to access the properties of the object.

Purpose:

● Required to access the property of the object.


● Perform CRUD (Create, Read, Update, Delete) operations on the objects.
○ C: Create
○ R: Read
○ U: Update
○ D: Delete

Characteristics:
● The memory of non-static methods is allocated inside the object.
● The memory for objects is stored in the heap.
● Can be accessed, used, or invoked with the help of an object reference.
● The block associated with non-static methods is called a non-static initializer.
● In a non-static context, both static and non-static members can be accessed directly
without any reference.

Static Methods
Definition:

● A method that belongs to the class is known as a static method.


● Also known as a class method.
● Used to access class properties and behaviors.

Purpose:

● To store common behaviors of all objects.

Characteristics:

● Memory is allocated in the class static block, which is present inside the static area or
static pool.
● Can be accessed, used, or invoked with the help of the class name.
● Static variables can be accessed directly in the static context.
● In other classes, use the class name to access them.
● Can also be accessed with instance variables.
Initializer Blocks
Definition:

● Blocks used to initialize variables and methods.


● Initializers are components of Java used to initialize the class and the object.

Types:

1. Static Initializer:
○ Declared inside the class block only.
○ Initialized during the class loading process.
○ Executed only once during class loading.
○ Execute in top-to-bottom order.
2. Non-Static Initializer:
○ Declared inside the class block only.
○ Executed during the object loading process.
○ Executed every time an object is created.
○ Execute in top-to-bottom order.

Object-Oriented Programming Principles (OOPs)

Object-oriented programming (OOP) design principles help programmers design objects


conveniently and easily, ensuring that software objects closely resemble real-world objects.
There are four main principles of OOP:

1. Encapsulation
2. Inheritance
3. Polymorphism
4. Abstraction

Encapsulation
Definition: Encapsulation is the process of wrapping up the properties (fields) and behaviors
(methods) of an object into a single unit, or class. It hides the internal state and requires all
interaction to be performed through an object's methods.

● ATM Machine:
○ Properties: location
○ Behaviors: withdraw()
Advantages:

1. Data Hiding: Ensures that the internal representation of an object is hidden from the
outside. Only the methods of the object can be used to interact with its internal state.
This provides a controlled way of accessing and modifying the data.
2. Data Validation: Allows validation of data before it is assigned to variables, ensuring
that the object maintains a valid state.

How to Achieve Data Hiding:

● Using access modifiers such as public, protected, default, and private.

Access Modifiers:

● Public: Accessible from any other class.


● Protected: Accessible within the same package and by subclasses.
● Default (package-private): Accessible only within the same package.
● Private: Accessible only within the same class.

Getter and Setter Methods:

● Getter Method: A public method that returns the value of a private field.
● Setter Method: A public method that sets the value of a private field.

public class Person {


private String name;
private int age;

// Getter method for name


public String getName() {
return name;
}

// Setter method for name


public void setName(String name) {
this.name = name;
}

// Getter method for age


public int getAge() {
return age;
}

// Setter method for age


public void setAge(int age) {
if (age > 0) { // Data validation
this.age = age;
}
}
}

Factory Method:
● A static method that returns an instance of a class. It is often used to encapsulate the
creation logic of an object.

Example:

public class Connection {


private Connection() {
// private constructor
}

public static Connection createConnection() {


// logic to create and return a new connection
return new Connection();
}
}

Inheritance
Definition: Inheritance is the mechanism by which one class (the child or subclass) inherits
the properties and behaviors (fields and methods) of another class (the parent or
superclass). This promotes code reusability and establishes a natural hierarchy between
classes.

Types of Inheritance in Java:

1. Single Inheritance: A class inherits from one superclass.


2. Multilevel Inheritance: A class inherits from a subclass, making it a subclass for
another class.
3. Hierarchical Inheritance: Multiple classes inherit from one superclass.
4. Multiple Inheritance: (Not supported directly in Java through classes but can be
achieved through interfaces) A class inherits from multiple classes.

Example:

// Parent class
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}

// Child class
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}

public class Main {


public static void main(String[] args) {
Dog myDog = new Dog();
myDog.eat(); // Inherited method
myDog.bark(); // Child class method
}
}

How to Achieve Inheritance:

● Using the extends keyword for class-to-class inheritance.


● Using the implements keyword for class-to-interface inheritance.

Purpose of Inheritance:

● Code Reusability: Methods and fields of the parent class can be reused in the child
class.
● Method Overriding: Allows a subclass to provide a specific implementation of a
method that is already defined in its superclass.
● Polymorphism: Refers to the ability to call the same method on different objects and
have each of them respond in their own way.
Polymorphism
Definition: Polymorphism means "many shapes" and allows objects to be treated as
instances of their parent class rather than their actual class. The two main types are
compile-time (method overloading) and runtime (method overriding).

Types of Polymorphism:

1. Compile-time Polymorphism (Method Overloading): The same method name is


used with different parameters within the same class.
2. Runtime Polymorphism (Method Overriding): A subclass provides a specific
implementation for a method that is already defined in its superclass.

Method Overloading:

class MathOperation {
// Method to add two integers
int add(int a, int b) {
return a + b;
}

// Method to add three integers


int add(int a, int b, int c) {
return a + b + c;
}
}

Method Overriding:

class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {


@Override
void sound() {
System.out.println("Dog barks");
}
}
public class TestPolymorphism {
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.sound(); // Calls the overridden method in Dog class
}
}

Advantages:

● Flexibility: Allows for the implementation of dynamic method calls.


● Ease of Maintenance: Easier to maintain and extend the code.

Abstraction
Definition: Abstraction is the concept of hiding the complex implementation details and
showing only the essential features of an object. It reduces complexity and allows the
programmer to focus on interactions at a high level.

How to Achieve Abstraction:

● Abstract Classes: Classes that cannot be instantiated and are declared with the
abstract keyword. They can have abstract methods (methods without a body) and
concrete methods (regular methods).
● Interfaces: A contract that classes can implement. Interfaces can have abstract
methods (implicitly public abstract) and, from Java 8 onwards, default and static
methods.

Example:

Abstract Class:

abstract class Animal {


// Abstract method (does not have a body)
abstract void sound();

// Regular method
void sleep() {
System.out.println("This animal sleeps");
}
}
class Dog extends Animal {
// Providing implementation of the abstract method
void sound() {
System.out.println("Dog barks");
}
}

public class Main {


public static void main(String[] args) {
Dog myDog = new Dog();
myDog.sound(); // Calls the overridden method in Dog class
myDog.sleep(); // Calls the regular method in Animal class
}
}

Interface:

interface Animal {
void sound(); // Abstract method
}

class Dog implements Animal {


public void sound() {
System.out.println("Dog barks");
}
}

public class Main {


public static void main(String[] args) {
Dog myDog = new Dog();
myDog.sound();
}
}

Advantages:

● Code Reusability: Common code can be shared among multiple classes.


● Modularity: Changes in the implementation do not affect users of the abstraction.
● Maintainability: Easier to manage and understand.
Coupling in Object-Oriented Programming
Coupling refers to the degree of direct knowledge that one class has about another. In
simpler terms, it measures how closely connected two classes or modules are. Lower
coupling is generally preferred because it makes the system more modular, easier to
understand, and easier to maintain.

Types of Coupling

1. Tight Coupling (High Coupling)


2. Loose Coupling (Low Coupling)

Tight Coupling

● Definition: Tight coupling occurs when classes are highly dependent on each other.
Changes in one class will often require changes in the other.
● Example: A Car class has an Engine class directly instantiated within it.

Loose Coupling

● Definition: Loose coupling occurs when classes are mostly independent and interact
with each other through well-defined interfaces or methods. Changes in one class
minimally affect others.
● Example: A Car class has an Engine class passed to it via a constructor or setter
method.

IS-A Relationship (Inheritance)

Definition: The IS-A relationship defines an inheritance relationship between classes. It


indicates that one class (child/subclass) is a specialized form of another class
(parent/superclass).

Characteristics of IS-A Relationship

1. Purpose of super():
○ Used to call the constructor of the immediate parent class.
○ Ensures that the parent class is initialized when the child class object is
created.
2. super() Call Statement:
○ Must be the first statement inside the constructor body.
○ Can only be used within a constructor.
○ Cannot use both super() and this() inside the same constructor.
○ By default, super() is called as the first statement in a constructor if this()
is not specified.
○ For multiple constructors, each can have its own super() call.
Example:

class Animal {
Animal() {
System.out.println("Animal constructor");
}
}

class Dog extends Animal {


Dog() {
super(); // Calls the parent class constructor
System.out.println("Dog constructor");
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
}
}

Characteristics of super.field:

● super is a keyword in Java used to refer to the parent class.


● Helps eliminate ambiguity between superclass and subclass variables and methods.
● Used to access properties and behaviors of the parent class from the child class.

Important Points on Inheritance

1. Accessibility:
○ Private members cannot be inherited.
○ Public, protected, and default members can be inherited.
2. Final Class:
○ Cannot be extended by any other class (e.g., String class in Java).
HAS-A Relationship (Composition/Aggregation)
Definition: The HAS-A relationship defines a composition or aggregation relationship
between classes. It indicates that one class contains or uses another class.

Characteristics of HAS-A Relationship

● Dependency: One object is dependent on another object.


● Examples:
○ CAR HAS AN ENGINE
○ PHONE HAS A BATTERY
○ COMPUTER HAS A PROCESSOR
● Instantiation:
○ Early Instantiation: Dependent object is created at the beginning.
○ Lazy Instantiation: Dependent object is created only when needed (using
helper methods).

Early Instantiation Example:

class Engine {
// Engine class implementation
}

class Car {
private Engine engine;

public Car() {
this.engine = new Engine(); // Early instantiation
}
}

Lazy Instantiation Example:

class Engine {
// Engine class implementation
}

class Car {
private Engine engine;

public Engine getEngine() {


if (engine == null) {
engine = new Engine(); // Lazy instantiation
}
return engine;
}
}

Composition vs. Aggregation

1. Composition (Tight Coupling):


○ The lifetime of the contained object depends on the lifetime of the container
object.
○ Example: A House object containing Room objects. When the house is
destroyed, the rooms are also destroyed.
2. Aggregation (Loose Coupling):
○ The lifetime of the contained object does not depend on the lifetime of the
container object.
○ Example: A Library object containing Book objects. Books exist
independently of the library.

How to Achieve HAS-A Relationship

1. Early Instantiation:
○ Achieved with initializers.
○ The dependent object is created during the construction of the depending
object.
2. Lazy Instantiation:
○ Achieved with helper methods.
○ The dependent object is created later when needed.

Conclusion

● IS-A Relationship: Achieved through inheritance (extends and implements


keywords). Used to represent generalization and specialization.
● HAS-A Relationship: Achieved through composition and aggregation. Used to
represent the dependency between objects.
● Coupling: Lower coupling (loose coupling) is preferred for better modularity,
maintainability, and flexibility.

super() Call Statement

IS-A Relationship:

● Purpose of super():
○ The super() call is used to invoke the constructor of the immediate parent
class.
○ Ensures that the parent class is properly initialized when the child class is
created.
● Usage:
○ super() must be the first statement inside the constructor body.
○ It can only be used within the constructor body.
○ You cannot use both super() and this() in a single constructor body.
○ By default, if no constructor call is specified, super() is the implicit first
statement in a constructor.
○ For classes with multiple constructors, each constructor can have its own
super() call.

Characteristics of super() Call Statement:

1. First Statement: Must be the first statement inside the constructor body.
2. Constructor Body: Can only be used inside the constructor body.
3. Mutual Exclusivity: Cannot use both super() and this() inside the same
constructor.
4. Default Call: By default, super() is the first statement unless this() is specified.
5. Multiple Constructors: For classes with multiple constructors, each can include a
super() call.

Example:
java
Copy code
class Parent {
Parent() {
System.out.println("Parent constructor");
}
}

class Child extends Parent {


Child() {
super(); // Calls the parent class constructor
System.out.println("Child constructor");
}
}

public class Main {


public static void main(String[] args) {
Child child = new Child();
}
}

super.field and super.method

● super Keyword:
○ super is used to eliminate ambiguity between superclass and subclass
variables and methods.
○ It is a non-static variable that can only be used in a non-static context.
○ Allows access to the properties and behaviors of the parent class from the
child class.

Example of super.field and super.method:


java
Copy code
class Parent {
int value = 10;

void display() {
System.out.println("Parent display");
}
}

class Child extends Parent {


int value = 20;

void display() {
super.display(); // Calls the parent class method
System.out.println("Child display");
}

void showValues() {
System.out.println("Parent value: " + super.value); //
Accesses the parent class field
System.out.println("Child value: " + this.value);
}
}

public class Main {


public static void main(String[] args) {
Child child = new Child();
child.display();
child.showValues();
}
}

Important Points on Inheritance


1. Accessibility:
○ Private members cannot be inherited.
○ Public, protected, and default members can be inherited.
2. Final Class:
○ A final class cannot be extended by any other class (e.g., the String class in
Java).

Overriding Methods with super

● Purpose: When a method is overridden in a subclass, you can use super to invoke
the version of that method from the superclass. This is useful when you want to
access or extend the functionality of the superclass's method while still benefiting
from the overridden version in the subclass.
● Syntax: super.methodName(parameters);

Example of Method Overriding:


java
Copy code
class Parent {
void display() {
System.out.println("Parent display");
}
}

class Child extends Parent {


void display() {
super.display(); // Calls the parent class method
System.out.println("Child display");
}
}

public class Main {


public static void main(String[] args) {
Child child = new Child();
child.display();
}
}

Summary

● super(): Used to call the parent class constructor.


● super.field and super.method: Used to access parent class fields and
methods to avoid ambiguity.
● Inheritance: Facilitates code reuse and method overriding.
● super in Overriding: Helps in invoking parent class methods from the child class to
extend or modify functionality.

4o

You might also like