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

Java Programming

The document introduces programming as the process of instructing a computer step by step, using Java as a language for these instructions. It covers fundamental concepts such as variables, data types, conditions, loops, and methods, emphasizing the importance of understanding these basics before moving on to more complex topics. The document also includes exercises and examples to reinforce learning and comprehension.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views43 pages

Java Programming

The document introduces programming as the process of instructing a computer step by step, using Java as a language for these instructions. It covers fundamental concepts such as variables, data types, conditions, loops, and methods, emphasizing the importance of understanding these basics before moving on to more complex topics. The document also includes exercises and examples to reinforce learning and comprehension.
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 — What is programming?

(zero
assumptions)
Forget Java. Forget HashMap.

Let’s start here:

Programming = telling a computer what to do, step by step.

That’s it. Nothing mystical.

A computer:

●​ does exactly what you tell it


●​ doesn’t “understand” intent
●​ only understands instructions

Think of it like this 🧠


Imagine you tell someone:

“Make tea.”

A human fills gaps.​


A computer can’t.

So you must say:

1.​ Boil water


2.​ Add tea leaves
3.​ Add sugar
4.​ Pour into cup

That’s programming.

What is Java then?


Java is just a language we use to give instructions.

Like:
●​ English
●​ Telugu
●​ Hindi

Java is the language the computer understands (after translation).

Your FIRST Java instruction


Every Java program starts somewhere.

public class Main {


public static void main(String[] args) {
[Link]("Hello");
}
}

Don’t panic. You do NOT need to understand all of it.

Right now, only care about ONE line:

[Link]("Hello");

What this means (plain English):

“Computer, print the word Hello on the screen.”

That’s it. No more.

Variables (this is the next brick)


Think of a variable as a box

A box that stores a value.

int age = 25;

Meaning:

Create a box called age and put 25 in it.


●​ int → type of box (number)
●​ age → name of box
●​ 25 → value inside

Another example
String name = "Vaishnavi";

Box name = name, value = "Vaishnavi"

That’s all a variable is.

Why programming starts feeling hard


Because people jump to:

●​ frameworks
●​ DSA
●​ interviews

before this feels natural.

We won’t do that.

Small exercise (VERY important)


Just answer in words, no code needed.

1️⃣ If I write:

int salary = 50000;

What does this mean in plain English?

2️⃣ If I change it to:

salary = 60000;

What happened?
🌱
Answer slowly.​
We’ll move only when this feels comfortable

—--->>>

Next basic idea: Doing things with variables


Right now, you know:

●​ A variable stores a value​

●​ The value can change​

Now let’s use it.

Example
int a = 10;
int b = 20;
int sum = a + b;

Plain English

●​ a has 10​

●​ b has 20​

●​ sum gets the result of adding a and b​


→ sum becomes 30​

The computer literally does math like a calculator.

Printing values
[Link](sum);

Means:
Print whatever is inside the box called sum

Changing values step by step


int balance = 1000;
balance = balance + 500;

Read it slowly:

Take the current value of balance, add 500, and store it back into balance.

So:

●​ First: balance = 1000​

●​ After: balance = 1500​

This pattern appears everywhere in real backend code.

Important mental model 🧠


In Java:

●​ Left side = where to store​

●​ Right side = what to calculate first​

Right side is always evaluated first.

Tiny check (no pressure)


Tell me in words what this does:

int x = 5;
x = x * 2;

Ans —--->
Most common variable types (you MUST know these)

1️⃣ int – whole numbers

int count = 10;

int salary = 50000;

2️⃣ double – decimal numbers

double price = 99.99;

double rating = 4.5;

3️⃣ boolean – true or false

boolean isActive = true;

boolean isPaid = false;

Very common in backend logic.

4️⃣ String – text

String name = "Vaishnavi";

String city = "Hyderabad";

⚠️ String is capital S (important).


Declaring vs initializing
Declaration (no value yet)

int x;

Initialization (assigning value)

x = 10;

Often done together: (declaring + initializing)

int x = 10;

NOTE:

