Programming and Java Fundamentals
Module Review and Exercises
You are viewing a free preview lesson.
Module Overview
এই module-এ আমরা programming এবং Java-এর fundamental concepts শিখেছি।
আমরা শুরু করেছি computer কীভাবে program execute করে তা দিয়ে। এরপর Java development environment setup, syntax, variables, data types, Strings, operators, input, conditions এবং loops ব্যবহার করে একটি complete console-based grade calculator তৈরি করেছি।
এই review lesson-এর উদ্দেশ্য:
- Module 1-এর গুরুত্বপূর্ণ conceptগুলো পুনরায় দেখা
- Concepts-এর মধ্যে connection বোঝা
- Common mistake identify করা
- Mixed programming problems solve করা
- পরবর্তী Object-Oriented Programming module-এর জন্য প্রস্তুত হওয়া
Module Learning Outcomes
এই module শেষ করার পর আপনি পারবেন:
- Programming এবং program execution explain করতে
- Java source code compile এবং run করতে
- JDK, JRE, JVM এবং bytecode-এর ভূমিকা বুঝতে
- Java syntax follow করে program লিখতে
- Variables, constants এবং data types ব্যবহার করতে
- Strings process এবং compare করতে
- Operators দিয়ে expressions তৈরি করতে
- Type conversion এবং casting করতে
Scannerদিয়ে user input নিতেif-elseএবংswitchদিয়ে decision নিতেfor,whileএবংdo-whileloops ব্যবহার করতেbreakএবংcontinueদিয়ে loop control করতে- একটি interactive console program তৈরি করতে
Part 1: Programming Fundamentals Review
What Is Programming?
Programming হলো computer-কে একটি নির্দিষ্ট কাজ করানোর জন্য instructions তৈরি করার process।
একটি program সাধারণত:
- Input নেয়
- Data process করে
- Decision নেয়
- Output তৈরি করে
Example:
Input:
Two numbers
Process:
Add the numbers
Output:
Total
Java example:
int firstNumber = 10;
int secondNumber = 20;
int total =
firstNumber + secondNumber;
System.out.println(total);
Output:
30
Algorithm
Algorithm হলো একটি problem solve করার ordered step-by-step procedure।
Example: দুটি number-এর মধ্যে largest value বের করা।
1. Read first number
2. Read second number
3. Compare the numbers
4. Display the larger number
5. If equal, display that they are equal
Java implementation:
int firstNumber = 20;
int secondNumber = 30;
if (firstNumber > secondNumber) {
System.out.println(
firstNumber + " is larger"
);
} else if (secondNumber > firstNumber) {
System.out.println(
secondNumber + " is larger"
);
} else {
System.out.println(
"The numbers are equal"
);
}
Part 2: How Java Programs Execute
Java source file:
Main.java
Compilation:
javac Main.java
Compiler bytecode তৈরি করে:
Main.class
Execution:
java Main
Flow:
Java source code
↓
Java compiler
↓
Bytecode
↓
JVM
↓
Machine instructions
↓
Program output
JDK, JRE, and JVM
JDK
JDK হলো Java application develop করার complete toolkit।
এতে থাকে:
- Java compiler
- Runtime components
- Development tools
- Debugging tools
JRE
JRE Java program run করার runtime environment।
JVM
JVM Java bytecode execute করে।
Simplified relationship:
JDK
└── Runtime components
└── JVM
Modern Java distribution-এ standalone JRE সবসময় আলাদাভাবে দেওয়া নাও হতে পারে, তবে conceptual difference জানা গুরুত্বপূর্ণ।
Bytecode
Java compiler source code-কে platform-independent bytecode-এ convert করে।
এই কারণে একই compiled Java bytecode different operating system-এর compatible JVM-এ run করতে পারে।
Write once
Run on a compatible JVM
Part 3: Java Program Structure
Basic Java program:
public class Main {
public static void main(String[] args) {
System.out.println(
"Hello, Java!"
);
}
}
Important parts:
public class Mainclass declarationmain()program entry point{}code block;statement terminatorSystem.out.println()console output
Case Sensitivity
Java case-sensitive।
String learnerName = "Sakib";
এগুলো আলাদা identifiers:
learnerName
LearnerName
LEARNERNAME
Wrong:
system.out.println("Hello");
Correct:
System.out.println("Hello");
Comments
Single-line:
// Calculate the total
Multi-line:
/*
* Calculate the final result.
*/
Documentation comment:
/**
* Displays the student result.
*/
Comments code explain করে, কিন্তু obvious code repeat করা উচিত নয়।
Part 4: Variables and Constants
Variable
Variable একটি named storage location।
String studentName = "Jalisa";
int age = 30;
double score = 85.5;
boolean active = true;
General syntax:
type variableName = value;
Reassignment
int score = 80;
score = 90;
Final value:
90
Constant
যে value reassign করা উচিত নয়, সেটি final দিয়ে declare করা যায়।
final int PASSING_MARK = 40;
Class-level constant:
static final int MAXIMUM_MARK = 100;
Constant naming convention:
UPPER_SNAKE_CASE
Meaningful Names
Poor:
int x = 40;
Better:
int passingMark = 40;
Constant হলে:
static final int PASSING_MARK = 40;
Part 5: Primitive Data Types
Java-এর আটটি primitive type:
| Type | Common Use |
|---|---|
byte | Very small integer |
short | Small integer |
int | General integer |
long | Large integer |
float | Lower-precision decimal |
double | General decimal |
char | Single UTF-16 code unit |
boolean | true or false |
Integer Types
byte smallValue = 100;
short shortValue = 30_000;
int learnerCount = 1_000_000;
long globalCount = 8_000_000_000L;
long literal-এর জন্য অনেক ক্ষেত্রে L suffix প্রয়োজন।
Floating-Point Types
float temperature = 36.5F;
double average = 85.75;
float literal-এর জন্য F suffix প্রয়োজন।
General decimal calculation-এর জন্য double commonly used।
Character
char grade = 'A';
char single quotes ব্যবহার করে।
Boolean
boolean enrollmentOpen = true;
boolean accountBlocked = false;
Overflow
int value = Integer.MAX_VALUE;
value++;
System.out.println(value);
Output:
-2147483648
Integer overflow silent wrap-around করতে পারে।
Integer Division
int result = 5 / 2;
Result:
2
Decimal result:
double result = 5.0 / 2;
Result:
2.5
Part 6: Strings and Text Values
String primitive type নয়। এটি একটি class এবং reference type।
String learnerName = "Subu";
String courseName =
"Java and OOP Foundation";
String double quotes ব্যবহার করে।
String text = "Java";
char single quotes ব্যবহার করে।
char letter = 'J';
Empty, Blank, and Null
String empty = "";
String blank = " ";
String missing = null;
Checks:
empty.isEmpty();
blank.isBlank();
Null-safe validation:
if (
learnerName != null
&& !learnerName.isBlank()
) {
System.out.println(
"Valid learner name"
);
}
String Concatenation
String firstName = "Subu";
String lastName = "Sakib";
String fullName =
firstName + " " + lastName;
Concatenation and Arithmetic
System.out.println(
"Total: " + 10 + 20
);
Output:
Total: 1020
Correct numeric calculation:
System.out.println(
"Total: " + (10 + 20)
);
Output:
Total: 30
Common String Methods
String value =
" Java Foundation ";
value.length();
value.strip();
value.toUpperCase();
value.toLowerCase();
value.contains("Java");
value.startsWith("Java");
value.endsWith("Foundation");
value.indexOf("Foundation");
value.replace("Java", "OOP");
String Equality
Wrong:
if (role == "ADMIN") {
}
Correct:
if ("ADMIN".equals(role)) {
}
Case-insensitive:
if (
"ADMIN".equalsIgnoreCase(role)
) {
}
String Immutability
String language = "java";
language.toUpperCase();
System.out.println(language);
Output:
java
Correct:
language =
language.toUpperCase();
Part 7: Operators and Expressions
Arithmetic Operators
+
-
*
/
%
Example:
int subtotal =
price * quantity;
Assignment Operators
=
+=
-=
*=
/=
%=
Example:
int total = 10;
total += 5;
Final:
15
Comparison Operators
==
!=
>
<
>=
<=
Example:
boolean passed =
mark >= 40;
Logical Operators
&&
||
!
Example:
boolean canEnroll =
age >= 18
&& emailVerified
&& !accountBlocked;
Increment and Decrement
count++;
count--;
Prefix:
int result = ++count;
Postfix:
int result = count++;
Standalone usage preferred:
count++;
Operator Precedence
int result = 10 + 5 * 2;
Result:
20
With parentheses:
int result = (10 + 5) * 2;
Result:
30
Part 8: Type Conversion and Casting
Widening Conversion
int learnerCount = 100;
long totalLearners =
learnerCount;
Automatic।
Narrowing Conversion
double average = 85.75;
int wholeAverage =
(int) average;
Result:
85
Casting rounds করে না। Decimal part truncate করে।
Casting Before Division
Correct:
double average =
(double) total / count;
Too late:
double average =
(double) (total / count);
Second version-এ integer division আগে হয়ে যায়।
String to Number
int age =
Integer.parseInt("30");
double price =
Double.parseDouble("4990.50");
long population =
Long.parseLong("8000000000");
Number to String
String ageText =
String.valueOf(30);
Safe Long-to-Int Conversion
long value = 1000L;
int result =
Math.toIntExact(value);
Out-of-range value হলে exception হবে।
Part 9: Reading User Input
Import:
import java.util.Scanner;
Create Scanner:
Scanner scanner =
new Scanner(System.in);
Read full line:
String learnerName =
scanner.nextLine();
Read integer:
int age =
scanner.nextInt();
Recommended consistent approach:
int age =
Integer.parseInt(
scanner
.nextLine()
.strip()
);
nextInt() and nextLine() Issue
int age =
scanner.nextInt();
scanner.nextLine();
String name =
scanner.nextLine();
Extra nextLine() remaining newline consume করে।
Input Validation
if (scanner.hasNextInt()) {
int age =
scanner.nextInt();
} else {
String invalidInput =
scanner.nextLine();
System.out.println(
"Invalid input: "
+ invalidInput
);
}
Part 10: Conditional Statements
Basic If
if (mark >= 40) {
System.out.println("Passed");
}
If-Else
if (mark >= 40) {
System.out.println("Passed");
} else {
System.out.println("Failed");
}
Else-If
if (mark >= 80) {
System.out.println("A");
} else if (mark >= 70) {
System.out.println("B");
} else if (mark >= 60) {
System.out.println("C");
} else {
System.out.println("Needs improvement");
}
Specific or higher threshold আগে রাখতে হয়।
Range Validation
boolean validMark =
mark >= 0
&& mark <= 100;
Invalid:
boolean invalidMark =
mark < 0
|| mark > 100;
Independent Conditions
if (mark >= 40) {
System.out.println("Passed");
}
if (mark >= 80) {
System.out.println("Distinction");
}
দুটি block-ই execute হতে পারে।
Part 11: Switch Review
Arrow-Style Switch
String dashboard = switch (role) {
case "ADMIN" ->
"Admin dashboard";
case "INSTRUCTOR" ->
"Instructor dashboard";
case "LEARNER" ->
"Learner dashboard";
default ->
"Unknown dashboard";
};
Multiple Labels
String dayType = switch (dayNumber) {
case 1, 2, 3, 4, 5 ->
"Weekday";
case 6, 7 ->
"Weekend";
default ->
"Invalid";
};
Switch vs If-Else
Use switch for:
- Exact menu option
- Role
- Status
- Enum
- Fixed command
Use if-else for:
- Numeric range
- Multiple boolean conditions
- Null checks
- Inequality
- Complex business rules
Part 12: Loop Review
For Loop
for (int number = 1; number <= 5; number++) {
System.out.println(number);
}
Suitable when repetition count বা range জানা।
While Loop
int number = 1;
while (number <= 5) {
System.out.println(number);
number++;
}
Suitable when loop condition-based এবং repetition count unknown।
Do-While Loop
int option;
do {
option =
Integer.parseInt(
scanner
.nextLine()
.strip()
);
} while (option != 3);
Body অন্তত একবার execute হয়।
Accumulator
int total = 0;
for (int number = 1; number <= 5; number++) {
total += number;
}
String Traversal
String learnerName = "Sumu";
for (
int index = 0;
index < learnerName.length();
index++
) {
System.out.println(
learnerName.charAt(index)
);
}
Condition:
index < learnerName.length()
<= ব্যবহার করলে invalid index error হবে।
Break
for (int number = 1; number <= 10; number++) {
if (number == 5) {
break;
}
System.out.println(number);
}
Continue
for (int number = 1; number <= 5; number++) {
if (number == 3) {
continue;
}
System.out.println(number);
}
Output:
1
2
4
5
Part 13: Complete Mixed Example
নিচের programটি learner names নিয়ে একটি simple result summary তৈরি করে।
import java.util.Scanner;
public class Main {
static final int PASSING_MARK = 40;
public static void main(String[] args) {
Scanner scanner =
new Scanner(System.in);
System.out.print(
"Enter learner name: "
);
String learnerName =
scanner
.nextLine()
.strip();
while (learnerName.isBlank()) {
System.out.println(
"Learner name is required."
);
System.out.print(
"Enter learner name: "
);
learnerName =
scanner
.nextLine()
.strip();
}
System.out.print(
"Enter subject count: "
);
int subjectCount =
Integer.parseInt(
scanner
.nextLine()
.strip()
);
while (
subjectCount < 1
|| subjectCount > 10
) {
System.out.println(
"Subject count must be between 1 and 10."
);
System.out.print(
"Enter subject count: "
);
subjectCount =
Integer.parseInt(
scanner
.nextLine()
.strip()
);
}
int totalMarks = 0;
int failedSubjects = 0;
for (
int subject = 1;
subject <= subjectCount;
subject++
) {
int mark;
do {
System.out.print(
"Enter mark for subject "
+ subject
+ ": "
);
mark =
Integer.parseInt(
scanner
.nextLine()
.strip()
);
if (mark < 0 || mark > 100) {
System.out.println(
"Invalid mark."
);
}
} while (mark < 0 || mark > 100);
totalMarks += mark;
if (mark < PASSING_MARK) {
failedSubjects++;
}
}
double average =
totalMarks
/ (double) subjectCount;
boolean passed =
failedSubjects == 0;
String grade;
if (!passed) {
grade = "F";
} else if (average >= 80) {
grade = "A";
} else if (average >= 70) {
grade = "B";
} else if (average >= 60) {
grade = "C";
} else if (average >= 50) {
grade = "D";
} else {
grade = "E";
}
String message = switch (grade) {
case "A" ->
"Excellent work, "
+ learnerName
+ "!";
case "B" ->
"Very good work, "
+ learnerName
+ ".";
case "C" ->
"Good progress, "
+ learnerName
+ ".";
case "D", "E" ->
"You passed, but keep practising.";
case "F" ->
"Review the failed subjects and try again.";
default ->
"Result unavailable.";
};
System.out.println();
System.out.println(
"=== Result Summary ==="
);
System.out.println(
"Learner: " + learnerName
);
System.out.println(
"Total: " + totalMarks
);
System.out.println(
"Average: "
+ "%.2f".formatted(
average
)
);
System.out.println(
"Failed subjects: "
+ failedSubjects
);
System.out.println(
"Grade: " + grade
);
System.out.println(
"Result: "
+ (
passed
? "Passed"
: "Failed"
)
);
System.out.println(
"Message: " + message
);
scanner.close();
}
}
Part 14: Debugging Exercises
Exercise 1: Integer Division
Problem:
int total = 250;
int count = 3;
double average =
total / count;
Expected decimal average।
Fix the code.
Exercise 2: String Equality
Problem:
String learnerName = "Sakib";
if (learnerName == "Sakib") {
System.out.println("Matched");
}
Rewrite using the recommended comparison method।
Exercise 3: Null Check
Problem:
String courseName = null;
if (
!courseName.isBlank()
&& courseName != null
) {
System.out.println("Valid");
}
Fix the condition order।
Exercise 4: Infinite Loop
Problem:
int number = 1;
while (number <= 5) {
System.out.println(number);
}
Fix the loop।
Exercise 5: Wrong Update Direction
for (
int number = 1;
number <= 10;
number--
) {
System.out.println(number);
}
Fix the loop।
Exercise 6: Invalid String Index
String name = "Nur";
for (
int index = 0;
index <= name.length();
index++
) {
System.out.println(
name.charAt(index)
);
}
Fix the condition।
Exercise 7: Fall-Through
int option = 1;
switch (option) {
case 1:
System.out.println("Create");
case 2:
System.out.println("Update");
default:
System.out.println("Unknown");
}
Fix using:
- Traditional
break - Arrow-style switch
Exercise 8: Invalid Range Logic
boolean validMark =
mark >= 0
|| mark <= 100;
Fix the expression।
Exercise 9: Product Accumulator
int product = 0;
for (int number = 1; number <= 5; number++) {
product *= number;
}
Fix the initial value।
Exercise 10: Sentinel Processing
Problem:
while (true) {
int number =
Integer.parseInt(
scanner.nextLine()
);
total += number;
if (number == -1) {
break;
}
}
Ensure -1 is not added to the total।
Part 15: Short Programming Exercises
Exercise 1: Personal Greeting
Create variables:
Name: Jalisa
Country: Estonia
Learning: Java
Output:
Jalisa is learning Java in Estonia.
Exercise 2: Twin Ages
Create variables for:
Subu age
Sumu age
Print whether their ages are equal।
Exercise 3: Nur's Score
Given:
int score = 78;
Print:
- Passed or failed
- Grade
- Whether distinction eligible
Distinction threshold:
80
Exercise 4: Largest Number
Read three integers and print the largest one।
Exercise 5: Number Classification
Read an integer and print:
- Positive, negative, or zero
- Even or odd
Exercise 6: Multiplication Table
Read a number and print its table from 1 to 10।
Exercise 7: Sum of a Range
Read start and end values।
Calculate the sum of all numbers in the range।
Example:
Start: 1
End: 5
Total: 15
Exercise 8: Factorial
Read a non-negative integer and calculate its factorial।
Exercise 9: Count Vowels
Read an English word or sentence and count vowels।
Exercise 10: Reverse Text
Read a String and reverse it using a loop।
Exercise 11: Password Attempts
Correct password:
java123
Maximum attempts:
3
Output:
Access granted
অথবা:
Account locked
Exercise 12: Menu Calculator
Create menu:
1. Add
2. Subtract
3. Multiply
4. Divide
5. Exit
Use:
do-whileswitch- Division-by-zero validation
Exercise 13: Running Total
Read numbers until user enters 0।
Calculate:
- Total
- Count
- Average
- Highest
- Lowest
Exercise 14: Grade Calculator
Read:
- Learner name
- Subject count
- Marks
Calculate:
- Total
- Average
- Pass/fail
- Grade
Use names such as:
Sakib
Jalisa
Subu
Sumu
Nur
during testing।
Part 16: Predict the Output
Question 1
int value = 5;
System.out.println(
value++ + 2
);
System.out.println(value);
Question 2
System.out.println(
"Total: " + 10 + 20
);
Question 3
int total = 0;
for (int number = 1; number <= 3; number++) {
total += number;
}
System.out.println(total);
Question 4
int number = 3;
while (number >= 1) {
System.out.println(number);
number--;
}
Question 5
for (int number = 1; number <= 5; number++) {
if (number == 3) {
continue;
}
System.out.println(number);
}
Question 6
String name = "Subu";
System.out.println(
name.charAt(
name.length() - 1
)
);
Question 7
double result =
(double) (5 / 2);
System.out.println(result);
Question 8
String role = "instructor";
String dashboard = switch (
role.toUpperCase()
) {
case "INSTRUCTOR" ->
"Harbor";
case "LEARNER" ->
"Dashboard";
default ->
"Unknown";
};
System.out.println(dashboard);
Predict the Output Answers
Answer 1
7
6
Postfix increment প্রথম expression-এ old value 5 ব্যবহার করে, তারপর value 6 হয়।
Answer 2
Total: 1020
Answer 3
6
Answer 4
3
2
1
Answer 5
1
2
4
5
Answer 6
u
Answer 7
2.0
Integer division আগে হয়েছে।
Answer 8
Harbor
Part 17: Module Assessment
Section A: Multiple Choice
Question 1
Java source file compile করার command কোনটি?
A. java Main.java
B. javac Main.java
C. compile Main.java
D. jdk Main.java
Question 2
Java program-এর entry point কোন method?
A. start()
B. run()
C. main()
D. execute()
Question 3
কোনটি primitive type নয়?
A. int
B. boolean
C. String
D. char
Question 4
String content compare করার recommended method কোনটি?
A. ==
B. equals()
C. compare
D. same()
Question 5
5 / 2 result কী?
A. 2.5
B. 2
C. 3
D. Compilation error
Question 6
Valid mark range check কোনটি?
A. mark >= 0 || mark <= 100
B. 0 <= mark <= 100
C. mark >= 0 && mark <= 100
D. mark > 0 && mark < 100
Question 7
যে loop body অন্তত একবার execute হয়:
A. for
B. while
C. do-while
D. None
Question 8
Current iteration skip করে:
A. break
B. return
C. continue
D. yield
Question 9
Switch expression block থেকে value দেয়:
A. break
B. yield
C. continue
D. next
Question 10
String-এর last valid index:
A. length()
B. length() + 1
C. length() - 1
D. 0
Section B: True or False
- Java case-sensitive।
Stringএকটি primitive type।==String content comparison-এর recommended method।whilebody zero times execute হতে পারে।do-while-এর শেষে semicolon প্রয়োজন।- Casting always rounds decimal values।
breakপুরো program terminate করে।continuecurrent iteration skip করে।Scanner.nextLine()full line পড়তে পারে।index <= text.length()safe String traversal condition।
Section C: Short Answers
- JDK, JRE এবং JVM-এর difference লিখুন।
- Variable এবং constant-এর difference লিখুন।
- Empty String, blank String এবং
null-এর difference লিখুন। - Widening এবং narrowing conversion explain করুন।
nextInt()-এর পরেnextLine()skip হওয়ার কারণ explain করুন।- Multiple
ifএবংelse-if-এর difference লিখুন। for,whileএবংdo-whileকখন ব্যবহার করবেন?break,continueএবংreturn-এর difference লিখুন।- Integer division avoid করার একটি example লিখুন।
- Loop-এর off-by-one error কী?
Assessment Answers
Multiple Choice
- B
- C
- C
- B
- B
- C
- C
- C
- B
- C
True or False
- True
- False
- False
- True
- True
- False
- False
- True
- True
- False
Final Practical Challenge
একটি console-based Learner Progress Tracker তৈরি করুন।
Program-এর menu:
1. Add learner result
2. View grading rules
3. Exit
Learner result-এর জন্য নিন:
- Learner name
- Completed lesson count
- Total lesson count
- Assignment score
- Final assessment score
Rules:
- Lesson counts negative হতে পারবে না
- Completed lessons total lessons-এর বেশি হতে পারবে না
- Scores
0–100range-এর মধ্যে হতে হবে - Course completion percentage calculate করতে হবে
- Final score:
Assignment score × 40%
Final assessment score × 60%
Course passed হবে যদি:
- Completion percentage
100% - Final score at least
40
Grade:
80–100 → A
70–79 → B
60–69 → C
50–59 → D
40–49 → E
Below 40 → F
Output example:
=== Learner Progress Report ===
Learner: Nur
Completed lessons: 21 of 21
Completion: 100.00%
Assignment score: 75.00
Final assessment: 85.00
Final score: 81.00
Grade: A
Result: Passed
Programটিতে ব্যবহার করুন:
- Constants
Scanner- Input validation
do-whileswitchif-else- Type conversion
- Formatted output
breakএবংcontinue
Module Summary
Module 1-এ আমরা শিখেছি:
- Programming problem-solving process
- Java source compilation এবং execution
- JDK, runtime components, JVM এবং bytecode
- Java program structure এবং syntax
- Variables এবং constants
- Primitive data types
- Strings এবং text processing
- Arithmetic, comparison এবং logical operators
- Type conversion এবং casting
- Console input with
Scanner - Conditional execution
- Traditional এবং modern
switch for,whileএবংdo-whileloopsbreakএবংcontinue- Validation, accumulation এবং reporting
- Complete console application development
এই foundation-এর ওপর পরবর্তী module-এ আমরা Java-এর Object-Oriented Programming concepts শুরু করব।
Next Module
পরবর্তী module-এ আমরা শিখব:
Object-Oriented Programming Foundations
Topics:
- Object-Oriented Programming কী
- Class এবং object
- Fields এবং methods
- Object creation
- Constructors
thiskeyword- Encapsulation
- Access modifiers
- Static এবং instance members
- Method parameters এবং return values
- Object relationships
- Practical class-based project