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

Install Notepad++ and Java Setup Guide

The document provides setup instructions for Java programming, including installation of Notepad++ and Java, along with coding rules and best practices. It explains the structure of Java classes, methods, variables, and the importance of the main method in program execution. Additionally, it covers object creation, memory structure, and the differences between instance and local variables, emphasizing coding conventions and error handling in Java.

Uploaded by

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

Install Notepad++ and Java Setup Guide

The document provides setup instructions for Java programming, including installation of Notepad++ and Java, along with coding rules and best practices. It explains the structure of Java classes, methods, variables, and the importance of the main method in program execution. Additionally, it covers object creation, memory structure, and the differences between instance and local variables, emphasizing coding conventions and error handling in Java.

Uploaded by

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

Java Notes -April 2025

April 19, 2025 11:10 AM

Setup Instructions [2025-04-19 ]


• Install Notepad++
• Follow the Java Installation video link (
JAVA download link :
[Link]

*Video guide* : Watch the setup in action:


[Link]

Rules for Java Programming


1. Java code must always be written inside a class.
2. Requirement: Create a class Student with name and roll number as variables, and ensure they are
printable.

Class Essentials
• class is a keyword (must be lowercase)
• Class name should:
○ Start with a capital letter
○ Be relevant to the content
• Example: class Student { ... }

Variables in Java
• Used to store data like name and roll number.
• Must be declared inside the class.
• Must have:
○ Meaningful names
○ Data types
• Examples:
String name = "techno"; // String type
int rno = 1; // Integer type

Coding Best Practices


• Use camelCase for variable names: stdRollno, stdRollnoInfo
• Follow proper indentation for clarity
• Use:
○ {} for class/method body
○ () for method calls/conditions
○ [] for arrays: int[] numbers = new int[5];
○ <> for generics: List<String> names = new ArrayList<>();

Saving and Compiling Java Code


• Save the file using double quotes with .java extension in Notepad++ (e.g., "[Link]")
• Compile with:

javac [Link]
• This creates a .class file if there are no syntax errors.

Java- April 2025 Page 1


1. Navigating to the correct folder [Refer image 1]

D:\TechnoCredits\Projects\APR25>

This is where your [Link] file is saved. You're already in the right directory.
2. Compiling the Java file [Refer image 2]
javac [Link]
○ javac is the Java compiler command.
○ [Link] is the Java source file you're compiling.
○ If there are no syntax errors, the command simply returns to the prompt without any error
message.

3. Successful Compilation [Refer image 3]


The final prompt appears with no errors:

D:\TechnoCredits\Projects\APR25>

This means a file named [Link] (compiled bytecode) has now been created in the same folder.

Next Step: Run the Program


To run your Java class (if it has a main method), type:
java Student

==========Java method explained===================

What is a Method in Java?


A method in Java is a block of code that performs a specific task. You can think of it like a function in
other programming languages.
We usually write the business logic inside the method. That means: what we want our program to
do—like print something, calculate values, store data, etc.

Basic Structure of a Method


Java- April 2025 Page 2
Basic Structure of a Method

returnType methodName(parameters) {
// method body (logic)
}

Method Components Explained


Part Explanation
method name You define this. It should be meaningful. Example: printStudentInfo
return type This tells Java what the method gives back. Use void if it doesn’t return anything
parameters These are optional. Inputs you give the method. Example: (int rollNo, String name)
body The code block between { } where logic is written

Example: Student class with a method:

class Student {
String name = "Techno";
int rno = 1;

// Method to print student info


void printStudentInfo() {
[Link]("Student Name: " + name);
[Link]("Roll Number: " + rno);
}
}

Example 1: Method with no parameters and does not return anything

void sayHello() {
[Link]("Hello, welcome to Java!");
}
Example 2: Method with parameters and does not return anything
void printStudentInfo(int rollNo, String name) {
[Link]("Roll Number: " + rollNo);
[Link]("Name: " + name);
}
Example 3: Method with return type

int add(int a, int b) {


return a + b;
}
========Java main method ==============================
Java- April 2025 Page 3
========Java main method ==============================
Java main Method Explained

public static void main(String[] args) {


// Code to run the program goes here
}

Breaking It Down:
Keyword Purpose
public Means this method is accessible from anywhere. Required for the JVM to access it.
static Allows the JVM to call the method without creating an object of the class.
void The method doesn’t return any value.
main The name of the method that Java looks for to start the program.

String[] args Accepts command-line arguments as a String array. It's optional to use them.

✅ Example: Basic Java Program with main

class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, Java!");
}
}

Output:

Hello, Java!
==============================More details ====================================
JVM and the main Method:
The Java Virtual Machine (JVM) is the engine that runs your Java programs.
When you run a Java program (like using java Student), here's what happens:
1. The JVM looks for the main method in the class you specified.
2. Execution starts from the main method.
3. Any other methods or logic are only executed if they are called from main.

Why This Matters:


Without a main method, the JVM doesn’t know where to begin, and you'll get an error like:
Error: Main method not found in class Student

✅ Quick Reminder: Proper main Method Syntax

public static void main(String[] args) {


// your program logic starts here
}
✅ public - So JVM can access it
✅ static - No object needed to call it
✅ void - It doesn’t return anything
✅ main - Special name the JVM looks for
✅ String[] args - Accepts input from the command line (optional to use)

