Java


Generated image

📘 Java Topic 1: What is Java?


🔹 Java Definition

Java is a high-level, object-oriented, platform-independent programming language used to develop software, web, desktop, mobile, and automation tools.

📖 Nepali Insight:
Java एकदमै popular programming language हो जुन एकपटक लेखेर धेरै platform मा चलाउन सकिन्छ (write once, run anywhere concept)।


🔹 Why Java is Important for QA Engineers

Reason QA Use
Selenium Support Most Selenium frameworks use Java
Test Frameworks TestNG, JUnit built in Java
Backend Testing Used in REST API, database layers
OOP Concepts Important for Page Object Model
Industry Demand Java QA jobs are in high demand

🔹 Java Program Structure Example

java

CopyEdit

public class HelloWorld {

    public static void main(String[] args) {

        System.out.println(“Hello, Lok!”);

    }

}

📖 Explanation:

  • public class HelloWorld: Class name
  • main(): Entry point
  • System.out.println(): Print to console

🔹 Key Java Features

Feature Description
Object-Oriented Everything is based on objects
Platform Independent Compile once, run anywhere (via JVM)
Strongly Typed Every variable must have a type
Multithreaded Supports parallel execution
Secure & Robust Built-in memory management

🔹 Basic Java Terms

Term Meaning
Class Blueprint or template
Object Instance of a class
Method Action performed (like function)
Variable Stores value
Data Type Type of data (int, String, boolean)

📘 Java Topic 2: Data Types, Variables, and Operators


🔹 What is a Variable?

A variable is a container in memory that stores data. You can change the value stored in it during program execution.

📖 Nepali View:
Variable भन्नाले data राख्न प्रयोग गरिने memory को नाम हो। यो changeable हुन्छ।

🧠 Example:

java

CopyEdit

int age = 30;

String name = “Lok”;


🔹 Types of Variables in Java

Type Description
Local Variable Defined inside a method
Instance Variable Defined inside a class but outside any method
Static Variable Shared by all objects (declared with static)

🔹 What is a Data Type?

A data type defines the type of value a variable can hold (integer, decimal, character, etc.).

📖 Nepali Insight:
Data Type ले variable भित्र कस्तो प्रकारको value राख्न सकिन्छ भनेर define गर्छ


✅ Java Data Types

🔸 1. Primitive Data Types (8 total)

Type Size Example Use
int 4 bytes int age = 25; Whole number
float 4 bytes float pi = 3.14f; Decimal with f
double 8 bytes double salary = 9999.99; Large decimal
char 2 bytes char grade = ‘A’; Single character
boolean 1 bit boolean status = true; True/False
byte 1 byte byte x = 100; Small number
short 2 bytes short y = 30000; Medium number
long 8 bytes long z = 123456789L; Big integer with L

🔸 2. Non-Primitive Data Types

Type Description Example
String Text String name = “Lok”;
Array Multiple values int[] nums = {1, 2, 3};
Class Custom type Person lok = new Person();

🔹 Java Operators

Operators are symbols that perform operations on variables and values.

📖 Nepali Insight:
Operator भन्नाले कुनै काम गराउने चिन्ह हो, जस्तै जोड्ने, घटाउने, compare गर्ने आदि।


✅ Types of Operators

