Type Casting In Java

Tanggal : 15 Feb 2023, Category : Pemprograman Website, Create By : admin

Type casting in Java is the process of converting a variable of one data type into another data type. There are two types of type casting in Java: implicit casting (also known as widening) and explicit casting (also known as narrowing).

Implicit Casting:

Implicit casting occurs when a value of a smaller data type is assigned to a variable of a larger data type. This is because the larger data type can hold all possible values of the smaller data type. For example:

int x = 5;
double y = x; // Implicit casting from int to double
System.out.println(y); // Output: 5.0

In this code, the value of x (an int) is implicitly cast to a double when it is assigned to y. This is possible because a double can hold all possible values of an int.

Explicit Casting:

Explicit casting is the process of converting a variable of a larger data type into a variable of a smaller data type. This is done by using the cast operator (datatype), where datatype is the target data type. For example:

double x = 3.14;
int y = (int) x; // Explicit casting from double to int
System.out.println(y); // Output: 3

In this code, the value of x (a double) is explicitly cast to an int using the cast operator. The fractional part of x is truncated when it is cast to an int.

It is important to note that explicit casting can result in loss of data or precision, as in the example above where the fractional part of x is truncated when it is cast to an int.

Type casting is often used when working with different data types in Java, for example when performing arithmetic operations with operands of different data types, or when passing data between different parts of a program. It is important to use type casting carefully and make sure to handle any potential loss of data or precision that may occur.


Keyword:
  • Type Casting In Java

Artikel Lain

Konstanta Php

Date : 08 Oct 2018, Category : Tutorial, Create By : admin

Konstanta dalam php adalah sebuah lokasi penyimpanan ayng berisikan nilai, akan tetapi nilai dari isi kontanta itu tidak bisa di rubah selama program berjalan, sebenarnya hanpir mirip dengan variable hanya .....

Beberapa Hal Yang Harus Anda Siapkan Jika Ingin Menjadi Programmer

Date : 03 Sep 2018, Category : Pemprograman Website, Create By : admin

Pada zaman sekarang banyak sekali perguruan tinggi yang sudah membuka jurusan atau ilmu mengenai komputer dari mulai pengembangan hardware dan software, Tak heran jika kalian kuliah di jurusan berkaitan dengan .....

Pengertian Dan Fungsi Css Dalam Pembuatan Website

Date : 15 Aug 2018, Category : Pemprograman Website, Create By : admin

CSS adalah singkatan dari Cascading Style Sheet atau di terjemahkan di google translate menjadi Lembar bergaya susun. Yaitu sebuah perintah atau intruksi yang dapat digunakan untuk menampilkan text dengan design yang menarik untuk sebuah .....