JavaJava · Chapterبەش 4 · Lectureوانە 4.3

Type Casting: Widening and Narrowingگۆڕینی جۆر: فراوانکردنی جۆر و تەسککردنەوەی جۆر

How Java turns a value of one primitive type into another: widening, which is automatic (and can still lose digits), and narrowing with a cast such as (int), which cuts off the fraction and can wrap round ((byte) 200 is -56). Also Math.round versus a cast, char and numbers, and where the cast goes in a percentage.

Java چۆن لە جۆرێکی سەرەتاییەوە دەگۆڕێت بۆ جۆرێکی تر: کە خۆکارە (و هێشتا دەتوانێت لەدەست بدات) و بە (int) و هاوشێوەکانی، کە دەبڕێتەوە و دەتوانێت بسوڕێتەوە ((byte) 200 دەبێتە -56). هەروەها Math.round بەراورد بە (int)، char و ژمارەکان و شوێنی (double) لە ڕێژەی سەدیدا.

13 min read12 خولەک خوێندنەوە · 14 stepsهەنگاو

What you will learnچی فێر دەبیت

  • Tell widening from narrowing and follow Java's real widening map, including char and the conversions that lose digits.
  • Write casts such as (int), and predict what they do: cutting toward zero and wrapping round.
  • Choose between a cast and Math.round, and put (double) in the right place in a division.
  • لە جیا بکەیتەوە و نەخشە ڕاستەقینەکەی Java بخوێنیتەوە، char و ئەو گۆڕینانەش کە لەدەست دەدەن.
  • (int) و هاوشێوەکانی بنووسیت و پێشبینی بکەیت چی دەکەن: بڕین بەرەو سفر و سووڕانەوە.
  • لە نێوان (int) و Math.round هەڵبژێریت و (double) لە شوێنی دروستی دابەشکردنێکدا دابنێیت.

What type casting isگۆڕینی جۆر چییە؟

Changing the type of a value is type casting (): a whole number used in a calculation with decimals, or a decimal price stored as a whole number. Java converts its number types and char into each other (The eight primitive types); a boolean never converts. There are two directions:

گۆڕینی جۆری پێی دەگوترێت (type casting): کە لە ژماردنێکی بەکار دێت، یان نرخێکی کە وەک هەڵدەگیرێت. Java جۆرە ژمارەییەکانی و char بۆ یەکتر دەگۆڕێت (هەشت جۆرە سەرەتاییەکە)؛ boolean هەرگیز ناگۆڕدرێت. دوو ئاراستە هەیە:

  • : from a smaller type to a bigger one, such as int to double. Java does it by itself.
  • : from a bigger type to a smaller one, such as double to int. You must ask for it by writing the new type in brackets: (int).
  • : لە جۆرێکی بچووکەوە بۆ جۆرێکی گەورەتر، وەک int بۆ double. Java خۆی دەیکات.
  • : لە جۆرێکی گەورەوە بۆ جۆرێکی بچووکتر، وەک double بۆ int. دەبێت خۆت داوای بکەیت بە نووسینی جۆرە نوێیەکە لە ناو کەوانەدا: (int).
A tea glass and a big mugئیستیکانێک و پەرداخێکی گەورە

Pour a full tea glass into a big mug: it always fits. Pour a full big mug into a tea glass: it may not fit, so you must pour on purpose and accept that some is lost.

ئیستیکانێکی پڕ چا بڕێژە ناو پەرداخێکی گەورە: هەمیشە جێی دەبێتەوە. پەرداخێکی گەورەی پڕ بڕێژە ناو ئیستیکانێک: لەوانەیە جێی نەبێتەوە، بۆیە دەبێت بە ئەنقەست بیڕێژیت و قبووڵ بکەیت هەندێکی بڕژێت.

Two panels. Widening: a small tea glass labelled int holding 9 is poured into a big mug labelled double, which then holds 9.0; a tick says it always fits and Java does it by itself. Narrowing: a big mug labelled double holding 9.78 is poured, with the label (int), into a small glass labelled int, which holds 9 while drops marked .78 spill; a cross says it may not fit, you must ask with (int), and the .78 is lost.دوو بەش. فراوانکردنی جۆر: ئیستیکانێکی بچووک بە ناوی int کە 9ـی تێدایە دەڕژێنرێتە ناو پەرداخێکی گەورە بە ناوی double، کە ئێستا 9.0 هەڵدەگرێت؛ نیشانەیەکی ڕاست دەڵێت هەمیشە جێی دەبێتەوە و Java خۆی دەیکات. تەسککردنەوەی جۆر: پەرداخێکی گەورە بە ناوی double کە 9.78ـی تێدایە بە نووسینی (int) دەڕژێنرێتە ناو ئیستیکانێکی بچووک بە ناوی int، کە 9 هەڵدەگرێت و دڵۆپەکانی 0.78 دەڕژێن؛ نیشانەی هەڵە دەڵێت لەوانەیە جێی نەبێتەوە، دەبێت بە (int) داوای بکەیت و بەشی 0.78 لەدەست دەچێت.
Widening always fits; narrowing must be asked for هەمیشە جێی دەبێتەوە؛ دەبێت داوای بکەیتCêIT
Where the analogy stops workingسنووری ئەم نموونەیە