Java- April 2025 Page 4


=======================Memory Structure of object ==================================

This is a fantastic visual explanation of how Java works with objects and memory. Let’s break it down
to fully understand what’s happening in this diagram and code:

✅ Code Breakdown
class Student {
String name = "techno";
int rno = 1;
void display() {
[Link](name);
[Link](rno);
}
public static void main(String[] args) {
Student s = new Student(); // Step 1: Object creation
[Link](); // Step 2: Method call using the object
}
}

Step-by-Step Flow:
main method (entry point)
• JVM starts execution from main.
• This is shown with the red 1 circle in the image.
Student s = new Student();
• A new object s of class Student is created.
• This object is stored in memory (RAM), and it holds:
○ name = "techno"
○ rno = 1
○ display() method
○ 's' is the reference to the object. This is marked with red 2 in the code and orange line in the
drawing.

[Link]();
• Calls the display() method using object (reference) s.
• Inside display(), it prints:
Output: techno
• 1
• The green arrow shows how s points to the memory where the values and method exist.

2025-04-20

✅ Q: After creating the object, can you access the methods and variables?

Java- April 2025 Page 5


✅ Q: After creating the object, can you access the methods and variables?
Yes! Once an object is created, you can access:
Methods
• Directly using the object.
[Link]();
Variables
• You can access them directly too using the object reference.
[Link]([Link]); // prints "techno"
[Link]([Link]); // prints 1

This is often done inside SOP ([Link]), especially for printing.

Then why use a method like display() at all?


Great question—and here's the real value:
Purpose of Methods in Java
1. Code Reusability
○ You write once, use many times.
○ Instead of repeating:

[Link]([Link]);
[Link]([Link]);

again and again, just call: [Link]();

2. Improved Maintainability (Lower Maintenance Cost)


○ If logic needs to change (e.g., add / formatting), change it only inside the method.
○ No need to search and update in multiple places.
3. Better Readability & Organization
○ Methods break code into meaningful blocks, making it easier to understand and debug.
4. Scalability
○ You can add parameters, return values, conditions inside methods as your app grows.

What Happens When You Print an Object Reference?


Example:
[Link](s);
Output (something like):
Student@6d06d69c
✅ This is the memory address (hashcode) where the object is stored, not the actual data.

Student s1 = new Student();

Explanation:
Java- April 2025 Page 6
Explanation:

Part Meaning
Student Class name → This is the reference type.
s1 Reference variable → Refers to an object of type Student.
new Student() Creates a new object of the Student class in memory.

✅ So putting it together:
• Student → is the reference type (also known as class type).
• s1 → is the reference variable (holds the memory address of the object).
• new Student() → creates the actual object in memory (in the heap).
And then s1 points to that memory location (object), which contains all the data (like name, rno,
etc.).

Bonus Tip:
You can create multiple objects and each will have its own copy of the instance variables:

Student s1 = new Student();


Student s2 = new Student();
Now s1 and s2 are two separate objects, even though they are of the same class.

Concatenation in Java (in SOP Statements):


✅ You can concatenate:
• String + String
• String + int
• String + any data type (Java automatically converts it to a string using .toString() internally)

Example 1:
[Link]("Employee id is " + empId);
[Link]("Employee name is " + empName);
• empId is an int
• empName is a String
• The + operator is used to join or concatenate the message with variable values.

Example 2 (combined):

[Link]("Employee name is " + empName + " and Employee id is " + empId);


• Combines two variables with custom text into a single print statement.
• Output will look like:
Employee name is Credits and Employee id is 123

Why is this useful?


• It makes your output readable and dynamic.
• Great for logging, debugging, and user messages.

Object creation and method calling :

Java- April 2025 Page 7


This image is an excellent visual breakdown of how object creation and method calling work in Java.
Let's walk through the marked numbers to clarify everything step by step:

Code & Diagram Explanation:

Employee employee = new Employee();


• ✅ This creates an object of the Employee class.
• employee is a reference variable pointing to the object in memory.

[Link]();
• ✅ This calls the display method using the reference variable employee.

void display() { ... }


• ✅ This is the method definition.
• It contains logic to print the employee details.

[Link]("Employee name is " + empName + " and Employee id is " + empId);


• ✅ This prints both the name and ID using string concatenation.
• Java handles both String and int here seamlessly.

• Marks the opening curly brace { of the Employee class.


• Shows where everything begins.

• Shows the method call [Link](); again, emphasizing object method invocation.

• Marks the closing brace } of the main method or the class (depending on indentation, but likely
the method here).

Memory Diagram (Right Side Box):


• Visualizes what’s stored in memory (RAM).
• The object contains:
○ empId = 123
○ empName = "Credits"
○ Method display()
The arrow shows how the reference variable (employee) points to this memory structure.

What is an Instance Variable in Java?


An instance variable is a variable that is:
• Declared inside a class, but
Java- April 2025 Page 8
• Declared inside a class, but
• Outside of any method, constructor, or block.

Key Characteristics:
• Each object of the class gets its own copy of the instance variable.
• They are created when an object is created and destroyed when the object is destroyed.
• They do not need to be initialized explicitly—they get default values if not assigned.
• They can have different values for different objects.

✅ Example:
class Student {
String name = "Techno"; // Instance variable
int rno = 1; // Instance variable
void display() {
[Link](name);
[Link](rno);
}
}
Here:
• name and rno are instance variables.
• Each time you do new Student(), a new copy of name and rno is created in memory for that
object.

