Programming and Java Fundamentals
Type Conversion and Casting
আপনি একটি free preview lesson দেখছেন।
Lesson Overview
একটি program-এ সব value সবসময় একই data type-এর হয় না।
উদাহরণ:
- একটি
intvaluelongvariable-এ রাখতে হতে পারে - একটি
doublevalueint-এ convert করতে হতে পারে - User-এর দেওয়া
"30"text-কে numeric30-এ convert করতে হতে পারে - একটি number-কে output-এর জন্য
String-এ convert করতে হতে পারে - একটি
char-এর Unicode value জানতে হতে পারে
এক type-এর value অন্য type-এ পরিবর্তন করার process-কে type conversion বলা হয়।
কিছু conversion Java automatically করে। কিছু conversion developer-কে explicitly করতে হয়।
এই lesson-এ আমরা শিখব:
- Type conversion কী
- Implicit এবং explicit conversion
- Widening conversion
- Narrowing conversion
- Casting syntax
- Numeric conversion
- Data loss
- Overflow এবং wrap-around
- Integer এবং decimal conversion
charএবং numeric conversion- String থেকে number conversion
- Number থেকে String conversion
- Boolean conversion
- Safe conversion
- Common casting-related error
Learning Objectives
এই lesson শেষ করার পর আপনি পারবেন:
- Type conversion কী, তা ব্যাখ্যা করতে
- Widening এবং narrowing conversion আলাদা করতে
- Java-এর automatic numeric conversion বুঝতে
- Casting operator ব্যবহার করতে
- Decimal value integer-এ convert করতে
- Conversion-এর সময় data loss শনাক্ত করতে
- Out-of-range value casting-এর result বুঝতে
charএবং integer value convert করতে- String থেকে primitive number parse করতে
- Primitive value String-এ convert করতে
- Invalid numeric text handle করার প্রয়োজন বুঝতে
- Safe type conversion-এর basic practice follow করতে
What Is Type Conversion?
এক data type-এর value অন্য data type-এ পরিবর্তন করার process-কে type conversion বলা হয়।
Example:
int studentCount = 100;
long totalStudents = studentCount;
এখানে int value একটি long variable-এ convert হয়েছে।
আরেকটি example:
double price = 99.75;
int wholePrice = (int) price;
এখানে double value explicitly int-এ cast করা হয়েছে।
Result:
99
Decimal অংশ হারিয়ে গেছে।
Why Is Type Conversion Necessary?
Type conversion প্রয়োজন হতে পারে যখন:
- Different numeric type-এর মধ্যে calculation করা হয়
- Method নির্দিষ্ট type expect করে
- External input text হিসেবে আসে
- Database value অন্য type-এ পাওয়া যায়
- API response parse করতে হয়
- File থেকে data পড়া হয়
- Decimal value round বা truncate করতে হয়
- Large value smaller type-এ নিতে হয়
- Character code নিয়ে কাজ করতে হয়
- Output-এর জন্য value text-এ convert করতে হয়
Main Types of Conversion
Java conversion broadly দুই ধরনের:
- Implicit conversion
- Explicit conversion
Implicit Conversion
Java যখন automatically এক type-এর value অন্য compatible type-এ convert করে, সেটিকে implicit conversion বলা হয়।
Example:
int value = 100;
long largerValue = value;
এখানে developer কোনো cast লেখেননি।
Java automatically int থেকে long convert করেছে।
Explicit Conversion
Developer যখন cast syntax ব্যবহার করে conversion request করেন, সেটিকে explicit conversion বলা হয়।
Example:
double price = 99.75;
int wholePrice = (int) price;
এখানে:
(int)
একটি explicit cast।
Widening Conversion
Smaller numeric type থেকে larger compatible numeric type-এ conversion-কে widening conversion বলা হয়।
Common widening order:
byte
↓
short
↓
int
↓
long
↓
float
↓
double
char থেকে কিছু numeric type-এও widening conversion হতে পারে:
char
↓
int
↓
long
↓
float
↓
double
Widening Example
int age = 30;
long ageAsLong = age;
এখানে int থেকে long conversion automatic।
More Widening Examples
byte smallValue = 100;
short shortValue = smallValue;
int intValue = shortValue;
long longValue = intValue;
float floatValue = longValue;
double doubleValue = floatValue;
সব conversion automatic হতে পারে।
Why Is Widening Usually Automatic?
Wider type সাধারণত smaller type-এর range accommodate করতে পারে।
Example:
byte range:
-128 to 127
int range:
-2,147,483,648 to 2,147,483,647
সব valid byte value int-এর মধ্যে fit করে।
তাই:
byte value = 100;
int result = value;
Safe।
Widening Does Not Always Mean Perfect Precision
Widening conversion range-wise safe হতে পারে, কিন্তু floating-point conversion-এ exact precision সবসময় preserved নাও হতে পারে।
Example:
long largeValue = 9_007_199_254_740_993L;
double convertedValue = largeValue;
System.out.println(convertedValue);
Possible output:
9.007199254740992E15
Large integer double-এ convert হলে precision হারাতে পারে।
তাই:
Wider type মানেই সবসময় exact value preservation নয়।
Widening Conversion Examples
byte to int
byte score = 100;
int expandedScore = score;
int to long
int studentCount = 50_000;
long totalStudentCount = studentCount;
int to double
int quantity = 5;
double decimalQuantity = quantity;
Output value:
5.0
float to double
float temperature = 36.5F;
double preciseTemperature = temperature;
Narrowing Conversion
Larger type থেকে smaller type-এ conversion-কে narrowing conversion বলা হয়।
Example:
double price = 99.75;
int wholePrice = (int) price;
Narrowing conversion-এ হতে পারে:
- Decimal অংশ হারানো
- Value range-এর বাইরে যাওয়া
- Overflow বা wrap-around
- Sign পরিবর্তন
- Precision loss
এই কারণে Java সাধারণত explicit cast require করে।
Casting Syntax
Casting syntax:
(targetType) value
Example:
double price = 99.75;
int wholePrice = (int) price;
এখানে:
- Target type:
int - Source value:
price
Narrowing Without Cast
Invalid:
double price = 99.75;
int wholePrice = price;
Compiler error হতে পারে:
possible lossy conversion from double to int
Correct:
int wholePrice = (int) price;
Casting Does Not Round
double value = 99.99;
int convertedValue = (int) value;
Result:
99
Casting decimal অংশ remove করে।
এটি round করে না।
Negative Decimal Casting
double value = -99.99;
int convertedValue = (int) value;
Result:
-99
Java zero-এর দিকে truncate করে।
Truncation
Decimal অংশ remove করার process-কে truncation বলা হয়।
Examples:
99.99 → 99
99.01 → 99
-99.99 → -99
-99.01 → -99
Casting nearest integer choose করে না।
Rounding vs Casting
Casting:
double value = 99.75;
int result = (int) value;
Result:
99
Rounding:
long result = Math.round(value);
Result:
100
Common Rounding Methods
Math.round()
Nearest whole number।
double value = 99.75;
long roundedValue = Math.round(value);
Result:
100
Math.floor()
Value-এর সমান বা ছোট nearest mathematical integer।
double value = 99.75;
double result = Math.floor(value);
Result:
99.0
Negative:
Math.floor(-99.25)
Result:
-100.0
Math.ceil()
Value-এর সমান বা বড় nearest mathematical integer।
double value = 99.25;
double result = Math.ceil(value);
Result:
100.0
Negative:
Math.ceil(-99.75)
Result:
-99.0
Casting Between Integer Types
long to int
long largeValue = 1000L;
int smallerValue = (int) largeValue;
Value int range-এর মধ্যে থাকায় result:
1000
Out-of-Range long to int
long largeValue = 3_000_000_000L;
int smallerValue = (int) largeValue;
System.out.println(smallerValue);
Possible output:
-1294967296
Result unexpected হতে পারে কারণ value int range-এর বাইরে।
Java runtime exception দেয় না। Lower bits preserved হয়ে wrap-around-like result তৈরি হয়।
Narrowing Can Change the Value
int value = 130;
byte convertedValue = (byte) value;
System.out.println(convertedValue);
Output:
-126
কারণ 130 byte range-এর বাইরে।
byte range:
-128 to 127
How Narrowing Wraps Values
byte 8 bits ব্যবহার করে।
130 decimal
এর lower 8-bit pattern interpreted হলে signed byte result হতে পারে:
-126
Beginner হিসেবে binary calculation মুখস্থ করার প্রয়োজন নেই।
মূল lesson:
Explicit cast compiler-কে conversion allow করতে বলে; এটি value safe থাকার guarantee দেয় না।
Safe Range Check Before Casting
long value = 3_000_000_000L;
if (
value >= Integer.MIN_VALUE
&& value <= Integer.MAX_VALUE
) {
int convertedValue = (int) value;
System.out.println(convertedValue);
} else {
System.out.println(
"Value cannot fit into int"
);
}
Math.toIntExact()
long থেকে int safe conversion-এর জন্য:
long value = 1000L;
int result = Math.toIntExact(value);
Value int range-এর বাইরে হলে exception হবে।
long value = 3_000_000_000L;
int result = Math.toIntExact(value);
Possible exception:
ArithmeticException
এটি silent corruption-এর চেয়ে safer।
Integer to Floating-Point Conversion
int score = 90;
double scoreAsDouble = score;
Result:
90.0
long to float
long value = 123456789L;
float convertedValue = value;
Conversion automatic হলেও precision হারাতে পারে।
System.out.println(convertedValue);
Possible output:
1.23456792E8
Floating-Point to Integer Conversion
double average = 85.75;
int wholeAverage = (int) average;
Result:
85
Large double to int
Java floating-point to integer narrowing-এর special rule আছে।
Example:
double value = 1.0E20;
int result = (int) value;
System.out.println(result);
Result Integer.MAX_VALUE হতে পারে:
2147483647
Negative large value Integer.MIN_VALUE হতে পারে।
NaN to Integer
double value = Double.NaN;
int result = (int) value;
System.out.println(result);
Result:
0
এই behaviour surprising হতে পারে।
Special floating-point value cast করার আগে validate করা উচিত।
Safe Floating-Point Conversion
double value = 99.75;
if (
!Double.isNaN(value)
&& !Double.isInfinite(value)
&& value >= Integer.MIN_VALUE
&& value <= Integer.MAX_VALUE
) {
int result = (int) value;
System.out.println(result);
}
Arithmetic Conversion
Arithmetic expression-এর সময় Java automatic promotion করে।
Example:
byte firstValue = 10;
byte secondValue = 20;
int total = firstValue + secondValue;
byte + byte result int হয়।
Why byte + byte Produces int
Java ছোট integer type-এর arithmetic সাধারণত int হিসেবে করে।
তাই:
byte total =
firstValue + secondValue;
Compiler error হতে পারে।
Correct:
int total =
firstValue + secondValue;
অথবা explicit narrowing:
byte total =
(byte) (firstValue + secondValue);
তবে result range check করা প্রয়োজন।
Mixed Numeric Expressions
int and long
int quantity = 10;
long totalUsers = 5_000_000_000L;
long result =
totalUsers + quantity;
Result long।
int and double
int quantity = 3;
double price = 99.50;
double total =
quantity * price;
Result double।
float and double
float firstValue = 10.5F;
double secondValue = 20.5;
double total =
firstValue + secondValue;
Result double।
Numeric Promotion Order
Simplifiedভাবে arithmetic expression-এ:
- কোনো operand
doubleহলে resultdouble - না হলে কোনো operand
floatহলে resultfloat - না হলে কোনো operand
longহলে resultlong - অন্যথায় result
int
Example:
byte + short → int
int + long → long
long + float → float
float + double → double
Casting Precedence
Cast একটি unary operation।
int result = (int) 10.75 + 5;
Evaluation:
(int) 10.75 → 10
10 + 5 → 15
Cast the Whole Expression
int result =
(int) (10.75 + 5.50);
Evaluation:
10.75 + 5.50 → 16.25
(int) 16.25 → 16
Parentheses conversion target পরিষ্কার করে।
Incorrect Cast Placement
int result =
(int) 10.75 + 5.50;
এই expression-এর result double, কারণ:
(int) 10.75 → 10
10 + 5.50 → 15.50
int variable-এ assign করলে compilation error হবে।
Correct:
int result =
(int) (10.75 + 5.50);
Division and Casting
Wrong decimal average:
int total = 5;
int count = 2;
double average =
total / count;
Result:
2.0
Cast Before Division
double average =
(double) total / count;
Evaluation:
(double) total → 5.0
5.0 / 2 → 2.5
Casting After Division Is Too Late
double average =
(double) (total / count);
Evaluation:
total / count → 2
(double) 2 → 2.0
Decimal অংশ ইতিমধ্যে হারিয়েছে।
char to Numeric Conversion
char একটি UTF-16 code unit represent করে।
char letter = 'A';
int code = letter;
System.out.println(code);
Output:
65
Widening automatic।
Numeric to char
int code = 65;
char letter = (char) code;
System.out.println(letter);
Output:
A
Explicit cast প্রয়োজন।
More Character Conversion Examples
char firstLetter = 'A';
char secondLetter =
(char) (firstLetter + 1);
System.out.println(secondLetter);
Output:
B
Digit Character vs Numeric Value
char digitCharacter = '7';
int unicodeValue =
digitCharacter;
System.out.println(unicodeValue);
Output:
55
এটি numeric 7 নয়। এটি character '7'-এর Unicode value।
Converting Digit Character to Number
char digitCharacter = '7';
int numericValue =
digitCharacter - '0';
System.out.println(numericValue);
Output:
7
কারণ digit characterগুলো sequential Unicode code ব্যবহার করে।
Safer Character Conversion
char digitCharacter = '7';
int numericValue =
Character.getNumericValue(
digitCharacter
);
Output:
7
Number to String Conversion
Primitive value text-এ convert করার কয়েকটি উপায় আছে।
String Concatenation
int age = 30;
String ageText = "" + age;
এটি কাজ করে, কিন্তু recommended নয়।
String.valueOf()
Recommended general approach:
int age = 30;
String ageText =
String.valueOf(age);
Wrapper toString()
int age = 30;
String ageText =
Integer.toString(age);
Other Types
long total = 1000L;
String totalText =
Long.toString(total);
double price = 99.50;
String priceText =
Double.toString(price);
boolean active = true;
String activeText =
Boolean.toString(active);
char grade = 'A';
String gradeText =
Character.toString(grade);
String.valueOf() Examples
String intText =
String.valueOf(100);
String doubleText =
String.valueOf(99.50);
String booleanText =
String.valueOf(true);
String charText =
String.valueOf('A');
String Concatenation Converts Automatically
int age = 30;
String message =
"Age: " + age;
Java age-কে String representation-এ convert করে।
Output:
Age: 30
String to Integer Conversion
String numeric text-কে integer-এ convert করতে:
String ageText = "30";
int age =
Integer.parseInt(ageText);
Using the Parsed Value
String quantityText = "3";
int quantity =
Integer.parseInt(quantityText);
int total =
quantity * 500;
System.out.println(total);
Output:
1500
String to long
String populationText =
"8000000000";
long population =
Long.parseLong(populationText);
String to double
String priceText = "99.50";
double price =
Double.parseDouble(priceText);
String to float
String temperatureText =
"36.5";
float temperature =
Float.parseFloat(
temperatureText
);
String to short
String valueText = "1000";
short value =
Short.parseShort(valueText);
String to byte
String valueText = "100";
byte value =
Byte.parseByte(valueText);
String to Boolean
String activeText = "true";
boolean active =
Boolean.parseBoolean(
activeText
);
Result:
true
Boolean Parsing Behaviour
Boolean.parseBoolean("true")
Result:
true
Case-insensitive:
Boolean.parseBoolean("TRUE")
Result:
true
Other text:
Boolean.parseBoolean("yes")
Result:
false
It does not throw an exception for "yes"।
String to char
String থেকে char পেতে:
String gradeText = "A";
char grade =
gradeText.charAt(0);
Validate Before charAt()
String gradeText = "";
char grade =
gradeText.charAt(0);
Runtime error হবে।
Safer:
if (
gradeText != null
&& !gradeText.isEmpty()
) {
char grade =
gradeText.charAt(0);
System.out.println(grade);
}
Parsing Invalid Numeric Text
String ageText = "thirty";
int age =
Integer.parseInt(ageText);
Runtime-এ:
NumberFormatException
Whitespace and Parsing
String ageText = " 30 ";
int age =
Integer.parseInt(ageText);
এটি error দিতে পারে।
Normalize করুন:
int age =
Integer.parseInt(
ageText.strip()
);
Decimal Text to Integer
Invalid:
String valueText = "10.5";
int value =
Integer.parseInt(valueText);
কারণ "10.5" valid integer format নয়।
Options:
double value =
Double.parseDouble(valueText);
তারপর প্রয়োজন হলে cast:
int wholeValue =
(int) value;
Parsing with Number Bases
Integer.parseInt() radix নিতে পারে।
Binary:
int binaryValue =
Integer.parseInt("1010", 2);
Result:
10
Hexadecimal:
int hexadecimalValue =
Integer.parseInt("FF", 16);
Result:
255
Wrapper valueOf() Methods
Parsing method primitive return করে:
int value =
Integer.parseInt("100");
valueOf() wrapper object return করে:
Integer value =
Integer.valueOf("100");
এই difference autoboxing এবং wrapper class lesson-এ বিস্তারিত শেখানো হবে।
Boolean Cannot Be Cast to Numeric Types
Invalid:
boolean active = true;
int value = (int) active;
Java boolean এবং numeric type-এর মধ্যে casting support করে না।
Numeric Value Cannot Be Cast to Boolean
Invalid:
int value = 1;
boolean active =
(boolean) value;
Java-তে 1 বা 0 boolean নয়।
Explicit logic ব্যবহার করুন:
boolean active =
value == 1;
String Cannot Be Cast Directly to Primitive Number
Invalid:
String ageText = "30";
int age =
(int) ageText;
Casting এবং parsing আলাদা।
Correct:
int age =
Integer.parseInt(ageText);
Primitive Number Cannot Be Cast to String
Invalid:
int age = 30;
String ageText =
(String) age;
Correct:
String ageText =
String.valueOf(age);
Casting vs Parsing
Casting
Compatible numeric বা reference type-এর representation change করে।
double value = 10.5;
int result = (int) value;
Parsing
Text-এর content interpret করে numeric বা boolean value তৈরি করে।
String valueText = "10";
int result =
Integer.parseInt(valueText);
Casting vs Conversion Method
Casting:
(int) value
Method conversion:
Integer.parseInt(text)
String.valueOf(number)
Math.toIntExact(longValue)
সব conversion casting নয়।
Autoboxing and Unboxing Preview
Primitive:
int score = 100;
Wrapper:
Integer scoreObject = score;
Java automatically primitive থেকে wrapper object convert করতে পারে।
এটি autoboxing।
Integer scoreObject = 100;
int score = scoreObject;
এটি unboxing।
Wrapper class এবং collection lesson-এ বিস্তারিত শেখানো হবে।
null and Unboxing Risk
Integer scoreObject = null;
int score = scoreObject;
Runtime-এ NullPointerException হতে পারে।
কারণ null wrapper primitive-এ unbox করা যায় না।
Practical Example: User Input Conversion
public class Main {
public static void main(String[] args) {
String ageInput = "30";
String scoreInput = "85.5";
String activeInput = "true";
int age =
Integer.parseInt(
ageInput
);
double score =
Double.parseDouble(
scoreInput
);
boolean active =
Boolean.parseBoolean(
activeInput
);
System.out.println(
"Age next year: "
+ (age + 1)
);
System.out.println(
"Score: " + score
);
System.out.println(
"Active: " + active
);
}
}
Output:
Age next year: 31
Score: 85.5
Active: true
Practical Example: Average Calculation
public class Main {
public static void main(String[] args) {
int totalMarks = 250;
int subjectCount = 3;
double average =
(double) totalMarks
/ subjectCount;
System.out.println(
"Average: " + average
);
}
}
Output:
Average: 83.33333333333333
Practical Example: Price Conversion
public class Main {
public static void main(String[] args) {
String priceInput = "4990.50";
double price =
Double.parseDouble(
priceInput
);
long priceInPaisa =
Math.round(price * 100);
System.out.println(
"Price: " + price
);
System.out.println(
"Price in paisa: "
+ priceInPaisa
);
}
}
Output:
Price: 4990.5
Price in paisa: 499050
Financial production code-এ decimal floating-point input handle করার সময় BigDecimal বেশি reliable হতে পারে।
Practical Example: Safe long to int
public class Main {
public static void main(String[] args) {
long learnerCount = 1000L;
int learnerCountAsInt =
Math.toIntExact(
learnerCount
);
System.out.println(
learnerCountAsInt
);
}
}
Practical Example: Character Code
public class Main {
public static void main(String[] args) {
char grade = 'A';
int gradeCode = grade;
char nextGradeCode =
(char) (grade + 1);
System.out.println(
"Grade: " + grade
);
System.out.println(
"Unicode value: "
+ gradeCode
);
System.out.println(
"Next character: "
+ nextGradeCode
);
}
}
Output:
Grade: A
Unicode value: 65
Next character: B
Practical Example: Seconds Conversion
public class Main {
public static void main(String[] args) {
String totalSecondsText =
"3675";
int totalSeconds =
Integer.parseInt(
totalSecondsText
);
int hours =
totalSeconds / 3600;
int remainingAfterHours =
totalSeconds % 3600;
int minutes =
remainingAfterHours / 60;
int seconds =
remainingAfterHours % 60;
System.out.println(
"Hours: " + hours
);
System.out.println(
"Minutes: " + minutes
);
System.out.println(
"Seconds: " + seconds
);
}
}
Output:
Hours: 1
Minutes: 1
Seconds: 15
Common Error: Assuming Casting Rounds
Wrong expectation:
double value = 9.9;
int result = (int) value;
Result:
9
10 নয়।
Round করতে:
long result =
Math.round(value);
Common Error: Casting After Integer Division
Wrong:
int total = 5;
int count = 2;
double average =
(double) (total / count);
Result:
2.0
Correct:
double average =
(double) total / count;
Result:
2.5
Common Error: Ignoring Narrowing Overflow
int value = 130;
byte result =
(byte) value;
Result:
-126
Cast successful মানেই result correct নয়।
Common Error: Parsing Invalid Text
int age =
Integer.parseInt("30 years");
Runtime error হবে।
Inputকে valid numeric format-এ আনতে হবে:
int age =
Integer.parseInt("30");
Common Error: Parsing Blank Text
int age =
Integer.parseInt(" ");
Runtime error হবে।
Validate:
String ageText = " ";
if (
ageText != null
&& !ageText.isBlank()
) {
int age =
Integer.parseInt(
ageText.strip()
);
}
Common Error: Direct String Cast
Invalid:
String ageText = "30";
int age =
(int) ageText;
Correct:
int age =
Integer.parseInt(ageText);
Common Error: Using Integer.parseInt() for Large Values
String populationText =
"8000000000";
int population =
Integer.parseInt(
populationText
);
Value int range-এর বাইরে।
Use:
long population =
Long.parseLong(
populationText
);
Common Error: Using Numeric Cast for Boolean
Invalid:
int value = 1;
boolean active =
(boolean) value;
Correct:
boolean active =
value == 1;
Common Error: Precision Loss
double value =
123456789.123456789;
float converted =
(float) value;
System.out.println(converted);
Result significantly rounded হতে পারে।
Common Error: Hidden Overflow in Arithmetic
int price = 2_000_000_000;
int quantity = 2;
long total =
price * quantity;
Multiplication int হিসেবে আগে overflow করে।
Correct:
long total =
(long) price * quantity;
অথবা:
long total =
price * 2L;
Cast Before Multiplication
long total =
(long) price * quantity;
এখানে price প্রথমে long হয়।
তাই multiplication long arithmetic ব্যবহার করে।
Common Error: Cast the Result Too Late
Wrong:
long total =
(long) (price * quantity);
যদি price * quantity int overflow করে, cast পরে কোনো benefit দেবে না।
Correct:
long total =
(long) price * quantity;
Safe Parsing with try-catch Preview
Invalid input handle করতে exception handling ব্যবহার করা হয়।
String ageText = "thirty";
try {
int age =
Integer.parseInt(
ageText
);
System.out.println(age);
} catch (NumberFormatException error) {
System.out.println(
"Age must be a number"
);
}
Exception handling future lesson-এ বিস্তারিত শেখানো হবে।
Conversion Checklist
Conversion করার আগে প্রশ্ন করুন:
- Source type কী?
- Target type কী?
- Conversion automatic কি?
- Explicit cast প্রয়োজন কি?
- Value target range-এর মধ্যে কি?
- Decimal অংশ হারাবে কি?
- Precision loss হবে কি?
- Overflow হতে পারে কি?
- Input text valid কি?
nullবা blank input handle করা হয়েছে কি?- Exact financial calculation প্রয়োজন কি?
- Safe helper method আছে কি?
Choosing the Correct Conversion
| Requirement | Approach |
|---|---|
int to long | Automatic widening |
int to double | Automatic widening |
double to int | Explicit cast |
long to int safely | Math.toIntExact() |
String to int | Integer.parseInt() |
String to long | Long.parseLong() |
String to double | Double.parseDouble() |
String to boolean | Boolean.parseBoolean() |
| Number to String | String.valueOf() |
char to int | Automatic widening |
int to char | Explicit cast |
| Decimal rounding | Math.round() |
| Round downward | Math.floor() |
| Round upward | Math.ceil() |
Important Terms
Type Conversion
এক data type-এর value অন্য data type-এ পরিবর্তন করা।
Implicit Conversion
Java automatically conversion করে।
Explicit Conversion
Developer cast বা conversion method ব্যবহার করেন।
Widening Conversion
Smaller compatible type থেকে larger type-এ conversion।
Narrowing Conversion
Larger type থেকে smaller type-এ conversion।
Casting
(targetType) value
syntax ব্যবহার করে explicit conversion।
Truncation
Decimal অংশ remove করা।
Precision Loss
Conversion-এর কারণে exact numeric detail হারানো।
Overflow
Value target type-এর maximum range exceed করা।
Parsing
Text content interpret করে numeric বা boolean value তৈরি করা।
Formatting
Value-কে text representation-এ পরিবর্তন করা।
Numeric Promotion
Expression evaluate করার সময় smaller type wider type-এ convert হওয়া।
Radix
Number system-এর base।
Example:
Binary radix = 2
Decimal radix = 10
Hexadecimal radix = 16
Practice Exercise 1: Widening or Narrowing
প্রতিটি conversion widening নাকি narrowing, তা লিখুন:
bytetointinttolonglongtointdoubletofloatfloattodoubleinttodoubledoubletointchartointinttochar
Practice Exercise 2: Write Widening Conversions
নিচের valueগুলো wider type-এ assign করুন:
byte smallValue = 100;
int studentCount = 5000;
long totalUsers = 8_000_000_000L;
float temperature = 36.5F;
Convert করুন:
byte→intint→longlong→doublefloat→double
Practice Exercise 3: Cast Decimal Values
নিচের values int-এ cast করে output লিখুন:
99.99
99.01
-99.99
-99.01
0.99
Explain করুন casting কীভাবে decimal অংশ handle করে।
Practice Exercise 4: Rounding
Value:
double value = 99.50;
Result বের করুন:
(int) valueMath.round(value)Math.floor(value)Math.ceil(value)
Practice Exercise 5: Fix the Average
Wrong:
int totalMarks = 250;
int subjectCount = 3;
double average =
totalMarks / subjectCount;
Casting ব্যবহার করে decimal average বের করুন।
Practice Exercise 6: Casting Position
দুটি expression-এর output compare করুন:
double firstAverage =
(double) (5 / 2);
double secondAverage =
(double) 5 / 2;
Explain করুন কেন result আলাদা।
Practice Exercise 7: Detect Data Loss
double originalValue =
123.987;
int convertedValue =
(int) originalValue;
Answer করুন:
- Converted value কত?
- কোন data হারিয়েছে?
- এটি rounding নাকি truncation?
Practice Exercise 8: Out-of-Range Cast
নিচের code run করুন:
int value = 130;
byte convertedValue =
(byte) value;
System.out.println(
convertedValue
);
Explain করুন output 130 নয় কেন।
Practice Exercise 9: Safe long to int
নিচের value safeভাবে int-এ convert করুন:
long learnerCount = 100_000L;
Math.toIntExact() ব্যবহার করুন।
তারপর নিচের value দিয়ে test করুন:
long learnerCount =
3_000_000_000L;
Practice Exercise 10: Prevent Multiplication Overflow
Wrong:
int productPrice =
2_000_000_000;
int quantity = 2;
long total =
productPrice * quantity;
Cast সঠিক জায়গায় বসিয়ে code fix করুন।
Practice Exercise 11: Character Conversion
char letter = 'A';
Convert করুন:
charথেকে Unicode integer- Integer code
66থেকেchar 'A'থেকে next character
Practice Exercise 12: Digit Character
char digitCharacter = '7';
Numeric value 7 বের করুন:
'0'subtract করেCharacter.getNumericValue()ব্যবহার করে
Practice Exercise 13: Convert Numbers to String
নিচের values String-এ convert করুন:
int age = 30;
long population = 8_000_000_000L;
double price = 4990.50;
boolean active = true;
char grade = 'A';
String.valueOf() ব্যবহার করুন।
Practice Exercise 14: Parse Strings
নিচের Strings সঠিক primitive type-এ parse করুন:
String ageText = "30";
String populationText = "8000000000";
String priceText = "4990.50";
String activeText = "true";
Practice Exercise 15: Normalize Before Parsing
Input:
String quantityText = " 5 ";
Whitespace remove করে int-এ parse করুন।
Expected output:
10
Parsed quantity-কে 2 দিয়ে multiply করুন।
Practice Exercise 16: Invalid Parsing
নিচের inputs parse করার সময় কী হবে?
"thirty"
"10.5"
""
" "
"999999999999999999999"
Integer.parseInt() ব্যবহার করলে সম্ভাব্য error ব্যাখ্যা করুন।
Practice Exercise 17: Boolean Parsing
Output predict করুন:
System.out.println(
Boolean.parseBoolean("true")
);
System.out.println(
Boolean.parseBoolean("TRUE")
);
System.out.println(
Boolean.parseBoolean("yes")
);
System.out.println(
Boolean.parseBoolean("1")
);
Practice Exercise 18: String to Character
Input:
String gradeText = "A";
First character extract করুন।
তারপর explain করুন empty String হলে কী হবে।
Practice Exercise 19: Binary Parsing
String binaryText = "1010";
Base 2 ব্যবহার করে integer-এ parse করুন।
Expected result:
10
Practice Exercise 20: Hexadecimal Parsing
String hexText = "FF";
Base 16 ব্যবহার করে integer-এ parse করুন।
Expected result:
255
Practice Exercise 21: Course Price Conversion
Input:
String coursePriceText =
"4990.50";
Tasks:
double-এ parse করুন- Price
100দিয়ে multiply করুন Math.round()ব্যবহার করে paisa-তে convert করুন- Output print করুন
Expected:
Price: 4990.5
Price in paisa: 499050
Practice Exercise 22: Student Input Conversion
Strings:
String mathematicsText = "80";
String englishText = "90";
String scienceText = "85";
Parse করে calculate করুন:
- Total
- Decimal average
Expected:
Total: 255
Average: 85.0
Practice Exercise 23: Conversion Errors
নিচের codeগুলো কেন invalid, তা explain এবং fix করুন।
Example 1
double price = 99.50;
int wholePrice = price;
Example 2
String ageText = "30";
int age = (int) ageText;
Example 3
int age = 30;
String ageText = (String) age;
Example 4
boolean active = true;
int value = (int) active;
Practice Exercise 24: Type Promotion
প্রতিটি expression-এর result type লিখুন:
byte + byteshort + shortint + longlong + floatfloat + doubleint * doublechar + int
Practice Exercise 25: Explain in Your Own Words
নিজের ভাষায় উত্তর দিন:
- Type conversion কী?
- Implicit conversion কী?
- Explicit conversion কী?
- Widening conversion কেন সাধারণত automatic?
- Narrowing conversion-এ cast কেন প্রয়োজন?
- Casting কি value safety guarantee করে?
- Casting এবং rounding-এর পার্থক্য কী?
- Truncation কী?
- Cast calculation-এর আগে বা পরে করার difference কী?
- Parsing কী?
- Casting এবং parsing-এর পার্থক্য কী?
Math.toIntExact()কেন useful?String.valueOf()কী করে?Integer.parseInt()কী করে?- Invalid numeric text parse করলে কী হতে পারে?
- Boolean কি numeric type-এ cast করা যায়?
charথেকে integer conversion কী represent করে?- Arithmetic promotion কী?
longassignment-এর আগেও overflow কেন হতে পারে?- Conversion-এর আগে range check কেন গুরুত্বপূর্ণ?
Knowledge Check
Question 1
Type conversion কী?
Question 2
Implicit conversion কী?
Question 3
Explicit conversion কী?
Question 4
Widening conversion কী?
Question 5
Narrowing conversion কী?
Question 6
Casting syntax কী?
Question 7
int থেকে long conversion-এ cast লাগে কি?
Question 8
double থেকে int conversion-এ cast লাগে কি?
Question 9
(int) 99.99-এর result কী?
Question 10
Casting কি round করে?
Question 11
Math.round(99.75) কী return করে?
Question 12
Math.floor(-99.25) কী return করে?
Question 13
Math.ceil(-99.75) কী return করে?
Question 14
Out-of-range narrowing cast কি exception দেয়?
Question 15
Safe long to int conversion-এর method কী?
Question 16
byte + byte result সাধারণত কোন type?
Question 17
Decimal average পাওয়ার জন্য cast কখন করতে হবে?
Question 18
char 'A'-এর integer value কী?
Question 19
Integer 65-কে char-এ convert করতে কী প্রয়োজন?
Question 20
String থেকে integer parse করার method কী?
Question 21
String থেকে long parse করার method কী?
Question 22
String থেকে double parse করার method কী?
Question 23
Primitive value String-এ convert করার general method কী?
Question 24
Invalid integer text parse করলে কোন exception হতে পারে?
Question 25
Boolean.parseBoolean("yes") কী return করে?
Question 26
Boolean কি int-এ cast করা যায়?
Question 27
String কি direct cast করে int করা যায়?
Question 28
Casting এবং parsing কি একই?
Question 29
(double) (5 / 2)-এর result কী?
Question 30
(double) 5 / 2-এর result কী?
Knowledge Check Answers
Answer 1
এক data type-এর value অন্য data type-এ পরিবর্তন করার process হলো type conversion।
Answer 2
Java automatically conversion করলে সেটি implicit conversion।
Answer 3
Developer cast বা conversion method ব্যবহার করলে সেটি explicit conversion।
Answer 4
Smaller compatible type থেকে wider type-এ conversion হলো widening conversion।
Answer 5
Larger type থেকে smaller type-এ conversion হলো narrowing conversion।
Answer 6
(targetType) value
Answer 7
না। সাধারণত automatic widening conversion হয়।
Answer 8
হ্যাঁ।
int result =
(int) doubleValue;
Answer 9
99
Answer 10
না। Decimal অংশ truncate করে।
Answer 11
100
Return type long।
Answer 12
-100.0
Answer 13
-99.0
Answer 14
সাধারণ integer narrowing cast exception দেয় না। Unexpected wrapped value তৈরি হতে পারে।
Answer 15
Math.toIntExact()
Answer 16
int
Answer 17
Division হওয়ার আগে কমপক্ষে একটি operand-কে double করতে হবে।
(double) total / count
Answer 18
65
Answer 19
Explicit cast:
(char) 65
Answer 20
Integer.parseInt()
Answer 21
Long.parseLong()
Answer 22
Double.parseDouble()
Answer 23
String.valueOf()
Answer 24
NumberFormatException
Answer 25
false
Answer 26
না।
Answer 27
না। Parsing method ব্যবহার করতে হয়।
Answer 28
না। Casting type-compatible representation conversion। Parsing text interpret করে value তৈরি করে।
Answer 29
2.0
Integer division আগে হয়েছে।
Answer 30
2.5
Division-এর আগে 5 double হয়েছে।
Lesson Summary
এই lesson-এ আমরা শিখেছি:
- Type conversion এক type-এর value অন্য type-এ পরিবর্তন করে
- Java কিছু conversion automatically করে
- Implicit conversion-এ explicit cast লাগে না
- Explicit conversion developer request করেন
- Widening conversion সাধারণত automatic
- Narrowing conversion explicit cast require করে
- Casting syntax হলো
(targetType) value - Decimal থেকে integer cast করলে fractional অংশ truncate হয়
- Casting rounding করে না
Math.round(),Math.floor()এবংMath.ceil()আলাদা result দেয়- Narrowing conversion data loss করতে পারে
- Out-of-range cast unexpected wrapped value তৈরি করতে পারে
Math.toIntExact()saferlongtointconversion দেয়- Arithmetic expression-এর সময় numeric promotion হয়
byteএবংshortarithmetic সাধারণতintresult দেয়- Decimal average পেতে division-এর আগে cast করতে হয়
- Cast result-এর পরে করলে lost precision ফিরে আসে না
charnumeric Unicode code unit represent করে- Numeric code explicit cast করে
charকরা যায় - String থেকে number conversion parsing-এর মাধ্যমে হয়
Integer.parseInt(),Long.parseLong()এবংDouble.parseDouble()common parser- Primitive value String-এ convert করতে
String.valueOf()ব্যবহার করা যায় - Invalid numeric text
NumberFormatExceptionতৈরি করতে পারে - Blank এবং null input parsing-এর আগে validate করা উচিত
- Boolean numeric type-এ cast করা যায় না
- String direct cast করে primitive number করা যায় না
- Casting এবং parsing আলাদা process
longvariable-এ assignment-এর আগেও integer arithmetic overflow হতে পারে- Safe conversion-এর জন্য range, precision এবং source value validate করা জরুরি
Next Lesson
পরবর্তী lesson-এ আমরা user input গ্রহণ করা শিখব।
আমরা জানব:
ScannerকীScannerimport করা- Keyboard input পড়া
nextLine()nextInt()nextDouble()nextBoolean()- Prompt দেখানো
- Multiple input নেওয়া
nextInt()এবংnextLine()problem- Input parsing
- Invalid input
- Scanner close করা
- একটি interactive console program তৈরি করা