A cast never spills: Java keeps a number that fits, and it can be a surprising one.

هەرگیز شتێک ناڕژێنێت: Java ژمارەیەک دەهێڵێتەوە کە جێی دەبێتەوە و لەوانەیە ژمارەیەکی سەیر بێت.

Widening: Java does it by itselfفراوانکردنی جۆر: Java خۆی دەیکات

Widening happens by itself when a value of a smaller type goes into a bigger type. Here the int 9 goes into a double variable:

خۆی ڕوو دەدات کاتێک جۆرێکی بچووک دەچێتە ناو جۆرێکی گەورەتر. لێرەدا intـی 9 دەچێتە ناو double:

Widening.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Widening {
    public static void main(String[] args) {
        int myInt = 9;
        double myDouble = myInt;      // automatic casting: int to double
        System.out.println(myInt);
        System.out.println(myDouble);
    }
}
Two variable boxes. myInt of type int holds 9. An arrow labelled automatic leads to myDouble of type double, which holds 9.0. Below: double myDouble = myInt; nothing is lost, 9 becomes 9.0.دوو سندووقی گۆڕاو. myInt جۆری int نرخی 9 هەڵدەگرێت. تیرێک بە ناوی «بە خۆکاری» دەچێتە myDouble جۆری double کە 9.0 هەڵدەگرێت. لە خوارەوە: double myDouble = myInt; هیچ لەدەست ناچێت، 9 دەبێتە 9.0.
int to double: automaticint بۆ double: خۆکارCêIT

Nothing is lost: every int value fits in a double, which simply prints .0. Widening happens wherever a bigger type is expected: in an assignment, when an int is given to a method that wants a double (Math.sqrt(9) gives 3.0), and inside calculations that mix types (Mixing types).

هیچ لەدەست ناچێت: هەموو int لە doubleـدا جێی دەبێتەوە، کە تەنیا .0 چاپ دەکات. لە هەر شوێنێکدا ڕوو دەدات کە جۆرێکی گەورەتر چاوەڕوان دەکرێت: لە ، کاتێک int دەدرێتە کە double دەوێت (Math.sqrt(9) دەدات ⁦3.0⁩) و لە ناو ئەو ژماردنانەدا کە جۆرەکان تێکەڵ دەکەن (تێکەڵکردنی جۆرەکان).

Which conversions are automatic?کام گۆڕینانە خۆکارن؟

The Java Language Specification (§5.1.2) lists exactly which conversions widen. Follow the arrows: a type converts by itself into every type further along its arrows.

تایبەتمەندیی زمانی Java (بڕگەی ⁦5.1.2⁩) بە وردی دەڵێت کام گۆڕینانە . بەدوای تیرەکاندا بڕۆ: هەر جۆرێک خۆی دەگۆڕێت بۆ هەموو ئەو جۆرانەی کە بە شوێنکەوتنی تیرەکانی پێیان دەگەیت.

The widening map. A row of boxes with arrows: byte (8 bits), short (16), int (32), long (64), float (32), double (64). A box char (16 bits) below short has its own arrow up to int. The arrow from long to float is dashed, and two dashed curves join int to float and long to double: these may lose digits. A crossed dashed line between short and char says a cast is needed both ways.نەخشەی فراوانکردنی جۆر. ڕیزێک سندووق بە تیرەوە: byte (8 بیت)، short (16)، int (32)، long (64)، float (32)، double (64). سندووقی char (16 بیت) لە خوار short تیرێکی خۆی بۆ int هەیە. تیری long بۆ float پچڕپچڕە و دوو کەوانەی پچڕپچڕ int بە float و long بە double دەبەستنەوە: ئەمانە لەوانەیە تاکژمارە لەدەست بدەن. هێڵێکی پچڕپچڕی خاچدراو لە نێوان short و char دەڵێت لە هەردوو ئاراستەدا گۆڕینی جۆر پێویستە.
Java's widening conversions لە JavaـداCêIT
  • byte → short → int → long → float → double
  • char → int, and from there on to long, float and double.
  • short and char are both 16 bits but hold different numbers (−32 768 to 32 767 and 0 to 65 535), so neither fits into the other. Many tutorials draw one chain short → char → int; Java's rules need a cast both ways, and also from byte to char:
  • byte → short → int → long → float → double
  • char → int و لەوێوە بۆ long، float و double.
  • short و char هەردووکیان ⁦16⁩ بەڵام ژمارەی جیاواز هەڵدەگرن (لە ⁦−32 768⁩ تا ⁦32 767⁩ و لە 0 تا ⁦65 535⁩)، بۆیە هیچیان لە ناو ئەوی تردا جێی نابێتەوە. زۆر فێرکاری یەک زنجیرە دەکێشن short → char → int؛ یاساکانی Java لە هەردوو ئاراستەدا (type)ـیان دەوێت، هەروەها لە byteـەوە بۆ char:
