0% found this document useful (0 votes)
26 views119 pages

Java

The document provides an overview of Java's history, key features, and its evolution as a programming language, highlighting its portability, security, and object-oriented principles. It contrasts Java with C++, discussing differences in memory management, syntax, and programming paradigms, while emphasizing the advantages of object-oriented programming. Additionally, it introduces foundational OOP concepts such as classes, objects, encapsulation, abstraction, inheritance, and polymorphism.

Uploaded by

9804427861a
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)
26 views119 pages

Java

The document provides an overview of Java's history, key features, and its evolution as a programming language, highlighting its portability, security, and object-oriented principles. It contrasts Java with C++, discussing differences in memory management, syntax, and programming paradigms, while emphasizing the advantages of object-oriented programming. Additionally, it introduces foundational OOP concepts such as classes, objects, encapsulation, abstraction, inheritance, and polymorphism.

Uploaded by

9804427861a
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

DAY-1

INTRODUCTION TO JAVA — HISTORY, FEATURES &


PLATFORM ARCHITECTURE
(Unit 1: Topics 1.1 and 1.3 from CMP-215 syllabus)

1. HISTORY OF JAVA
Java was created to solve major computing challenges such as portability, security, reliability,
and ease of development. Its timeline demonstrates how it grew into one of the most widely
used programming languages worldwide.

1991 — Project Green (The Beginning)


A team at Sun Microsystems, led by James Gosling, Patrick Naughton, and Mike Sheridan,
began designing a programming language for consumer electronic devices such as TV boxes,
remote controls, and other embedded systems.

Requirements identified:

●​ Platform independence​

●​ Security​

●​ Memory safety​

●​ High stability​

Original Name: Oak


Real-Life Example:​
A TV remote works without installing drivers. Java was designed to make software behave
similarly across all hardware environments.

1995 — Java 1.0 Released (Birth of Java)


Due to trademark issues, Oak was renamed Java. This release coincided with the rapid growth
of the internet.

Reasons for popularity:

●​ Ability to run applets inside web browsers​

●​ Introduction of the principle “Write Once, Run Anywhere (WORA)”​

Real-Life Example:​
A Java program written on Windows runs identically on Linux or macOS without modification.

1998 — Java 2 Platform (J2SE, J2EE, J2ME)


Java evolved into separate editions to meet different application needs:

●​ Java 2 Standard Edition (J2SE) – Desktop and general programming​

●​ Java 2 Enterprise Edition (J2EE) – Enterprise and distributed systems​

●​ Java 2 Micro Edition (J2ME) – Mobile and embedded devices​

Real-Life Example:​
Java powered ATMs, early mobile phones (Nokia, Motorola), and enterprise banking servers.

2006 — Java Becomes Open Source (OpenJDK)


Sun Microsystems released Java under the GNU GPL license as OpenJDK (Open Java
Development Kit).
Real-Life Example:​
Android uses OpenJDK as its underlying Java platform. Many cloud servers run Java
applications compiled with OpenJDK.

2010 — Oracle Corporation Acquires Sun Microsystems


Oracle became the primary maintainer and driver of Java’s development.

2014 → Present — Modern Java (Fast, Secure,


Cloud-Ready)
With releases such as Java 8, Java 11, Java 17, and Java 21, Java introduced:

●​ Lambda expressions​

●​ Stream API​

●​ Modular system​

●​ Faster and optimized JVM (Java Virtual Machine)​

●​ Cloud-ready enhancements​

Real-Life Usage Today:​


Netflix backend systems, Amazon’s order fulfillment system, banking systems in Nepal,
enterprise ERPs, and Android application development.

Verified References
Oracle Java History: [Link]
OpenJDK Project: [Link]
James Gosling Interview: [Link]
2. KEY FEATURES OF JAVA

1. Simple
Java removes complex features found in C++, such as pointers, manual memory handling, and
multiple inheritance through classes. This simplifies development and reduces errors.

Real-Life Example:​
Java is like driving an automatic scooter, while C++ is like driving a manual gear bike. The
simpler system results in fewer mistakes.

2. Object-Oriented Programming Language (OOP)


Java is built around OOP principles such as encapsulation, inheritance, polymorphism, and
abstraction.​
Software is modeled as objects containing attributes and behaviors.

Real-Life Example:​
A Car object:

●​ Attributes: color, model, engine​

●​ Behaviors: start(), brake(), accelerate()​

3. Platform Independent (WORA: Write Once, Run


Anywhere)
Java source code is compiled into platform-independent bytecode.​
The JVM (Java Virtual Machine) executes the bytecode on any operating system.

Real-Life Example:​
Just like a TikTok video plays the same across Android, iPhone, laptops, and televisions, Java
bytecode runs identically on all platforms.
4. Secure
Java eliminates pointer manipulation, enforces bytecode verification, and uses a secure
class-loading mechanism.

Real-Life Example:​
Banks use Java for online transactions because memory corruption attacks are prevented
through Java’s secure architecture.

5. Robust
Java includes automatic garbage collection, strong type checking, and extensive error handling.

Real-Life Example:​
A C++ application may crash due to memory leaks, but Java automatically manages memory,
preventing such failures.

6. Multithreaded
Java supports concurrent execution of multiple tasks through built-in threading mechanisms.

Real-Life Example:​
A phone can download files, stream music, and browse the internet simultaneously — Java can
implement such multitasking in software.

7. Dynamic
Java applications can load classes at runtime, enabling extensible and flexible systems.

Real-Life Example:​
VS Code allows adding extensions without reinstalling the software; Java applications can
behave similarly through dynamic class loading.

3. JAVA EDITIONS (SE, EE, ME, JavaFX) —


1. Java SE (Java Standard Edition)
Definition:​
The foundational Java platform used for general-purpose programming.

Full Form: Standard Edition

Includes:​
Core OOP concepts, data structures, collections, threading, file handling, JavaFX user interface
libraries.

Real-Life Uses:​
Desktop tools, academic projects, command-line utilities, billing software.

2. Java EE (Java Enterprise Edition)


Definition:​
A platform used to build enterprise-level, multi-tier, distributed applications.

Full Form: Enterprise Edition

Includes:​
Servlets, JSP (JavaServer Pages), JPA (Java Persistence API), EJB (Enterprise JavaBeans),
web services.

Real-Life Uses:​
eSewa backend, banking systems, government e-portals, telecom billing systems.

3. Java ME (Java Micro Edition)


Definition:​
A lightweight Java platform for mobile and embedded systems.

Full Form: Micro Edition

Real-Life Uses:​
Set-top boxes, smart electricity meters, older Nokia mobile phones, SIM card applications.
4. JavaFX (Graphical User Interface Framework)
Definition:​
A modern GUI (Graphical User Interface) framework for building desktop applications.

Real-Life Uses:​
POS systems, data visualization dashboards, interactive desktop applications.

4. JAVA PLATFORM COMPONENTS —


JDK, JRE, JVM, BYTECODE
(Unit 1: Topics 1.3.1 – 1.3.4)

4.1 JDK (Java Development Kit)


Definition:​
A complete software development kit for creating, compiling, and running Java applications.

Full Form: Java Development Kit

