java core basics
java core basics
Here are the notes from the lecture on JDK, JRE, JVM, and Java program execution:
Key Concepts:
o Includes tools and libraries for writing Java code, such as the debugger and javac
compiler.
o Java programs are written in files with a .java extension (e.g., Test.java).
2. Compilation to Bytecode:
o The javac compiler converts the .java file into bytecode, which has a .class extension
(e.g., Test.class).
3. Execution by JVM:
o The JVM takes the bytecode and converts it into machine code, which is platform-
dependent (specific to the operating system).
o Just-In-Time (JIT) Compiler: Within the JVM, a JIT compiler optimizes frequently
used code blocks by compiling them into machine code, avoiding repeated
interpretation. This makes the execution faster for those specific blocks.
Java
class Test {
public static void main(String[] args) {
System.out.println("Hello World");
2. Open Command Prompt: Navigate to the folder where the Test.java file is saved.
3. Compile the Java file: Use the javac command followed by the filename.
Bash
javac Test.java
4. Run the Java program: Use the java command followed by the class name (without the .class
extension).
Bash
java Test
o This command executes the bytecode through the JVM, printing "Hello World" to the
console.
The javac and java tools are located in the bin directory of the JDK installation. When running java
Test, you do not need to specify .class because the JVM expects a class file.
• Query successful
• Class Definition
o A class acts as a blueprint for creating objects (e.g., a student, a car, a laptop).
o It defines the properties (like name, roll number for a student) that an object of that
class will have.
o The example uses class Test, where Test is the name of the class.
o public static void main(String[] args) is the entry point of any Java program.
o It has a specific "signature" that cannot be changed, otherwise the program will not
run.
o public: This is an access modifier, meaning the method can be accessed from outside
the class. The Java Virtual Machine (JVM) needs to access this method directly.
o static: This keyword indicates that the method belongs to the class itself, not to an
instance (object) of the class. This allows the JVM to call the main method directly
using Test.main() without creating an object of the Test class.
o void: This specifies that the method does not return any value.
o String[] args: This means the method accepts an array of strings as parameters.
These are used to pass command-line arguments to the program.
o System is a class in Java's java.lang package that provides access to system resources,
including the console.
o println() is a method that prints the given string to the console and then moves to
the next line.
• Semicolons
o In Java, a semicolon (;) is used to indicate the end of a statement. It helps the
compiler understand the structure of the code.
Initial Code:
Java
class Test {
System.out.println("Hello World");
The args array can be used to access arguments passed during execution.
Java
class Test {
System.out.println("Hello World");
System.out.println(args[0]);
System.out.println(args[1]);
• Output:
• Hello World
• apple
• mango
The apple and mango are passed as command-line arguments and are stored in the args array, which
can then be accessed within the main method.
• In Java, variables can store various types of data, such as names, salaries, or ages, unlike in
math where they primarily store numbers.
o Data Types:
o The choice of data type depends on the required capacity, similar to choosing a glass
size for a drink.
o You don't need to memorize the exact ranges; they can be easily found using
Byte.MIN_VALUE, Byte.MAX_VALUE, etc.
2. Decimal Numbers
o Data Types:
▪ float: Stores smaller decimal numbers and offers less precision (approx. 7
decimal digits).
▪ Requires an f suffix.
▪ double: Stores larger decimal numbers and offers more precision (around 15
decimal digits).
3. Characters (char)
o You can convert a char to an int to see its Unicode value (e.g., 'A' is 65).
o Range of char in Java is from 0 to 65535, allowing for a wide variety of characters
from different languages and symbols.
o Can also be represented using Unicode escape sequences (e.g., \u2764 for a heart
symbol).
4. Booleans (boolean)
The lecture also explains how data types are converted in Java:
o Occurs when converting a smaller data type to a larger, compatible data type.
o Examples:
o Examples:
• byte: 1 byte
• short: 2 bytes
• int: 4 bytes
• long: 8 bytes
• float: 4 bytes
• double: 8 bytes
• char: 2 bytes
• boolean: 1 bit
• Query successful
• Case Sensitivity
o Variable names in Java are case-sensitive. For example, amount and Amount would
be treated as two different variables.
o Using a variable with a different case than its declaration will result in an error, as the
system won't recognize it.
• Allowed Characters
o Variable names can include letters, numbers, underscores (_), and dollar signs ($).
• Starting Character
• Reserved Keywords
o Keywords like String, int, class, public, static, and void have special meanings in Java
and cannot be used for variable naming.
o There's no need to memorize all reserved keywords; you'll become familiar with
them as you code.
• Camel Case
o The first letter of the first word should be lowercase, and the first letter of
subsequent words should be uppercase.
• Meaningful Names
• Query successful
Arithmetic Operators
• Addition (+):
o When mixing data types (e.g., int and double), Java automatically converts the
smaller data type to the larger one to avoid data loss. For instance, an int will be
converted to a double if added to a double.
o Similarly, long values can be converted to float if the float can hold larger values due
to scientific notation, though this might lead to precision loss.
• Subtraction (-):
• Multiplication (*):
o Example: monthlyTotal * 12
o Be cautious when multiplying large numbers, as the result might exceed the range of
an int and require a long to prevent overflow.
o If one operand is a long, the other operand (even an int literal) will be automatically
promoted to long before multiplication.
• Division (/):
o Example: yearlyTotal / 3
o When dividing two integers, the result will also be an integer, truncating any decimal
part.
• Modulus (%):
o Returns the remainder of a division.
Operator Precedence
Operator precedence determines the order in which operations are performed in an expression.
• Multiplication (*), Division (/), and Modulus (%) have higher precedence than addition and
subtraction.
• If operators have the same precedence (e.g., multiplication and division), they are evaluated
from left to right.
• Increment (++) and Decrement (--) operators have the highest precedence.
These operators provide a shorthand for performing an operation and assigning the result back to
the same variable.
• Increment (++):
o Post-increment (a++): The value of the variable is used first, then incremented.
Java
int a = 99;
System.out.println(b); // Output: 99
o Pre-increment (++a): The value of the variable is incremented first, then used.
Java
int a = 99;
• Decrement (--):
o Post-decrement (a--): The value of the variable is used first, then decremented.
o Pre-decrement (--a): The value of the variable is decremented first, then used.
Comments
• In Java, two forward slashes (//) are used to create a single-line comment. Any text after //
on that line will be ignored by the compiler.
• Query successful
This lecture provides an in-depth explanation of bitwise operators in Java, covering their purpose,
how they work, and various types.
• Computers store data in binary (0s and 1s). For example, the integer 5 is stored as its binary
equivalent, 101.
• Bitwise operators are used to directly manipulate these individual bits (0s and 1s) of a
number.
• They are faster than arithmetic operators because they operate directly on the bits of a
number.
• Operands: Bitwise operations can only be applied to integral values such as byte, short, int,
and long. They cannot be used with decimal numbers (floating-point numbers) because their
bits are divided into parts (sign, exponent, significant), making direct manipulation difficult.
o Rule: The result bit is 1 only if both corresponding bits are 1; otherwise, it's 0. This
can be thought of as multiplication.
o Truth Table:
▪ 0&0=0
▪ 0&1=0
▪ 1&0=0
▪ 1&1=1
o Code Example:
Java
2. OR Operator (|)
o Rule: The result bit is 1 if at least one of the corresponding bits is 1; otherwise, it's 0.
o Truth Table:
▪ 0|0=0
▪ 0|1=1
▪ 1|0=1
▪ 1|1=1
o Code Example:
Java
o Rule: The result bit is 1 if the corresponding bits are different; otherwise, it's 0.
o Truth Table:
▪ 0^0=0
▪ 0^1=1
▪ 1^0=1
▪ 1^1=0
o Code Example:
Java
o Code Example:
Java
int c = ~a;
System.out.println(c); // Output: -6
o Purpose: Shifts the bits of a number to the left by a specified number of positions.
o Rule: Bits shifted off to the left are discarded, and zeros are filled in from the right.
o Code Example:
Java
Java
o Purpose: Shifts the bits of a number to the right by a specified number of positions.
o Rule: Bits shifted off to the right are discarded. The leftmost bit (sign bit) is filled with
the original sign bit (0 for positive, 1 for negative).
Java
Java
System.out.println(c); // Output: -2 (The leftmost bits are filled with 1s to preserve the negative sign)
o Purpose: Shifts the bits of a number to the right by a specified number of positions,
filling the leftmost bits with zeros, regardless of the original sign.
o Rule: Bits shifted off to the right are discarded, and zeros are always filled in from the
left.
o Difference from >>: Unlike >>, this operator does not preserve the sign of the
number. It always fills with zeros, potentially turning a negative number into a
positive one.
o Code Example:
Java
System.out.println(c); // Output: A large positive number (because the leading 1s are replaced by 0s)
This lecture covers the different ways to print output to the console in Java, specifically focusing on
System.out.println, System.out.print, and System.out.printf.
System.out.println
• Purpose: Used to print data to the console and then move the cursor to the next line.
• System Class: A class in Java that contains utility methods for interacting with the system's
runtime environment. This environment is the infrastructure provided by the JRE (Java
Runtime Environment).
• out: A static member of the System class that is connected to the console. It's used to print
anything to the console.
• Overloaded Methods: println has multiple overloaded versions, meaning it can accept
various data types as arguments (e.g., integers, characters, strings, long).
• Empty println(): Calling println() without any arguments will print a blank line.
Java
• Concatenation with +:
Java
int a = 1;
int b = 2;
Java
o When mixing strings and numbers, the numbers are converted to strings and then
concatenated.
Java
int a = 1;
int b = 2;
String c = "Sum";
System.out.println(c + a + b); // Output: Sum12 (c+a is evaluated first, then concatenated with b)
o Parentheses () can be used to control the order of operations due to their higher
precedence.
Java
String c = "Sum";
int a = 1;
int b = 2;
System.out.print
• Purpose: Similar to println, but it does not add a new line character at the end. The cursor
remains on the same line after printing.
Java
System.out.print(1); // Prints 1
// Output: 1xHello
System.out.printf
• Purpose: Provides formatted output, similar to the printf function in C. It allows for multiple
arguments and uses format specifiers as placeholders.
• No New Line by Default: Like print, printf does not add a new line character at the end. To
add a new line, use \n.
• Example:
Java
String c = "Sum";
int a = 1;
int b = 2;
System.out.printf("Character: %c, Float: %f\n", 'd', 1.2f); // Output: Character: d, Float: 1.200000
• Controlling Decimal Places: For floating-point numbers, you can specify the number of
decimal places using %.nf (where n is the number of decimal places).
Java
System.out.printf("Float with one decimal: %.1f\n", 1.2f); // Output: Float with one decimal: 1.2
System.out.printf("Float with two decimals: %.2f\n", 1.2f); // Output: Float with two decimals: 1.20
• Locale: printf can also take a Locale object as an argument to format numbers and dates
according to specific geographical conventions.
Java
import java.util.Locale;
// ...
• Query successful
This lecture focuses on the String data type in Java, contrasting it with primitive data types and
explaining its underlying structure and memory management.
• Definition: A String is a sequence of characters. Unlike single characters stored using char,
strings are used for multiple characters like names or city names.
• Declaration:
o Strings are declared using the String keyword, followed by a variable name, and the
value enclosed in double quotes.
o The video reviews primitive data types like int, char, and boolean.
o Key Difference: String is not a primitive data type; it is a class in Java. This means
String variables are reference variables, not directly storing the value like primitives.
• Class as a Blueprint: A class is a blueprint for creating objects. It defines the properties
(variables) and behaviors (methods) that objects of that class will have.
o Example: A Student class can have properties like name (String), address (String),
standard (int), and rollNumber (int).
• Object Creation: Objects are instances of a class. They are created using the new keyword.
o Example: Student student = new Student(); creates a new Student object.
• Accessing Object Properties: You can access an object's properties using the dot operator.
• Heap Memory: When an object is created using new, memory is allocated for it in the Heap
memory. The Heap is a portion of memory provided by the operating system for the JVM to
store objects.
• Reference Variables: When you declare a String variable (or any object), it's a reference
variable. It doesn't store the actual object but rather the memory address of where the
object is stored in the Heap.
o Contrast with Primitives: For primitive types (e.g., int a = 1;), the variable a directly
stores the value 1 in its allocated memory.
o Memory Behavior: Each time new String() is used, a new object is created in the
Heap memory, even if the string literal value is the same.
o Example:
Java
System.out.println(a == b); // Output: false (because 'a' and 'b' point to different memory locations)
o Memory Behavior: Java uses a special area in the Heap called the String Pool (or
String Constant Pool) for string literals.
▪ If a string literal already exists in the String Pool, Java reuses the existing
object and returns its reference.
▪ If the literal doesn't exist, a new object is created in the String Pool.
o Example:
Java
String c = "Ram";
String d = "Ram";
System.out.println(c == d); // Output: true (because 'c' and 'd' point to the same memory location in
the String Pool)
• The == operator, when used with String objects, compares their memory references
(addresses), not their actual content.
• To compare the actual content (equality of characters) of two strings, you should use the
.equals() method, which will be covered in the next video.
• The video demonstrates setting up a new Java project in IntelliJ IDEA to organize code
examples for different lectures.
• A TestStudent class demonstrates creating Student objects and accessing their properties.
• Query successful
This lecture provides a comprehensive guide to various String methods in Java. The instructor
explains each method with examples and demonstrates their usage.
• length():
o Example:
Java
System.out.println(length); // Output: 3
• charAt(int index):
Java
System.out.println(charAtIndex5); // Output: t
System.out.println(charAtIndex0); // Output: A
System.out.println(lastChar); // Output: a
• equals(String anotherString):
o Unlike ==, which checks for reference equality (if two objects are the same in
memory), equals() checks for content equality.
o Example:
Java
• equalsIgnoreCase(String anotherString):
o Example:
Java
• compareTo(String anotherString):
o The comparison is based on the difference in ASCII values of the first differing
characters.
o Example:
Java
System.out.println(str1.compareTo(str1)); // Output: 0
Java
• compareToIgnoreCase(String str):
o Example:
Java
String a = "Random";
String b = "random";
System.out.println(a.compareToIgnoreCase(b)); // Output: 0
• substring(int beginIndex):
o Returns a new string that is a substring of this string. The substring begins at the
specified beginIndex and extends to the end of the string.
o Example:
Java
o Returns a new string that is a substring of this string. The substring begins at the
specified beginIndex and extends to the character at endIndex - 1. The character at
endIndex is excluded.
o Example:
Java
System.out.println(name.substring(5, 8)); // Output: Pan (from index 5 up to, but not including, index
8)
• toUpperCase():
o Example:
Java
• toLowerCase():
o Example:
Java
• trim():
o Example:
Java
o Important Note: All string methods return a new string. The original string remains
unchanged because strings are immutable in Java. This immutability is crucial for
optimization, especially with the String Pool.
o Returns a new string resulting from replacing all occurrences of target with
replacement.
o Example:
Java
// Replacing a character
Java
• contains(CharSequence s):
o Returns true if this string contains the specified sequence of characters, false
otherwise.
Java
• startsWith(String prefix):
o Example:
Java
• endsWith(String suffix):
o Example:
Java
• isEmpty():
o Example:
Java
• isBlank():
o Returns true if the string is empty or contains only whitespace characters, false
otherwise. (Introduced in Java 11)
o Example:
Java
o Returns the index within this string of the first occurrence of the specified character
or substring.
o Example:
Java
System.out.println(name.indexOf("Pan")); // Output: 5
o Returns the index within this string of the last occurrence of the specified character
or substring.
o Example:
Java
o Returns the index of the first occurrence of the specified character or substring,
starting the search at fromIndex.
o Example:
Java
• String.valueOf(primitiveData):
o A static method that converts various primitive data types (like int, double, boolean,
char[]) to their string representation.
o Example:
Java
int a = 10;
o A static method used for formatting strings using placeholders, similar to printf in C.
o Example:
Java
o Example:
Java
Key Takeaways:
• Methods vs. Code: Methods are blocks of code that perform specific tasks.
• Accessing Methods: String methods are accessed using the dot operator (.) on a String
object (e.g., name.length()).
• String Immutability: Strings in Java are immutable. All methods that modify a string (like
toUpperCase(), replace(), substring()) return a new string, leaving the original string
unchanged. This is a fundamental concept and a common interview question.
• Static Methods: Methods accessed directly on the class name (e.g., String.valueOf(),
String.format()) are static methods.
Comments in Java:
• Single-line comment: //
This lecture covers conditional statements in Java, including relational operators, logical operators, if-
else statements, and switch-case statements.
Relational Operators
Relational operators compare two values and return a boolean result (true or false).
• Less Than (<): Checks if the left operand is less than the right operand.
o Example: a < b
• Greater Than (>): Checks if the left operand is greater than the right operand.
o Example: a > b
o Example: a == b
o For strings, == checks for reference equality (if they point to the same object in
memory), not value equality.
o Example: a != b
• Greater Than or Equal To (>=): Checks if the left operand is greater than or equal to the right
operand.
o Example: a >= b
• Less Than or Equal To (<=): Checks if the left operand is less than or equal to the right
operand.
o Example: a <= b
Relational operators can be used with various data types like integers, doubles, and characters. When
used with characters, their ASCII values are compared.
Logical Operators
• Logical AND (&&): Returns true if both conditions are true. If the first condition is false, the
second condition is not evaluated (short-circuiting).
o Example: (ramMarks >= 33) && (ramAge <= 18)
• Logical OR (||): Returns true if at least one condition is true. If the first condition is true, the
second condition is not evaluated (short-circuiting).
Conditional Statements
If-Else Statements
If-else statements allow you to execute different blocks of code based on a condition.
Java
• if-else statement: Executes one block of code if the condition is true and another block if it's
false.
Java
int age = 2;
} else {
• if-else if-else ladder: Used for multiple conditions. It checks conditions sequentially, and
once a condition is true, its block is executed, and the rest of the ladder is skipped.
Java
System.out.println("Grade A");
System.out.println("Grade B");
} else if (marks >= 60) {
System.out.println("Grade C");
} else {
System.out.println("Grade D");
Switch-Case Statements
Switch-case statements provide an alternative to long if-else if ladders when you have a single
expression to test against multiple possible values.
• Syntax:
Java
int day = 3;
case 1:
System.out.println("Monday");
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
System.out.println("Invalid Day");
• How it works: The switch statement evaluates the expression and jumps directly to the
matching case label.
• break statement: Essential to terminate a case block. Without break, the code will "fall
through" and execute subsequent case blocks until a break is encountered or the switch
block ends.
• default: Similar to the else block in if-else statements, the default block is executed if none of
the case values match the expression.
• Advantages:
o Cleaner and more maintainable code compared to long if-else if ladders.
• Supported Data Types: switch statements can be used with byte, short, char, int, String
(from Java 7), and enum.
• Unsupported Data Types: switch statements cannot be used with double or other floating-
point types due to precision issues. For these, if-else statements must be used.
This lecture provides a comprehensive overview of loops in Java, covering while, do-while, and for
loops, along with practical examples and concepts like nested loops, break, and continue statements.
• While Loop
• Do-While Loop
• For Loop
While Loop
• The code inside the while loop's block continues to execute as long as the specified condition
remains true.
Java
int i = 0;
System.out.println("Hello World");
i = i + 1; // or i++
o i is incremented inside the loop to eventually make the condition false and prevent
an infinite loop.
Java
int i = 1;
while (i <= 50) {
System.out.println(i);
i++;
Do-While Loop
• The do-while loop guarantees that the code block will execute at least once, even if the
condition is initially false. The condition is checked after the first execution.
Java
int i = 1;
do {
System.out.println(i);
i++;
For Loop
• The for loop is generally preferred for its structured approach, as initialization, condition, and
update are all defined within the loop's header.
Java
System.out.println(j);
• Advantages:
o Scope: Variables declared in the for loop's initialization are scoped to the loop,
preventing naming conflicts outside.
• Execution Flow:
Java
System.out.println(i);
o This example demonstrates declaring and updating multiple variables within the for
loop's header.
Java
Java
int sum = 0;
int i = 1;
sum = sum + i;
i++;
Java
int result = 0;
while (n > 0) {
n = n / 10; // Divides the number by 10, effectively removing the last digit
System.out.println(result); // Output: 8
Java
while (n > 0) {
r = r * n;
n--; // Decrement n
Nested Loops
• Example: Printing "Hello World" 100 times using two nested for loops
Java
int rs = 0;
// System.out.println("Hello World");
o The inner loop completes all its iterations for each single iteration of the outer loop.
Java
for (int j = 0; j <= i; j++) { // Controls the number of stars in each row
o The inner loop's condition (j <= i) depends on the outer loop's variable i, causing the
number of stars to increase with each row.
1. break Statement
o When break is encountered, the loop is exited, and execution continues with the
statement immediately following the loop.
Java
int i = 0;
System.out.println(i);
if (i == 500) {
i++;
o In nested loops, break only exits the innermost loop it is contained within.
2. continue Statement
o Used to skip the current iteration of a loop and proceed to the next iteration.
o When continue is encountered, the remaining code in the current loop iteration is
skipped, and the loop proceeds to the next iteration (checking the condition and
performing the update).
Java
int i = 1;
if (i == 5) {
System.out.println(i);
i++;
if (k == 5) {
System.out.println(k);
o The importance of manually updating the loop variable before continue in while
loops to prevent infinite loops. In for loops, the update part handles this
automatically.
Arrays in Java
This lecture provides a comprehensive overview of arrays in Java, covering 1D, 2D, and jagged arrays,
along with practical examples and explanations of their declaration, initialization, and traversal.
1. Introduction to Arrays
• Problem with individual variables: Storing a large number of similar data types (e.g., 1000
integers) using individual variables (e.g., int x = 1; int y = 2;) is inefficient and impractical.
• Solution: Arrays: Arrays allow storing a collection of similar kind of data together. For
example, int[] array = {1, 2, 3};.
• Purpose of Arrays: Arrays are used when you need a collection of similar data types.
• Declaration Syntax:
Java
type[] variableName;
o The type specifies the data type of elements in the array (e.g., int, char, String).
• Initialization Syntax:
Java
Java
o The array variable (e.g., arr) is a reference variable that stores the starting address of
the array in the heap. This reference variable itself is stored in the stack memory.
o Default values: When an array is initialized, its elements are automatically assigned
default values (e.g., 0 for int, null for String, false for boolean).
Java
• Array elements are accessed using their index, which starts from 0. Example: arr[0], arr[1],
arr[2].
• Assigning values: You can assign values to specific indices. Example: arr[0] = 89;
4. Traversing Arrays
• Using a for loop: This is the most common way to iterate through array elements.
Java
System.out.println(arr[i]);
o arr.length: This is a property (not a method) that returns the size of the array.
Java
System.out.println(element);
o This loop directly provides the element's value, not its index.
• Printing an entire array directly: Printing an array directly using System.out.println(arr); will
print its hash code, not its elements. Example output: [I@6e08ea8a
o [ indicates an array.
o I indicates integer type (other types like B for byte, C for char, D for double, F for
float).
• Searching an Element:
Java
if (element == target) {
System.out.println("Found");
This example uses a for-each loop to check for the presence of an element.
Java
arr[0] = 2;
arr[1] = 12;
arr[2] = 4322;
arr[3] = -32;
arr[4] = 22;
max = arr[i];
o Integer.MIN_VALUE is used to ensure any array element will be greater than the
initial max value, even if all elements are negative.
Java
System.out.println(arr[i]);
This loop iterates backward from the last index to the first.
Java
int[] arr = {-2, 4, 55, -4, 11, -55, -11, 2, 11}; // Example array
int sum = 0;
sum += element;
o This creates a 3x3 matrix initialized with default values (zeros for int).
Java
int[][] nums = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
• Traversing 2D Arrays (Nested Loops): To traverse a 2D array, you need nested for loops.
Java
7. Jagged Arrays
• Concept: Jagged arrays are 2D arrays where each row can have a different number of
columns (different lengths).
Java
o You first specify the number of rows, then initialize each row with its own length.
• Accessing and Traversing Jagged Arrays: The same nested loop structure used for regular 2D
arrays works for jagged arrays because arr[i].length dynamically gets the length of each inner
array.
Java
charArray[0][0] = 'A';
charArray[0][1] = 'B';
charArray[1][0] = 'C';
charArray[1][1] = 'D';
charArray[1][2] = 'E';
charArray[2][0] = 'F';
charArray[2][1] = 'G';
System.out.println();
This lecture provides an overview of Object-Oriented Programming (OOP) in Java, covering its core
concepts and four main principles.
What is OOP?
• Class: A blueprint for creating objects. In Java, everything is written inside a class.
• Object: An instance of a class. Anything you see around you (e.g., laptop, phone, bottle) can
be considered an object.
• Objects have two main characteristics:
o Properties (or Fields/Data): Attributes that describe the object (e.g., for a car: brand,
model, color, max speed). These are defined in the blueprint (class).
o Behavior (or Methods): Actions that the object can perform (e.g., for a car:
accelerate, brake). In Java, behaviors are implemented as methods.
Code Example: Car Class (Blueprint) The instructor demonstrates creating a Car class with properties
and methods:
Java
// Properties (Fields)
String color;
int speed;
String brand;
int year;
String model;
// Behaviors (Methods)
• Properties like color, speed, brand, year, and model are defined.
Code Example: Creating a Car Object In a Test class with a main method (the entry point of a Java
application):
Java
Car car = new Car(); // Creating a new Car object from the blueprint
car.brand = "Tata";
car.year = 2024;
car.model = "Safari";
System.out.println(car.speed); // Output: 41
1. Encapsulation
2. Abstraction
3. Inheritance
4. Polymorphism
1. Encapsulation
• Definition: Bundling data (fields) and methods that operate on the data into a single unit (a
class).
• It also involves data hiding, meaning restricting direct access to some of an object's
components.
• If a field is private, it cannot be directly accessed or modified from outside the class.
• To access or modify private fields, getters (to retrieve data) and setters (to modify data)
methods are used.
Java
// public void setModel(String model) { this.model = model; } // Removed to prevent model change
// public void setYear(int year) { this.year = year; } // Removed to prevent year change
speed++;
speed--;
• By making fields private, direct modification (e.g., car.year = 2030;) is prevented, leading to
compilation errors.
• The instructor demonstrates how specific setters (e.g., setModel, setYear) can be removed to
prevent certain properties from being changed after object creation.
2. Inheritance
• Definition: Allows one class (child/subclass) to inherit properties and behaviors from another
class (parent/superclass).
// Parent Class
String name;
int age;
// Child Class
String breed;
• This means a Cat object will automatically have name and age properties in addition to its
own breed property.
Java
cat.breed = "Persian";
• Even though name and age are not explicitly defined in Cat, they are accessible because Cat
inherits from Animal.
3. Polymorphism
• This means a subclass object can be assigned to a reference variable of its superclass type.
• It often involves method overriding, where a subclass provides a specific implementation for
a method that is already defined in its superclass.
Code Example: Polymorphism (Animal, Cat, Dog)
Java
// Superclass
System.out.println("Some sound");
// Subclass 1
System.out.println("Meow");
// Subclass 2
@Override
System.out.println("Woof");
Java
• Even though dog is an Animal type reference, when makeSound() is called, the Dog class's
makeSound() method is executed because the actual object created is a Dog.
4. Abstraction
• Definition: Hiding internal implementation details and showing only the necessary
information to the user.
• Real-life example: Using a TV remote. You press a button to change the channel without
needing to know the complex internal workings of the TV.
• Another example: Driving a car. You change gears without needing to understand the
internal mechanics of the engine and transmission.
This lecture serves as an introductory overview, with deeper dives into each concept planned for
future lessons. This lecture provides an overview of Object-Oriented Programming (OOP) in Java,
covering its core concepts and four main principles.
What is OOP?
• Class: A blueprint for creating objects. In Java, everything is written inside a class.
• Object: An instance of a class. Anything you see around you (e.g., laptop, phone, bottle) can
be considered an object.
• Objects have two main characteristics:
o Properties (or Fields/Data): Attributes that describe the object (e.g., for a car: brand,
model, color, max speed). These are defined in the blueprint (class).
o Behavior (or Methods): Actions that the object can perform (e.g., for a car:
accelerate, brake). In Java, behaviors are implemented as methods.
Code Example: Car Class (Blueprint) The instructor demonstrates creating a Car class with properties
and methods:
Java
// Properties (Fields)
String color;
int speed;
String brand;
int year;
String model;
// Behaviors (Methods)
• Properties like color, speed, brand, year, and model are defined.
Code Example: Creating a Car Object In a Test class with a main method (the entry point of a Java
application):
Java
Car car = new Car(); // Creating a new Car object from the blueprint
car.brand = "Tata";
car.year = 2024;
car.model = "Safari";
System.out.println(car.speed); // Output: 41
1. Encapsulation
2. Abstraction
3. Inheritance
4. Polymorphism
1. Encapsulation
• Definition: Bundling data (fields) and methods that operate on the data into a single unit (a
class).
• It also involves data hiding, meaning restricting direct access to some of an object's
components.
• If a field is private, it cannot be directly accessed or modified from outside the class.
• To access or modify private fields, getters (to retrieve data) and setters (to modify data)
methods are used.
Java
// public void setModel(String model) { this.model = model; } // Removed to prevent model change
// public void setYear(int year) { this.year = year; } // Removed to prevent year change
speed++;
speed--;
• By making fields private, direct modification (e.g., car.year = 2030;) is prevented, leading to
compilation errors.
• The instructor demonstrates how specific setters (e.g., setModel, setYear) can be removed to
prevent certain properties from being changed after object creation.
2. Inheritance
• Definition: Allows one class (child/subclass) to inherit properties and behaviors from another
class (parent/superclass).
// Parent Class
String name;
int age;
// Child Class
String breed;
• This means a Cat object will automatically have name and age properties in addition to its
own breed property.
Java
cat.breed = "Persian";
• Even though name and age are not explicitly defined in Cat, they are accessible because Cat
inherits from Animal.
3. Polymorphism
• This means a subclass object can be assigned to a reference variable of its superclass type.
• It often involves method overriding, where a subclass provides a specific implementation for
a method that is already defined in its superclass.
Code Example: Polymorphism (Animal, Cat, Dog)
Java
// Superclass
System.out.println("Some sound");
// Subclass 1
System.out.println("Meow");
// Subclass 2
@Override
System.out.println("Woof");
Java
• Even though dog is an Animal type reference, when makeSound() is called, the Dog class's
makeSound() method is executed because the actual object created is a Dog.
4. Abstraction
• Definition: Hiding internal implementation details and showing only the necessary
information to the user.
• Real-life example: Using a TV remote. You press a button to change the channel without
needing to know the complex internal workings of the TV.
• Another example: Driving a car. You change gears without needing to understand the
internal mechanics of the engine and transmission.
This lecture serves as an introductory overview, with deeper dives into each concept planned for
future lessons.
This lecture provides a comprehensive overview of methods in Java, covering their definition, syntax,
parameters, return types, method overloading, and variable arguments, along with practical
examples.
• They help in organizing code, reducing repetition, and making it easier to maintain and
modify.
• Instead of writing the same code multiple times, you can define it once in a method and call
it whenever needed.
• Example: Calculating the sum of two numbers or the sum of elements in an array. If you
need to perform these operations multiple times, writing the code repeatedly leads to
redundancy and makes changes difficult.
Method Syntax
Java
// Method Body
• Access Modifier: Specifies the visibility of the method (e.g., public, private). public means
the method can be accessed from any class, while private restricts access to the same class.
• Static Keyword: (To be covered later in the course). For now, if the main method is static,
other methods called within it must also be static.
• Return Type: The data type of the value the method returns. If the method does not return
any value, void is used.
• Parameters: A comma-separated list of input variables that the method accepts. These are
optional.
• Method Body: Contains the actual code that performs the method's task.
Examples of Methods
o Initially, the method prints the sum directly and does not return any value, hence
void is used as the return type.
Java
int sum = 0;
sum += i;
o This method can be called multiple times with different arrays without rewriting the
summation logic.
o To make the method more flexible, it can return the calculated sum as an int.
Java
int sum = 0;
sum += i;
// Or directly print:
Java
return str.trim().toUpperCase();
}
// Calling the method
Java
return a + b;
Method Overloading
• Method overloading allows multiple methods in the same class to have the same name but
different parameters.
o Number of parameters: e.g., sum(int a, int b) and sum(int a, int b, int c).
• Method Signature: Consists of the method name and its parameter list (types and order).
The return type and access modifiers are NOT part of the method signature.
Java
int sum = 0;
for (int i : a) {
sum += i;
return sum;
• Varargs eliminate the need to create separate overloaded methods for different numbers of
arguments.
o When a primitive data type (like int, double, boolean) is passed to a method, a copy
of its value is passed.
o Changes made to the parameter inside the method do not affect the original variable
outside the method.
Java
x = x * 10;
return x;
o However, String objects are immutable in Java. This means that any operation that
appears to modify a string (like toUpperCase()) actually creates a new string object.
Java
String a = "apple";
o When a custom object (like an instance of a Cat class) is passed, a copy of the
reference to that object is passed.
o Since objects are mutable, changes made to the object's properties (e.g.,
cat.setName()) through this copied reference will affect the original object in
memory.
Java
class Cat {
String name;
}
public static void makeCatNameUpperCase(Cat cat) {
a.setName("bob");
makeCatNameUpperCase(a);
o This is a crucial concept: while the reference itself is passed by value (a copy of the
memory address), the object at that memory address can be modified.
• This args array is used to receive command-line arguments passed to the Java application
when it is executed.
• Example:
Java
if (args.length > 0) {
This example demonstrates how to write a method to check if a given integer is a prime number.
return false;
// If a number has a divisor greater than x/2, it must also have a divisor less than x/2.
return false;
• Query successful
Recursion in Java
This lecture covers recursion, a programming concept where a method calls itself. The video explains
recursion by first demonstrating how to calculate the factorial of a number using a loop and then re-
implementing it using recursion.
Factorial Calculation
1. Iterative Approach (using a loop) The traditional way to calculate the factorial of a number n
involves a loop.
Java
• Base Case: The crucial part of a recursive function is the base case, which stops the
recursion. For factorials, 1! = 1.
Java
return 1;
This recursive implementation also yields 120 for factorial(5). The video demonstrates the execution
flow of this recursive call using a visual representation of function calls waiting for each other to
finish.
The video explains how recursion works with the call stack.
• This follows a Last-In, First-Out (LIFO) principle, similar to a stack of books or bricks.
For factorial(5):
10. factorial(5) receives 24, calculates 5 * 24 = 120, and returns 120 to main. This process shows
how calls are added to the stack and then resolved from top to bottom.
The video further illustrates recursion with another example: calculating the sum of the first n
natural numbers.
Java
return 1;
The video concludes by emphasizing that recursion is a fundamental concept for Data Structures and
Algorithms (DSA).
• Packages are essentially folders used to organize classes, similar to how you organize files
and folders on your computer.
• They help in differentiating classes with the same name. For example, you can have two Cat
classes in different packages (e.g., Test and Test2) without conflict.
• Every class in a package will have a package declaration at the top, indicating its location.
• Java has many pre-built packages like java.lang (which contains String and Math classes).
• The java.lang package is automatically imported, so you don't need to explicitly write import
java.lang.*. Other packages, like java.util.List, need to be explicitly imported.
• When creating an object of a class that exists in multiple packages, you'll be prompted to
choose which one.
• You can access a class by its fully qualified name (e.g., Test2.Cat).
• Alternatively, you can import the class using the import statement (e.g., import Test2.Cat;).
• If you import a class, and there's another class with the same name in a different package,
you'll need to use the fully qualified name to distinguish them (e.g., Test.Cat vs. Test2.Cat).
Class Path
• The class path is where the Java Virtual Machine (JVM) looks for compiled .class files.
• When running a Java program with packages from the command line, you need to specify
the correct class path.
• Example of running a Java class with a package from the command line:
o Compile: javac Test.java (This creates Test.class inside the Test package directory).
o If you are inside the Test directory and try to run java Test, it will fail because the
JVM looks for Test/Test within the current directory.
o To run it correctly, navigate one directory up (e.g., to src if Test is inside src).
o Then, run using the fully qualified name: java Test.Test. This tells the JVM to look for
the Test package and then the Test class within it.
o Alternatively, you can use the -classpath or -cp flag to specify where to find the
classes: java -cp . Test.Test (where . means the current directory).
• Classes that are not declared public within the same file are considered package-private.
This means they can only be accessed within the same package.
• Inner classes (nested classes) can be used to encapsulate classes within another class. To
create an instance of an inner class, you first need an instance of the outer class.
Java
// Inside Cycle.java
class Cycle {
// ...
class MiniCycle {
// ...
// To access MiniCycle from another class in the same package (e.g., Car.java)
The next lecture will cover access modifiers, which are closely related to packages.
• Query successful
What is Encapsulation?
Encapsulation is about bundling data (properties/fields) and methods (behaviors) that operate on the
data within a single unit (a class) and restricting direct access to some of the component's parts. This
means you control how data is accessed and modified, typically through methods.
Key Concepts:
• Class as a Blueprint: A class is a blueprint that defines the properties (data) and behaviors
(methods) of objects.
o Properties (Fields/Instance Variables): These describe the characteristics of an
object. For example, a Student class might have name, address, and roll number as
properties.
o Behaviors (Methods): These define what an object can do or how it interacts with its
data.
o Local Variable: Declared inside a method (e.g., String name inside main method).
o Instance Variable: Declared within a class but outside any method, attached to an
object of that class (e.g., String name inside Student class).
o public: Members declared as public can be accessed from anywhere. Methods used
to interact with private fields are typically public.
o Setters: Public methods used to set the value of a private instance variable. They
often include validation logic to ensure data integrity.
o Getters: Public methods used to retrieve the value of a private instance variable.
o Why use them? They provide a controlled way to access and modify data, allowing
you to implement validation and business logic centrally within the class.
Code Examples:
Java
class Student {
String name;
int age;
int rollNumber;
Problem: Direct access allows setting invalid values (e.g., negative age or roll number).
Java
class Student {
if (x < 0) {
} else {
this.age = x;
return this.age;
// Getters and Setters for name and rollNumber can be generated by IDE
return name;
}
public void setName(String name) {
this.name = name;
return rollNumber;
this.rollNumber = rollNumber;
Benefit: Centralized control over data modification, allowing for validation and preventing invalid
states.
This example demonstrates how encapsulation is used to manage bank account operations like
deposit and withdrawal with proper validation.
Java
class BankAccount {
return accountNumber;
}
this.accountNumber = accountNumber;
// Getter for balance (no setter for balance to prevent direct modification)
return balance;
if (amount > 0) {
this.balance += amount;
} else {
this.balance -= amount;
} else {
}
// In Test class (main method)
Result: The output shows the validation messages and the correct balance after operations. This
demonstrates how encapsulation ensures that bank account operations adhere to business rules.
Summary of Encapsulation:
• Data Hiding: Fields are made private to prevent direct external access.
• Controlled Access: Data is accessed and modified only through public methods (getters and
setters, or other behavior-specific methods like deposit and withdraw).
• Centralized Logic: Business rules and validation logic are contained within the methods of
the class, ensuring consistency and preventing errors.
• Maintainability: Changes to data representation or validation logic only affect the class itself,
not external code that uses the class.
• Query successful
This lecture focuses on constructors in Java, explaining their purpose, types, and how they are used
to initialize objects.
• A key characteristic of a constructor is that its name is the same as the class name, and it
has no return type.
Types of Constructors
1. Default Constructor
o Example:
Java
2. Parameterized Constructor
o Parameterized constructors allow you to initialize object fields with specific values
at the time of object creation.
o Example:
Java
String name;
int rollNumber;
int age;
// Parameterized Constructor
this.age = age;
this.name = name;
this.rollNumber = rollNumber;
o The this keyword is used to refer to the instance variables of the class, distinguishing
them from local parameters with the same name.
Constructor Overloading
• Constructor overloading means having multiple constructors in a class with the same name
(which is the class name) but with different parameter lists (different number of parameters
or different types of parameters).
• This allows for flexible object creation, where you can initialize an object with different sets
of initial values.
o Overloading the Default Constructor: You can define a default constructor that sets
specific initial values instead of the system defaults.
Java
String name;
int rollNumber;
int age;
public Student() {
Java
String name;
int rollNumber;
int age;
this.age = age;
this.name = name;
this.rollNumber = rollNumber;
this.name = name;
this.rollNumber = rollNumber;
Benefits of Constructors
• Reduces code: Allows for setting initial values in a single line during object creation, avoiding
multiple set method calls.
• Enforces conditions: Can include logic to validate initial values (e.g., ensuring age is not
negative).
• Query successful
This lecture on Inheritance in Java covers several key concepts, including different types of
inheritance, method overriding, constructor chaining, and the super keyword.
1. Introduction to Inheritance
• Inheritance is one of the four core principles of Object-Oriented Programming (OOP),
alongside encapsulation, polymorphism, and abstraction.
• It allows a class (child class) to inherit properties and behaviors from another class (parent
class), promoting code reusability and reducing redundancy.
2. Types of Inheritance
• Single Inheritance
Java
// Animal.java
// Dog.java
// Dog can have its own specific methods or override parent methods
Java
// Test.java
• Multi-Level Inheritance
o A class inherits from a parent class, which in turn inherits from another class,
forming a chain.
Java
// GrandParent.java
this.age = age;
this.name = name;
}
// Getters and Setters for name, age, and hasSuperPowers
// Parent.java
// Child.java
// Test.java
Child child = new Child(8, "Ram"); // Child's own age and name
child.childMethod();
• Hierarchical Inheritance
o Example: Dog and Cat classes both extending the Animal class.
Java
// Cat.java
System.out.println("Meow");
Java
// Test.java
}
3. Method Overriding
• Method overriding occurs when a child class provides a specific implementation for a
method that is already defined in its parent class.
• The method in the child class must have the same name, return type, and parameters as the
method in the parent class.
• Example: The Dog class overrides the sayHello() method from the Animal class.
Java
// Animal.java
// Dog.java
System.out.println("Woof");
• The @Override annotation is optional but highly recommended. It tells the compiler that the
method is intended to override a method in a superclass. If it doesn't, the compiler will
throw an error.
4. Constructor Chaining
• When an object of a child class is created, the constructors of its parent classes are implicitly
called in a chain, starting from the topmost parent.
• This ensures that the initial setup and properties of all superclasses are properly initialized
before the child class's constructor executes.
Java
// GrandParent.java
// Parent.java
// Child.java
// Test.java
// Output:
▪ The super() call must be the first statement in the constructor body. This
ensures that the parent class is fully initialized before the child class.
▪ If the parent class only has parameterized constructors, the child class must
explicitly call one of them using super() with appropriate arguments.
▪ This is useful when a child class has overridden a method, but you still want
to call the parent's implementation of that method.
• Java does not support multiple inheritance (a class extending more than one class).
o Example: If Smartphone could extend Camera and MusicPlayer, and both Camera
and MusicPlayer had a method with the same signature (e.g., powerOn()), the
Smartphone object wouldn't know which powerOn() method to call.
• Java solves this problem using Interfaces, which will be discussed in future lectures.
Java
// Phone.java
System.out.println("Calling...");
// MusicPlayer.java
System.out.println("Playing Music...");
// Camera.java
System.out.println("Clicked Photo");
// public class Smartphone extends Camera, MusicPlayer, Phone { // Not allowed in Java
// }
This lecture covers the concept of Polymorphism in Object-Oriented Programming (OOP), one of its
four core principles, along with encapsulation, inheritance, and abstraction.
What is Polymorphism?
Polymorphism allows methods to perform different actions based on the object they are acting
upon. The key characteristic is that the method name and signature remain the same, yet they
produce different results. The term "Polymorphism" itself means "many forms" (Poly = many, Morph
= forms).
Types of Polymorphism
o Decision Time: The decision of which method to call is made at compile time. The
compiler determines the correct method based on the arguments provided during
the method call.
o Example:
▪ Class: Calculator
▪ Methods:
Java
class Calculator {
return a + b;
return a + b + c;
return a + b;
class Main {
public static void main(String[] args) {
▪ In this example, the add method has "many forms" depending on the
parameters passed.
o Decision Time: The decision of which method to call is made at run time by the Java
Virtual Machine (JVM). This is also known as Dynamic Method Dispatch.
o Key Concept: Upcasting: You can create a reference of the parent class and assign it
an object of the child class.
o Example:
▪ Classes:
Java
class Animal {
@Override
System.out.println("Meow");
@Override
System.out.println("Woof");
System.out.println("Bye Bye");
class Test {
▪ Even though myDog and myCat are Animal references, the JVM determines
at runtime to call the sayHello() method of the actual object type (Dog or
Cat).
▪ Important Note: When using a parent class reference for a child class object
(upcasting), you can only access methods that are defined in the parent
class. You cannot call methods unique to the child class using the parent
reference.
Downcasting
• Definition: Downcasting is the process of converting a parent class reference to a child class
reference. This is typically done when you have an object that was originally a child class but
was upcasted to a parent class reference.
• Example:
Java
o This is similar to casting primitive data types, e.g., int e = (int) d; where d is a double.
Summary
What is Abstraction?
Abstraction is about hiding internal details and showing only the necessary functionalities. The video
uses the example of an AC remote: you can operate the AC (change temperature, mode, etc.)
without needing to know how the AC works internally.
Achieving Abstraction in Java
Abstraction in Java can be achieved using abstract classes and abstract methods.
Abstract Methods
• To declare a method as abstract, use the abstract keyword before the return type.
Java
Abstract Classes
• If a class contains one or more abstract methods, the class itself must be declared as
abstract.
Java
// Abstract method
// Concrete method
System.out.println("Animal is sleeping");
• Abstract classes can have both abstract and concrete (regular) methods. Concrete methods
have a definition/body.
• It is not mandatory for an abstract class to have abstract methods. You can have an abstract
class with only concrete methods, though this is less common.
• Cannot create objects (instantiate) of an abstract class. This is because abstract classes may
have methods without definitions, making it impossible to execute them if an object were
created.
• Can create references of an abstract class. These references can point to objects of their
concrete subclasses.
Java
Animal dog = new Dog(); // Animal is an abstract class, Dog is a concrete subclass
1. Implement all inherited abstract methods. If they don't, they must also be declared
as abstract.
• Problem without Abstraction: Initially, the Animal class had a sayHello() method with a
generic "..." implementation, which wasn't specific to any animal.
o Concrete subclasses like Dog and Cat extend Animal and provide their specific
implementations for sayHello().
Java
// Dog.java
@Override
System.out.println("Woof");
// Cat.java
@Override
System.out.println("Meow");
}
• Benefits: This approach forces subclasses to provide implementations for the abstract
methods, ensuring consistency and avoiding generic or meaningless implementations in the
parent class.
• Subclasses like Cycle and Car extend Vehicle and provide their specific implementations for
these methods.
• These constructors are primarily used for initial setup of common fields or logic that all
subclasses might need.
• private abstract methods are not allowed. If a method is private, it cannot be overridden by
subclasses, which defeats the purpose of an abstract method.
• protected abstract methods: A protected abstract method can be accessed within the same
package and by subclasses (even in different packages). This is useful when you want to
restrict access but still allow subclasses to implement the method.
Abstraction is useful when you have a generic parent class with many child classes. It allows you to
declare common functionalities in the parent class without providing a concrete implementation,
forcing the child classes to define their specific behaviors. This ensures that all subclasses adhere to a
defined structure and implement necessary methods.
This lecture covers Java access modifiers: Public, Private, Default, and Protected.
• Protected: Accessible within the same package and by subclasses (even in different
packages).
• Default: No keyword is used. Accessible only within the same package.
• Concept: Members (fields, methods, classes) declared as public can be accessed from any
other class, regardless of the package.
• Example:
o Student.java:
Java
package accessmodifier.school;
System.out.println("Hello");
o Test.java:
Java
package accessmodifier.test;
import accessmodifier.school.Student;
o Output: Hello
• Concept: Members declared as private are only accessible within the class they are declared
in.
o Student.java:
Java
package accessmodifier.school;
System.out.println("Hello");
o In Test.java, student.name = "Ram"; will cause a compilation error because name has
private access.
• Private Constructors:
o Use Case 1: Utility Classes: When a class only contains static methods and no object
creation is needed.
▪ Utils.java:
Java
package accessmodifier.school;
// Prevents instantiation
System.out.println("Bye");
▪ Test.java:
Java
package accessmodifier.test;
import accessmodifier.school.Utils;
o Use Case 2: Singleton Pattern: Ensures only one instance of a class is created
throughout the application.
▪ School.java:
Java
package accessmodifier.school;
return instance;
▪ Test.java:
Java
package accessmodifier.test;
import accessmodifier.school.School;
▪ Debugging shows that the constructor new School() is only called once.
• Concept: If no access modifier is specified, it's considered default (also known as package-
private). Members are accessible only within the same package.
o School.java:
Java
package accessmodifier.school;
• Concept: Members declared as protected are accessible within the same package and by
subclasses (even if the subclass is in a different package).
• Example:
Java
package accessmodifier.zoo;
this.name = name;
this.sound = newSound;
Java
package accessmodifier.zoo;
Java
package accessmodifier.test;
import accessmodifier.zoo.Dog;
• Key Point: A protected member can be accessed directly by a subclass (like Dog accessing
changeSound and sound), but not directly by an unrelated class in a different package (like
Test trying to access changeSound directly). However, it can be accessed by any class within
the same package, even if it's not a subclass.
Private Yes No No No No
Export to Sheets
• Clarification on Protected: The chart highlights that protected members are accessible
within the same package, even by non-subclasses. This is demonstrated by accessing
changeSound from a class in the same package as Animal, even if it doesn't extend Animal.
• Query successful
This lecture covers the static keyword in Java, explaining its use for memory management and how it
applies to variables, methods, and blocks.
• Class Part, Not Instance Part: When static is applied to a member (variable or method), it
becomes a part of the class itself, rather than an instance of the class. This means you can
access static members directly using the class name, without needing to create an object of
that class.
• Memory Management: static helps in memory management by ensuring that only one copy
of a static member exists, which is shared by all objects of that class. This prevents
redundant copies and saves memory.
Applying static
o Example: To count the number of Student objects created, a static int count variable
can be used. Each time a Student object is created (via its constructor), count is
incremented.
o Code Example:
Java
public Student() {
o If count were not static, each Student object would have its own count variable, and
it would always be 1 for each instance.
2. Static Methods:
o A static method can be called directly using the class name, without creating an
object.
o Example: A getCount() method can be made static to return the static count variable.
o Code Example:
Java
count++;
o Restrictions:
▪ Static methods cannot directly use non-static data members or call non-
static methods. This is because non-static members belong to an object, and
a static method is called on the class itself, without an object context.
▪ this and super keywords cannot be used within a static context because they
refer to the current object and parent object, respectively.
3. Static Blocks:
o It is primarily used for static initialization, especially when complex logic is required
to initialize static variables.
o Code Example:
Java
static {
}
// Other fields and methods
// When Student class is used (e.g., Student.getCount()), the static block runs
o Static blocks are useful for one-time setup tasks, such as establishing a database
connection in a DatabaseManager class.
• Utility Classes: Classes that contain only static methods are often called utility classes (e.g.,
Math class in Java). These methods perform common, reusable operations that don't require
an object instance.
o Example: A Utils class with max() and min() methods to find the maximum or
minimum of two numbers.
o Code Example:
Java
if (a > b) {
return a;
} else {
return b;
if (str != null) {
return str.trim().toUpperCase();
} else {
return "";
}
// Usage
• Singleton Design Pattern: static is crucial for implementing the Singleton design pattern,
which ensures that a class has only one instance and provides a global point of access to it.
o This is achieved by making the constructor private and providing a public static
method to return the single instance of the class.
o Code Example:
Java
private static School instance = new School(); // Single instance created when class loads
private School() {
// Usage
This lecture explains the final keyword in Java, which can be applied to variables, methods, and
classes, with different implications for each.
Final Variables
• Purpose: The final keyword makes a variable a constant, meaning its value cannot be
changed once initialized.
• Example:
Java
public class Car {
o If you try to change a final variable after initialization, it will result in a compile-time
error.
o Attempting to generate a setter for a final variable will show that it's not possible.
• Initialization:
Java
static {
Java
public Car() {
Final Methods
• Purpose: When a method is declared final, it cannot be overridden by any subclass. This is
useful for enforcing specific behavior that should not be altered by subclasses, such as safety
features.
• Example:
Java
System.out.println("Four airbags");
// @Override
// }
Final Classes
• Purpose: When a class is declared final, it cannot be extended by any other class. This
prevents inheritance and ensures that the class's implementation remains unchanged.
• Example:
Java
// Class implementation
// // Class implementation
// }
o Trying to extend a final class will result in a compile-time error, stating that it cannot
inherit from a final class.
Final Constructors
• Reasoning:
o Constructors are used to initialize the state of an object.
o Constructors are not inherited or overridden in the same way as regular methods; a
subclass has its own constructor, which may call the parent's constructor using
super().
o Applying final to a constructor would not serve any meaningful purpose and is not
allowed by the Java compiler.
This set of lectures covers fundamental concepts in Java Object-Oriented Programming (OOP),
including Encapsulation, Constructors, Inheritance, Polymorphism, Abstraction, Access Modifiers, the
static keyword, the final keyword, and Interfaces.
Here are the summarized notes and code examples from each lecture:
1. Encapsulation in Java
https://youtu.be/ifJ0eCrEC44?list=PLA3GkZPtsafY62QhQ030p85HAer0pFDdr
Key Concepts:
• Local vs. Instance Variables: Local variables are inside methods; instance variables are inside
a class but outside methods.
• Getters and Setters: Public methods to control access and modification of private instance
variables, often including validation.
Java
class Student {
if (x < 0) {
System.out.println("Invalid Age");
this.age = 0;
} else {
this.age = x;
return this.age;
student.setAge(15);
System.out.println(student.getAge());
2. Constructors in Java
https://youtu.be/uCAaTvO7dn0?list=PLA3GkZPtsafY62QhQ030p85HAer0pFDdr
What are Constructors? Special methods used to initialize objects. They are automatically called
when an object is created, helping set initial values for fields. A constructor's name is the same as the
class name, and it has no return type.
Types of Constructors:
Constructor Overloading: Having multiple constructors in a class with the same name but different
parameter lists.
Java
String name;
int rollNumber;
int age;
public Student() {
// Parameterized Constructor
this.age = age;
this.name = name;
this.rollNumber = rollNumber;
this.name = name;
this.rollNumber = rollNumber;
3. Inheritance in Java
https://youtu.be/CGHL1zuD5fY?list=PLA3GkZPtsafY62QhQ030p85HAer0pFDdr
What is Inheritance? Allows a class (child/subclass) to inherit properties and behaviors from another
class (parent/superclass), promoting code reusability.
Types of Inheritance:
• Single Inheritance: One child class inherits from one parent class.
Method Overriding: A child class provides a specific implementation for a method already defined in
its parent class.
Constructor Chaining: When a child object is created, parent constructors are implicitly called in a
chain from the topmost parent.
The super Keyword: Refers to the immediate parent class. Used to:
Multiple Inheritance (Not Supported in Java): Java does not support a class extending more than
one class to avoid the "Diamond Problem." This is solved using Interfaces.
Java
// Animal.java
System.out.println("...");
// Dog.java
@Override
System.out.println("Woof");
// Test.java
4. Polymorphism in Java
https://youtu.be/TRlz0X5hD7E?list=PLA3GkZPtsafY62QhQ030p85HAer0pFDdr
What is Polymorphism? Allows methods to perform different actions based on the object they are
acting upon, while the method name and signature remain the same. Means "many forms."
Types of Polymorphism:
1. Compile-Time Polymorphism (Method Overloading): Multiple methods with the same name
but different parameters within the same class. The decision of which method to call is made
at compile time.
• Downcasting: Converting a parent class reference back to a child class reference (e.g., Dog
actualDog = (Dog) myDog;).
Java
class Animal {
System.out.println("...");
@Override
System.out.println("Meow");
@Override
System.out.println("Woof");
System.out.println("Bye Bye");
class Test {
5. Abstraction in Java
https://youtu.be/W0Qv4UkCo6k?list=PLA3GkZPtsafY62QhQ030p85HAer0pFDdr
What is Abstraction? Hiding internal details and showing only necessary functionalities.
Achieving Abstraction:
• Abstract Methods: Methods with a declaration but no body, using the abstract keyword.
Implementation is provided by subclasses.
• Abstract Classes: A class containing one or more abstract methods must be declared
abstract. Can have both abstract and concrete methods.
Key Rules:
Java
// Concrete method
// Dog.java
@Override
System.out.println("Woof");
// Cat.java
@Override
System.out.println("Meow");
// Test.java
Animal dog = new Dog(); // Reference to abstract class, object of concrete subclass
https://youtu.be/ZlUuQIw-a9U?list=PLA3GkZPtsafY62QhQ030p85HAer0pFDdr
Overview: Control the visibility and accessibility of classes, fields, and methods.
• Public: Accessible from anywhere.
• Protected: Accessible within the same package and by subclasses (even in different
packages).
Java
package accessmodifier.school;
System.out.println("Hello");
package accessmodifier.test;
import accessmodifier.school.Student;
https://youtu.be/qfMOfbhVpB0?list=PLA3GkZPtsafY62QhQ030p85HAer0pFDdr
Key Concepts:
• Class Part, Not Instance Part: Static members belong to the class, not to individual objects.
• Memory Management: Only one copy of a static member exists, shared by all objects.
2. Static Methods: Called directly using the class name. Cannot directly use non-static members
or this/super.
3. Static Blocks: Executed when the class is loaded, used for static initialization.
Java
public Student() {
// Usage
https://youtu.be/CYBDq23Uzt0?list=PLA3GkZPtsafY62QhQ030p85HAer0pFDdr
Java
Java
System.out.println("Four airbags");
Java
// ...
Final Constructors:
• Constructors cannot be declared final. They are not inherited or overridden in the same way
as methods.
9. Interfaces in Java
https://youtu.be/PpxzFint1IA?list=PLA3GkZPtsafY62QhQ030p85HAer0pFDdr
What is an Interface? A blueprint for a class, used to achieve multiple inheritance and pure
abstraction.
Key Characteristics:
• No constructors.
• Can only contain abstract methods and static constants (implicitly public, static, final).
Interface Features (Java 8+):
• Static Methods: Belong to the interface, called directly using the interface name.
• Default Methods: Have a default implementation within the interface, can be overridden by
implementing classes.
Achieving Multiple Inheritance: A class can implement multiple interfaces, allowing it to inherit
functionalities from multiple sources.
void playMusic();
void stopMusic();
void endCall();
@Override
@Override
}
@Override
@Override
This video provides an in-depth explanation of four types of inner classes in Java: Member Inner
Class, Static Nested Class, Local Inner Class, and Anonymous Inner Class.
• Concept: A class defined inside another class, where the inner class is a member of the outer
class. It is associated with an instance of the outer class.
o The Car class has model (String) and isEngineOn (boolean) fields.
o The Engine class has start() and stop() methods that interact with the isEngineOn
field of the outer Car class.
Java
class Car {
this.model = model;
this.isEngineOn = false;
}
class Engine { // Member Inner Class
if (!isEngineOn) {
isEngineOn = true;
} else {
if (isEngineOn) {
isEngineOn = false;
} else {
Java
engine.start();
engine.stop();
}
• Benefit: Allows the inner class to directly access members (fields and methods) of the outer
class instance. It establishes a strong association between the inner and outer class
instances.
• Alternative (without Inner Class): If not using an inner class, the Engine class would need to
explicitly take a Car instance in its constructor to access Car's properties, leading to more
verbose and less encapsulated code.
• Concept: A static class defined inside another class. Unlike member inner classes, it belongs
to the outer class itself, not to an instance of the outer class.
Java
class Computer {
this.brand = brand;
this.model = model;
class OperatingSystem {
this.osName = osName;
this.type = type;
Java
os.displayInfo();
usb.displayInfo();
• Benefit:
o No Instance Dependency: Does not require an instance of the outer class to be
created.
o Memory Management: Prevents unnecessary memory allocation for the inner class
if the outer class instance is created but the inner class is not used.
o Grouping: Useful for logically grouping classes that are related but don't depend on
an outer class instance.
• Concept: A class defined inside a method or a block of code. Its scope is limited to the
method or block where it is defined.
Java
class Hotel {
this.name = name;
this.totalRooms = totalRooms;
this.reservedRooms = reservedRooms;
if (numberOfRooms <= 0) {
return false;
return false;
return true;
if (validator.validate()) {
reservedRooms += numberOfRooms;
System.out.println("Reservation confirmed for " + guestName + " for " + numberOfRooms + "
rooms.");
} else {
System.out.println("Reservation failed.");
Java
• Benefit:
o Contextual: The class is only relevant within the method it's defined in.
o Access to Method Parameters: Can access final or effectively final local variables and
parameters of the enclosing method.
Java
interface Payment {
Java
class ShoppingCart {
this.totalAmount = totalAmount;
paymentMethod.pay(totalAmount);
}
Java
cart.processPayment(new Payment() {
@Override
});
• Benefit:
o No Naming Overhead: Avoids the need to create a separate named class file for a
simple, one-off implementation.
The video concludes by summarizing when to use each type of inner class:
• Member Inner Class: When the inner class is strongly associated with and depends on an
instance of the outer class.
• Static Nested Class: When grouping related classes together, but the inner class does not
depend on an instance of the outer class.
• Local Inner Class: When a class's functionality is specific to a single method and its scope
should be limited to that method.