ShortAndChar.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class ShortAndChar {
    public static void main(String[] args) {
        short s = 65;
        char c = s;               // short -> char?
        char letter = 'A';
        short t = letter;         // char -> short?
    }
}

Which conversions are automatic?کام گۆڕینانە خۆکارن؟

Widening can still lose digitsفراوانکردنی جۆر هێشتا دەتوانێت تاکژمارە لەدەست بدات

Widening never loses the size of a number, but three conversions can lose digits: int → float, long → float and long → double. A float keeps only about 7 digits and a double about 15 to 16 (float or double?):

هەرگیز قەبارەی ژمارەیەک لەدەست نادات، بەڵام سێ گۆڕین دەتوانن لەدەست بدەن: int بۆ float، long بۆ float و long بۆ double. float تەنیا نزیکەی 7 دەهێڵێتەوە و double نزیکەی ⁦15⁩ تا ⁦16⁩ (float یان double؟):

LostDigits.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class LostDigits {
    public static void main(String[] args) {
        int big = 123456789;
        float f = big;                    // int -> float: automatic
        System.out.println(big);
        System.out.println(f);
        System.out.println((int) f);
        long huge = 9007199254740993L;    // 2 to the power 53, plus 1
        double d = huge;                  // long -> double: automatic
        System.out.println(huge);
        System.out.println(d);
    }
}
Digit boxes. int 123456789 becomes float 123456792: the first seven digits are the same, the last two changed. long 9007199254740993 becomes double 9007199254740992: only the last digit changed. Notes: a float keeps about 7 digits and prints 1.23456792E8; a double keeps about 15 to 16 digits.سندووقی تاکژمارەکان. int 123456789 دەبێتە float 123456792: حەوت تاکژمارەی یەکەم وەک خۆیانن، دوو دوایینەکە گۆڕان. long 9007199254740993 دەبێتە double 9007199254740992: تەنیا دوایین تاکژمارە گۆڕا. تێبینی: float نزیکەی 7 تاکژمارە دەهێڵێتەوە و 1.23456792E8 چاپ دەکات؛ double نزیکەی 15 تا 16 تاکژمارە.
Big whole numbers can lose their last digitsژمارە گەورەکان دەتوانن دوایین لەدەست بدەنCêIT

Java does this silently, with no error. Keep big whole numbers in int or long; every int fits exactly in a double, but not every long.

Java ئەمە بە بێدەنگی دەکات، بێ هیچ هەڵەیەک. ژمارە گەورەکان لە int یان longـدا بهێڵەرەوە؛ هەموو intـێک ڕێک لە doubleـدا جێی دەبێتەوە، بەڵام هەموو longـێک نا.

Narrowing: you must write the castتەسککردنەوەی جۆر: دەبێت (type) بنووسیت

Going from a bigger type to a smaller one is narrowing. You must do it by hand: put the new type in brackets in front of the value. The type in brackets is called a cast:

چوون لە جۆرێکی گەورەوە بۆ جۆرێکی بچووکتر . دەبێت بە دەست بیکەیت: جۆرە نوێیەکە لە ناو کەوانەدا بخە پێش . جۆرەکەی ناو کەوانە پێی دەگوترێت cast:

Narrowing.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Narrowing {
    public static void main(String[] args) {
        double myDouble = 9.78;
        int myInt = (int) myDouble;   // manual casting: double to int
        System.out.println(myDouble);
        System.out.println(myInt);
    }
}
The statement int myInt = (int) myDouble; with three coloured parts: int myInt is the new variable, (int) is the type you want, myDouble is the value, 9.78. The result: myInt gets 9.ڕستەکە int myInt = (int) myDouble; بە سێ بەشی ڕەنگاوڕەنگ: int myInt گۆڕاوێکی نوێیە، (int) ئەو جۆرەیە کە دەتەوێت، myDouble نرخەکەیە، 9.78. ئەنجام: myInt نرخی 9 وەردەگرێت.
The cast: the new type in bracketsجۆرە نوێیەکە لە ناو کەوانەداCêIT

Without the cast, javac refuses, because the value could change: int myInt = myDouble; gives incompatible types: possible lossy conversion from double to int. The cast says: I know, do it anyway. The original variable does not change: myDouble still holds 9.78.

بەبێ (int)، javac ڕەتی دەکاتەوە، چونکە لەوانەیە بگۆڕێت: int myInt = myDouble; دەدات incompatible types: possible lossy conversion from double to int. (int) دەڵێت: دەزانم، هەر بیکە. ناگۆڕێت: myDouble هێشتا ⁦9.78⁩ هەڵدەگرێت.

Narrowing: you must write the castتەسککردنەوەی جۆر: دەبێت (type) بنووسیت