Local Variables in Java


A local variable is a variable that is:
• Declared inside a method, constructor, or block.
• Created when the method is called and destroyed once the method finishes.

Key Characteristics:
• Scope is limited to the block/method in which it's declared.
• You must initialize a local variable before using it — Java won't assign default values like it does
with instance variables.
• They cannot have access modifiers like public, private, etc. [By default, it is already private to the
method in which it is declared and used]
• Stored in stack memory.

✅ Example:

class Demo {
void show() {
int x = 10; // local variable
[Link]("x = " + x);
}
}
Here, x is a local variable:
• It is accessible only within the show() method.
• Once show() is finished, x is gone.

Comparison of Local and Instance Variable:


Feature Instance Variable Local Variable
Declared in Class (outside methods) Inside methods or blocks

Java- April 2025 Page 9


Declared in Class (outside methods) Inside methods or blocks
Lifetime As long as object exists Until method execution ends
Default value Yes No, must initialize
Scope Entire class (with object) Only inside the method
Stored in Heap memory Stack memory

Perfect image to explain local vs instance variables — this example makes it crystal clear!

Code Breakdown:
class Example1 {
int num = 10; // Instance variable

void processData() {
int num = 100; // Local variable
[Link](num); // Prints 100 (local variable shadows instance variable)
}

void display() {
[Link](num); // Prints 10 (instance variable)
}
}

✅ Output:

100 // from processData()


10 // from display()

What’s Happening?
• Inside processData(), a local variable num = 100 is declared, which shadows the instance variable
(num = 10). That’s why it prints 100.
• In display(), there’s no local num, so it accesses the instance variable, which is 10.

Conclusion:
• Local variable has priority over the instance variable inside its method/block.
• Scope matters — Java chooses the closest variable in the scope hierarchy.

Duplicate Variables in Java


You cannot declare two variables with the same name in the same scope, even if their data types
are different.

❌ Example of Duplicate Variable:


public class Test {
Java- April 2025 Page 10
public class Test {
public static void main(String[] args) {
String num = "Amruta";
int num = 100; // ❌ Compile-time error: variable 'num' is already defined
}
}
Why?
Java identifies variables by name within a given scope, not by type. So "num" is already taken —
declaring it again, even with a different type, causes a compile-time error.

✅ Valid Version (Different Scopes):


public class Test {
String num = "Amruta"; // Instance variable
public static void main(String[] args) {
int num = 100; // ✅ This is fine — different scope (inside main method)
[Link](num); // Prints 100
}
}
Here, the instance variable and local variable can have the same name, but they exist in different
scopes, so it's allowed.

Code Breakdown:

class Example2 {
int num = 10; // Instance variable

void updateNum() {
num = num + 10; // Increases instance variable 'num' by 10
}

void display() {
[Link](num); // Prints the updated value of 'num'
}

public static void main(String[] args) {


Example2 example2 = new Example2(); // Step 1: Object creation
[Link](); // Step 2: num = 10 + 10 = 20
[Link](); // Step 3: Outputs 20
}
}

✅ What’s Happening in the Memory (as shown in the diagram):


Java- April 2025 Page 11
✅ What’s Happening in the Memory (as shown in the diagram):
• An object example2 is created — a block of memory is allocated.
• Inside this block:
○ num is initialized to 10.
○ updateNum() adds 10 → now num = 20.
○ display() prints the updated value → 20.

Key Concepts Reinforced:


• num is an instance variable, so it belongs to the object.
• updateNum() modifies the instance variable directly.
• No local variable shadowing here — only the instance variable is in action.

Example 2:

Great! This above code snippet demonstrates local vs instance variable behavior beautifully.

What's Different Now?


Inside updateNum():

int num = num + 10;


This creates a local variable named num, which shadows the instance variable num. So, the right-
hand side num refers to the instance variable (10), and a new local num (with value 20) is created —
but it's not stored in the object!

Important Concept:
If you declare a variable inside a method with the same name as an instance variable, the
method uses the local one, not the instance variable.
So the instance variable num is never actually updated. It remains 10 the entire time.

Output Trace:
Here’s how the main method executes:

[Link](); // prints 10
[Link](); // local num = 20 (no effect on instance variable)
[Link](); // prints 10 again
[Link]();
[Link]();
[Link](); // still prints 10

✅ Final Output:
10 10 10

Java- April 2025 Page 12


10 10 10

Important Concept:

Local value has to be initialized each time before using it. Whereas, instance variable has default
value of the type it is [data type] i.e. 0

Instance Variable example Local Variable example


class Example { class Demo {
int num; // instance variable void test() {
→ default is 0 int x; // local variable
// [Link](x); ❌ Compile-time error: variable x
void show() { might not have been initialized
[Link](num); // x = 5;
prints 0 [Link](x); // ✅ OK
} }
} }

This diagram does a great job showing how instance variables work with different objects in Java.
Let’s break it down in a clear way:

✅ Code Summary:
You have a class Example4 with:

int num1 = 10;


Java- April 2025 Page 13
int num1 = 10;
int num2 = 20;

And two methods:


• processData() updates both instance variables.
• display() prints them.

What's happening:

Example4 example4_1 = new Example4(); // Object 1