Category Operators Example
Arithmetic +, -, *, /, % a + b, a % b
Relational ==, !=, <, >, <=, >= a > b
Logical &&, `  
Assignment =, +=, -=, *= a += 5
Unary ++, — i++, –i
Ternary ? : a > b ? a : b

🧠 Example:

java

CopyEdit

int a = 5;

int b = 10;

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


✅ Summary

Concept Example QA Use
Variable int age = 30; Store dynamic data
Data Type boolean isValid = true; Define type of value
Operator if(a > b) Perform logic in code

📘 Java Topic 3: Conditional Statements (if, else, switch)


🔹 What are Conditional Statements?

Conditional statements allow your program to make decisions — to execute certain code only if a specific condition is true.

📖 Nepali Insight:
Conditional statement ले भन्न सक्छ — “यदि यस्तो भयो भने यस्तो गर, नभए अर्कै गर।”


✅ 1. if Statement

Executes a block of code only if the condition is true.

java

CopyEdit

int age = 18;

if (age >= 18) {

    System.out.println(“Eligible to vote”);

}

📖 Nepali: यदि उमेर १८ वा बढी छ भने मतदान गर्न मिल्छ।


✅ 2. if…else Statement

Adds an alternate block to execute if the condition is false.

java

CopyEdit

if (age >= 18) {

    System.out.println(“Eligible to vote”);

} else {

    System.out.println(“Not eligible”);

}


✅ 3. if…else if…else

Used to check multiple conditions.

java

CopyEdit

int score = 75;

if (score >= 90) {

    System.out.println(“Grade A”);

} else if (score >= 75) {

    System.out.println(“Grade B”);

} else {

    System.out.println(“Grade C”);

}

📖 Nepali: कुन-कुन level मा के काम गर्ने भनेर step-wise check गर्न।


✅ 4. switch Statement

Used to select one of many code blocks to execute — better than using many else if for specific cases.

java

CopyEdit

int day = 3;

switch (day) {

    case 1: System.out.println(“Sunday”); break;

    case 2: System.out.println(“Monday”); break;

    case 3: System.out.println(“Tuesday”); break;

    default: System.out.println(“Invalid”);

}

📖 Nepali: दिन अनुसार के देखाउने भन्ने कुरा चुनिन्छ।


🔹 Notes on switch:

  • break prevents fall-through (stops execution after match)
  • default is optional but handles unmatched cases

✅ When to Use What?

Use Case Statement
One simple condition if
Either this or that if…else
Multiple conditions if…else if…else
Multiple known fixed values switch

🧪 QA Use Example

You may use these in:

  • Test data generation logic
  • Conditional validation scripts
  • Flow control in automation framework (TestNG, Selenium)

📘 Java Topic 4: Loops (for, while, do-while)


🔹 What is a Loop?

A loop is used to execute a block of code repeatedly until a specific condition is met.

Generated image

📖 Nepali Insight:
Loop ले एकै काम बारम्बार गराउँछ — जति पटक चाहिन्छ, उति पटक।


✅ 1. for Loop

Used when the number of iterations is known or fixed.

java

CopyEdit

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

    System.out.println(“Hello ” + i);

}

📖 Example Output:

nginx

CopyEdit

Hello 1

Hello 2

Hello 3

Hello 4

Hello 5


✅ 2. while Loop

Used when the number of iterations is unknown, but depends on a condition.

java

CopyEdit

int i = 1;

while (i <= 5) {

    System.out.println(“Hello ” + i);

    i++;

}

📖 Nepali: while ले पहिले condition check गर्छ अनि मात्र loop चलाउँछ।


✅ 3. do…while Loop

  • Executes the loop at least once, even if the condition is false at first.
  • Condition is checked after one full execution.

java

CopyEdit

int i = 1;

do {

    System.out.println(“Hello ” + i);

    i++;

} while (i <= 5);

🧠 Use this when you want the action to happen at least one time.


🔹 Loop Flow Summary

Loop Type Condition Checked Runs at least once?
for Before start Only if true
while Before start Only if true
do…while After first execution ✅ Always once

🔹 Common QA Use Cases

  • Data-driven testing: Loop through data
  • Retry logic: Keep trying until status = “Success”
  • Batch verification: Loop over rows, items, or fields

🔹 Example – Print Even Numbers from 1 to 10

java

CopyEdit

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

    if (i % 2 == 0) {

        System.out.println(i);

    }

}

📖 Output:

CopyEdit

2

4

6

8

10


✅ Bonus: Enhanced for-each Loop (For Arrays/Collections)

java

CopyEdit

String[] cities = {“Dallas”, “Austin”, “Houston”};

for (String city : cities) {

    System.out.println(city);

}

📘 Java Topic 5: Arrays and Strings


🔹 What is an Array?

An array is a data structure that stores multiple values of the same type in a single variable, using an index to access each element.

📖 Nepali Insight:
Array भन्नाले एकै नाममा धेरै समान प्रकारका data राख्न मिल्ने list हो — जसमा प्रत्येक item को number (index) हुन्छ।


✅ Array Declaration & Initialization

java

CopyEdit

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

🧠 Indexing starts from 0:

  • numbers[0] = 10
  • numbers[1] = 20

🔹 Accessing Array Elements

java

CopyEdit

System.out.println(numbers[2]); // Output: 30


🔹 Looping Through Array

java

CopyEdit

for (int i = 0; i < numbers.length; i++) {

    System.out.println(numbers[i]);

}

✅ Output:

CopyEdit

10

20

30

40

50


🔹 for-each Loop

java

CopyEdit

for (int num : numbers) {

    System.out.println(num);

}

📖 Nepali: Array का सबै elements एक-एक गरेर access गर्न सजिलो तरीका।


🔹 String in Java

A String is a sequence of characters. It is an object in Java, not a primitive data type.

Generated image

java

CopyEdit

String name = “Lok QA”;


✅ String Methods

Method Purpose Example
length() Length of string name.length() → 6
charAt(index) Character at index name.charAt(0) → ‘L’
toUpperCase() Convert to caps name.toUpperCase()
toLowerCase() Convert to small name.toLowerCase()
equals() Compare (case sensitive) “Lok”.equals(“lok”) → false
equalsIgnoreCase() Compare (ignore case) → true
contains() Check substring name.contains(“QA”) → true
substring(x, y) Extract part name.substring(0, 3) → “Lok”
split() Break string into parts “A-B-C”.split(“-“)

🔹 String Concatenation

java

CopyEdit

String first = “Lok”;

String last = “Subedi”;

String full = first + ” ” + last;

System.out.println(full);  // Lok Subedi


🔹 Immutable Nature of Strings

Strings in Java are immutable — once created, they cannot be changed.

📖 Nepali: String लाई change गरेजस्तो लागे पनि Java मा actually नयाँ object बन्छ।

✅ Use StringBuilder or StringBuffer for mutable strings in performance-heavy applications.


🧪 QA Use Examples:

  • Parse test data (e.g., split values)
  • Validate text from UI/API
  • Loop over data sets stored in arrays

📘 Java Topic 6: Object-Oriented Programming (OOPs) Concepts


Generated image

🔹 What is OOP?

OOP (Object-Oriented Programming) is a programming paradigm where real-world entities like objects, classes, and relationships are used to design software.

📖 Nepali Insight:
OOP भन्नाले सबै कुरा object (वास्तविक वस्तु) को रूप मा सोची software design गर्ने तरिका हो।


✅ 4 Pillars of OOP

Principle Description Example
Encapsulation Bind data and code in a single unit (class) Use of private variables + public methods
Inheritance One class inherits from another Child extends Parent
Polymorphism One method behaves differently Method Overloading / Overriding
Abstraction Hide complex logic, show only essentials Abstract classes/interfaces

🔸 1. Encapsulation

  • Wrapping data (variables) and code (methods) into a single unit (class)
  • Achieved using private variables and public getters/setters

java

CopyEdit

public class Student {

    private String name;

    public void setName(String newName) {

        name = newName;

    }

    public String getName() {

        return name;

    }

}

🧠 Used in test frameworks to protect variables and control access.


🔸 2. Inheritance

  • One class inherits properties/methods of another class using extends keyword

java

CopyEdit

class Vehicle {

    void start() { System.out.println(“Starting…”); }

}

class Car extends Vehicle {

    void horn() { System.out.println(“Beep!”); }

}

🧠 POM frameworks use inheritance to avoid repeating common code.


🔸 3. Polymorphism

  • Same method, different forms
  • Two types:
    • Compile-time (Method Overloading) – same method name, different parameters
    • Runtime (Method Overriding) – child class overrides parent method

java

CopyEdit

class MathOps {

    int add(int a, int b) { return a + b; }                  // Overload 1

    double add(double a, double b) { return a + b; }         // Overload 2

}

class Parent {

    void greet() { System.out.println(“Hello Parent”); }

}

class Child extends Parent {

    void greet() { System.out.println(“Hello Child”); }     // Override

}


🔸 4. Abstraction

  • Hiding implementation details and showing only functionality
  • Achieved via:
    • Abstract class (can have abstract + normal methods)
    • Interface (100% abstract in older Java versions)

java

CopyEdit

abstract class Animal {

    abstract void sound();

}

class Dog extends Animal {

    void sound() { System.out.println(“Bark”); }

}

🧠 Interfaces like WebDriver, Runnable in Selenium are examples of abstraction.


🔹 Class vs Object

Term Meaning
Class Blueprint/template
Object Instance of a class (actual entity in memory)

java

CopyEdit

class Book {

    String title;

}

public class Main {

    public static void main(String[] args) {

        Book b = new Book(); // Object created

        b.title = “Java Notes”;

    }

}


✅ Summary Table

Concept Meaning Keyword
Encapsulation Protect data private, get, set
Inheritance Reuse code extends
Polymorphism Flexibility @Override, method overloading
Abstraction Hide logic abstract, interface

📘 Java Topic 7: Class, Object, Constructor, this, and super Keywords


🔹 What is a Class?

A class is a blueprint/template used to create objects. It defines properties (variables) and behaviors (methods) of an object.

📖 Nepali Insight:
Class भन्नाले एउटा design हो — जसको आधारमा object तयार हुन्छ।

java

CopyEdit

public class Car {

    String color;

    void start() {

        System.out.println(“Car started”);

    }

}


🔹 What is an Object?

An object is an instance of a class — the real, memory-allocated version of the blueprint.

java

CopyEdit

public class TestCar {

    public static void main(String[] args) {

        Car myCar = new Car();  // Object creation

        myCar.color = “Red”;

        myCar.start();          // Method call

    }

}

🧠 Multiple objects can be created from the same class with different data.


🔹 Constructor in Java

A constructor is a special method that is automatically called when an object is created.

📖 Nepali View:
Object बनाउँदा जे काम तुरुन्तै चलाउनु पर्छ, त्यो constructor भित्र राखिन्छ।


✅ Types of Constructors

Type Description
Default Constructor No arguments
Parameterized Constructor Takes arguments to initialize object

java

CopyEdit

class Person {

    String name;

    // Constructor

    Person(String personName) {

        name = personName;

    }

    void greet() {

        System.out.println(“Hello ” + name);

    }

}


🔹 this Keyword

Refers to the current object’s instance. Often used when local and instance variables have the same name.

java

CopyEdit

class Student {

    String name;

    Student(String name) {

        this.name = name;  // ‘this’ refers to the current object

    }

}

📖 Nepali Insight:
this ले “म यो object भित्रको variable हो” भनेर जनाउँछ।


🔹 super Keyword

Refers to the parent class. Used to:

  • Call parent’s constructor
  • Access parent’s variable/method

java

CopyEdit

class Animal {

    String sound = “Generic sound”;

}

class Dog extends Animal {

    void printSound() {

        System.out.println(super.sound);  // Accessing parent variable

    }

}

Also used as:

java

CopyEdit

super(); // Calls parent class constructor

📖 Nepali View:
super ले भन्न सक्छ — “म parent class को कुरा गर्दैछु।”


✅ Summary Table

Concept Description Keyword
Class Blueprint of object class
Object Instance of class new
Constructor Auto-runs when object created ClassName()
this Refers to current object this.variable
super Refers to parent class super.variable or super()

📘 Java Topic 8: Inheritance in Depth (Types, Constructors, Method Overriding)


🔹 What is Inheritance?

Inheritance is the process by which one class (child/subclass) inherits properties and behaviors from another class (parent/superclass).

📖 Nepali Insight:
Inheritance भन्नाले एउटा class ले अर्को class को गुण र काम (method) अपनाउनु हो।


✅ Why Use Inheritance?

Benefit Description
Code Reusability Common code lives in parent class
Maintainability Logic change in one place applies to all
Scalability Helps in framework design (like POM in Selenium)

✅ Syntax

java

CopyEdit

class Parent {

    void greet() {

        System.out.println(“Hello from Parent”);

    }

}

class Child extends Parent {

    void show() {

        System.out.println(“I am the Child”);

    }

}

java

CopyEdit

Child c = new Child();

c.greet(); // Inherited from Parent

c.show();  // Own method


🔹 Types of Inheritance in Java

Type Description Support in Java
Single One child, one parent
Multilevel Parent → Child → Grandchild
Hierarchical One parent, many children
Multiple Multiple parents (via classes) ❌ (only via interfaces)

🔸 Single Inheritance

java

CopyEdit

class Animal {

    void eat() { System.out.println(“Eating”); }

}

class Dog extends Animal {

    void bark() { System.out.println(“Barking”); }

}


🔸 Multilevel Inheritance

java

CopyEdit

class Animal {

    void eat() {}

}

class Dog extends Animal {

    void bark() {}

}

class Puppy extends Dog {

    void weep() {}

}


🔸 Hierarchical Inheritance

java

CopyEdit

class Animal {

    void eat() {}

}

class Dog extends Animal {}

class Cat extends Animal {}


🔹 Constructor Behavior in Inheritance

  • When a child class object is created, parent constructor runs first (even if not explicitly written)
  • Use super() to call parent constructor manually

java

CopyEdit

class Parent {

    Parent() {

        System.out.println(“Parent constructor”);

    }

}

class Child extends Parent {

    Child() {

        super(); // calls Parent()

        System.out.println(“Child constructor”);

    }

}


🔹 Method Overriding

When a child class defines a method with the same name and parameters as the parent, it overrides the parent’s method.

java

CopyEdit

class Parent {

    void show() {

        System.out.println(“Parent version”);

    }

}

class Child extends Parent {

    @Override

    void show() {

        System.out.println(“Child version”);

    }

}

📖 Nepali Insight:
Parent ले बनाएको method लाई child ले आफू अनुसार change गर्ने हो — @Override ले भन्न सक्छ “म पुरानो method बदल्दैछु।”


✅ Rules of Method Overriding

Rule Must Follow
Same method name
Same number and type of parameters
Must be in parent-child relationship
Cannot reduce visibility (e.g., public → private)
Use @Override annotation Recommended

🧪 QA & Automation Use

  • Base TestBase class can be extended by all test classes
  • Common methods like launchBrowser() go in the parent
  • @Override setup or teardown logic in subclasses

✅ Summary Table

Concept Description
Inheritance One class inherits from another
Types Single, Multilevel, Hierarchical
Constructor Parent runs first (super() optional)
Method Overriding Redefining inherited method

📘 Java Topic 9: Polymorphism (Compile-Time vs Run-Time)


🔹 What is Polymorphism?

Polymorphism means “many forms” — in Java, it allows one method or object to behave differently in different contexts.

📖 Nepali Insight:
Polymorphism भन्नाले एउटै method ले context अनुसार फरक काम गर्नु हो — जस्तै एउटै शब्दले फरक अर्थ दिने जस्तो।


🔸 Types of Polymorphism in Java

Type Also Known As When Happens
Compile-time Method Overloading During compilation
Run-time Method Overriding During program execution

✅ 1. Compile-Time Polymorphism (Method Overloading)

When multiple methods in the same class have the same name but different parameters (type, number, or order).

java

CopyEdit

class Calculator {

    int add(int a, int b) {

        return a + b;

    }

    double add(double a, double b) {

        return a + b;

    }

    int add(int a, int b, int c) {

        return a + b + c;

    }

}

📖 Nepali View:
add() method ले parameter अनुसार अलग-अलग काम गर्छ — यो compile time मा decide हुन्छ।

🧠 Compiler checks which method to run based on arguments passed.


✅ 2. Run-Time Polymorphism (Method Overriding)

When a child class redefines a method of the parent class.

java

CopyEdit

class Animal {

    void sound() {

        System.out.println(“Animal sound”);

    }

}

class Dog extends Animal {

    @Override

    void sound() {

        System.out.println(“Dog barks”);

    }

}

java

CopyEdit

Animal a = new Dog();

a.sound();  // Output: Dog barks

📖 Nepali Insight:
Parent class को reference बाट child को method call हुनु — यो run-time मा decide हुन्छ।


🔹 Real QA Use of Polymorphism

Scenario Use
Selenium POM Base class has click(), overridden in derived pages
API Test Setup Base request logic overridden in each test case
Framework Reusability Common logic handled via polymorphic calls

🔹 Key Differences

Feature Compile-Time Run-Time
Also Called Overloading Overriding
Resolved At Compile time Execution time
Requires Inheritance? ❌ No ✅ Yes
Method Signature Must be different Must be same
Example add(int, int) & add(double, double) show() overridden in child class

✅ Summary

Term Meaning QA Relevance
Polymorphism Many forms Reusable & flexible code
Overloading Method with same name, diff args Utility methods
Overriding Same method redefined in child Page classes in Selenium

📘 Java Topic 10: Abstraction and Interface


🔹 What is Abstraction?

Abstraction means showing only the essential details and hiding complex implementation from the user.

📖 Nepali Insight:
Abstraction भन्नाले user लाई काम कस्तो हुन्छ भनेर देखाउने तर भित्र के हुन्छ भन्ने लुकाउने तरिका हो।


🔹 Why Abstraction?

Purpose Benefit
Hide complexity Focus only on what matters
Standardize behavior Force all child classes to follow structure
Useful in frameworks Define method structure, implementation later

✅ 1. Abstract Class

A class declared with the keyword abstract, which can have both abstract (unimplemented) and concrete (implemented) methods.


🔸 Abstract Class Syntax

java

CopyEdit

abstract class Vehicle {

    abstract void start();  // abstract method

    void fuelType() {

        System.out.println(“Diesel or Petrol”);

    }

}

java

CopyEdit

class Car extends Vehicle {

    void start() {

        System.out.println(“Car starts with key”);

    }

}

📖 Nepali View:
Abstract class मा केही method खाली राखिन्छ, जुन child ले override गर्नैपर्छ।


✅ 2. Interface

An interface is a completely abstract structure used to define a contract (100% abstract in older versions of Java).

📖 Interface भन्नाले “जो inherit गर्छ उसले यी method हरु बनाउनु पर्छ” भन्ने नियम हो।


🔸 Interface Syntax

java

CopyEdit

interface Animal {

    void sound();  // abstract by default

}

class Dog implements Animal {

    public void sound() {

        System.out.println(“Dog barks”);

    }

}

🧠 Key Rule: Class must implement the interface and define all its methods.


🔹 Interface vs Abstract Class

Feature Abstract Class Interface
Inheritance extends implements
Method Types Abstract + Concrete Only abstract (until Java 8+)
Variables Can have instance vars Only static + final (constants)
Multiple inheritance ❌ Not allowed ✅ Yes (a class can implement multiple interfaces)
Use case Base class with shared logic Contract without implementation

✅ Real-World QA Example (Interface)

java

CopyEdit

interface WebPage {

    void openPage();

    void validateHeader();

}

java

CopyEdit

class LoginPage implements WebPage {

    public void openPage() { /* logic */ }

    public void validateHeader() { /* logic */ }

}

🧪 Used in:

  • Selenium POM frameworks
  • API test interfaces (Reusable contracts)

✅ Summary

Concept Use
Abstraction Hide internal logic, show only function
Abstract Class Partial implementation + abstraction
Interface Full abstraction, multi-inheritable
QA Use Framework design, Page-level contracts, reusable logic

📘 Java Topic 11: Access Modifiers (public, private, protected, and default)


🔹 What are Access Modifiers?

Access modifiers in Java control the visibility/scope of classes, methods, and variables.

📖 Nepali Insight:
Access modifier भन्नाले code कुन-कुन ठाउँबाट access गर्न मिल्छ भन्ने निर्धारण गर्ने keyword हो।


✅ Types of Access Modifiers

Modifier Accessible Within Across Packages
public Anywhere ✅ Yes
private Only within the same class ❌ No
protected Same package + subclass outside package ✅ (if inherited)
(default) Only within the same package ❌ No

🔸 1. public

  • Can be accessed from anywhere (inside or outside the package)

java

CopyEdit

public class MyClass {

    public int value = 10;

    public void show() {

        System.out.println(“Public method”);

    }

}

📖 Use for: Utility methods, shared constants, Selenium Page Objects.


🔸 2. private

  • Accessible only within the same class — not visible even to child classes.

java

CopyEdit

public class Secret {

    private String pin = “1234”;

    private void access() {

        System.out.println(“Private method”);

    }

}

📖 Use for: Sensitive data, encapsulation (e.g., private WebElement loginBtn)


🔸 3. protected

  • Accessible within the same package or subclass in another package.

java

CopyEdit

class Base {

    protected void show() {

        System.out.println(“Protected method”);

    }

}

📖 Used when creating reusable base classes that are extended in other packages.


🔸 4. (Default) — No modifier

  • When no keyword is used, it’s package-private — only accessible within the same package.

java

CopyEdit

class Helper {

    void helpMe() {

        System.out.println(“Default access”);

    }

}

📖 Used for internal logic or helper classes not intended to be exposed.


✅ Summary Table

Modifier Same Class Same Package Subclass (Diff Pkg) Other Pkg
public
protected
(default)
private

🧪 QA & Automation Use

  • private WebElement in POM (encapsulation)
  • public void clickLogin() for test scripts
  • protected WebDriver driver in base class
  • Default for internal utility/helper methods

📘 Java Topic 12: static and final Keywords in Java


🔹 What is the static Keyword?

The static keyword in Java is used to indicate that a method or variable belongs to the class, not to any specific object.

📖 Nepali Insight:
static भन्नाले त्यो variable वा method class सँग सम्बन्धित हुन्छ, object सँग होइन।


✅ Use Cases of static

Can Be Applied To Meaning
static variable Shared across all objects
static method Can be called without creating object
static block Code that runs when class loads
static class Used in nested class structures

🔸 Example: Static Variable

java

CopyEdit

class Student {

    static String schoolName = “Test High School”;

    String studentName;

    Student(String name) {

        studentName = name;

    }

}

java

CopyEdit

System.out.println(Student.schoolName);  // No need for object

🧠 All student objects will share the same school name.


🔸 Example: Static Method

java

CopyEdit

class MathUtil {

    static int square(int x) {

        return x * x;

    }

}

java

CopyEdit

System.out.println(MathUtil.square(4));  // Output: 16

📖 Use static methods for utility functions.


🔹 What is the final Keyword?

The final keyword is used to restrict modification. Once declared final, you cannot change it, override it, or extend it.

📖 Nepali View:
final भन्नाले अब यो चीज change गर्न मिल्दैन भन्ने हो।


✅ Use Cases of final

Final On Meaning
Variable Value cannot be changed
Method Cannot be overridden
Class Cannot be extended

🔸 Final Variable Example

java

CopyEdit

final int MAX_USERS = 100;

✅ You cannot do: MAX_USERS = 200;


🔸 Final Method Example

java

CopyEdit

class Parent {

    final void greet() {

        System.out.println(“Hello”);

    }

}

class Child extends Parent {

    // greet() cannot be overridden here

}


🔸 Final Class Example

java

CopyEdit

final class Constants {

    static final String APP_NAME = “MyApp”;

}

❌ You cannot extend a final class:

java

CopyEdit

// class MyClass extends Constants → ❌ Error


🔹 static vs final

Keyword Purpose
static Shared by all, belongs to class
final Prevent changes (constant, locked)

🧠 You can combine them:

java

CopyEdit

static final String URL = “https://example.com”;


✅ QA Framework Usage

Use Example
Constants public static final String LOGIN_URL
Common methods static waitForElement()
Prevent override Use final in base methods you don’t want changed

✅ Summary Table

Keyword Use Can Modify? Belongs To
static Shared/class-level Class
final Locked/constant Depends on use
static final Global constant Class

📘 Java Topic 13: Exception Handling (try-catch-finally, throws, throw, Custom Exceptions)


🔹 What is Exception Handling?

Exception handling in Java is the process of handling runtime errors so that the program doesn’t crash unexpectedly.

📖 Nepali Insight:
Exception handling भन्नाले program चल्दाखेरी गल्ती आए पनि program रोकिएर नअडोस् भनेर safety mechanism राख्ने हो।


✅ Why Use It?

Purpose Benefit
Handle unexpected errors Prevent crashes
Maintain flow Skip only faulty logic, not full program
Show meaningful messages Guide user or developer

🔹 Common Exception Types

Type Example
ArithmeticException Division by zero
NullPointerException Calling method on null object
ArrayIndexOutOfBoundsException Invalid array index
NumberFormatException Converting invalid string to number
IOException File read/write issues

✅ 1. try-catch Block

java

CopyEdit

try {

    int result = 10 / 0;

} catch (ArithmeticException e) {

    System.out.println(“Cannot divide by zero”);

}

📖 Nepali View:
Try block मा error आए भने Catch block ले त्यो संभाल्छ।


✅ 2. finally Block

  • Always executes whether exception occurs or not

java

CopyEdit

try {

    int result = 10 / 2;

} catch (Exception e) {

    System.out.println(“Error”);

} finally {

    System.out.println(“Always runs”);

}

📖 Use it to close database, file, or browser (cleanup code).


✅ 3. throw Keyword

Used to manually throw an exception.

java

CopyEdit

throw new ArithmeticException(“Manual error”);


✅ 4. throws Keyword

Used in method signature to pass responsibility of exception handling to caller.

java

CopyEdit

public void readFile() throws IOException {

    // file code

}

📖 Nepali: “Yo method चलाउँदा exception आउन सक्छ, सम्भाल्नु तिमीले।” 😄


✅ 5. Custom Exception

Create your own exception by extending Exception or RuntimeException.

java

CopyEdit

class AgeException extends Exception {

    AgeException(String message) {

        super(message);

    }

}

class Voter {

    void checkAge(int age) throws AgeException {

        if (age < 18) {

            throw new AgeException(“You are underage”);

        }

    }

}

🧪 Used in test frameworks to handle special validation failures.


✅ Summary Table

Keyword Use
try Code that may throw error
catch Handle the error
finally Always executes
throw Manually throw exception
throws Declare exception in method
Custom Exception Define your own exception type

🧪 QA Usage

  • Retry on failure (try-catch)
  • Gracefully skip test steps if element not found
  • Custom error for test validation failure
  • API/DB connection handling

📘 Java Topic 14: Collections in Java (List, Set, Map, ArrayList, HashMap)


🔹 What is the Java Collection Framework?

Java Collections is a framework that provides ready-made data structures like List, Set, Map, etc., to store and manipulate groups of data.

📖 Nepali Insight:
Collection Framework भन्नाले धेरै data लाई सजिलै संगठित गरी राख्न मिल्ने Java को predefined classes को समूह हो।


✅ Why Collections?

Need Example
Store multiple values All test case IDs
Maintain unique items Browser names in suite
Store key-value pairs Username → Password map
Iterate data dynamically Form input fields, list of results

🔹 Key Interfaces in Collection Framework

Interface Description
List Ordered, allows duplicates
Set Unordered, no duplicates
Map Stores key-value pairs

🔸 1. List Interface → ArrayList

java

CopyEdit

import java.util.ArrayList;

ArrayList<String> cities = new ArrayList<>();

cities.add(“Dallas”);

cities.add(“Austin”);

cities.add(“Dallas”);  // Allowed

System.out.println(cities);  // [Dallas, Austin, Dallas]

Feature Supports
Order preserved
Duplicates
Index access ✅ (e.g., cities.get(0))

🔸 2. Set Interface → HashSet

java

CopyEdit

import java.util.HashSet;

HashSet<String> browsers = new HashSet<>();

browsers.add(“Chrome”);

browsers.add(“Firefox”);

browsers.add(“Chrome”);  // Ignored

System.out.println(browsers);  // [Chrome, Firefox]

Feature Supports
Order preserved
Duplicates

📖 Use Set when you want uniqueness (e.g., environment configs)


🔸 3. Map Interface → HashMap

java

CopyEdit

import java.util.HashMap;

HashMap<String, String> credentials = new HashMap<>();

credentials.put(“admin”, “1234”);

credentials.put(“user”, “abcd”);

System.out.println(credentials.get(“admin”));  // Output: 1234

Feature Supports
Key-value format
Duplicate keys ❌ (replaced if exists)
Values can repeat

📖 Use Map when you need pair-based storage — like locators, usernames, form data, headers.


🔹 Iterating Collections

✅ For List or Set:

java

CopyEdit

for (String name : cities) {

    System.out.println(name);

}

✅ For Map:

java

CopyEdit

for (String key : credentials.keySet()) {

    System.out.println(key + ” = ” + credentials.get(key));

}


🧪 QA Use Examples

Use Case Collection
Store list of locators List<WebElement>
Unique browsers in test Set<String>
Data-driven testing Map<String, String> for test data
Multiple test failures List<String> failedTests

✅ Summary Table

Type Class Duplicates? Ordered? Use Case
List ArrayList Test steps, names, inputs
Set HashSet Browser list, IDs
Map HashMap Key ❌ ✅ via LinkedHashMap Test data, configs

📘 Java Topic 15: Looping with Collections (for-each, Iterator, Lambda)


🔹 Why Loop Through Collections?

Collections like List, Set, and Map hold multiple data items. Looping allows you to access, verify, or perform actions on each item — useful in both manual and automation testing.

📖 Nepali Insight:
Collection मा भएका सबै items एक-एक गरेर चलाउन loop प्रयोग गरिन्छ — data check, action perform गर्न सजिलो हुन्छ।


🔸 1. for-each Loop

Used to iterate through all items in a List, Set, or array.

java

CopyEdit

ArrayList<String> browsers = new ArrayList<>();

browsers.add(“Chrome”);

browsers.add(“Firefox”);

for (String browser : browsers) {

    System.out.println(browser);

}

✅ Best for simple iteration when index isn’t needed.


🔸 2. Iterator Interface

Provides controlled access to elements, including the ability to safely remove items while iterating.

java

CopyEdit

import java.util.Iterator;

import java.util.ArrayList;

ArrayList<String> names = new ArrayList<>();

names.add(“Lok”);

names.add(“QA”);

Iterator<String> it = names.iterator();

while (it.hasNext()) {

    System.out.println(it.next());

}

✅ Use it.remove() inside the loop to remove items safely.

📖 Nepali View:
Iterator ले collection मा कुन-कुन item छन् भनेर check गर्दै एक-एक गरेर access गर्न दिन्छ।


🔸 3. Looping Through Map

java

CopyEdit

HashMap<String, String> loginData = new HashMap<>();

loginData.put(“admin”, “admin123”);

loginData.put(“user”, “user456”);

for (String key : loginData.keySet()) {

    System.out.println(“Username: ” + key + “, Password: ” + loginData.get(key));

}

✅ Use entrySet() for direct key-value looping:

java

CopyEdit

for (Map.Entry<String, String> entry : loginData.entrySet()) {

    System.out.println(entry.getKey() + ” = ” + entry.getValue());

}


🔸 4. Lambda Expressions (Java 8+)

Simplified functional syntax for compact iteration.

java

CopyEdit

browsers.forEach(browser -> System.out.println(browser));

✅ Lambda with Map:

java

CopyEdit

loginData.forEach((key, value) -> System.out.println(key + ” → ” + value));

📖 Nepali View:
Lambda ले code छोट्याउँछ — एकै लाइनमा पूरा काम गर्न सकिन्छ।


✅ When to Use What?

Situation Use
Simple list/array for-each
Need to remove item while looping Iterator
Key-value pairs Map.entrySet()
Modern compact syntax Lambda

🧪 QA Use Case Examples

Collection Example
List<WebElement> Loop through all buttons on a page
Set<String> Print all unique browsers used in test
Map<String, String> Data-driven testing with credentials
Lambda Report all test result summaries concisely

✅ Summary Table

Method Best For Syntax Simplicity
for-each All collections ✅ Easy
Iterator When modifying/removing 🔁 More control
Lambda Modern syntax 🔥 Compact and clean
Map.entrySet() Key-value pairs ✅ Accurate

📘 Java Topic 16: File Handling in Java (Text, Excel, JSON)


🔹 Why File Handling in QA?

In real-world automation, we often:

  • Read test data from external files (text, Excel, JSON)
  • Write logs or output results
  • Validate file downloads (e.g., from ClaimCenter, policy PDF)

📖 Nepali Insight:
File handling ले तपाईंलाई file बाट data पढ्न, लेख्न र verify गर्न मद्दत गर्छ — जुन testing मा frequently use हुन्छ।


🔸 1. Reading and Writing Text Files

Reading a .txt File:

java

CopyEdit

import java.io.*;

BufferedReader reader = new BufferedReader(new FileReader(“testdata.txt”));

String line;

while ((line = reader.readLine()) != null) {

    System.out.println(line);

}

reader.close();

Writing to a .txt File:

java

CopyEdit

BufferedWriter writer = new BufferedWriter(new FileWriter(“result.txt”));

writer.write(“Test Passed”);

writer.newLine();

writer.close();

📌 Used for logging, storing test outputs, reports.


🔸 2. Excel File Handling (Apache POI)

Used to read/write data from .xls or .xlsx Excel files.
Requires external library: Apache POI

Reading Excel:

java

CopyEdit

import org.apache.poi.ss.usermodel.*;

import java.io.*;

FileInputStream file = new FileInputStream(“data.xlsx”);

Workbook workbook = WorkbookFactory.create(file);

Sheet sheet = workbook.getSheet(“Sheet1”);

String value = sheet.getRow(0).getCell(0).getStringCellValue();

System.out.println(value);

workbook.close();

Writing Excel:

java

CopyEdit

sheet.getRow(0).createCell(1).setCellValue(“Tested”);

FileOutputStream outFile = new FileOutputStream(“data.xlsx”);

workbook.write(outFile);

workbook.close();

📖 Excel is popular for manual + automation hybrid frameworks.


🔸 3. JSON File Handling (Simple JSON or Jackson)

✅ JSON is widely used in:

  • API request/response validation
  • Storing config or test data

📘 Reading JSON with org.json.simple:

java

CopyEdit

import org.json.simple.*;

import org.json.simple.parser.*;

FileReader reader = new FileReader(“data.json”);

JSONParser parser = new JSONParser();

JSONObject obj = (JSONObject) parser.parse(reader);

System.out.println(obj.get(“username”));

✅ JSON Example:

json

CopyEdit

{

  “username”: “admin”,

  “password”: “admin123”

}

📌 Jackson and Gson are more advanced options for object mapping.


🔹 Exception Handling with Files

Always use:

  • try-catch for IOException, ParseException
  • finally or try-with-resources to close files

✅ Summary Table

File Type Purpose Tools
.txt Logs, simple data BufferedReader, FileWriter
.xlsx Structured data Apache POI
.json API data/config JSON.simple, Jackson, Gson

🧪 QA Use Cases

Scenario File Type
Export failed test steps .txt
Store test input for DDT .xlsx
Validate API payload .json
Log timestamped test status .txt, .csv

📘 Java Topic 17: Date and Time (LocalDate, LocalDateTime, Formatting)


🔹 Why Date and Time in QA?

In test automation, you often:

  • Capture execution timestamps
  • Validate date fields (e.g., DOB, claim date)
  • Generate dynamic future/past dates for input
  • Log test activity

📖 Nepali Insight:
Java मा date/time प्रयोग गरेर test timing check, report मा date राख्ने, वा date-based logic validate गर्न सकिन्छ।


✅ Java 8 Date-Time API (Modern & Preferred)

The java.time package introduced in Java 8 provides:

  • Immutable classes (thread-safe)
  • Clear formatting/parsing
  • Replaces old Date and Calendar

🔸 1. LocalDate – For Date Only

java

CopyEdit

import java.time.LocalDate;

LocalDate today = LocalDate.now();

System.out.println(today);  // 2025-06-23

✅ Create custom date:

java

CopyEdit

LocalDate specific = LocalDate.of(2023, 12, 25);

✅ Add/subtract days:

java

CopyEdit

LocalDate nextWeek = today.plusDays(7);

LocalDate lastMonth = today.minusMonths(1);


🔸 2. LocalDateTime – Date + Time

java

CopyEdit

import java.time.LocalDateTime;

LocalDateTime current = LocalDateTime.now();

System.out.println(current);  // 2025-06-23T21:55:30.321

✅ Set custom datetime:

java

CopyEdit

LocalDateTime custom = LocalDateTime.of(2023, 5, 10, 15, 30);


🔸 3. Formatting Date-Time

Use DateTimeFormatter to format or parse dates.

java

CopyEdit

import java.time.format.DateTimeFormatter;

DateTimeFormatter format = DateTimeFormatter.ofPattern(“dd-MM-yyyy”);

String formattedDate = today.format(format);

System.out.println(formattedDate);  // 23-06-2025

✅ Full DateTime Example:

java

CopyEdit

DateTimeFormatter fullFormat = DateTimeFormatter.ofPattern(“dd/MM/yyyy HH:mm:ss”);

System.out.println(LocalDateTime.now().format(fullFormat));


✅ Parsing a String to Date

java

CopyEdit

String dateStr = “15-08-2024”;

DateTimeFormatter formatter = DateTimeFormatter.ofPattern(“dd-MM-yyyy”);

LocalDate parsedDate = LocalDate.parse(dateStr, formatter);


🔹 Common Formats for QA Use

Format String Output Example Meaning
“dd-MM-yyyy” 23-06-2025 Day-Month-Year
“yyyy/MM/dd” 2025/06/23 Year first
“HH:mm:ss” 14:35:20 24-hour time
“dd MMM yyyy” 23 Jun 2025 Readable form

🧪 QA Use Cases

Use Case Method
Get current date for report name LocalDate.now()
Generate future date for policy plusDays(), plusMonths()
Compare dates in form fields .isAfter(), .isBefore()
Log test execution time LocalDateTime.now().format()

✅ Summary Table

Class Use
LocalDate Date only (no time)
LocalDateTime Date + time
DateTimeFormatter Format and parse dates
.plusDays() / .minusDays() Shift date dynamically
.format() Convert to readable string

📘 Java Topic 18: Methods (static, instance, parameters, return types)


🔹 What is a Method?

A method is a block of code that performs a specific task, and can be called whenever needed.

📖 Nepali Insight:
Method भन्नाले code को त्यो block हो जसले एउटा काम गर्न बनाइएको हुन्छ, जसलाई बारम्बार call गर्न सकिन्छ।


✅ Why Use Methods?

Benefit Description
Code reusability Write once, use many times
Modularity Break logic into smaller parts
Readability Easier to understand and maintain
Testing Test individual methods easily

🔹 Method Syntax

java

CopyEdit

returnType methodName(parameters) {

    // method body

    return value; // if returnType ≠ void

}


✅ Example 1: Method Without Parameters

java

CopyEdit

public void greet() {

    System.out.println(“Welcome Lok!”);

}

➡ Call it using:

java

CopyEdit

greet();  // if in same class


✅ Example 2: Method With Parameters

java

CopyEdit

public void greetUser(String name) {

    System.out.println(“Hello ” + name);

}

➡ Call:

java

CopyEdit

greetUser(“Lok”);


✅ Example 3: Method With Return Type

java

CopyEdit

public int add(int a, int b) {

    return a + b;

}

➡ Call:

java

CopyEdit

int result = add(10, 20);

📖 Nepali View:
Method ले value फिर्ता गर्ने हो भने return keyword चाहिन्छ।


🔹 Types of Methods in Java

Type Description How to Call
Instance Method Belongs to an object obj.methodName()
Static Method Belongs to class ClassName.methodName()

🔸 Instance Method Example

java

CopyEdit

class Calculator {

    int multiply(int x, int y) {

        return x * y;

    }

}

➡ Call it:

java

CopyEdit

Calculator c = new Calculator();

int product = c.multiply(4, 5);


🔸 Static Method Example

java

CopyEdit

class Utility {

    static void display() {

        System.out.println(“Static method called”);

    }

}

➡ Call it:

java

CopyEdit

Utility.display();  // No need to create object

📖 Nepali Tip:
static method ले object नचाहिने — direct call गर्न मिल्छ।


✅ Return Type Options

Return Type Example
void No return value
int, String, boolean Returns a value of that type
List<String> Returns a collection
CustomClass Returns an object

🧪 QA Use Case Examples

Use Case Method Type
Click button void clickButton()
Get text from page String getHeaderText()
Add two test data values int add(int a, int b)
Return API status boolean isResponseOK()

✅ Summary Table

Keyword Meaning
void No return value
return Return result
static Call without object
Parameters Inputs to method
Instance Method tied to object

📘 Java Topic 19: Accessors and Mutators (getters & setters)


🔹 What Are Accessors and Mutators?

  • Accessors are methods used to retrieve (get) the value of a private variable → getX()
  • Mutators are methods used to change (set) the value of a private variable → setX(value)

📖 Nepali Insight:
Private variable को value बाहिरबाट access गर्न getter र परिवर्तन गर्न setter method प्रयोग हुन्छ।


🔹 Why Use Getters and Setters?

Reason Benefit
Encapsulation Protect variables from direct access
Validation Add checks before updating values
Flexibility You can later change internal logic without changing method call

🔸 Example

java

CopyEdit

public class Employee {

    private String name;

    private int age;

    // Getter (accessor)

    public String getName() {

        return name;

    }

    // Setter (mutator)

    public void setName(String name) {

        this.name = name;

    }

    // Getter for age

    public int getAge() {

        return age;

    }

    // Setter for age with validation

    public void setAge(int age) {

        if (age > 18) {

            this.age = age;

        }

    }

}


🔸 How to Use in Main Method

java

CopyEdit

Employee emp = new Employee();

emp.setName(“Lok”);

emp.setAge(30);

System.out.println(emp.getName());  // Lok

System.out.println(emp.getAge());   // 30


✅ Naming Convention

Method Type Format
Getter getVariableName()
Setter setVariableName(value)

➡ Java uses camelCase: e.g., getFirstName(), setFirstName(“Lok”)


🔹 Common QA Automation Uses

Purpose Example
Page Object Model Set and get input values
Test Data Objects (POJO) Use getters/setters to access data fields
Data Validation Add checks inside setters for invalid inputs

✅ Summary Table

Term Purpose Returns
Getter Access private variable Value
Setter Modify private variable void
Follows Encapsulation

📖 Nepali View:
Getters ले variable पढ्न मद्दत गर्छ, setters ले value change गर्न दिन्छ, direct access रोक्दछ।

📘 Java Topic 20: Constructor Overloading & Chaining (this() and super() usage)


🔹 What is a Constructor?

A constructor is a special method that is automatically called when an object is created.
Its purpose is to initialize variables or prepare the object.

📖 Nepali Insight:
Constructor भनेको class को object बनाउँदा साथै चल्ने method हो — जुन automatically run हुन्छ।


✅ Types of Constructors

Type Description
Default Constructor No parameters
Parameterized Constructor Takes arguments to initialize fields

🔸 Example:

java

CopyEdit

class Person {

    String name;

    int age;

    // Default Constructor

    Person() {

        name = “Unknown”;

        age = 0;

    }

    // Parameterized Constructor

    Person(String name, int age) {

        this.name = name;

        this.age = age;

    }

}


🔹 What is Constructor Overloading?

Having multiple constructors in the same class with different parameter lists.

📖 Nepali View:
Constructor को version फरक फरक बनाउनु — ताकि object बनाउन flexible तरीका होस्।

java

CopyEdit

class Book {

    Book() {

        System.out.println(“Default Book”);

    }

    Book(String title) {

        System.out.println(“Book title: ” + title);

    }

    Book(String title, int pages) {

        System.out.println(“Book: ” + title + “, Pages: ” + pages);

    }

}


🔹 What is Constructor Chaining?

Calling one constructor from another constructor using:

  • this() – Call another constructor in same class
  • super() – Call constructor from parent class

✅ Using this()

java

CopyEdit

class Student {

    String name;

    int age;

    Student() {

        this(“Lok”, 25);  // Calls another constructor

    }

    Student(String name, int age) {

        this.name = name;

        this.age = age;

    }

}

📖 Nepali Tip:
this() ले यही class को अर्को constructor call गर्छ।


✅ Using super()

java

CopyEdit

class Animal {

    Animal() {

        System.out.println(“Animal constructor”);

    }

}

class Dog extends Animal {

    Dog() {

        super();  // Call parent class constructor

        System.out.println(“Dog constructor”);

    }

}

📖 super() ले parent class को constructor call गर्छ।


✅ Rules

Rule Detail
this() must be the first line in constructor
super() must also be first (you can’t use both together)
Use this() to reduce duplicate code
Only constructors can call this() and super()

🧪 QA Use Case

Use Case Example
Framework utility class Overloaded constructors for different test data
Base test class super() to reuse parent setup logic
POM structure this() for field initialization in multiple forms

✅ Summary Table

Concept Meaning Example
Constructor Overloading Multiple constructors Book(String) and Book()
Constructor Chaining Call one constructor from another this(), super()
this() Same class constructor this(“Lok”, 25);
super() Parent class constructor super();

🔹 1. Prime Number Check

A prime number is only divisible by 1 and itself (e.g., 2, 3, 5, 7…).

📖 Nepali Insight:
Prime number भन्नाले जसलाई 1 र आफू बाहेक अरु कुनै संख्याले divide गर्न सकिँदैन।

✅ Java Code:

java

CopyEdit

int num = 7;

boolean isPrime = true;

if (num <= 1) isPrime = false;

else {

    for (int i = 2; i < num; i++) {

        if (num % i == 0) {

            isPrime = false;

            break;

        }

    }

}

System.out.println(isPrime ? “Prime” : “Not Prime”);


🔹 2. Palindrome Check

A palindrome is a word/number that reads the same forward and backward (e.g., “121”, “madam”).

📖 Nepali:
Palindrome भनेको अगाडिबाट पढ्दा र पछाडिबाट पढ्दा एउटै देखिने number/string हो।

✅ Java Code (number):

java

CopyEdit

int num = 121, reversed = 0, original = num;

while (num != 0) {

    int digit = num % 10;

    reversed = reversed * 10 + digit;

    num /= 10;

}

System.out.println(original == reversed ? “Palindrome” : “Not Palindrome”);

✅ Java Code (string):

java

CopyEdit

String str = “madam”;

String reversed = new StringBuilder(str).reverse().toString();

System.out.println(str.equals(reversed) ? “Palindrome” : “Not Palindrome”);


🔹 3. Odd or Even Check

📖 Nepali:
Even number ले 2 ले divide हुँदा remainder दिँदैन (0), Odd ले दिन्छ (1)।

✅ Java Code:

java

CopyEdit

int num = 7;

if (num % 2 == 0) {

    System.out.println(“Even”);

} else {

    System.out.println(“Odd”);

}


🔹 4. Difference: final, finally, finalize

Keyword Type Purpose Example
final Keyword Prevent change (variable, method, class) final int x = 10;
finally Block Runs after try-catch regardless Cleanup code
finalize() Method Called before object is garbage collected Rarely used now

✅ Example: final

java

CopyEdit

final int speed = 100;

// speed = 200; // ❌ Error: can’t change

✅ Example: finally

java

CopyEdit

try {

    int result = 10 / 2;

} catch (Exception e) {

    System.out.println(“Error”);

} finally {

    System.out.println(“Always executes”);

}

✅ Example: finalize() (not recommended in modern Java)

java

CopyEdit

protected void finalize() {

    System.out.println(“Object is garbage collected”);

}

📖 Nepali Tip:

  • final = change गर्न नपाइने
  • finally = सधैं चल्ने block
  • finalize() = JVM ले object हटाउनु अघि call गर्ने method

📘 Java Logic Practice – Factorial, Fibonacci, Reverse String & Number


🔹 1. Factorial of a Number

The factorial of a number n is n × (n-1) × (n-2)…× 1

📖 Nepali Insight:
Factorial भन्नाले कुनै पनि संख्या n को सबैभन्दा सानो सम्म गुणन हो।
E.g., 5! = 5×4×3×2×1 = 120

✅ Java Code:

java

CopyEdit

int n = 5;

int fact = 1;

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

    fact *= i;

}

System.out.println(“Factorial: ” + fact);  // Output: 120


🔹 2. Fibonacci Series

Fibonacci series: 0, 1, 1, 2, 3, 5, 8,…
Each number = sum of previous two

📖 Nepali View:
यो series मा अर्को संख्या पहिला दुईको योग हो।

✅ Java Code:

java

CopyEdit

int n = 10;

int a = 0, b = 1;

System.out.print(“Fibonacci: ” + a + ” ” + b + ” “);

for (int i = 2; i < n; i++) {

    int c = a + b;

    System.out.print(c + ” “);

    a = b;

    b = c;

}


🔹 3. Reverse a Number

📖 Nepali:
संख्या उल्ट्याउने — 123 becomes 321

✅ Java Code:

java

CopyEdit

int num = 123;

int reversed = 0;

while (num != 0) {

    int digit = num % 10;

    reversed = reversed * 10 + digit;

    num /= 10;

}

System.out.println(“Reversed: ” + reversed);


🔹 4. Reverse a String

📖 Nepali:
String लाई पछाडिबाट अगाडि बनाउने।

✅ Java Code:

java

CopyEdit

String str = “Lok”;

String reversed = “”;

for (int i = str.length() – 1; i >= 0; i–) {

    reversed += str.charAt(i);

}

System.out.println(“Reversed String: ” + reversed);  // koL

✅ Or use:

java

CopyEdit

String reversed = new StringBuilder(str).reverse().toString();


✅ Summary Table

Logic Input Output
Factorial 5 120
Fibonacci 10 terms 0 1 1 2 3 5 8 13 21 34
Reverse Number 1234 4321
Reverse String “Test” “tseT”

📘 Java Logic Practice – Part 2 (Armstrong, Swap, Prime in Range)


🔹 1. Armstrong Number

A number is called Armstrong if the sum of its digits raised to the power of number of digits equals the original number.

📖 Nepali Insight:
153 = 1³ + 5³ + 3³ = 1 + 125 + 27 = 153 → Armstrong number हो।

✅ Java Code:

java

CopyEdit

int num = 153, original = num;

int result = 0;

while (num != 0) {

    int digit = num % 10;

    result += Math.pow(digit, 3);

    num /= 10;

}

System.out.println(result == original ? “Armstrong” : “Not Armstrong”);

📌 Use Math.pow(digit, numberOfDigits) for any length number.


🔹 2. Swap Two Numbers Without Temp Variable

📖 Nepali View:
दुई संख्यालाई एक अर्कासँग third variable प्रयोग नगरी साट्ने।

✅ Java Code:

java

CopyEdit

int a = 5, b = 10;

a = a + b;  // 15

b = a – b;  // 5

a = a – b;  // 10

System.out.println(“a: ” + a + “, b: ” + b);

✅ Output:

makefile

CopyEdit

a: 10

b: 5


🔹 3. Prime Numbers in a Range (e.g., 1 to 50)

📖 Nepali Insight:
1 देखि 50 भित्रका सबै Prime संख्या छान्ने।

✅ Java Code:

java

CopyEdit

for (int i = 2; i <= 50; i++) {

    boolean isPrime = true;

    for (int j = 2; j <= i / 2; j++) {

        if (i % j == 0) {

            isPrime = false;

            break;

        }

    }

    if (isPrime) {

        System.out.print(i + ” “);

    }

}

✅ Output:

CopyEdit

2 3 5 7 11 13 17 19 23 29 31 37 41 43 47


✅ Bonus Logic (Extra Fast)

🔸 Check Even Digits in a Number

java

CopyEdit

int num = 2468;

boolean allEven = true;

while (num != 0) {

    int digit = num % 10;

    if (digit % 2 != 0) {

        allEven = false;

        break;

    }

    num /= 10;

}

System.out.println(allEven ? “All even digits” : “Not all even”);

🔸 Count Digits in a Number

java

CopyEdit

int num = 987654;

int count = 0;

while (num != 0) {

    count++;

    num /= 10;

}

System.out.println(“Digits: ” + count);


✅ Summary Table

Task Example Input Output
Armstrong 153 Armstrong
Swap a=5, b=10 a=10, b=5
Prime in range 1–50 List of primes
Even digit check 2468 All even
Digit count 987654 6
Scroll to Top