A cast cuts off the fraction(int) کەرتەکە دەبڕێتەوە

A cast from double or float to a whole-number type does not round. It throws the fraction away (truncation, ), which always moves the number toward zero: 9.78 becomes 9, and -3.99 becomes -3, not -4.

گۆڕین لە double یان floatـەوە بۆ جۆرێکی نزیک ناکاتەوە. فڕێ دەدات ()، کە هەمیشە ژمارەکە بەرەو سفر دەبات: ⁦9.78⁩ دەبێتە 9 و -3.99 دەبێتە -3، نەک -4.

Animation. (int) 9.78: the digits 9, point, 7, 8 sit in a double box; a dashed cut line appears at the decimal point; the point and the digits 7 and 8 drop away, faded: the fraction is thrown away, there is no rounding; the box becomes an int holding 9, so 9.78 becomes 9, not 10. Then (int) -3.99: the same cut leaves -3, toward zero, not down.
Animation. (int) 9.78: the digits 9, point, 7, 8 sit in a double box; a dashed cut line appears at the decimal point; the point and the digits 7 and 8 drop away, faded: the fraction is thrown away, there is no rounding; the box becomes an int holding 9, so 9.78 becomes 9, not 10. Then (int) -3.99: the same cut leaves -3, toward zero, not down.
The cast drops the fraction, toward zero(int) فڕێ دەدات، بەرەو سفرCêIT
CutOff.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class CutOff {
    public static void main(String[] args) {
        System.out.println((int) 9.78);
        System.out.println((int) 3.99);
        System.out.println((int) -3.99);
        System.out.println((int) 0.999);
    }
}

Narrowing: you must write the castتەسککردنەوەی جۆر: دەبێت (type) بنووسیت

Rounding instead: Math.roundلە جیاتی بڕین نزیکی بکەرەوە: ⁦Math.round⁩

For the nearest whole number, use Math.round instead of a cast. It returns a long, so cast its answer when you need an int:

بۆ نزیکترین ، لە جیاتی (int) Math.round بەکار بهێنە. long دەگەڕێنێتەوە، بۆیە ئەگەر intـت دەوێت جۆری وەڵامەکەی بگۆڕە:

RoundOrCut.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class RoundOrCut {
    public static void main(String[] args) {
        double price = 9.78;
        System.out.println((int) price);          // cut off
        System.out.println(Math.round(price));    // nearest whole number
        System.out.println((int) -9.78);
        System.out.println(Math.round(-9.78));
        int rounded = (int) Math.round(price);    // Math.round gives a long
        System.out.println(rounded);
    }
}
Two number lines. Top: 9.78 between 8 and 11; a curved arrow labelled (int) goes down to 9, a green arrow labelled Math.round goes up to 10; 0 is to the left. Bottom: -9.78 between -11 and -8; (int) goes to -9, toward 0 on the right; Math.round goes to -10. Note: (int) drops the fraction, so it always moves toward 0; Math.round gives the nearest whole number.دوو هێڵی ژمارەکان. سەرەوە: 9.78 لە نێوان 8 و 11؛ تیرێکی چەماوە بە ناوی (int) دەچێتە 9، تیرێکی سەوز بە ناوی Math.round دەچێتە 10؛ 0 لای چەپە. خوارەوە: -9.78 لە نێوان -11 و -8؛ (int) دەچێتە -9، بەرەو 0 لای ڕاست؛ Math.round دەچێتە -10. تێبینی: (int) کەرتەکە فڕێ دەدات، بۆیە هەمیشە بەرەو 0 دەچێت؛ Math.round نزیکترین ژمارەی تەواو دەدات.
Cut toward 0, or go to the nearestبڕین بەرەو 0، یان چوون بۆ نزیکترینCêIT

Other ways to round (floor, ceil, rint) and the rule for halves are in The Math class.

ڕێگاکانی تری (floor، ceil، rint) و یاسای نیوەکان لە کلاسەکەی Mathدان.

Narrowing: you must write the castتەسککردنەوەی جۆر: دەبێت (type) بنووسیت

When a small type needs no castکەی جۆرێکی بچووک پێویستی بە (type) نییە

There is one exception. A whole number written straight into the code (a ) may go into a byte, short or char without a cast when its value fits, because javac can check a fixed number. A variable is different: javac does not look at what is inside it, so it asks for a cast:

یەک ئاوارتە هەیە. کە ڕاستەوخۆ لە کۆدەکەدا نووسرابێت () دەتوانێت بەبێ (type) بچێتە ناو byte، short یان char ئەگەر جێی ببێتەوە، چونکە javac دەتوانێت ژمارەیەکی جێگیر بپشکنێت. جیاوازە: javac سەیری ناوەوەی ناکات، بۆیە (type) دەوێت:

