Type Casting In Java In Hindi

📔 : Java 🔗

Type Casting एक mechanism / process है जिसमे किसी एक data type की दी गयी value को दुसरे data type में convert करते हैं। इसे Type Conversion भी कहते हैं।


हम जानते हैं कि Java में कोई भी variable define करते समय उसका data type भी define करना पड़ता है, जिससे compiler को पता चल सके कि variable में store होने वाली value का क्या है, लेकिन फिर भी हमें कई जगह value को दूसरे data type में convert करने की जरूरत पड़ ही जाती है।

इस topic में हम देखेंगे कि किसी variable का data type कैसे change करें।


java में 2 type की casting define की गयी है -

  1. Implicit Type Casting (automatically) - जब smaller type से large data type में convert करते हैं तो उसे Implicit Type Casting या Widening Casting कहते हैं , यह automatically होती है।

    byte -> short -> char -> int -> long -> float -> double

  2. Explicit Type Casting (manually) - जब large type से small data type में convert करते हैं तो उसे Explicit Type Casting या Narrowing Casting कहते हैं, इसे manually हमें करना पड़ता है। हालाँकि इस process में value की information lost भी हो सकती है , क्योंकि large data type की range ज्यादा होती है और small data type की range कम होती है।

    double -> float -> long -> int -> char -> short -> byte

Java Implicit Type Casting

Implicit Type Casting में variable declare करते समय ही वो data type के value store करते हैं जिसमे हमें convert करना है। यह process automatically होती है। इसे Widening Type Casting भी कहते हैं।

File : ImplicitCasting.java

CopyFullscreenClose FullscreenRun
class ImplicitCasting
{
  public static void main(String[] args) 
  {
    int num = 20;
    // now convert it into double.
    double num_convert = num; // it will automatically cast int to double.

    System.out.println(num);
    System.out.println(num_convert);
  }
}
Output
javac ImplicitCasting.java
java ImplicitCasting
20
20.0

Java Explicit Type Casting

Explicit Type Casting हमें manually करनी पड़ती है , इसमें हमें convert करने वाले data type का नाम value से पहले लिखना पड़ता है , जैसा कि नीचे आप example में देख सकते हैं। इसे Narrowing Type Casting भी कहते हैं।

File : ExplicitCasting.java

CopyFullscreenClose FullscreenRun
class ExplicitCasting
{
  public static void main(String[] args) 
  {
    double num = 20.2342342f;
    // now convert it into int.
    int num_convert = (int) num;

    System.out.println(num);
    System.out.println(num_convert);
  }
}
Output
javac ExplicitCasting.java
java ExplicitCasting
20.234233856201172
20

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)

Get connected with me. :) LinkedIn Twitter Instagram Facebook

b2eprogrammers