Example4 example4_2 = new Example4(); // Object 2
example4_1.processData(); // Only modifies data of example4_1
example4_1.display(); // Outputs: 30 : 30
example4_2.display(); // Outputs: 10 : 20 (unchanged)

Key Concepts Highlighted:


• Every time you use new, a new object is created in memory (as shown in the green & pink
diagrams).
• example4_1 and example4_2 have their own copies of num1 and num2.
• Calling processData() on example4_1 does not affect example4_2.

Why This Matters:


This demonstrates:
• Encapsulation – each object manages its own state.
• Instance Isolation – changes made through one object don’t affect others unless shared explicitly.

String concatenated with anything is String itself


The output of this program:

[Link](num1 + num2 + " is answer");


Ans: 3 is answer

Why?
• num1 = 1, num2 = 2
• num1 + num2 = 3 (Integer addition)
• Then "3" + " is answer" → String concatenation

Key Concept:
When any number is concatenated with a String, the whole expression becomes a String.
Java handles it like this:
1. num1 + num2 → 3 (still an int)
2. 3 + " is answer" → "3 is answer" (String)

One more example for concatenation:

Java- April 2025 Page 14


Another example for instance and local variables :

✅ Concept Highlighted: Instance vs Local Variables


Instance Variables

int num1; // Default: 0


int num2; // Default: 0
String name; // Default: null
• Declared at class level → Automatically initialized
• Default values if not explicitly set:
○ int → 0
○ String → null

Local Variables

int input = 100;


• Declared inside a method
• Must be explicitly initialized before use
• Exists only within the method scope

Current Flow:

Example6 example6 = new Example6();


[Link](); // Calls display() method
Since updateValue() is never called:
• num1, num2, and name remain at their default values
• Output will be:

0:0:null

If you call [Link](); before display();


Then output becomes:

100:200:null
Because updateValue() assigns new values to num1 and num2.

Java- April 2025 Page 15


Because updateValue() assigns new values to num1 and num2.

Calculator Program:

Write a program for calculator having add, sub, mul, div [Link] :

Addtion of 10 and 2 is 12
Subtraction of 10 and 2 is 8
Multiplication of 10 and 2 is 20
Div of 10 and 2 is 5Total is : 45

Bank Assignment: 2

Assignment - 2 : 20th April'2025Create a class called Bank.


Have one instance variable called balance, initial balance is 1000 rs.
Create a method to debitAmt, creditAmt, [Link] method will debitAmt by 500 rs.
createAmt method will creditAmt by 200 [Link] :
debitAmt()
creditAmt()
creditAmt()
printBalance()
creditAmt()
printBalance()
debitAmt()
printBalance()output :
Remaning balance is 900
Remaning balance is 1100
Remaning balance is 600

Assignment - 3 : 20th April'2025


Create a class called EmployeeDetails,
empid, empFirstName, empLastName, [Link] a method to initialised empid,
empFirstName, empLastName, empSalary.

Java- April 2025 Page 16


empFirstName, empLastName, empSalary.
create a method to update empSalary.
salary should be updated by 2000 rs.
printDetail method should print all the details of [Link] :
Employee id is 123
Employee first name is Maulik
Employee last name is Kanani
Employee current salary is 7000

2025-04-21

[Link]

What is a Static Variable?


A static variable belongs to the class itself, not to any one object.
All objects share the same copy of the static variable.
✅ So if one object changes the static variable, all other objects see that change!

Analogy: Static Variable = School Name


Imagine you're creating a class called Student.
Each student (object) has a name and roll number (instance variables).
But all students go to the same school. The school name is shared – that's a static variable!

class Student {
String name;
int rollNo;
static String schoolName = "ABC High School";
}
Now, if you change schoolName for one student, all others are affected because it’s shared.

Use Static When:


You want to use the variable without creating an object.
You want a single shared value (like PI, companyName, bankName, etc.)

✅ Summary Table:
Feature Instance Variable Static Variable

Belongs to Object Class

Memory Per object Once per class


allocated
Access via [Link] [Link]
Shared between ❌ No
Java- April 2025 Page 17
Shared between ❌ No ✅ Yes (all objects)
objects

STATIC (Shared) class Example8 { Key Concepts:


--------------- static int x = 10; // static → shared 1. Static Variable (x)
x (starts at 10) across all objects
ex8_1.processData() int y = 100; // instance → static int x = 10;
→ x = 11 separate for each object • Shared across all instances of the class.
ex8_2.processData() • Modifying x in one object affects the value for
→ x = 12 void processData() { all objects.
x = x + 1; // modifies shared x • In processData(), x is incremented: x = x + 1.
INSTANCE y = y + 1; // modifies 2. Instance Variable (y)
(Separate) individual y
------------------- } int y = 100;
ex8_1 → y = 100 → • A separate copy is maintained for each object.
y = 101 void display() { • Modifying y in one object does not affect the
ex8_2 → y = 100 → [Link](x + ":" + y); value in another.
y = 101 } • In processData(), y is also incremented: y = y +
1.
public static void main(String[] args)
{ What happens during execution?
Example8 ex8_1 = new Step-by-step:
Example8(); // Object 1
ex8_1.processData(); // x= Example8 ex8_1 = new Example8();
11, y=101 (for ex8_1) ex8_1.processData(); // x = 11, y (of ex8_1) = 101
Example8 ex8_2 = new Example8();
Example8 ex8_2 = new ex8_2.processData(); // x = 12, y (of ex8_2) = 101
Example8(); // Object 2 ex8_1.display(); // prints 12:101
ex8_2.display(); // prints 12:101
ex8_2.processData(); // x=
12, y=101 (for ex8_2)
• Both display() calls show x = 12 because it's
ex8_1.display(); // prints 12:101 static and was incremented twice.
ex8_2.display(); // prints 12:101 • y = 101 for both instances, because each got
} their own y incremented once after object
} creation.