Fits.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Fits {
    public static void main(String[] args) {
        byte a = 100;          // the constant 100 fits in a byte
        char c = 65;           // 65 fits in a char: it is the letter A
        int x = 100;
        byte b = x;            // x is a variable, not a constant
    }
}
Four cards about byte, which holds -128 to 127. byte a = 100; tick: a literal that fits. byte b = 128; cross: too big for a byte. int x = 100; byte c = x; cross: a variable, javac does not check its value. byte c = (byte) x; tick: a cast, you take responsibility.چوار کارت لەبارەی byte، کە -128 تا 127 هەڵدەگرێت. byte a = 100; ڕاستە: لیتەراڵێک کە جێی دەبێتەوە. byte b = 128; هەڵەیە: بۆ byte زۆر گەورەیە. int x = 100; byte c = x; هەڵەیە: گۆڕاوێکە، javac نرخەکەی ناپشکنێت. byte c = (byte) x; ڕاستە: گۆڕینی جۆر، تۆ بەرپرسیاریت.
Literals that fit, variables that need a cast کە جێیان دەبێتەوە، کە (type)ـیان دەوێتCêIT

Narrowing can change the value completelyتەسککردنەوەی جۆر دەتوانێت نرخەکە بە تەواوی بگۆڕێت

If the value does not fit into the smaller type, you can get a completely different number, and there is no error. Between whole-number types Java keeps only the lowest bits that fit: a byte keeps the last 8. 200 is 11001000 in binary; in a byte the first bit is the sign bit, so it means -56 (200 - 256), the same wrap-round as overflow:

ئەگەر لە جۆرە بچووکەکەدا جێی نەبێتەوە، دەتوانیت ژمارەیەکی بە تەواوی جیاواز وەربگریت و هیچ هەڵەیەکیش نییە. لە نێوان جۆرەکانی Java تەنیا نزمترین دەهێڵێتەوە کە جێیان دەبێتەوە: byte دوایین 8 دەهێڵێتەوە. ⁦200⁩ بە شێوەی 11001000ـە؛ لە byteـدا یەکەم ، بۆیە واتای -56 دەدات (200 - 256)، هەمان سووڕانەوەی سەرڕێژبوون:

ByteWrap.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class ByteWrap {
    public static void main(String[] args) {
        int big = 200;
        byte small = (byte) big;
        System.out.println(small);
        System.out.println((byte) 127);
        System.out.println((byte) 128);
        System.out.println((byte) 256);
        System.out.println((short) 70000);
    }
}
A wheel of the 256 byte values: 0 at the top, 64 on the right, 127 and -128 next to each other at the bottom, -64 on the left. A green arrow counts +200 steps clockwise from 0 and stops at -56. Beside it: a byte holds only -128 to 127; after 127 it wraps round to -128; so 200 lands on -56; 200 - 256 = -56; Java keeps the last 8 bits, 11001000, and the first bit 1 means negative.بازنەیەک بە 256 نرخی byte: 0 لە سەرەوە، 64 لای ڕاست، 127 و -128 لە خوارەوە لە تەنیشت یەکترن، -64 لای چەپ. تیرێکی سەوز لە 0ـەوە 200 هەنگاو بە ئاراستەی میلی کاتژمێر دەژمێرێت و لە -56 دەوەستێت. لە تەنیشتیەوە: byte تەنیا -128 تا 127 هەڵدەگرێت؛ دوای 127 دەسوڕێتەوە بۆ -128؛ بۆیە 200 دەگاتە -56؛ 200 - 256 = -56؛ Java دوایین 8 بیت دەهێڵێتەوە (11001000) و یەکەم بیت کە 1ـە واتە نەرێنی.
(byte) 200 wraps round to -56(byte) 200 دەسوڕێتەوە بۆ -56CêIT

There and back: char, byte and shortبۆ double و گەڕانەوە: char، byte و short

A char is a number too (A char is a number): 'X' is character number 88. So a char widens to int, long, float or double by itself, and comes back only with a cast. The lab task below does this with three types.

charـیش ژمارەیە (charـێک ژمارەیەکە): 'X' ژمارە ⁦88⁩ـە. بۆیە char بە خۆکاری دەبێتە int، long، float یان double و تەنیا بە (char) دەگەڕێتەوە. ئەرکی تاقیگەی خوارەوە ئەمە بە سێ جۆر دەکات.

Three rows. char 'X' goes automatically to the double 88.0 and back with (char) to 'X'. byte 120 goes to 120.0 and back with (byte) to 120. short 2020 goes to 2020.0 and back with (short) to 2020. Green arrows: automatic (widening); dark arrows: a cast (narrowing). Note: 'X' is character number 88, so it becomes 88.0.سێ ڕیز. char 'X' بە خۆکاری دەبێتە doubleـی 88.0 و بە (char) دەگەڕێتەوە بۆ 'X'. byte 120 دەبێتە 120.0 و بە (byte) دەگەڕێتەوە بۆ 120. short 2020 دەبێتە 2020.0 و بە (short) دەگەڕێتەوە بۆ 2020. تیرە سەوزەکان: خۆکار (فراوانکردنی جۆر)؛ تیرە تۆخەکان: (type) (تەسککردنەوەی جۆر). تێبینی: ژمارەی نووسەی 'X' دەکاتە 88، بۆیە دەبێتە 88.0.
To double by itself, back with a castبە خۆکاری بۆ double، بە (type) گەڕانەوەCêIT
ExerciseڕاهێنانLab: change three types to double and backتاقیگە: سێ جۆر بگۆڕە بۆ double و بیانگەڕێنەوە