Variable naming rules (important)


✅ Valid:
int totalAmount;

int userAge;

boolean isVerified;

❌ Invalid:
int 1age; // cannot start with number

int total-amt; // no special characters

Best practice:​
Use camelCase:

accountBalance

merchantId

paymentStatus
This matters in interviews.

Scope (very important concept)

Variable inside a block { }

if (true) {

int x = 10;

👉 x exists only inside the if block.​


Outside → ❌ not accessible.

Variable outside block

int x = 10;

if (true) {

x = 20;

👉 x is accessible everywhere in that method.

Key rules to remember (lock these in)


●​ A variable stores one value at a time
●​ The type cannot change
●​ Left side = where to store
●​ Right side = calculation happens first
Quick self-check (answer in words)
1️⃣ What does this mean?

boolean isLoggedIn = false;

2️⃣ What will be the final value of x?

int x = 5;

x = x + 3;

x = x * 2;

👉
Answer these, and we’ll move next to​
types vs memory (why int vs double matters).

Next core concept: Conditions (if)


This is how a program makes decisions.

Think real life:

If it’s raining → take umbrella​


Else → don’t take umbrella

Java version of that idea


int age = 20;

if (age >= 18) {


[Link]("Adult");
} else {
[Link]("Minor");
}

Read it like English:

●​ If age is 18 or more​

○​ print “Adult”​

●​ Otherwise​

○​ print “Minor”​

The program checks the condition and chooses a path.

Important symbols (only these for now)


●​ > greater than​

●​ < less than​

●​ >= greater than or equal​

●​ <= less than or equal​

●​ == equals (comparison, NOT assignment)​

⚠️ = is for storing​
⚠️ == is for checking

Very small exercise (answer in words)


Given this code:

int marks = 35;

if (marks >= 40) {


[Link]("Pass");
} else {
[Link]("Fail");
}

ANS:-----? 👉 What will be printed?

Why? ANS —--?

You’ve now learned three core building blocks of all programming:

1️⃣ Variables (store data)​


2️⃣ Operations (do math / change values)​
3️⃣ Conditions (if/else) → decision making

That’s already huge 🌱

Next concept (still basics): Repeating things — loops


Imagine this real-life instruction:

“Print Hello 5 times”

You could write:

[Link]("Hello");
[Link]("Hello");
[Link]("Hello");
[Link]("Hello");
[Link]("Hello");

But that’s dumb and repetitive.

So we use a loop.

for loop (most common)


for (int i = 1; i <= 5; i++) {
[Link]("Hello");
}

Don’t panic. Read it slowly.

Plain English:

●​ Start with i = 1​

●​ As long as i <= 5, do what’s inside { }​

●​ After each run, increase i by 1​

So it prints Hello 5 times.

What is i?
Just a counter variable.

●​ First: i = 1​

●​ Then: 2, 3, 4, 5​

●​ Stops when i becomes 6​

Mini check (super simple)


Without writing code, tell me:

👉 How many times will this print?


for (int i = 1; i <= 3; i++) {
[Link]("Java");
}

Ans—--?

Let’s add one tiny layer on loops—still basics, still gentle.


Using the loop variable (i)
Now instead of printing the same thing, let’s use the counter.

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


[Link](i);
}

What happens?

●​ First time → prints 1​

●​ Second → 2​

●​ Third → 3​

So output is:

1
2
3

Very important idea 🧠


The variable i:

●​ Exists only inside the loop​

●​ Changes automatically​

●​ Is often used for counting, indexing, repeating work​

You’ll see this pattern everywhere in real code.

One more example (logic + loop together)


for (int i = 1; i <= 5; i++) {
if (i % 2 == 0) {
[Link](i);
}
}

Don’t worry about % too much yet.​


Just know:

●​ i % 2 == 0 means even number​

What will this print?

Numbers from 1 to 5 that are even.

So:

2
4

Tiny exercise (last one for today)


In words, tell me what this does:

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


[Link]("Hi");
}

Ans—----?

Arrays — storing multiple values