Output:
Java- April 2025 Page 18
Output:

12:101
12:101

Static Variable Access – Best Practice:


Static variables belong to the class, not to instances, so they are accessed using class name.

Example10.x // ✅ Recommended
ex10.x // Not recommended (though it works)

static int x = 10; Execution Flow:


int y = 20; 1. [Link](); // x = 20, y = 22
2. [Link](); // x = 30, y = 24
void updateData() { 3. [Link](); // prints 30:24
x = x + 10; 4. [Link](); // x = 40, y = 26
y = y + 2; 5. [Link](); // prints 40:26
}
Another new object • x (static) is already 40
Example10 ex10_1 = new Example10(); • y (instance) = 20 (default for new object)
6. ex10_1.updateData(); // x = 50, y = 22
7. ex10_1.display(); // prints 50:22
8. [Link](); // prints 50:26
Java- April 2025 Page 19
8. [Link](); // prints 50:26

Key Rule:
Non-static (instance) variables are always accessed using a reference variable of the class
because they belong to objects, not the class itself.
class Student {
int rollNo = 1; // non-static
static String school = "ABC School"; // static
}

public class Test {


public static void main(String[] args) {
Student s1 = new Student();
[Link]([Link]); // ✅ Correct
[Link]([Link]); // ✅ Correct

// [Link]([Link]); ❌ Error! Can't access instance variable via class


name
}
}
Summary:
Type Accessed by Belongs to
static [Link] Class (shared)
non-static [Link] Object instance

Control Statement in JAVA:

Java compiler executes the code from top to bottom. The statements in the code are executed
according to the order in which they appear. However, Java provides statements that can be used
to control the flow of Java code. Such statements are called control flow statements. It is one of
the fundamental features of Java, which provides a smooth flow of program.

Java provides three types of control flow statements.


1. Decision Making statements
○ if statements
Simple if statement: if you need to write only a single statement inside the if statement
then curly brackets {} are not required.
If you need to write multiple statements are there then
○ If-else statement

○ switch statement [pending]


2. Loop statements
○ do while loop [pending]
while loop [pending]
Java- April 2025 Page 20
○ while loop [pending]
○ for loop [done]
○ Enhanced for loop
3. Jump statements
○ break statement : it breaks the loop [and not the if condition ;)
○ continue statement : it continues the loop i.e. increment / decrement the index and checks
the condition and continues.
If-else

If-else ladder

Syntax of if-else-if Ladder

if (condition1) {
// block 1: executes if condition1 is true
} else if (condition2) {
// block 2: executes if condition2 is true
} else if (condition3) {
// block 3: executes if condition3 is true
} else {
// default block: executes if none of the above conditions are true
}

Example: Grade Evaluation

public class GradeChecker {


public static void main(String[] args) {
int score = 75;
if (score >= 90) {
[Link]("Grade: A");
} else if (score >= 80) {
[Link]("Grade: B");
} else if (score >= 70) {
[Link]("Grade: C");
} else if (score >= 60) {
[Link]("Grade: D");
} else {
Java- April 2025 Page 21
} else {
[Link]("Grade: F");
}
}
}
Output:
Grade: C

Key Points:
• Conditions are evaluated top to bottom.
• As soon as one condition is true, the block executes, and the rest are skipped.
• The last else is optional, used to handle cases when none of the conditions are true.

Java Control Flow Rules for if and else


✅ 1. if block alone is allowed
You can write just an if block without needing an else.

if (x > 0) {
[Link]("x is positive");
}

✅ 2. if-else and nested if-else are allowed


You can use if with else, or nest multiple if-else blocks.

if (x > 0) {
[Link]("Positive");
} else {
[Link]("Not positive");
}
Nested Example:

if (x != 0) {
if (x > 0) {
[Link]("Positive");
} else {
[Link]("Negative");
}
}

❌ 3. else block alone is NOT allowed


You cannot use else without a matching if. Java will throw a compile-time error.

// ❌ Invalid:
else {
[Link]("This will cause an error");
}

Why?
The else clause must always be tied to a preceding if. Java needs to know what condition the else is
the alternative to.

Java- April 2025 Page 22


• 2025-04-28
• Static variables:
○ Belong to the class itself, not to any specific object.
○ Loaded into memory once when the class is first loaded by the JVM (Java Virtual Machine).
○ Accessible without creating an object (can be accessed using [Link]).
• Instance (non-static) variables:
○ Belong to a specific object (instance) of the class.
○ Loaded into memory when an object is created.
○ Each object gets its own copy of the instance variables.
• Local variables:
○ Declared inside a method, constructor, or block.
○ Loaded into memory only when the method/block is loaded into memory.
○ Exist only during the method execution; they are destroyed after the method finishes.

Q. Does JVM require object to load main method in memory ?


No, since the main method is loaded into the static area when the class loads and hence does not
require object creation.
class is loaded into the memory when
1. run the class
2. object is created