Store char let1 = 'X', byte num = 120 and short year = 2020. Print them, convert each one to double and print again, then convert them back to their original types and print them once more.

char let1 = 'X'، byte num = 120 و short year = 2020 هەڵبگرە. چاپیان بکە، هەریەکەیان بگۆڕە بۆ double و دووپاتە چاپیان بکە، پاشان بیانگەڕێنەوە بۆ جۆرە سەرەکییەکانیان و جارێکی تر چاپیان بکە.

Hintئاماژە

Widening needs nothing; for the way back write the type in brackets.

هیچی ناوێت؛ بۆ گەڕانەوە جۆرەکە لە ناو کەوانەدا بنووسە.

Show answerوەڵامەکە پیشان بدە
Task4.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Task4 {
    public static void main(String[] args) {
        char let1 = 'X';
        byte num = 120;
        short year = 2020;
        System.out.println("******* Task 4 *******");
        System.out.println("all values before type casting:");
        System.out.println(let1 + "\t" + num + "\t" + year);

        double d1 = let1;      // widening: automatic
        double d2 = num;
        double d3 = year;
        System.out.println("all values after type casting:");
        System.out.println(d1 + "\t" + d2 + "\t" + d3);

        char back1 = (char) d1;     // narrowing: a cast is needed
        byte back2 = (byte) d2;
        short back3 = (short) d3;
        System.out.println("reversing back all values to the original data type:");
        System.out.println(back1 + "\t" + back2 + "\t" + back3);
    }
}

The way to double is widening, so no cast is written; the way back is narrowing and needs (char), (byte) and (short). 'X' prints as 88.0 because a double holds its character number. \t is a tab, which lines the values up.

ڕێگای چوون بۆ double ، بۆیە هیچ (type)ـێک نانووسرێت؛ ڕێگای گەڕانەوە و (char)، (byte) و (short)ـی دەوێت. 'X' وەک ⁦88.0⁩ چاپ دەکرێت چونکە double هەڵدەگرێت. \t تابێکە کە ڕیز دەکات.

Where the cast goes: a percentageشوێنی (double): ڕێژەی سەدی

Casts matter in real calculations. Shilan came to 18 of 24 lessons: what percentage is that? Both counts are int, so the place of (double) decides the answer:

لە ژماردنی ڕاستەقینەدا گرنگە. شیلان لە ⁦18⁩ وانە لە کۆی ⁦24⁩ وانە ئامادە بوو: ئەمە چەند لە سەدە؟ هەردوو ژمارەکە intـن، بۆیە شوێنی (double) وەڵامەکە دیاری دەکات:

Attendance.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Attendance {
    public static void main(String[] args) {
        int attended = 18;      // Shilan came to 18 of 24 lessons
        int lessons = 24;
        System.out.println(attended / lessons * 100);
        System.out.println((double) (attended / lessons) * 100);
        System.out.println((double) attended / lessons * 100);
    }
}
A row of 24 squares with 18 filled: 18 / 24. Three rows of code. attended / lessons * 100 becomes 0 * 100, then 0: int / int gives 0 first, cross. (double) (attended / lessons) * 100 becomes (double) 0 * 100, then 0.0: the cast comes too late, cross. (double) attended / lessons * 100 becomes 18.0 / 24 * 100, then 75.0: cast first, tick.ڕیزێکی 24 چوارگۆشە کە 18یان پڕە: 18 / 24. سێ ڕیز کۆد. attended / lessons * 100 دەبێتە 0 * 100، پاشان 0: int / int سەرەتا 0 دەدات، هەڵەیە. (double) (attended / lessons) * 100 دەبێتە (double) 0 * 100، پاشان 0.0: (double) زۆر درەنگ هات، هەڵەیە. (double) attended / lessons * 100 دەبێتە 18.0 / 24 * 100، پاشان 75.0: سەرەتا (double)، دروستە.
Cast before you divideپێش دابەشکردن جۆرەکە بگۆڕەCêIT

A cast belongs to the value right after it and is done before *, / and % (precedence). (double) attended makes 18.0 first, so the division is real division. (double) (attended / lessons) is too late: 18 / 24 is already 0 (integer division).

(double) هی ئەو کە ڕاستەوخۆ دوای دێت و پێش *، / و % ئەنجام دەدرێت (پێشینەیی کارپێکەرەکان). (double) attended سەرەتا ⁦18.0⁩ دروست دەکات، بۆیە دابەشکردنەکە دابەشکردنی ڕاستەقینەیە. (double) (attended / lessons) زۆر درەنگە: 18 / 24 پێشتر بووە 0 (دابەشکردنی ژمارەی تەواو).