Includes:​
Java compiler (javac), Java Runtime Environment (JRE), debugger, development tools,
standard Java libraries.

Purpose:​
Allows developers to write and build Java programs.

Analogy:​
A full kitchen where you can prepare and cook food.

4.2 JRE (Java Runtime Environment)


Definition:​
A runtime environment that provides the necessary components to run Java applications.

Full Form: Java Runtime Environment

Includes:​
JVM (Java Virtual Machine) and standard Java libraries.

Purpose:​
Allows execution of Java bytecode but does not provide compilation tools.

Analogy:​
A dining room where you can only eat food, not cook it.

4.3 JVM (Java Virtual Machine)


Definition:​
A virtual processor that executes Java bytecode by converting it into operating-system-specific
machine instructions.

Full Form: Java Virtual Machine

Responsibilities:​
Class loading, bytecode verification, memory allocation, garbage collection, Just-In-Time (JIT)
compilation.

Purpose:​
Makes Java applications platform independent.

Analogy:​
A smartphone operating system that can run all apps regardless of where they were developed.

4.4 Bytecode
Definition:​
Bytecode is the platform-independent intermediate representation generated from Java source
code during compilation.

Purpose:​
Allows the same program to run on any operating system with a JVM.
Conversion Example:​
[Link] → compiled with javac → [Link] (bytecode)

Analogy:​
A PDF file — once exported, it opens on any device regardless of the system used to create it.

JAVA EXECUTION MODEL (DIAGRAM)


Source Code (.java)
|
| Compiled by javac (Java Compiler)
v
Bytecode (.class File)
|
| Executed by JVM (Java Virtual Machine)
v
Machine-Level Instructions
|
v
Final Program Output

DAY 2
C++ vs Java, Procedure-Oriented vs Object-Oriented
(Covers Syllabus Topics 1.2 and 1.4 from CMP 215)

WHAT YOU WILL LEARN TODAY


●​ Syntax & conceptual differences between C++ and Java​

●​ Memory management differences​

●​ Why Java removed pointers​

●​ Why Java is not fully object-oriented​

●​ What Procedure-Oriented Programming (POP) is​

●​ What Object-Oriented Programming (OOP) is​

●​ How OOP changes the way we think about programs​

Outcome:​
A clear understanding of why Java was created, how it differs from C++, and why OOP became
the dominant approach.

1. C++ vs Java
C++ and Java share similarities in syntax, but their design philosophies are very different.​
C++ focuses on performance and control, while Java focuses on safety, portability, and ease of
development.

1.1 Fundamental Definitions


C++​
A general-purpose programming language supporting both procedural and object-oriented
programming. It provides low-level memory control through pointers.

Java​
A high-level, purely object-oriented language (except primitive data types) designed for
portability, security, and reliability.

1.2 Comparison Table (Professional Format)


Feature C++ Java

Platform Dependency Platform-dependent Platform-independent (via JVM)

Compilation Model Compiled to machine Compiled to bytecode and executed


code by JVM

Memory Management Manual (new and Automatic Garbage Collection


delete)

Pointers Fully supported Not supported

Multiple Inheritance Supported Not supported (handled via


(Classes) interfaces)

Security Less secure Highly secure (runtime checks)

Programming Paradigm Procedural + OOP Pure OOP (except primitives)

Speed Faster (direct hardware Slightly slower (JVM overhead)


access)

Exception Handling Optional Mandatory for many errors

Operator Overloading Supported Not supported