• method to method calling is allowed


• non-static to non-static direct calling is allowed
• static to non-static direct calling is not allowed.
• We need object to access the non -static from the static

Return Type in Methods


The return type of a method specifies the type of value the method will return after it finishes
executing. It is defined before the method name in the method signature.
If a method performs a calculation or operation and needs to send the result back to the caller, a
return type is used.

Example:

Java- April 2025 Page 23


class Calculator {
int add(int num1, int num2) {
int total = num1 + num2;
return total; // returns an integer
}
}
In the example:
• int is the return type.
• The method add takes two int parameters (num1 and num2) and returns their sum.
• The return type has no dependency on the parameters—it's determined by what the method
actually returns.

Using the Return Value:


To use the returned value from a method, you must store it in a variable of the same type as that
of the return type:

Calculator calc = new Calculator();


int result = [Link](5, 7); // 'result' stores the returned int value

If a method does not return any value, its return type is declared as void.

Return Statement and Compiler Checks


When a method has a non-void return type, the Java compiler checks all possible execution paths
within the method to ensure that a value is returned on every path.

If there's even one path where control could reach the end of the method without a return
statement, the compiler throws a compile-time error (CE).

Example – Valid:

int getValue(boolean flag) {


if (flag) {
return 10;
} else {
return 20;
}
}
✅ All paths return a value → No compile-time error.

Example – Invalid:

int getValue(boolean flag) {


if (flag) {

Java- April 2025 Page 24


if (flag) {
return 10;
}
// Missing return for the 'else' path
}

❌ Not all paths return a value → Compile-time error

So, the compiler ensures that every possible route through the method results in a return
statement when the return type is not void.

Q. Can we have class name and file name different?





Ans : You can have the class name and file name different. The problem starts when we have
multiple files then it would be difficult to track the exact file when you need to make changes in the
file as the .CLASS and .java filename does not match

Q. Can we have multiple java classes in a single java file?





Ans : Yes, we can but the problem is two .CLASS files will be created ,but it would be difficult to fix
the errors as it would be difficult to track the .CLASS and it's associated java file

Q. Can we have 2 different java files with the same name [one in small case and another in Capital
file]
Ans : No, OS does not allow to create 2 files with the same name no matter which case it is.
But, while compiling the file or running the file it is case sensitive i.e. you cannot do like file [Link]
and while running you are trying to rum with a name as abc [not allowed]

Bonus Tip: Even same name folder is not allowed in the system.

Q. Why we set the java path in the path variable?


Ans : For OS to find the java executable path. This will help the OS to find it which will further run
the file as and when executed.

Q. What if there are 2 Java installed on your ?


Ans : It will pick up the later one

Q. When there are 2 java versions and we want to use the later one in the path variable
In that case, will JAVA-HOME help??
Ans : No, still it will pick the first one. The solution to it is replace the both the versions with
Java- April 2025 Page 25
Ans : No, still it will pick the first one. The solution to it is replace the both the versions with
%JAVA-HOME%\bin

Access Modifiers: [private, default, protected and public ]


default and private will never go outside the package
yes, there would be CE when you narrow down the scope of the variable and methods in a class
on the other hand there would be no CE when you broaden the scope of the variables and
methods.
protected members are accessible when in both the classes are in parent-child relationship
class A protected m1() --> will be accessible in p2.B class when B is the child of class A [which is
in p1 package]
-----------------------------------------------
Object Oriented Programming [OPPs]
Encapsulation:
Binding of data members (variables) and member functions (methods) together in a single entity
(class) is known as encapsulation.
class Employee{
String empid;
String empName;
void display(){
sop(empid +" -> "+ empName);
}
}
Java by default provides encapsulation but encapsulation should be proper.
Here, it is not proper encapsulation because the methods and variables can be accessed by any
other client class by creating the object of Car class and can set any value which might disobey the
agreement of BMW standards.
Hence, to achieve proper encapsulation, we should make the variables private and putting if
conditions to verify that the speed cannot be negative and should not exceed the max speed (if
any) set by BMW



Inheritance [ 6 cases]

Deriving properties from parent class to child class or from super class to sub class.
-> extends keyword is used to create parent child relation.
-> A extends B .... A is a child class, B is a parent class

Inheritance Advantages:
Code Reusability
Ability to change the behaviour during runtime [Overriding]
Hence, we can say that Inheritance and Overriding are inter-dependent
Java- April 2025 Page 26
Hence, we can say that Inheritance and Overriding are inter-dependent

Case Case Case 3 : Case Case Case 6 :


1: 2: A a = new B(); // Dynamic
Polymorphism
4: 5: case 6 :

A a = new B b = new B b = new A a = new A a = new B();


A(); B(); sop(a.x); // 10 A(); B(); B b = new B();
sop(a.x); sop(a.y); // 12 [properties A b = new
// 10 sop(b.x); do not change, hence 12 sop(b.x); A(); b = (B)a;
sop(a.y); // 10 of class A] sop(b.y);
// 12 sop(b.y); sop(b.z); //A a = sop(b.x);
sop(a.z); // 20 a.m1(); // A m1 new A(); sop(b.y);
// CE sop(b.z); a.m2(); // B m2 [behaviour b.m1(); //A b = sop(b.z);
// 30 changes during run time, b.m2(); new B();
a.m1(); // hence child class B will be b.m3(); b.m1();
A m1 b.m1(); // executed] a = b; b.m2();
a.m2(); // A m1 b.m3();
A m2 b.m2(); // a.x; // 10
a.m3(); // B m2 a.y; // 12
CE b.m3(); // a.z; // CE double num1 = 10; // 8 bytes
B m3 int x = num1;
a.m1(); //
A m1
a.m2();//
A m2
a.m3(); //
CE

b is of child type and a is of type parent, hence, in


case 6, though LHS is creating the object of child
but the reference type is of parent which is getting
assigned to child reference. This is not logically
possible.



-----ClassCastException Example-------------------------------
Admin = parent
College = child
Admin a = new Admin();
College c = new College();
c= (College) a; // this will throw ClassCastException during run time as admin can not be typecast to
College

1) All eligible data members of parent class is traversed into child class. Eligible means child doesn't
have same data members and is visible (accessible).