Common mistakesهەڵە باوەکان

You wroteنووسیتJava saysJava دەڵێتFixچارەسەر
int n = 9.78;incompatible types: possible lossy conversion from double to intWrite (int) 9.78 if cutting off is what you want, or keep a double.ئەگەر بڕینت دەوێت (int) 9.78 بنووسە، یان double بهێڵەرەوە.
(int) 9.78 and expecting 10(int) 9.78 و چاوەڕوانی ⁦10⁩(no message: 9)(هیچ پەیامێک: ⁦9⁩)Math.round(9.78) gives 10.Math.round(9.78) دەدات ⁦10⁩.
char c = s; // s is a shortpossible lossy conversion from short to charshort ↔ char always needs a cast: (char) s.short ↔ char هەمیشە (type)ـی دەوێت: (char) s.
(double) (a / b)(no message: the fraction is already gone)(هیچ پەیامێک: پێشتر ڕۆیشتووە)Cast an operand: (double) a / b.جۆری بگۆڕە: (double) a / b.
(byte) 200 and expecting 200(byte) 200 و چاوەڕوانی ⁦200⁩(no message: -56)(هیچ پەیامێک: -56)Use a type that fits, such as int.جۆرێک بەکار بهێنە کە جێی ببێتەوە، وەک int.
int n = (int) passed; // booleanincompatible types: boolean cannot be converted to intA boolean is never a number; decide with an if statement.boolean هەرگیز ژمارە نییە؛ بە ڕستەی if بڕیار بدە.
int n = (int) "42";incompatible types: String cannot be converted to intA cast cannot read text: Integer.parseInt("42") gives 42 (Numbers and text).(int) ناتوانێت دەق بخوێنێتەوە: Integer.parseInt("42") دەدات ⁦42⁩ (ژمارە و دەق).

Practiceڕاهێنان

ExerciseڕاهێنانPredict the outputپێشبینیی دەرخستە بکە

What does each line print? (int) 7.9 · (int) -7.9 · (byte) 130 · (char) 75 · Math.round(7.5) · (double) 7 / 2 · (double) (7 / 2)

هەر دێڕێک چی چاپ دەکات؟ (int) 7.9 · (int) -7.9 · (byte) 130 · (char) 75 · Math.round(7.5) · (double) 7 / 2 · (double) (7 / 2)

Show answerوەڵامەکە پیشان بدە
Predict.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Predict {
    public static void main(String[] args) {
        System.out.println((int) 7.9);
        System.out.println((int) -7.9);
        System.out.println((byte) 130);
        System.out.println((char) 75);
        System.out.println(Math.round(7.5));
        System.out.println((double) 7 / 2);
        System.out.println((double) (7 / 2));
    }
}

Casts cut toward zero (7, -7); 130 wraps round to 130 - 256 = -126; character 75 is K; Math.round sends 7.5 up to 8; (double) 7 / 2 is real division, 3.5; in (double) (7 / 2) the integer division comes first: 3.0.

بەرەو سفر دەبڕێت (7، -7)؛ ⁦130⁩ دەسوڕێتەوە بۆ 130 - 256 = -126؛ ژمارە ⁦75⁩ پیتی Kـە؛ Math.round ⁦7.5⁩ دەبات بۆ 8؛ (double) 7 / 2 دابەشکردنی ڕاستەقینەیە، ⁦3.5⁩؛ لە (double) (7 / 2)ـدا یەکەم دێت: ⁦3.0⁩.

ExerciseڕاهێنانFix the programبەرنامەکە چاک بکە

This program does not compile. Read the message, then fix it in two different ways.

ئەم کۆمپایل نابێت. بخوێنەرەوە، پاشان بە دوو ڕێگای جیاواز چاکی بکە.

Total.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Total {
    public static void main(String[] args) {
        int total = 7.5 * 2;
        System.out.println(total);
    }
}
Show answerوەڵامەکە پیشان بدە
Total.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Total {
    public static void main(String[] args) {
        double total = 7.5 * 2;          // keep the fraction
        int whole = (int) (7.5 * 2);     // or cut it off on purpose
        System.out.println(total);
        System.out.println(whole);
    }
}

7.5 * 2 is a double (15.0), and javac will not put it into an int by itself. Keep it as a double, or cast on purpose with (int).

7.5 * 2 جۆری doubleـە ⁦(15.0)⁩ و javac خۆی نایخاتە ناو int. وەک double بیهێڵەرەوە، یان بە ئەنقەست (int) بنووسە.

ExerciseڕاهێنانAn average markنمرەی تێکڕا

Hana's two marks add up to 15. Store int sum = 15; and int count = 2; and print the average as 7.5, not 7.

