0% found this document useful (0 votes)
7 views

Data Types

Uploaded by

raviraje104
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Data Types

Uploaded by

raviraje104
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

DATA TYPES AND CASTING IN JAVA

 DATA TYPES :
There are two main categories of data types:
1. Primitive data types.
2. Non-Primitive data types.

1. Primitive Data Types:


These are predefined by Java, and include the following:

- byte: 8-bit integer, range from -128 to 127.


- short: 16-bit integer, range from -32,768 to 32,767.
- int: 32-bit integer, range from -2^31 to 2^31-1.
- long: 64-bit integer, range from -2^63 to 2^63-1.
- float: Single-precision 32-bit IEEE 754 floating-point.
- double: Double-precision 64-bit IEEE 754 floating-point.
- char: A single 16-bit Unicode character.
- boolean: Represents true or false values.

2.Non-Primitive Data Types :

These are defined by the programmer, and include:-

- Strings

- Arrays

- Classes

- Interfaces

- Enumerations

Primitive data types are more efficient for basic data operations,
while non-primitive types are objects, offering more flexibility and
methods.
DATA TYPES AND CASTING IN JAVA
CASTING
Typecasting in Java is the process of converting one data type into another. It
can be classified into two types.

Types of Casting :
Type casting is when you assign a value of one primitive data type to another type.

In Java, there are two types of casting:

 Widening Casting (automatically) - converting a smaller type to a larger type size


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

 Narrowing Casting (manually) - converting a larger type to a smaller size type


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

Widening Casting :
Widening casting is done automatically when passing a smaller size type to a
larger size type:

Example -
public class Main {

public static void main(String[] args) {

int myInt = 9;

double myDouble = myInt; // Automatic casting: int to


double

System.out.println(myInt); // Outputs 9

System.out.println(myDouble); // Outputs 9.0

}
DATA TYPES AND CASTING IN JAVA

Narrowing Casting :
Narrowing casting must be done manually by placing the type in
parentheses () in front of the value:

Example -
public class Main {

public static void main(String[] args) {

double myDouble = 9.78d;

int myInt = (int) myDouble; // Manual casting: double to


int

System.out.println(myDouble); // Outputs 9.78

System.out.println(myInt); // Outputs 9

You might also like