together
Till now, you’ve stored one value in one variable.
int salary = 60000;

But what if you have many values?

Example:

●​ marks of 5 students​

●​ salaries of 10 employees​

●​ prices of items​

You could do:

int m1 = 50;
int m2 = 60;
int m3 = 70;

That becomes messy very fast.

What is an array?
👉 An array is a list of values of the same type.
Think of it as:

A row of boxes, all of the same kind.

Creating an array (very basic)


int[] marks = {50, 60, 70, 80};

Read it in English:

Create a box called marks that can store many integers, and
put 50, 60, 70, 80 in it.
How Java stores it (mental picture)
Index: 0 1 2 3
Value: 50 60 70 80

⚠️ Important rule​
Array index always starts from 0, not 1.

This is VERY important. Everyone trips here at first.

Accessing values from an array


marks[0] → 50
marks[1] → 60
marks[2] → 70
marks[3] → 80

So if I write:

[Link](marks[2]);

It prints:

70

Updating a value in array


marks[1] = 65;

Meaning:

Go to index 1 and replace 60 with 65

Now array becomes:


50, 65, 70, 80

Arrays + loop (this is where power starts)


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

Don’t panic. Read slowly.

Plain English:

●​ Start from index 0​

●​ Go till last element​

●​ Print each value one by one​

This prints:

50
65
70
80

Tiny check (super important)


Answer in words.

Given:

int[] nums = {10, 20, 30};

[Link](nums[1]);
👉 What will be printed?
Take your time.

ANS—--->

Let’s lock this in and add one tiny but powerful idea that connects
arrays + loops + logic. Still basics.

Finding the total (sum) of an array


Real-life question:

“What is the total marks of all students?”

Java way:
int[] marks = {50, 60, 70};
int sum = 0;

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


sum = sum + marks[i];
}

[Link](sum);

Read it like English:

●​ Start sum at 0​

●​ Go through each value in marks​

●​ Add it to sum​

●​ Finally print sum​


So output is:

180

Key pattern (remember this)


This pattern appears everywhere in backend + DSA:

result = result + array[i];

It could be:

●​ sum​

●​ count​

●​ max​

●​ min​

Same idea, different use.

Another very common task: find the biggest


number
int[] nums = {10, 5, 25, 8};
int max = nums[0];

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


if (nums[i] > max) {
max = nums[i];
}
}

[Link](max);
What this does (high level):

●​ Assume first number is biggest​

●​ Compare with others​

●​ Update when you find bigger​

●​ End with the largest value​

This prints:

25

Tiny exercise (last one for now)


In words only:

Given:

int[] nums = {3, 6, 2};


int sum = 0;

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


sum = sum + nums[i];
}

[Link](sum);

👉 What will be printed?


ANS—--->

Next CORE Java concept:

Methods (functions)
This is where Java becomes real backend code.

What is a method?

A method is:

A named block of code that does one job (As if an


action).

Instead of writing the same logic again and again, you put it in a method.

Simple example