Java- April 2025 Page 27


2) A a = new B(); //can take guarantee from parent class but executes child class
3) B b = new A(); CE after type casting will get runtime error

Checks:
Is explicit type casting required to remove the CE?

But, does that helps during execution [JVM should allow]


If it creates invalid statement, then will get [Link]

b = (B)a;
B b = new A();

Garbage Collection : when the reference count of any object is zero, then it is ready for garbage
collection. This comes into picture when the CPU schedules the GC process then these will be
removed from the memory.

Anonymous object - when a object is created without capturing it in a reference variable then that
object is called Anonymous object. It is allowed and can be used only once.
If next time you wish to call any other method of the class then you need to create a new object
[either Anonymous or with reference]
When multiple calling is required then we should use reference variable to capture the object
which can be used for further multiple calls.

Increment / Decrement Operators:


Post Increment --> Use the current value and then increment the value by 1.
Pre Increment --> First increment the value by 1 and then use
Post Decrement --> Use the current value and then decrement the value by 1.
Pre Decrement --> First decrement current value by 1 and then use it

Polymorphism [Overloading & Overriding]

One name multiple forms:


2 imp concepts:
A. Overloading :
• Always happen in same class.
• Method name must be same.
• Parameters must be different [number of parameters or sequence of parameters must be
different or type of parameters must be different]
• return type can be anything
• access non modifier can be anything [static, final]
• implementation can be same or different

Advantage: To give seamless experience to the user.




Java- April 2025 Page 28



B. Overriding:


To prove that the method is overridden:
• Create 2 classes A[Parent] and class B[Child] in parent-child relationship.
• Write overridden methods in both the classes.
• Creates the possibility of object creation using Dynamic Polymorphism .
• Now, call the overridden method.
• If the behaviour of child class method is executed then it shows that the method is overridden.

Example:
WebDriver driver = new ChromeDriver();
ChromeDriver will override the methods of WebDriver
ChromeDriver can have it's own methods as well.
While overriding the class to follow the overriding rules.

In the above example, there is a ambiguity situation while calling the method.
Indirect Overloading Example:


12/05/2025:
protected access modifier:
• two classes should be in parent-child relationship.
• protected members should be accessed in a protected way i.e. on the object of child class. [never
on parent class object]
• If you want to override the method then you need to make sure that the signature is exact same.
Here, the access modifier should be either same or wider than that of the class.

Best Practice: to write the @Override annotation as it gives clarity that the method overridden and
improves the readability of the code.

Checks:

Java- April 2025 Page 29


Checks:
-> class should be visible first.
--> If method is not visible then you can never override that method

@Override Annotation: It is used when in child class and parent class have the same method but
the parent class method is protected then use @Override method to inform the compiler to check
for all the rules of Override else throw error

Multilevel Inheritance:
All rules of inheritance will follow but in multiple levels.



All the classes in Java are in the hierarchy of Object class.


We need not to import the [Link] package. It is invisibility imported by compiler.

'final' keyword:

• final is keyword and its an access non modifer.


• final keyword is applicable on variable, method and class.
• variable is final, we can not change the value of that variable.
• instance and local variables can be declared as 'final'

✅ 1. final variables:
When a variable is declared as final, it means its value cannot be changed once assigned.
If a class is declared as final, it cannot have subclasses (extended), but that does not make its
variables final by default.

Example:

final class FinalClass {


int x = 10; // NOT final
}
You can change x:

FinalClass obj = new FinalClass();


obj.x = 20; // This is allowed, because x is not declared as final
Example:

Java- April 2025 Page 30


class Builder{

public static final String GSTNumber = "AB123NV";


}
class Test{
final int x = 10;

void m1(){
sop(x);
x++; // CE you cannot change the value of the final variable.
}
}

class Client{
main(){
Test test = new Test();
int temp = test.x; // here, you can access it
temp++; // you are allowed to increment because you have stored it in another variable and
making changes into it.
}
}

Correction:
"Variables of a final class are not final unless explicitly declared final."

✅ 2. final methods:
• When a method is declared as final, it cannot be overridden in a subclass.
• Methods in a final class are not implicitly final, but they cannot be overridden anyway, because
you can't have a subclass of a final class.

Correction:
"final methods are not implicitly final unless you declare them so, but if the class is final,
overriding is not possible."

Example:

final class FinalClass {


void method1() {} // Not final, but cannot be overridden because the class is final
final void method2() {} // Explicitly final
}