Header Files Required (#include) Not required

1.3 Why Java Removed Certain C++ Features


Feature in C++ Removed in Reason
Java

Pointers Yes Prevent memory corruption and unsafe


operations

Multiple Inheritance Yes Avoid ambiguity (diamond problem)

Manual Memory Yes Reduce memory leaks and crashes


Management

Header Files Yes Simplify development

Operator Overloading Yes Reduce complexity

Java was designed to eliminate common C++ developer errors.

1.4 Real-Life Analogy


C++ is like a manual transmission car:​
You control everything — gears, clutch, engine speed — giving you more control but increasing
risk.

Java is like an automatic transmission car:​


The system handles complexity internally, allowing you to focus on driving safely and efficiently.

2. Procedure-Oriented Programming (POP)


vs Object-Oriented Programming (OOP)

2.1 Definitions
Procedure-Oriented Programming (POP)​
A programming paradigm where the main focus is on functions or procedures that operate on
data.​
Data is often global, and functions manipulate it directly.
Object-Oriented Programming (OOP)​
A paradigm based on real-world modeling where data and behaviors are grouped into objects.​
The emphasis is on objects rather than actions.

2.2 POP vs OOP — Professional Comparison Table


Aspect POP OOP

Focus Functions/processes Objects and data

Data Security Low (global data) High (encapsulation)

Reusability Limited High (inheritance,


polymorphism)

Scalability Poor Excellent

Real-world Modeling Weak Strong

Maintenance Difficult Easier

Examples C, early C++ Java, Python, C#, modern


C++

2.3 Why OOP Is Superior for Modern Applications


●​ Closer to how humans think (entities & behaviors)​

●​ Makes large applications easier to maintain​

●​ Supports modularity and reuse​

●​ Encapsulation protects sensitive data​

This is why Java is built around OOP principles.

2.4 Real-Life Analogy


POP = A list of instructions (recipe).

●​ If one step changes, you must edit multiple parts.​

OOP = A kitchen with reusable tools.

●​ Tools (objects) stay the same; you just call different behaviors.​

3. Why Java Is Not Fully Object-Oriented


Java is often called “almost purely object-oriented,” but not fully, because:

1.​ Primitive data types (int, double, char, boolean) are not objects.​

2.​ Static methods belong to the class, not objects.​

3.​ Java uses wrapper classes instead of making primitives objects by default.​

This was done to keep Java efficient and beginner-friendly.

4. Introduction to OOP Thinking


(Foundation for Day 3)
Before we explore OOP concepts deeply tomorrow, here is the conceptual shift Java requires:

POP Thinking OOP Thinking

“What steps solve this problem?” “Which objects interact and how?”

Data flows freely Data is controlled and protected

Hard to maintain systems Modular, reusable, extendable


systems
Real-Life Transition Example
POP approach to a school system:​
Write functions like addStudent(), updateStudent(), getMarks().​
Data is passed everywhere.

OOP approach:​
Create objects like Student, Teacher, Subject, each with its own data and behavior.

This shift is essential for real-world software design.

DAY 2 OUTCOME
After completing Day 2, you should be able to:

●​ Clearly explain differences between C++ and Java​

●​ Understand why Java removed risky C++ features​

●​ Explain POP vs OOP confidently​

●​ Understand the conceptual advantages of OOP​

●​ Begin thinking in terms of objects rather than procedures

DAY 3
OOP BASICS + STRUCTURE OF A JAVA PROGRAM
(Covers Syllabus Topics 1.5 and 1.6 from CMP 215)
WHAT YOU WILL LEARN TODAY
●​ Definition of Class & Object​

●​ Encapsulation​

●​ Abstraction​

●​ Inheritance (introductory level)​

●​ Polymorphism (introductory level)​

●​ Structure of a Java class​

●​ Structure of main()​

●​ Naming conventions (standard Java style)​

Outcome:​
By the end of Day 3, you should be able to read, understand, and explain any
beginner-level Java program, including identifying classes, objects, methods, and naming
patterns.

1. CLASS AND OBJECT —


FOUNDATIONAL OOP CONCEPTS

1.1 Class (Blueprint Concept)


Definition:​
A class is a blueprint, template, or design from which objects are created.​
It defines attributes (data) and methods (behaviors).

Academic Explanation:​
A class does not occupy memory until an object is created.​
It only describes what the object will contain and how it will behave.
Real-Life Analogy:​
A class is like an architectural blueprint of a house.​
The blueprint itself is not a house.​
Actual houses (objects) are created from it.

1.2 Object (Instance of a Class)


Definition:​
An object is a real, usable instance created from a class.​
It occupies memory and performs actions defined by the class.

Real-Life Analogy:​
If “Car” is a class,​
then “Red Honda City 2020 with plate number XYZ” is an object.

1.3 UML Representation

1.4 Example in Java


2. ENCAPSULATION — DATA
PROTECTION

Definition:
Encapsulation is the process of binding data (variables) and methods (functions) together and
restricting direct access to the internal data.

This is done using:

●​ private variables​

●​ public getter/setter methods​


Purpose:​
Data protection, controlled access, modular design.

Real-Life Analogy:
An ATM machine hides internal operations; users interact only through a secure interface.

Java Example (Encapsulation)

3. ABSTRACTION — HIDING COMPLEXITY

Definition:
Abstraction hides unnecessary internal details and shows only the essential features.
Purpose:​
Reduce complexity, improve readability, focus on behavior rather than implementation.

Real-Life Analogy:
A car driver only sees the accelerator and steering wheel, not the engine mechanism.

Java Example (Abstraction)

4. INHERITANCE (INTRODUCTION)

Definition:
Inheritance allows a new class (child/subclass) to acquire properties and behaviors of an
existing class (parent/superclass).

Purpose:​
Reusability, reduce code duplication, establish natural hierarchy.
Real-Life Analogy:
A child inherits physical traits and characteristics from parents.

Java Example (Inheritance)

5. POLYMORPHISM (INTRODUCTION)

Definition:
Polymorphism allows one action to behave differently based on the object performing it.

Two main forms:

1.​ Compile-time polymorphism (Method Overloading)​


2.​ Runtime polymorphism (Method Overriding)​

Real-Life Analogy:
A person can be:

●​ A student in college​

●​ A customer in a shop​

●​ A passenger in a vehicle​

Same person, different roles.

Simple Example (Method Overloading)

6. STRUCTURE OF A JAVA PROGRAM


A standard Java program consists of:

1.​ Package declaration (optional)​

2.​ Import statements (optional)​

3.​ Class definition​


4.​ Variables and methods​

5.​ main() method (entry point)​

Example Structure

7. WHAT GOES INSIDE main()


The main() method is the starting execution point of any standalone Java program.

public static void main(String[] args)


Breakdown:

●​ public: accessible everywhere​

●​ static: no object needed to call it​

●​ void: returns nothing​

●​ String[] args: command-line arguments​

8. JAVA NAMING CONVENTIONS


(STANDARD PRACTICE)
Element Convention Example

Class Name PascalCase EmployeeRecord

Method Name camelCase calculateSalary()

Variable Name camelCase employeeName

Constant UPPER_CASE MAX_VALUE

Package Name lowercase [Link]

DAY 3 OUTCOME
You should now be able to:

●​ Define and differentiate classes and objects​

●​ Explain encapsulation and abstraction with examples​

●​ Understand the purpose of inheritance and polymorphism​

●​ Identify parts of a Java program​

●​ Write and read simple Java class structures​

●​ Apply correct naming conventions​

DAY 4
Writing, Compiling, Running Java Programs + Scanner
Class
(Covers Syllabus Topics 1.7 and 1.8 from CMP 215)

WHAT YOU WILL LEARN TODAY


●​ How to write a Java program properly​

●​ How Java compilation works (javac)​

●​ How Java execution works (java)​

●​ Using terminal/command prompt to run programs​

●​ Using an IDE (IntelliJ / Eclipse / VS Code)​


●​ How to take user input using the Scanner class​

●​ Basic errors beginners face, and how to fix them​

Outcome:​
By the end of Day 4, you will be able to write, compile, and run any basic Java program,
take user input, and understand the role of the compiler and JVM during execution.

1. WRITING A SIMPLE JAVA PROGRAM


Every Java program must be written inside a class, and execution always begins with the
main() method.

1.1 Example Program

Key Points:
1.​ File name = Class name (when public)​
Example: [Link]​

2.​ main() is the entry point​


The JVM starts execution from main().​

3.​ [Link]() prints output.​


2. COMPILING A JAVA PROGRAM — javac
The Java compiler javac converts .java source code into bytecode (.class files).

2.1 Compilation Command

javac [Link]

If no errors exist, this creates a file:

[Link]

This .class file contains bytecode, which is platform-independent.

3. RUNNING A JAVA PROGRAM — java


To run the program:

java Hello

Notice:

●​ You run the class name, not the file name​

●​ You do not include .class or .java​


4. FULL PROGRAM LIFECYCLE (Diagram)

5. COMMON BEGINNER ERRORS AND


FIXES
Error Cause Fix

class Hello is public, File name and class Rename file


should be declared in a name mismatch
file named [Link]

Missing semicolon Syntax error Add ;

main method not found main is missing or Ensure signature: public


incorrectly written static void
main(String[] args)

cannot find symbol Using variable Declare properly


without declaring it
6. WRITING & RUNNING JAVA PROGRAMS
IN IDEs
6.1 Popular IDEs:
●​ IntelliJ IDEA​

●​ Eclipse​

●​ Visual Studio Code (with Java extension)​

IDE Benefits:

●​ Auto-complete​

●​ Error highlighting​

●​ Run button​

●​ Project structure handling​

Even though IDEs simplify the workflow, understanding javac and java is essential for
fundamentals.

7. TAKING USER INPUT — Scanner Class


The Scanner class (from [Link] package) is used to take input from the keyboard.
7.1 Example: Reading Input

7.2 Common Scanner Methods


Method Description

nextInt() Reads an integer

nextDouble() Reads a decimal number

nextLine() Reads a full line of text

next() Reads a single word

nextBoolean() Reads true/false

8. HANDLING BASIC INPUT ERRORS


Problem: Input mismatch​
Example: User enters text when number expected.
Solution:​
Use nextLine() after numeric input to clear the buffer.​
Or apply try-catch (covered later in exception handling).

9. PRACTICE PROGRAMS (HIGHLY


IMPORTANT)
9.1 Program 1: Add two numbers
9.2 Program 2: Check if user is adult or minor
9.3 Program 3: Read name, address, phone number

DAY 4 OUTCOME
By completing Day 4, you should be able to:

●​ Write a correct Java program structure​

●​ Compile using javac​


●​ Run using java​

●​ Understand how JVM executes bytecode​

●​ Use Scanner to accept user input​

●​ Fix common syntax and runtime errors​

●​ Work confidently both in terminal and IDE​

DAY 5
Java Tokens, Keywords, Identifiers, Variables, Constants
(Covers Syllabus Topics 2.1 and 2.2 from CMP 215)

WHAT YOU WILL LEARN TODAY


●​ What tokens are​

●​ Types of tokens in Java​

●​ Identifiers and naming rules​

●​ Java keywords (full list + explanation)​

●​ Variables and variable declaration rules​

●​ Difference between variable, literal, identifier​

●​ Constants using final​

●​ Real-life examples and code demonstrations​


Outcome:​
By the end of Day 5, you will clearly understand what Java code is made of, how to name
things properly, and how variables/constants work inside programs.

1. JAVA TOKENS

Definition:
Tokens are the smallest individual units or building blocks of a Java program.​
Everything you write in code is composed of tokens.

Types of Java Tokens


1.​ Keywords​

2.​ Identifiers​

3.​ Literals​

4.​ Operators​

5.​ Separators (Symbols)​

6.​ Comments​

1.1 Keywords
Keywords are reserved words in Java with predefined meaning.​
You cannot use them as variable names, class names, or identifiers.

Examples:​
int, class, public, static, void, return
Full List of Java Keywords (Important for Exams)

(goto and const are reserved but not used in Java)

1.2 Identifiers
Identifiers are names given to variables, classes, methods, interfaces, etc.

Examples:​
studentName, Employee, calculateTotal()

Identifier Rules (Very Important)

●​ Must start with a letter, _, or $​

●​ Cannot start with a digit​

●​ Cannot contain spaces​

●​ Cannot be a keyword​
●​ Java is case-sensitive (Age and age are different)​

Valid vs Invalid

Valid Identifiers Invalid Identifiers

sum 1number

totalAmount class

_index student name

$price new

1.3 Literals
Literals represent fixed constant values used in a program.

Examples:

●​ Integer literal → 10​

●​ Floating literal → 5.67​

●​ Character literal → 'A'​

●​ String literal → "Hello"​

●​ Boolean literal → true, false​


1.4 Operators
Operators perform operations on variables.

Examples: +, -, *, /, =, ==, &&, %​


(Explained in detail on Day 7)

1.5 Separators (Symbols)


These symbols help structure the program:

Symbol Meaning

; Statement terminator

{} Block of code

() Method / condition bracket

[] Array

, Separator

. Member access operator

1.6 Comments
Comments are notes ignored by the compiler.

// single-line comment

/* multi-line

comment */

2. VARIABLES IN JAVA

Definition:
A variable is a named memory location used to store data.

Every variable has:

1.​ Name (identifier)​

2.​ Type​

3.​ Value​

2.1 Declaring Variables


int age;

double salary;

String name;

2.2 Initializing Variables


int age = 20;

double salary = 45000.50;

String city = "Kathmandu";

2.3 Variable Declaration Rules


●​ Must follow identifier rules​

●​ Must have a type​

●​ Cannot use keywords as names​

●​ Must be declared before use​

3. DIFFERENCE: VARIABLE vs
IDENTIFIER vs LITERAL
Term Meaning Example

Identifier Name given to entity age

Literal Actual fixed value 20

Variable Identifier + stored value int age = 20;

4. CONSTANTS IN JAVA (final)


A constant is a variable whose value cannot be changed after assignment.

Use the final keyword.

Example: Constant
final double PI = 3.14159;

final int MAX_USERS = 100;

Naming Rule:

Constants are written in UPPER_CASE.

Real-Life Analogy for Constants


●​ Your citizenship number: fixed​

●​ Your date of birth: cannot change​

●​ In a banking system → interest rate constant​

These values never change once assigned.

5. PRACTICE PROGRAMS (For Mastery)

5.1 Program: Display student profile


5.2 Program: Using all token types

DAY 5 OUTCOME
After completing Day 5, you should be able to:

●​ Identify all Java tokens​

●​ Use valid identifiers​

●​ Recognize Java keywords​

●​ Declare and use variables correctly​

●​ Understand constants and the final keyword​

●​ Write beginner-level programs using proper naming rules​

DAY 6
Data Types in Java (Primitive & Non-Primitive)
(Covers Syllabus Topic 2.3 from CMP 215)
WHAT YOU WILL LEARN TODAY
●​ What data types are and why they matter​

●​ Primitive data types (size, range, default values)​

●​ Non-primitive/reference data types​

●​ Memory allocation differences​

●​ Type conversion (widening)​

●​ Type casting (narrowing)​

●​ Real-life examples and code demonstrations​

Outcome:​
By the end of Day 6, you will clearly understand how Java stores data, which type to use
for which purpose, and how conversions work during calculations and assignments.

1. WHAT ARE DATA TYPES?


A data type specifies:

1.​ The type of data stored​

2.​ The size of memory allocated​

3.​ The range of possible values​

4.​ The operations allowed on that data​

Java is a strongly typed language, meaning every variable must have a type before use.

Example:
int age = 20;

double price = 150.75;

String name = "Rohan";

2. PRIMITIVE DATA TYPES (8 Types)


These are built-in, basic data types provided by Java.​
They store simple values and not objects.

2.1 Table of Primitive Types

Type Size Range Default Example


Value

byte 1 -128 to 127 0 byte a = 10;


byte

short 2 -32,768 to 32,767 0 short s = 200;


bytes

int 4 ~ -2 billion to +2 billion 0 int age = 20;


bytes
long 8 very large range 0L long population =
bytes 8000000000L;

float 4 6–7 decimal digits 0.0f float marks = 88.67f;


bytes

double 8 15–16 decimal digits 0.0d double salary = 45000.50;


bytes

char 2 Unicode characters '\u0000' char grade = 'A';


bytes

boolean 1 bit true/false false boolean isActive = true;

2.2 Real-Life Examples


●​ byte batteryLevel → mobile battery percentage (0 to 100)​

●​ int studentId → school roll number​

●​ double bankBalance → money with decimals​

●​ char section → 'A', 'B', 'C'​

●​ boolean isVerified → true/false login flags​


3. NON-PRIMITIVE DATA TYPES
(REFERENCE TYPES)
These store references (addresses), not actual values.

Common Non-Primitive Types


1.​ String​

2.​ Arrays​

3.​ Classes & Objects​

4.​ Interfaces​

3.1 String Example


String name = "Pratik";

Strings are objects; even though we write them like primitives, they are stored in the
heap memory.

3.2 Array Example


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

3.3 Class/Object Example


Student s1 = new Student();

4. MEMORY MODEL DIFFERENCE


(IMPORTANT)
Primitive Non-Primitive

Stored in stack Stored in heap

Holds actual value Holds memory address


(reference)

Fast Slower

Fixed size Dynamic size

5. TYPE CONVERSION (WIDENING)


Also called implicit conversion.​
Happens automatically when a smaller type is converted into a larger type.

Order:​
byte → short → int → long → float → double

Example:
int a = 10;

double b = a; // automatic widening

No data loss occurs.

6. TYPE CASTING (NARROWING)


Manual conversion from larger type to smaller type.

Risk: Data loss may occur.​


Syntax requires cast operator (type).

Example:

double d = 45.78;

int x = (int) d; // narrowing (decimal lost)

6.1 Real-Life Analogy


●​ Widening = pouring water from a small glass into a big bucket (no loss).​

●​ Narrowing = pouring from a bucket into a glass (overflow/loss possible).​

7. SPECIAL NOTES ABOUT DATA TYPES

7.1 Integer literals default to int


long num = 12345678900; // error

long num = 12345678900L; // correct

7.2 Decimal literals default to double


float price = 12.5; // error

float price = 12.5f; // correct

7.3 Character stores Unicode


char letter = 'न'; // Nepali Devnagari also allowed

8. PRACTICE PROGRAMS

8.1 Display all primitive types


8.2 Demonstrate widening and narrowing
DAY 6 OUTCOME
After completing Day 6, you should be able to:

●​ Identify and use all primitive data types​

●​ Differentiate primitive vs reference types​

●​ Understand memory allocation differences​

●​ Apply widening and narrowing conversions correctly​

●​ Choose the right type (int vs float vs double etc.)​

●​ Avoid common mistakes with literals and casting​

DAY 7
Operators in Java (Arithmetic, Relational, Logical,
Assignment, Unary, Short-Circuit Logic)
(Covers Syllabus Topic 2.4 from CMP 215)

WHAT YOU WILL LEARN TODAY


●​ What operators are and why they are necessary​

●​ Categories of operators in Java​

●​ Arithmetic operators​

●​ Relational operators​

●​ Logical operators​

●​ Unary operators​

●​ Assignment operators​

●​ Short-circuit logical operators (&&, ||)​

●​ Operator precedence basics​

●​ Real-life examples and code demonstrations​

Outcome:​
By the end of Day 7, you will be able to write correct mathematical and logical
expressions, compare values, use conditions efficiently, and understand how Java
evaluates expressions internally.

1. INTRODUCTION TO OPERATORS

Definition:
Operators are symbols that perform operations on variables and values.
Example:

int sum = a + b;

Here,​
+ is an operator​
a and b are operands.

Java operators are grouped into several categories.

2. ARITHMETIC OPERATORS
Used for basic mathematical operations.

Operator Meaning Example Result

+ Addition 10 + 5 15

- Subtraction 10 - 5 5

* Multiplication 10 * 5 50

/ Division 10 / 4 2

% Modulus 10 % 4 2
(remainder)
Important Notes:
●​ Integer division always drops decimals.​

●​ Modulus is useful for checking even/odd, cyclic rotations, etc.​

Example:
int a = 10, b = 4;

[Link](a / b); // 2

[Link](a % b); // 2

3. RELATIONAL OPERATORS
These compare two values.​
Used heavily in decision-making (if, while).

Operator Meaning

== equal to

!= not equal

> greater than


< less than

>= greater or
equal

<= less or equal

Example:
int age = 20;

[Link](age >= 18); // true

Real-Life Analogy:
Relational operators answer questions like:

●​ Is this student older than 18?​

●​ Is the bill amount greater than the discount limit?​

●​ Is the password length equal to required length?​

4. LOGICAL OPERATORS
Used to combine multiple conditions.​
Operate only on boolean values.
Operator Meaning Example

&& Logical AND both conditions must be true

! Logical NOT reverses boolean value

Example:
int age = 20;

boolean hasId = true;

if (age >= 18 && hasId) {

[Link]("Entry permitted.");

Real-Life Example:
To log into an account:

correct username AND correct password ⇒ login success


5. SHORT-CIRCUIT OPERATORS (VERY
IMPORTANT)
Java evaluates only as much as necessary.

5.1 && Short-Circuit AND


If the left condition is false, Java skips the right condition.

Example:

if (x > 10 && y++ > 5) { }

If x > 10 is false → y++ is never executed.

5.2 || Short-Circuit OR
If the left condition is true, Java skips the right condition.

Why this matters?

Avoids unnecessary evaluation and prevents errors.

Example:

if (user != null && [Link] > 18)

If user is null, Java never checks [Link] → prevents crash.


6. UNARY OPERATORS
Operate on a single operand.

Operator Meaning Example

++ Increment by 1 x++

-- Decrement by 1 x--

+ Unary plus +x

- Unary minus -x

! Logical NOT !flag

Pre vs Post Increment

Form Meaning

++x Pre-increment (increase first, then use value)

x++ Post-increment (use current value, then increase)


Example:

int x = 5;

[Link](++x); // 6

[Link](x++); // prints 6, then x becomes 7

7. ASSIGNMENT OPERATORS
These update the value of a variable.

Operator Meaning Example

= Assign x = 10

+= Add & assign x += 5 → x = x + 5

-= Subtract & assign x -= 5

*= Multiply & assign x *= 5

/= Divide & assign x /= 5

%= Modulus & assign x %= 5


8. OPERATOR PRECEDENCE (BASIC)
Higher precedence operators are evaluated first.

Order (high → low):

1.​ ++ --​

2.​ * / %​

3.​ + -​

4.​ < > <= >=​

5.​ == !=​

6.​ &&​

7.​ ||​

8.​ =​

9. PRACTICE PROGRAMS
9.1 Arithmetic & Relational Test

9.2 Short-Circuit Example


9.3 Operator Mixing

DAY 7 OUTCOME
You now understand:

●​ All major categories of operators​

●​ How arithmetic, relational, and logical operators work​

●​ How short-circuit evaluation prevents errors​

●​ How increment/decrement works (pre & post)​

●​ How assignment operators simplify calculations​

●​ How operator precedence impacts expression results​

You are now ready for Control Statements.


DAY 8
Control Statements in Java (Part 1: Branching
Statements)
(Covers Syllabus Topic 2.5.1 from CMP 215)

WHAT YOU WILL LEARN TODAY


●​ What control statements are​

●​ How decision-making works in Java​

●​ if statement​

●​ if-else​

●​ nested if​

●​ else-if ladder​

●​ switch statement​

●​ When to use which type​

●​ Real-life examples​

●​ Clean code practices​

Outcome:​
By the end of Day 8, you will be able to write all branching statements confidently and
choose the correct control structure for real-world problems.
1. INTRODUCTION TO CONTROL
STATEMENTS
A program normally executes statements top to bottom, but control statements allow you
to:

●​ Make decisions​

●​ Repeat actions​

●​ Jump to different parts of code​

Today's focus is branching (decision-making).

2. THE IF STATEMENT
Used when you want to execute a block of code only if a condition is true.

Syntax
if (condition) {

// statements

Example
int age = 20;
if (age >= 18) {

[Link]("Eligible to vote");

Real-Life Example:
If it is raining → take an umbrella.

3. IF-ELSE STATEMENT
Used when you want to handle two possible outcomes.

Syntax
if (condition) {

// true block

} else {

// false block

Example
int marks = 45;
if (marks >= 40) {

[Link]("Pass");

} else {

[Link]("Fail");

4. ELSE-IF LADDER
Used when you have multiple conditions to check.

Syntax
if (condition1) {

...

} else if (condition2) {

...

} else if (condition3) {

...

} else {

...

}
Example
int marks = 72;

if (marks >= 80) {

[Link]("Distinction");

} else if (marks >= 60) {

[Link]("First Division");

} else if (marks >= 45) {

[Link]("Second Division");

} else {

[Link]("Fail");

When to use:
●​ Multiple ranges​

●​ Multiple categories​

●​ Step-by-step decisions​

5. NESTED IF STATEMENTS
An if inside another if.
Example
int age = 20;

boolean hasVoterId = true;

if (age >= 18) {

if (hasVoterId) {

[Link]("Eligible to vote");

} else {

[Link]("Age ok, but no voter ID");

} else {

[Link]("Not eligible");

When to use:
Use nested-if when decisions are dependent on each other.

6. SWITCH STATEMENT
Used for multi-way branching when comparing the same variable to multiple values.

Best used for:

●​ Menu selection​
●​ Day/month names​

●​ Grades​

●​ Fixed value conditions​

Syntax
switch (expression) {

case value1:

statements;

break;

case value2:

statements;

break;

default:

statements;

Important Notes
●​ break prevents fall-through​

●​ default is optional but recommended​


●​ Cases must be constant values​

Example: Day of Week


int day = 3;

switch (day) {

case 1: [Link]("Sunday"); break;

case 2: [Link]("Monday"); break;

case 3: [Link]("Tuesday"); break;

case 4: [Link]("Wednesday"); break;

default: [Link]("Invalid day");

Example: Simple Calculator


int a = 10, b = 5;

char op = '+';

switch (op) {

case '+': [Link](a + b); break;

case '-': [Link](a - b); break;

case '*': [Link](a * b); break;

case '/': [Link](a / b); break;


default: [Link]("Invalid operator");

7. IF-ELSE vs SWITCH (Important


Differences)
Feature if-else switch

Conditions Ranges, expressions Fixed values only

Speed Slightly slower for many Faster for constant


conditions comparisons

Use case Complex logic Menus, categories, enums

Data types Supports all int, char, String, enum

8. COMMON MISTAKES
Mistake Explanation

Using = instead of == = assigns, == compares


Missing break in switch Causes fall-through

Writing unreachable code Java will not compile

Not using braces Leads to logical errors

9. PRACTICE PROGRAMS

9.1 Grade Calculator


import [Link].*;

class Grade {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter marks: ");

int marks = [Link]();

if (marks >= 80) {

[Link]("Distinction");

} else if (marks >= 60) {

[Link]("First Division");
} else if (marks >= 45) {

[Link]("Second Division");

} else {

[Link]("Fail");

9.2 Menu-driven Program Using Switch


import [Link].*;

class Menu {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("1. Add");

[Link]("2. Subtract");

[Link]("3. Multiply");

[Link]("Choose option: ");

int option = [Link]();

switch (option) {
case 1: [Link]("Adding..."); break;

case 2: [Link]("Subtracting..."); break;

case 3: [Link]("Multiplying..."); break;

default: [Link]("Invalid choice");

DAY 8 OUTCOME
After completing Day 8, you should be able to:

●​ Write if, if-else, nested-if, else-if ladder​

●​ Use switch for clean multi-way selection​

●​ Decide which branching structure fits a problem​

●​ Understand control flow and decision-making logic​

●​ Handle menus, grading systems, and input-based decisions​

DAY 9
Control Statements (Part 2: Looping & Jumping
Statements)
(Covers Syllabus Topics 2.5.2 and 2.5.3 from CMP 215)
WHAT YOU WILL LEARN TODAY
●​ Why loops are needed​

●​ for loop​

●​ while loop​

●​ do-while loop​

●​ Differences between loops​

●​ Infinite loops​

●​ Nested loops​

●​ Jump statements: break, continue, return​

●​ Real-life examples​

●​ Pattern printing (intro)​

Outcome:​
By the end of Day 9, you will be able to write loops confidently, control iterations, stop
loops early, skip iterations, and identify which loop is appropriate for each situation.

1. INTRODUCTION TO LOOPING
A loop allows you to execute a block of code repeatedly until a condition becomes false.

Examples of real-life loops:

●​ A machine counting products one by one​

●​ Taking attendance roll numbers from 1 to N​

●​ Printing bills for multiple customers​


2. FOR LOOP
Best used when number of iterations is known.

Syntax
for (initialization; condition; update) {

// statements

Example: Print numbers 1 to 5


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

[Link](i);

Real-Life Example:
Print student roll numbers from 1 to 40.

Flow
1.​ Initialization → run once​
2.​ Condition check​

3.​ Execute body​

4.​ Update​

5.​ Repeat​

3. WHILE LOOP
Best used when iterations are unknown but depend on a condition.

Syntax
while (condition) {

// statements

Example:
int i = 1;

while (i <= 5) {

[Link](i);

i++;

}
Real-Life Example:
Keep asking for password until the correct one is entered.

4. DO-WHILE LOOP
Executes at least once, even if condition is false.

Syntax
do {

// statements

} while (condition);

Example:
int i = 1;

do {

[Link](i);

i++;

} while (i <= 5);


Real-Life Example:
ATM machine shows “Insert Card” message at least once even before knowing card
status.

5. DIFFERENCE BETWEEN FOR, WHILE,


DO-WHILE
Loop Condition Check Best Use

for Before body Fixed number of iterations

while Before body Condition-based repetition

do-while After body Must run at least once

6. NESTED LOOPS
A loop inside another loop.

Example: Nested for loops


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

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


[Link](j + " ");

[Link]();

Output
123

123

123

7. INFINITE LOOPS
Using for:
for (;;) {

[Link]("Running...");

Using while:
while (true) {

[Link]("Hello");
}

Use carefully — system may crash.

8. JUMP STATEMENTS

8.1 break
Stops the loop immediately.

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

if (i == 5) break;

[Link](i);

Output: 1 2 3 4

8.2 continue
Skips the current iteration and jumps to the next.

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

if (i == 3) continue;

[Link](i);

}
Output: 1 2 4 5

8.3 return
Exits the method, not just the loop.

public static void test() {

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

if (i == 3) return;

[Link](i);

[Link]("This will not run");

9. PRACTICE PROGRAMS

9.1 Sum of first N numbers


int sum = 0;

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

sum += i;

[Link](sum);
9.2 Print multiplication table
int n = 5;

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

[Link](n + " x " + i + " = " + (n * i));

9.3 Reverse counting using while loop


int i = 5;

while (i >= 1) {

[Link](i);

i--;

9.4 At least one execution (do-while)


int password = 1234;

int input;

do {

input = [Link]();
} while (input != password);

9.5 Continue example


Print numbers 1–10 but skip multiples of 3:

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

if (i % 3 == 0) continue;

[Link](i);

DAY 9 OUTCOME
You now understand:

●​ All loop types and their use cases​

●​ Difference between for, while, do-while​

●​ How to build nested loops​

●​ How break, continue, return affect execution​

●​ How to avoid infinite loops​

●​ How loops behave in real-world logic​


DAY 10
Arrays in Java (1D & 2D)
(Covers Syllabus Topic 2.6 from CMP 215)

WHAT YOU WILL LEARN TODAY


●​ What arrays are and why they are used​

●​ Array declaration, creation, initialization​

●​ One-dimensional arrays (1D)​

●​ Two-dimensional arrays (2D / matrices)​

●​ Accessing, updating, traversing arrays​

●​ Common mistakes (index errors)​

●​ Real-life examples (billing, attendance, marks storage)​

●​ Intro to array-based problems​

Outcome:​
By the end of Day 10, you will be able to create, manipulate, store, and retrieve
collections of data efficiently using arrays.

1. INTRODUCTION TO ARRAYS
An array is a data structure that stores multiple values of the same type in a single
variable.​
Each value is stored at an index, starting from 0.
Why Arrays?
Without arrays:

int s1 = 30;

int s2 = 40;

int s3 = 50;

With arrays:

int[] marks = {30, 40, 50};

Cleaner, scalable, and easier to manage.

2. DECLARING & CREATING ARRAYS


Java arrays require size (fixed at creation time).

2.1 Declaration
int[] arr;

2.2 Creation
arr = new int[5]; // space for 5 integers
2.3 Combined
int[] arr = new int[5];

2.4 Initialization
arr[0] = 10;

arr[1] = 20;

2.5 Initialization Shortcut


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

3. ACCESSING ARRAY ELEMENTS


Arrays use zero-based indexing.

[Link](arr[0]); // first element

[Link](arr[4]); // fifth element

4. TRAVERSING ARRAYS USING LOOPS


4.1 Using for loop
for (int i = 0; i < [Link]; i++) {

[Link](arr[i]);

4.2 Using enhanced for loop (for-each)


for (int x : arr) {

[Link](x);

5. COMMON ARRAY ERRORS

5.1 ArrayIndexOutOfBoundsException
Occurs when you exceed array limits.

Example:

int[] a = new int[3];

a[3] = 10; // ERROR (indexes 0–2 only)

5.2 Null Pointer Error


int[] a;

[Link](a[0]); // a not initialized

6. REAL-LIFE EXAMPLES OF 1D ARRAYS

Example 1: Store marks of 5 students


int[] marks = {78, 85, 90, 66, 88};

Example 2: Billing system


Store product prices:

double[] price = {120.50, 89.99, 45.00};

Example 3: Attendance system


Store present/absent flags:

boolean[] attendance = {true, false, true, true};


7. TWO-DIMENSIONAL ARRAYS (2D
ARRAYS / MATRICES)
A 2D array is essentially an array of arrays.

Commonly used for:

●​ Matrices​

●​ Tables​

●​ Timetables​

●​ Seating arrangements​

●​ Marks of multiple subjects​

7.1 Declaration
Int[ ][ ] matrix;

7.2 Creation
matrix = new int[3][3]; // 3x3 matrix

7.3 Combined
Int[ ][ ] matrix = new int[3][3];
7.4 Initialization Shortcut
Int[ ][ ] matrix = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

8. ACCESSING 2D ARRAY ELEMENTS


[Link](matrix[0][0]); // first row, first column

[Link](matrix[2][1]); // third row, second column

9. TRAVERSING 2D ARRAYS

Nested for loops


for (int i = 0; i < [Link]; i++) {

for (int j = 0; j < matrix[i].length; j++) {

[Link](matrix[i][j] + " ");

}
[Link]();

10. REAL-LIFE EXAMPLES OF 2D ARRAYS

Example 1: Marks of students in different subjects


Student Math Science English

--------------------------------

S1 78 80 90

S2 67 72 84

In Java:

Int[ ][ ] marks = {

{78, 80, 90},

{67, 72, 84}

};

Example 2: Attendance Sheet


Boolean[ ][ ] attendance = new boolean[30][31];
30 students, 31 days.

Example 3: Restaurant Billing Table


Double[ ][ ] bills = {

{100.50, 80.00, 60.75},

{90.00, 120.00, 55.25},

};

11. PRACTICE PROGRAMS

11.1 Find sum of array elements


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

int sum = 0;

for (int i = 0; i < [Link]; i++) {

sum += arr[i];

[Link]("Sum = " + sum);


11.2 Find largest element in array
Int[ ] arr = {4, 9, 2, 11, 5};

int max = arr[0];

for (int i = 1; i < [Link]; i++) {

if (arr[i] > max)

max = arr[i];

[Link]("Largest = " + max);

11.3 Matrix Addition (2D Arrays)


Int[ ][ ] a = {{1,2,3},{4,5,6}};

Int[ ][ ] b = {{7,8,9},{1,2,3}};

Int[ ][ ] c = new int[2][3];

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

for (int j = 0; j < 3; j++) {

c[i][j] = a[i][j] + b[i][j];

}
DAY 10 OUTCOME
You now understand:

●​ What arrays are​

●​ How to declare, create, initialize 1D and 2D arrays​

●​ How indexing works​

●​ How to traverse using loops​

●​ Real-world use cases: billing, attendance, marks systems​

●​ How to apply arrays in practical applications​

DAY 11
Strings in Java (String Class, Methods, StringBuffer)
(Covers Syllabus Topic 2.7 from CMP 215)

WHAT YOU WILL LEARN TODAY


●​ What Strings are​

●​ Why Strings are objects in Java​

●​ How string memory works (String Pool vs Heap)​

●​ Important String methods​

●​ Difference between == and .equals()​

●​ Lexicographical comparison using compareTo()​


●​ Mutable Strings using StringBuffer​

●​ Real-life examples​

●​ Practical code demonstrations​

Outcome:​
By the end of Day 11, you will understand how to store, process, compare, and modify
text efficiently in Java.

1. INTRODUCTION TO STRINGS
In Java, a String is an object that represents a sequence of characters.

Example:

String name = "Pratik";

Although Strings look like primitives, they are objects of the String class
([Link]).

2. WHY STRINGS ARE OBJECTS (NOT


PRIMITIVE)
A primitive data type stores a single value.​
A String stores a sequence of characters → requires object structure.

Example:

'P' 'r' 'a' 't' 'i' 'k'

Thus Java treats it as a non-primitive, immutable object.


3. STRING IMMUTABILITY (VERY
IMPORTANT)
Strings in Java cannot be changed once created.

Example:

String s = "Hello";

s = s + " World";

Memory explanation:

●​ "Hello" is created​

●​ "Hello World" is a new object​

●​ Old "Hello" stays in String Pool unless garbage collected​

Immutability makes Strings:

●​ Secure​

●​ Thread-safe​

●​ Memory-efficient​

4. STRING MEMORY MODEL (STRING


POOL vs HEAP)
4.1 String Literal (Stored in String Pool)
String s1 = "Java";

String s2 = "Java";

●​ Both refer to the same object​

●​ Because String Pool stores unique literals​

4.2 Using new keyword (Stored in Heap)


String s3 = new String("Java");

●​ New memory created​

●​ Even if the content is same​

5. STRING CREATION METHODS

5.1 Literal
String s = "Nepal";

5.2 new Keyword


String s = new String("Nepal");

6. IMPORTANT STRING METHODS

6.1 length()
Returns number of characters.

String name = "Pratik";

[Link]([Link]()); // 6

6.2 charAt()
Returns character at index.

[Link]([Link](0)); // P

6.3 substring()
Extracts part of the string.

String s = "HelloWorld";

[Link]([Link](0, 5)); // Hello


6.4 toUpperCase() / toLowerCase()
[Link]("java".toUpperCase()); // JAVA

6.5 trim()
Removes leading/trailing spaces.

String s = " hello ";

[Link]([Link]()); // "hello"

6.6 replace()
String s = "ball";

[Link]([Link]('b', 'c')); // call

6.7 contains()
"HelloWorld".contains("World"); // true

7. COMPARING STRINGS
7.1 Using == (checks memory address)
String a = "Java";

String b = "Java";

[Link](a == b); // true (same pool address)

7.2 Using equals() (checks content)


String a = new String("Java");

String b = new String("Java");

[Link](a == b); // false (different objects)

[Link]([Link](b)); // true (same content)

Rule:
Always use .equals() for string comparison in real code.

8. compareTo() METHOD
(LEXICOGRAPHICAL COMPARISON)
Returns:
●​ 0 → strings equal​

●​ Positive → s1 > s2​

●​ Negative → s1 < s2​

Example:

"apple".compareTo("ball"); // negative

"dog".compareTo("cat"); // positive

Used for sorting names, searching, alphabetical order.

9. CONCATENATION

Using + operator:
String full = "Pratik " + "Panta";

Using concat():
"Hello".concat(" World");

10. STRINGBUFFER (MUTABLE STRING)


StringBuffer allows modification without creating new objects.

Used when:

●​ Frequent updates​

●​ Loops performing string operations​

●​ Performance critical tasks​

10.1 Creating StringBuffer


StringBuffer sb = new StringBuffer("Hello");

10.2 append()
[Link](" World");

10.3 insert()
[Link](0, "Java ");

10.4 reverse()
[Link]();
Why use StringBuffer?
Because String is immutable.​
StringBuffer is mutable + thread-safe.

11. REAL-LIFE EXAMPLES OF STRINGS


●​ Usernames, passwords​

●​ OTP verification​

●​ Names of students​

●​ API token values​

●​ JSON/XML responses​

●​ Chat messages​

●​ File paths​

●​ Search queries​

12. PRACTICE PROGRAMS

12.1 Compare 2 Strings


String a = "hello";

String b = "hello";

if ([Link](b)) {
[Link]("Same");

} else {

[Link]("Different");

12.2 Count vowels in a String


String s = "education";

int count = 0;

for (int i = 0; i < [Link](); i++) {

char c = [Link](i);

if ("aeiou".contains(c + "")) {

count++;

[Link]("Vowels = " + count);

12.3 Palindrome Check


String s = "level";

String rev = "";


for (int i = [Link]() - 1; i >= 0; i--) {

rev += [Link](i);

if ([Link](rev)) {

[Link]("Palindrome");

} else {

[Link]("Not Palindrome");

12.4 Using StringBuffer


StringBuffer sb = new StringBuffer("Java");

[Link](" Programming");

[Link](sb);

DAY 11 OUTCOME
After completing Day 11, you now understand:

●​ String creation​

●​ String immutability​
●​ Memory model (Pool vs Heap)​

●​ Important methods like length(), substring(), equals(), compareTo()​

●​ Mutable strings using StringBuffer​

●​ Real-world usage of String processing​

DAY 12
Methods in Java (User-Defined, Predefined, Static
Methods)
(Covers Syllabus Topic 2.8 from CMP 215)

WHAT YOU WILL LEARN TODAY


●​ What a method is and why methods are used​

●​ Method definition (syntax + components)​

●​ Method calling​

●​ Predefined methods (from Java library)​

●​ User-defined methods​

●​ Static vs non-static methods​

●​ Method parameters & return types​

●​ Method overloading (intro)​

●​ Real-life examples​

●​ Clean coding rules for methods​


Outcome:​
By the end of Day 12, you will be able to create reusable, modular Java programs using
methods and understand how data flows between methods.

1. INTRODUCTION TO METHODS
A method is a block of code designed to perform a specific task.

Why do we use methods?


To:

●​ Reduce code repetition​

●​ Improve readability​

●​ Break large programs into smaller parts​

●​ Reuse logic​

●​ Organize code better​

2. METHOD SYNTAX (VERY IMPORTANT)


returnType methodName(parameters) {

// method body

}
Example
int add(int a, int b) {

return a + b;

Components Explained

Part Meaning

returnType data type returned by method

methodName identifier used to call method

parameters input values to method

body code executed

3. METHOD CALLING
To use a method, you call it.

Example:

int result = add(5, 10);


4. PREDEFINED METHODS
Java provides many built-in methods.

Examples:

[Link](16); // returns 4.0

[Link](10, 20); // returns 20

"hello".length(); // returns 5

5. USER-DEFINED METHODS
You create your own methods.

Example 1: Method with return value


int square(int x) {

return x * x;

Example 2: Method without return (void)


void greet() {

[Link]("Good morning!");
}

Example 3: Method with parameters


void showDetails(String name, int age) {

[Link](name + " is " + age + " years old");

6. STATIC METHODS
A static method belongs to the class, not to objects.

You can call it without creating an object.

Example
static void display() {

[Link]("Static method");

Call directly:

display();

Or using class name:


[Link]();

Real-Life Example
Utility functions like:

●​ calculator operations​

●​ helper methods​

●​ math functions​

These do not depend on object state, so static is used.

7. NON-STATIC METHODS
Require an object to be called.

class Student {

void show() {

[Link]("Non-static method");

Student s = new Student();

[Link]();

Use non-static methods when:


●​ You want to work with object data​

●​ Each object stores its own state​

8. METHOD PARAMETERS & RETURN


TYPES

Parameters
Values you pass to a method.

Types:

●​ No parameter​

●​ Single parameter​

●​ Multiple parameters​

Return Types
A method must return the type declared.

Examples:

returnType Meaning

int returns integer


double returns decimal

String returns text

void returns nothing

9. METHOD OVERLOADING (INTRO)


Same method name, different parameters.

Example
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; }

Java decides which method to call based on parameter types & count.

10. REAL-LIFE EXAMPLES OF METHODS


Example 1: Banking Application
double deposit(double currentBalance, double amount) {

return currentBalance + amount;

Example 2: Attendance System


boolean isPresent(int studentId) {

return true; // logic

Example 3: Billing System


double calculateBill(double price, int qty) {

return price * qty;

11. PRACTICE PROGRAMS

11.1 Sum of two numbers


class Test {
static int sum(int a, int b) {

return a + b;

public static void main(String[] args) {

[Link](sum(10, 20));

11.2 Maximum of three numbers


static int max(int a, int b, int c) {

if (a >= b && a >= c) return a;

if (b >= a && b >= c) return b;

return c;

11.3 Check even or odd


static boolean isEven(int n) {

return n % 2 == 0;

}
11.4 Static vs Non-static Example
class Demo {

static void staticMethod() {

[Link]("Inside static method");

void nonStaticMethod() {

[Link]("Inside non-static method");

public class Main {

public static void main(String[] args) {

[Link]();

Demo d = new Demo();

[Link]();

DAY 12 OUTCOME
You now understand:

●​ How methods work​

●​ How to define and call methods​

●​ Return types and parameters​

●​ Static vs non-static methods​

●​ Predefined vs user-defined methods​

●​ Method overloading basics​

You might also like