static void sayHello() {

[Link]("Hello");

Meaning:

“Whenever I call sayHello, print Hello.”

To use it:

sayHello();

Note: here sayHello() is the method

Method with input (VERY IMPORTANT)

static int add(int a, int b) {

return a + b;

Read in English:
Take two numbers, add them, and give the result back.

Usage:

int result = add(10, 20);

[Link](result);

Output:

30

Tiny check (no code writing)


In words only:

👉 What does this method do?


static int square(int x) {

return x * x;

And if I call:

square(5);

What is returned?

ANS—---->

Methods — let’s lock it in


You already saw this:

static int square(int x) {

return x * x;

Why methods matter (VERY important)


Methods are:

●​ building blocks of programs​

●​ how backend APIs are written​

●​ how microservices are structured​

Every controller/service method you’ve written before​


⬅️ this is where it comes from.

Another simple method (read slowly)


static boolean isAdult(int age) {

if (age >= 18) {

return true;

} else {

return false;

}
Meaning:

Check age.​
If 18 or more → return true​
Else → return false

Usage:

isAdult(20) → true

isAdult(15) → false

Shorter (but same logic)


Java allows this:

static boolean isAdult(int age) {

return age >= 18;

Same result. Cleaner code.

Methods + arrays (very common)


static int sumArray(int[] nums) {

int sum = 0;

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

sum = sum + nums[i];

}
return sum;

Meaning:

Take an array of numbers​


Add all values​
Return the total

Usage:

int[] data = {10, 20, 30};

int result = sumArray(data);

Result:

ANS—>

Key mental rule 🧠


●​ return → sends value back to caller​

●​ Method stops executing after return​

●​ Method output type must match return type​

Tiny check (important)


In words only:
👉 What does this method return?
static int getFirst(int[] nums) {

return nums[0];

And if I call:

int[] a = {5, 10, 15};

getFirst(a);

What is returned?

ANS—-->

DAY - 2​

1️⃣ Data Types in Java


Java has two categories:

A) Primitive Types (store actual value)


Type Example Meaning

int 10 Whole numbers

doubl 10.5 Decimal numbers


e
boole true/false Logical values
an

char 'A' Single character

long 100000L Large integer

float 10.5f Decimal (less


precise)

byte small Rarely used


numbers

short small int Rarely used

👉 For backend work:​


int, double, boolean, String cover 90%.

B) Non-Primitive (Reference Types)


●​ String​

●​ Arrays​

●​ Objects​

●​ Classes​

●​ Interfaces​

They store reference (memory address).

2️⃣ Literals
A literal is simply a fixed value written directly in code.

Examples:
int x = 10; // 10 is an integer literal
double d = 5.5; // 5.5 is double literal
char c = 'A'; // 'A' is char literal
String s = "Hi"; // "Hi" is string literal
boolean b = true; // true is boolean literal

Nothing complex here — just raw values.

3️⃣ Type Conversion


A) Implicit (Widening) – Automatic
Small → Big

int a = 10;
double d = a; // int → double (automatic)

Safe conversion.

B) Explicit (Casting) – Manual


Big → Small

double d = 10.5;
int a = (int) d; // becomes 10

You lose decimal part.

⚠️ Interview favorite topic.

4️⃣ Arithmetic Operators


Used for math.
Operat Meaning
or

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulus
(remainder)

Example:

int a = 10;
int b = 3;
[Link](a % b); // 1

5️⃣ Relational Operators


Used in conditions.

Operat Meaning
or

> Greater than

< Less than

>= Greater than


equal

<= Less than


equal

== Equal

!= Not equal
Example:

int age = 20;


age >= 18 // true

7️⃣ Ternary Operator (Shortcut


if-else)
Syntax:

condition ? value_if_true : value_if_false;

Example:

int age = 20;


String result = (age >= 18) ? "Adult" : "Minor";

Cleaner but don’t overuse it.

8️⃣ Switch Statement


Used when checking multiple fixed values.

Quick Refresher (important rules)


●​ Works with:​

○​ int​

○​ char​
○​ String​

○​ enum​

●​ Needs break to prevent fall-through​

●​ default is optional​

●​ Case values must be constant

Example:

int day = 2;

switch (day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
default:
[Link]("Invalid");
}

Important:

●​ break prevents fall-through​

●​ Used for fixed matching, not ranges

Now Let’s Test Your Foundation


Answer quickly:

1️⃣ What is the output?

int a = 10;
double b = a;
[Link](b);

2️⃣ What is the result?

[Link](10 / 3);

3️⃣ What does this print?

int x = 5;
String result = (x > 10) ? "Big" : "Small";
[Link](result);

Answer these 3 —?

Logical Operators in Java


(Complete)
Logical operators work with boolean values (true / false).

1️⃣ AND — && (Short-circuit AND)


true && true → true

true && false → false

false && true → false

false && false → false

Important:

If the first condition is false, Java will NOT evaluate the second
condition.

Example:

if (age > 18 && hasId) {


// executes only if both are true

If age > 18 is false → Java stops immediately.

This is called short-circuit evaluation.

2️⃣ OR — || (Short-circuit OR)


true || true → true

true || false → true

false || true → true

false || false → false

Important:

If the first condition is true, Java stops and doesn’t check the second.

3️⃣ NOT — !
Negates a boolean.

boolean isActive = false;

[Link](!isActive); // true

Simple inversion.

The Ones You’re Probably


Thinking About
Yes — there are also:
4️⃣ Single & (Bitwise AND, but works with
boolean too)
true & false → false

Difference from &&:

●​ & ALWAYS evaluates both sides​

●​ && may skip second condition​

Same idea for OR:

5️⃣ Single | (Bitwise OR)


true | false → true

Also always evaluates both sides.

6️⃣ XOR — ^
Exclusive OR.

true ^ true → false

true ^ false → true

false ^ true → true

false ^ false → false

Meaning:

True only if exactly one condition is true.

Rare in backend interviews, but good to know.


Important Interview-Level Insight
Difference between && and &:

if (a != 0 && (10 / a) > 2)

If a is 0:

●​ && prevents division by zero​

●​ & would evaluate both sides → crash​

That’s why && is used in real code.

Quick Check
What will this print?

boolean a = true;

boolean b = false;

[Link](a ^ b);

Answer with just: ?​


true or false

What will this print?

[Link](10 / 3.0);

Think carefully about types.


Answer with just the number. —->

What will this print?

[Link]((double)(10 / 3));

Excellent question. This is a real backend engineer question,


not beginner-level.

Let’s answer it properly.

❗ Why we use BigDecimal instead


of double for money
Short answer:

Because double is not precise, and money calculations require


exact precision.

🔬 The Real Problem with double


double stores numbers in binary floating-point format.

Some decimal numbers cannot be represented exactly in binary.

Example:

[Link](0.1 + 0.2);

You expect:

0.3

But Java prints:

0.30000000000000004

Why?

Because:

●​ 0.1 cannot be stored exactly in binary​

●​ 0.2 cannot be stored exactly in binary​

●​ The tiny rounding errors accumulate​

💣 Why this is dangerous in


payments
Imagine:

double balance = 1000.00;

balance = balance - 0.10;

balance = balance - 0.20;


After thousands of transactions,​
you may get:

999.6999999999998

Now multiply that across:

●​ Millions of users​

●​ Millions of transactions​

This becomes a financial disaster.

Why BigDecimal should be used


instead of double (esp for
payments)
BigDecimal:

●​ Stores numbers as exact decimal values​

●​ No floating-point approximation​

●​ Precise arithmetic​

●​ Designed for finance​

Example:

import [Link];

BigDecimal a = new BigDecimal("0.1");


BigDecimal b = new BigDecimal("0.2");

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

Output:

0.3

Exact. No rounding garbage.

🧠 Real Backend Rule


For:

●​ Payments​

●​ Banking​

●​ Currency​

●​ Accounting​

👉 Always use BigDecimal​


👉 Never use double

Switch Questions:
Question 1 (Basic
fall-through)
What will this print?

int day = 2;

switch (day) {

case 1:

[Link]("One");

case 2:

[Link]("Two");

case 3:

[Link]("Three");

break;

default:

[Link]("Other");

Answer exactly what prints (line by line).

Question 2 (With break)


int x = 1;
switch (x) {

case 1:

[Link]("A");

break;

case 2:

[Link]("B");

default:

[Link]("C");

What prints?

Question 3 (String switch)


String role = "ADMIN";

switch (role) {

case "USER":

[Link]("User access");

break;

case "ADMIN":

[Link]("Admin access");

default:

[Link]("General access");
}

What prints?

Question 4 (Compilation check)


Will this compile?

int a = 5;

switch (a) {

case 2 + 3:

[Link]("Five");

break;

Yes or No?

Now One Advanced Switch


Question (SDE-2 level)
What will this print?

int x = 0;

switch (x) {
case 0:

[Link]("Zero");

case 1:

[Link]("One");

default:

[Link]("Default");

Answer exactly what prints (line by line).

This one checks if fall-through is truly locked in.

You might also like