کۆی دوو نمرەی هانا ⁦15⁩ـە. int sum = 15; و int count = 2; هەڵبگرە و تێکڕاکە وەک ⁦7.5⁩ چاپ بکە، نەک 7.

Show answerوەڵامەکە پیشان بدە
Average.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Average {
    public static void main(String[] args) {
        int sum = 15;           // two marks: 7 and 8
        int count = 2;
        double average = (double) sum / count;
        System.out.println(average);
    }
}

(double) sum turns 15 into 15.0 before the division.

(double) sum پێش دابەشکردن ⁦15⁩ دەکات بە ⁦15.0⁩.

ExerciseڕاهێنانWrap roundسووڕانەوە

Without running it, say what (byte) 300 and (byte) -129 print. Then check with Java.

بەبێ جێبەجێکردن بڵێ (byte) 300 و (byte) -129 چی چاپ دەکەن. پاشان بە Java بیپشکنە.

Show answerوەڵامەکە پیشان بدە
Wrap300.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Wrap300 {
    public static void main(String[] args) {
        System.out.println((byte) 300);
        System.out.println((byte) -129);
    }
}

A byte has 256 values, so add or subtract 256 until the number is in -128 … 127: 300 - 256 = 44 and -129 + 256 = 127.

⁦byte 256⁩ هەیە، بۆیە ⁦256⁩ زیاد یان کەم بکە تا ژمارەکە بکەوێتە نێوان -128 و 127: 300 - 256 = 44 و -129 + 256 = 127.

Summaryکورتە

  • Widening (smaller to bigger type) is automatic: byte → short → int → long → float → double, and char → int. int to float, long to float and long to double may lose digits.
  • Narrowing (bigger to smaller) needs a cast, the type in brackets: (int) 9.78. short ↔ char always needs one.
  • A cast to a whole-number type cuts the fraction off, toward zero; Math.round rounds.
  • A value that does not fit wraps round ((byte) 200 is -56) or, from a double, stops at the largest int.
  • A cast applies to the value right after it: (double) a / b, not (double) (a / b).
  • (جۆری بچووک بۆ گەورە) خۆکارە: byte → short → int → long → float → double و char → int. int بۆ float، long بۆ float و long بۆ double لەوانەیە لەدەست بدەن.
  • (گەورە بۆ بچووک) جۆرەکەی لە ناو کەوانەدا دەوێت: (int) 9.78. short ↔ char هەمیشە پێویستی پێیەتی.
  • گۆڕین بۆ جۆرێکی دەبڕێتەوە، بەرەو سفر؛ Math.round نزیک دەکاتەوە.
  • کە جێی نەبێتەوە دەسوڕێتەوە ((byte) 200 دەبێتە -56)، یان لە doubleـەوە لە گەورەترین intـدا دەوەستێت.
  • (double) لەسەر ئەو کە ڕاستەوخۆ دوای دێت: (double) a / b، نەک (double) (a / b).
Review questionsپرسیارەکانی پێداچوونەوە
Why does double d = 9; compile but int i = 9.5; does not?بۆچی double d = 9; کۆمپایل دەبێت بەڵام int i = 9.5; نا؟

int → double is widening and always fits. double → int is narrowing and could lose the .5, so javac wants a cast.

int بۆ double و هەمیشە جێی دەبێتەوە. double بۆ int و لەوانەیە ⁦0.5⁩ لەدەست بدات، بۆیە javac (int)ـی دەوێت.

What is the difference between (int) 2.9 and Math.round(2.9)?جیاوازیی نێوان (int) 2.9 و Math.round(2.9) چییە؟

The cast cuts off the fraction and gives 2; Math.round gives the nearest whole number, 3 (as a long).

(int) دەبڕێتەوە و 2 دەدات؛ Math.round نزیکترین دەدات، 3 (وەک long).

Why is (byte) 200 equal to -56?بۆچی (byte) 200 یەکسانە بە -56؟

A byte keeps only the last 8 bits, 11001000. With the sign bit set, that pattern means 200 - 256 = -56.

byte تەنیا دوایین 8 دەهێڵێتەوە، ⁦11001000⁩. کاتێک 1ـە، ئەو شێوەیە واتە 200 - 256 = -56.

Lesson complete!وانەکە تەواو بوو!

Well done. Review the key terms, then go on to the next lesson.دەستخۆش. سەیرێکی زاراوە سەرەکییەکان بکەرەوە، پاشان بڕۆ بۆ وانەی داهاتوو.

Key termsزاراوە سەرەکییەکان

Next lessonوانەی داهاتوو

Arithmetic, Increment and Assignment Operatorsکارپێکەرە ژمێرەییەکان و کارپێکەرەکانی دانانی نرخ، ++ و --

References and further readingسەرچاوەکان و خوێندنەوەی زیاتر

This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.

Appearanceڕووکار

Modeدۆخ
Styleشێواز
Coloursڕەنگەکان

Saved on this device only.تەنیا لەسەر ئەم ئامێرە پاشەکەوت دەکرێت.