✅ Summary:
Element What final means
final variable Cannot be reassigned once initialized
final method Cannot be overridden
final class Cannot be extended (no subclasses)

Q. Can we declare local variables as private and final?


Ans : No, as local variable are already private to the method in which it is declared.
Final - Yes, which means even reassignments are not allowed with in the method.
Java- April 2025 Page 31
Final - Yes, which means even reassignments are not allowed with in the method.

Examples below:

class Test{
int x = 1;

void m1(){
final int x = 1000;
x = x + 10; //CE
sop(x);
}

void display(){
x++;
sop(x);
}

void processData(){
int x = 1;
x++;
sop(x);
}
}

Imp 'final' --> final method cannot be overridden but can be


overloaded as the signature would change .
class Manager{ class Employee extends class JrEmployee extends
Manager{ Employee{
final void encryption(){
@Override @Override
} void encryption(){ void encryption(){

final void m1(){ } }


} }
}

void m1(int x){

Java- April 2025 Page 32

Common questions

Powered by AI

Anonymous objects in Java are used when a single-use, temporary instantiation is sufficient, eliminating the need for a named reference variable. This can be effective in scenarios like passing an object to a method that performs one-time operations. However, because anonymous objects do not have named references, they are generally eligible for garbage collection after use, promoting efficient memory management . The trade-off is a lack of multiple usages, thereby necessitating re-creation for repeated operations, which can be less efficient compared to using a persisted reference .

In Java, instance variables are automatically initialized with default values based on their data types, such as 0 for ints and null for Strings, if not explicitly assigned . This means that even if an instance variable is not initialized by the programmer, it has a definite value upon object instantiation. In contrast, local variables inside methods do not receive any default values and must be explicitly initialized before use . This requirement ensures that any attempt to use a local variable without initialization results in a compile-time error, encouraging explicit handling of values within method scope and enhancing code safety by preventing uninitialized usage .

In Java, when local and instance variables share the same name, scope hierarchy dictates that the local variable takes precedence within its defined scope . This is because Java selects the closest variable based on the scope hierarchy principle. If a variable is declared within a method block, it shadows the instance variable of the same name, meaning the local value is used within that block. This demonstrates a key principle of encapsulation and scope priorities in Java, where variable resolution follows a specific hierarchy that ensures method-local variables override class-level declarations when accessed within the method .

Polymorphism in Java allows methods to perform differently based on the object type that invokes them, facilitating dynamic execution at runtime. This is achieved through method overriding, where a subclass provides a specific implementation of a method already defined in its superclass. For example, if class B extends class A and both have a method m2(), the object created as A a = new B() uses A's reference but calls B's m2() during execution, demonstrating runtime polymorphism . This enables code flexibility and reuse, allowing behavior modification without altering code structure .

Encapsulation in Java involves bundling data members and methods together within a class and controlling access through access modifiers. Without using proper access modifiers like 'private', data members and methods are exposed to external access, potentially violating encapsulation by allowing arbitrary external interactions . Additionally, failing to implement validation conditions for class member operations can breach the intended logic or constraints of a class, such as exceeding set speed limits in a car class. Proper encapsulation ensures that internal state is neither accidentally nor maliciously altered, thus maintaining object integrity and respecting design contracts .

Java implements method overloading by allowing the same method name to be used with different parameter signatures within the same class. This can involve differences in parameter number, types, or order. The advantage of method overloading is that it provides a seamless user experience, enabling methods to perform related but varied operations based on input, thus allowing for intuitive method calls without remembering distinct method names for each variant . This reduces cognitive load on developers and enhances API usability by adhering to a coherent naming strategy while supporting diverse functionalities .

Type casting in Java's inheritance model allows an object reference to be transformed between compatible types (parent to child and vice versa). While upward casting (casting to a parent type) is generally safe, downward casting (parent to child) requires explicit casting and can result in a runtime error if the object being cast does not actually instantiate the target type. This is known as ClassCastException, which occurs when the inherent properties of an object do not align with the expected subclass properties . This potential issue emphasizes the importance of proper type checking in polymorphic behavior to avoid runtime exceptions, ensuring that type casting only captures intended class hierarchies .

Java initializes instance variables with default values specific to their data types if no explicit initialization occurs: ints to 0, booleans to false, and object references (e.g., Strings) to null . This feature is important because it ensures that every instance variable has a set state upon object instantiation, reducing the risk of uninitialized variable errors. Thus, developers can rely on a level of predictability regarding an object's state, which enhances code robustness and reduces runtime errors from unassigned values .

Protected members in Java are accessible within their defining class, subclasses, and other classes in the same package. This access level facilitates inheritance by allowing subclasses to use and extend superclass members without exposing them to the broader package as public would. It supports encapsulation by limiting visibility to related classes, enhancing modular design within a package . Inherited protected methods promote reusability while maintaining controlled exposure, adhering to the principles of inheritance and encapsulation within object-oriented programming .

To ensure proper encapsulation in a Java class, developers should declare class variables as private, preventing direct external access. This means those variables can only be accessed or modified through public or protected getter and setter methods, which encapsulate the underlying data. These accessor methods should include validation logic to enforce invariant conditions or business rules, thereby preventing illegal state modifications. Such practices not only protect internal state integrity but also abstract complexity, allowing controlled access to class members while adhering to encapsulation principles .

You might also like