0% found this document useful (0 votes)
3 views35 pages

Understanding Java Data Types

The document provides an overview of data and data types in Java, defining data as raw facts that can be processed by a computer. It categorizes data types into primitive (e.g., byte, int, float) and non-primitive (e.g., String, Arrays) types, detailing their characteristics and uses. Additionally, it explains literals as fixed values directly written in code, with examples of different types of literals in Java.

Uploaded by

sanketh.s577425
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views35 pages

Understanding Java Data Types

The document provides an overview of data and data types in Java, defining data as raw facts that can be processed by a computer. It categorizes data types into primitive (e.g., byte, int, float) and non-primitive (e.g., String, Arrays) types, detailing their characteristics and uses. Additionally, it explains literals as fixed values directly written in code, with examples of different types of literals in Java.

Uploaded by

sanketh.s577425
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

MODULE-1[CHAPTER-2]

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
What is Data?

 Data refers to raw facts, figures, or values that can


be processed or stored in a computer.
 It could be numbers, text, images, audio, video, or
any kind of information.
 Example:
 25, "Hello", 3.14, A, True, etc. are all data.
 In programming, data is what we input, process, and
output.

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIRMVIT


Data Types

 Data types represent the different values to be stored in


the variable. In java, there are two types of data types:
1. Primitive data types
2. Non-primitive data types

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIRMVIT


PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIRMVIT
1. Primitive Data Types:

 Definition: These are the most basic and fundamental data


types in Java, pre-defined by the language itself.
 They directly store the actual value of the data in memory.
 Examples: byte, short, int, long, float, double, char, boolean.
 Characteristics:
 Have a fixed size and range of values.
 Stored directly on the stack memory.
 Cannot be null.
 They always hold a value.
 Do not have associated methods.

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIRMVIT


2. Non-Primitive (Reference) Data Types:

 Definition: These are more complex data types that are not pre-
defined but are created by the programmer or are built-in classes.
 Instead of storing the actual data, they store a reference (memory
address) to an object that holds the data in the heap memory.
 Examples: String, Arrays, Classes, Interfaces, Enums.

 Characteristics:
 Their size is not fixed and can vary depending on the data they contain.
 Stored on the heap memory, with a reference to them stored on the
stack.//Heap memory is a region of a computer’s memory used for
dynamic memory [Link] is managed at runtime (when the program
is running), not at compile time.//
 Can be null, meaning they don't refer to any object.
 Can have methods and attributes, allowing for more complex operations.

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIRMVIT


1. The Primitive Types
 Java defines eight primitive (or simple) data types viz.
 byte, short, int, long : belonging to Integers group involving whole-valued signed numbers.
 char : belonging to Character group representing symbols in character set like alphabets,
digits, special characters etc.
 float, double : belonging to Floating-point group involving numbers with fractional part.
 boolean : belonging to Boolean group, a special way to represent true/false values.
 These types can be used as primitive types, derived types (arrays) and as member of user-
defined types (classes).
 All these types have specific range of values irrespective of the platform in which the
program being run.
 In C and C++ the size of integer may vary (2 bytes or 4 bytes) based on the platform.
Because of platform-independent
 nature of Java, such variation in size of data types is not found in Java, and thus making a
Java program to perform better.

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIRMVIT


 Integers:
 Java defines four integer types .byte, short, int and long. All these are signed
numbers(can store both negative & positive number) and Java does not support
unsigned numbers(can store only positive numbers).
 The width of an integer type should not be thought of as the amount of storage it
consumes, but rather as the behaviour.
 it defines for variables and expressions of that type.
 The Java runtime environment is free to use whatever size it wants, as long as the
types behave as you declared them.
 The width and ranges of these integer types vary widely, as shown in this table:
+--------+----------------+-------------------------------+
| Name | Width (in bits)| Range |
+--------+----------------+-------------------------------+
| long | 64 | -2⁶³ to +2⁶³–1 |
| int | 32 | -2³¹ to +2³¹–1 |
| short | 16 | -2¹⁵ to +2¹⁵–1 (-32768 to 32767) |
| byte | 8 | -2⁷ to +2⁷–1 (-128 to 127) |
+--------+----------------+-------------------------------+

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIRMVIT


 byte : This is the smallest integer type.
 Variables of type byte are especially useful when you are working with a stream of data from a network or file.
They are also useful when you are working with raw binary data that may not be directly compatible with
Java’s other built-in types.
 Byte variables are declared by use of the byte keyword. For example,
byte b, c;
 short : It is probably the least-used Java type. Here are some examples of short variable declarations: short
s;
short t;
 int : The most commonly used integer type is int. In addition to other uses, variables of type int are
commonly employed to control loops and to index arrays. Although you might think that using a byte or short
would be more efficient than using an int in situations in which the larger range of an int is not needed, this
may not be the case.
 The reason is that when byte and short values are used in an expression they are promoted to int when the
expression is evaluated. (Type promotionis described later in this chapter.) Therefore, int is often the best
choice when an integer is needed.

 long : It is useful for those occasions where an int type is not large enough to hold the desired value. The
range of a long is quite large. This makes it useful when big, whole numbers are needed.

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIRMVIT


Program to illustrate need for long data type
class Light
{
public static void main(String args[ ])
{
int lightspeed;
long days, seconds, distance; In 1000 days light will travel about
16070400000000 miles.
// approximate speed of light in miles per second
lightspeed = 186000;
days = 1000; // specify number of days here
seconds = days * 24 * 60 * 60; // convert to seconds
distance = lightspeed * seconds; // compute distance
[Link]("In " + days);
[Link](" days light will travel about ");
[Link](distance + " miles.");
}
}

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIRMVIT


Floating –Point Types
 Floating-point (or real) numbers are used when evaluating expressions that require fractional
precision. Java implements the standard (IEEE–754) set of floating-point types and operators.
 There are two kinds of floating-point types, float and double, which represent single- and
double-precision numbers, respectively. Their width and ranges are shown here:

 float : The type float specifies a single-precision value that uses 32 bits of storage.
 Single precision is faster on some processors and takes half as much space as double
precision, but will become imprecise when the values are either very large or very small.
 Variables of type float are useful when you need a fractional component, but don’t require a
large degree of precision.
 For example, float can be useful when representing currencies, temperature etc. Here are
some example float variable declarations:float hightemp, lowtemp;

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIRMVIT


 double : Double precision is actually faster than single precision on some modern processors that
have been optimized for high-speed mathematical calculations.
 All transcendental math functions, such as sin( ), cos( ), and sqrt( ), return double values.
 When you need to maintain accuracy over many iterative calculations, or are manipulating large-valued
numbers, double is the best choice.
WAP Finding area of a cirlce
class Area
{
public static void main(String args[])
{ Area of circle is 366.436224
double pi, r, a;
r = 10.8;
pi = 3.1416;
a = pi * r * r;
[Link]("Area of circle is " + a);
}
}

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIRMVIT


Characters
 In Java, char is the data type used to store characters.
 In C or C++, char is of 8 bits, whereas in Java it requires 16 bits.
 Java uses Unicode to represent characters. Unicode is a computing industry standard for the
consistent encoding, representation and handling of text expressed in many languages of the world.
 Unicode has a collection of more than 109,000 characters covering 93 different languages like Latin,
Greek, Arabic, Hebrew etc. That is why, it requires 16 bits. The range of a char is 0 to 65,536.
 The standard set of characters known as ASCII still ranges from 0 to 127 as always, and the extended
8-bit character set, ISOLatin-1, ranges from 0 to 255. Since Java is designed to allow programs to be
written for worldwide use, it makes sense that it would use Unicode to represent characters. Though
it seems to be wastage of memory as the languages like English, German etc.
 can accommodate their character set in 8 bits, for a global usage point of view, 16-bits are necessary.
 Though, char is designed to store Unicode characters, we can perform arithmetic operations on them.
 For example, we can add two characters (but, not char variables!!), increment/decrement character
variable etc.
 Consider the following example for the demonstration of characters.

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIRMVIT


Demonstration of char data type
class CharDemo {
public static void main(String args[]) {
char ch1 = 88, ch2 = 'Y'; // 88 is ASCII for 'X'
[Link]("ch1 and ch2: ");
[Link](ch1 + " " + ch2);
ch1++; // increment in ASCII (or Unicode) value
[Link]("ch1 now contains " + ch1);
--ch2; // decrement in ASCII (or Unicode) value ch1 and ch2: X Y
[Link]("ch2 now contains " + ch2);
ch1 now contains Y
ch2 now contains X
/*
ch2 now contains w
ch1 = 35;
ch2 = 30;
char ch3;
ch3 = ch1 + ch2; // Error: result is int, not char
*/
ch2 = (char) ('6' + 'A'); // valid, result needs cast to char //6->54 A->65 SUM=119
[Link]("ch2 now contains " + ch2);
}
}

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIRMVIT


Booleans
 For storing logical values (true and false),
 Java provides this primitive data type.
 Boolean is the output of any expression involving
relational operators.
 For control structures (like if, for, while etc.)
 we need to give boolean type. In C or C++, false and true
values are indicated by zero and a non-zero numbers
respectively.
 And the output of relational operators will be 0 or 1.
 But, in Java, this is not the case. Consider the following
program as an illustration.

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIRMVIT


Demonstration of Boolean data type
class BoolDemo
{
public static void main(String args[])
{
boolean b = false; b is false
[Link]("b is " + b); b is true
b = true; True block
[Link]("b is " + b); 3<5 is true
if(b)
[Link]("True block");
b = false;
if(b)
[Link]("False Block will not be executed");
b=(3<5);
[Link]("3<5 is " +b);
} NOTE: Size of a Boolean data type is JVM dependent. But, when Boolean
} variable appears in an expression, Java uses 32-bit space (as int) for
Boolean to evaluate expression.
PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIRMVIT
literal
 A literal is a fixed value that you directly write in your code, not stored in a variable, not the
result of a computation — just the constant value itself.
 A literal = the constant value written in the source code.
 Variables can store literals, but the literal itself is the actual value.
 Integer literals

 int x = 10; // here 10 is a literal


 int y = 0x1F; // here 0x1F (hex 31) is a literal

 Floating-point literals
 double pi = 3.14159; // 3.14159 is a literal

 Character literals
 char c = 'A'; // 'A' is a literal

 String literals
 String s = "Hello"; // "Hello" is a literal

 Boolean literals
 boolean flag = true; // true is a literal
A Closer Look at Literals
 A literal is the source code representation of a fixed value. In other words, by literal we mean any number, text, or
other information that represents a value.
 Literals are represented directly in our code without requiring computation. Here we will discuss Java literals in
detail.
 Integer Literals :::
 Integers are the most commonly used type in the typical program.
 Any whole number value is an integer literal. For example, 1, 25, 33 etc. These are all decimal values, having a base
10.
 With integer literals we can use octal (base 8) and hexadecimal (base 16) also. Octal values are denoted in Java by a
leading zero.
 Normal decimal numbers cannot have a leading zero. Thus, a value 09 will produce an error from the compiler, since 9
is outside of octal’s 0 to 7 range.
 Hexadecimal constants denoted with a leading zero-x, (0x or 0X). The range of a hexadecimal digit is 0 to 15, so A
through F (or a through f ) are substituted for 10 through 15.
 Integer literals create an int value, which in Java is a 32-bit integer value.
 It is possible to assign an integer literal to other integer types like byte or long. When a literal value is assigned to a
byte or short variable, no error is generated if the literal value is within the range of the target type.
 An integer literal can always be assigned to a long variable. However, to specify a long literal, you will need to
explicitly tell the compiler that the literal value is of type long. You do this by appending an upper- or lowercase L to
the literal.
 For example, 0x7ffffffffffffffL or 9223372036854775807L is the largest long. An integer can also be assigned to a char
as long as it is within range.

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIRMVIT


Floating-Point Literals
 Floating-point numbers represent decimal values with a fractional component.
 They can be expressed in either standard or scientific notation.
 Standard notation consists of a whole number component followed by a decimal point followed by
a fractional component.
 For example, 2.0, 3.14159, and 0.6667 represent valid standard-notation floating-point numbers.
Scientific notation uses a standard-notation, floating-point number plus a suffix that specifies a
power of 10 by which the number is to be multiplied.
 The exponent is indicated by an E or e followed by a decimal number, which can be positive or
negative.
 Examples include 6.022E23, 314159E–05, and 2e+100.
 Floating-point literals in Java default to double precision.
 To specify a float literal, you must append an F or f to the constant.
 You can also explicitly specify a double literal by appending a D or d. Doing so is, of course,
redundant. The default double type consumes 64 bits of storage, while the less-accurate float
type requires only 32 bits.

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIRMVIT


 Boolean Literals
 Boolean literals are simple. There are only two logical values that a boolean value can have, true
and false.
 The values of true and false do not convert into any numerical representation.
 The true literal in Java does not equal 1, nor does the false literal equal 0. In Java, they can only
be assigned to variables declared as boolean, or used in expressions with Boolean operators.
 Character Literals
 Characters in Java are indices into the Unicode character set.
 They are 16-bit values that can be converted into integers and manipulated with the integer
operators, such as the addition and subtraction operators.
 A literal character is represented inside a pair of single quotes.
 All of the visible ASCII characters can be directly entered inside the quotes, such as ‘a’, ‘z’, and
‘@’. For characters that are impossible to enter directly, there are several escape sequences that
allow you to enter the character you need, such as ‘\’’ for the single-quote character itself and
‘\n’ for the new-line character.
 There is also a mechanism for directly entering the value of a character in octal or hexadecimal.
For octal notation, use the backslash followed by the three-digit number.
 For example, ‘\141’ is the letter ‘a’. For hexadecimal, you enter a backslash-u (\u), then exactly
four hexadecimal digits. Following table shows the character escape sequences.

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIRMVIT


PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIRMVIT
String Literals
 String literals are a sequence of characters enclosed within a pair of double quotes.
 Examples of string literals are

“Hello World”
“two\nlines”
“\“This is in quotes\””

 Java strings must begin and end on the same line.


 There is no line-continuation escape sequence as there is in some other languages.
 In Java, strings are actually objects and are discussed later in detail.

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIRMVIT


Variables
 The variable is the basic unit of storage. A variable is defined by the combination of an identifier, a type, and an
optional initializer.
 In addition, all variables have a scope, which defines their visibility, and a lifetime.
 Declaring a Variable
 In Java, all variables must be declared before they can be used.
 The basic form of a variable declaration is shown here:
type identifier [ = value][, identifier [= value] ...] ;
 The type is any of primitive data type or class or interface.
 The identifier is the name of the variable.
 We can initialize the variable at the time of variable declaration.
 To declare more than one variable of the specified type, use a comma-separated list. Here are several examples of
variable declarations of various types.
 Note that some include an initialization.
int a, b=5, c; byte z =
22; double pi = 3.1416;
char x = '$';

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIRMVIT


Dynamic Initialization
 Although the preceding examples have used only constants as initializers, Java
allows variables to be initialized dynamically, using any expression valid at the
time the variable is declared.
 For example,

int a=5, b=4;


Int c=a*2+b; //variable declaration & dynamic
initialization

 The key point here is that the initialization expression may use any element valid
at the time of the initialization including calls to methods,othere variables or
literals.

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIRMVIT


The Scope and Lifetime of Variables
 A variable in Java can be declared within a block. A block is begin with an opening curly brace
and ended by a closing curly brace.
 A block defines a scope which determines the accessibility of variables and/or objects defined
within it.
 It also determines the lifetime of those objects.
 Many languages like C/C++ have two scopes . global and local.
 But in Java, every line of code should be embedded within a class. That is, no code is written
outside the class. So, usage of the terms global and local makes no sense.
 Instead, Java has two scopes . class level scope and method (or function) level scope. Class level
scope is discussed later and we will discuss method scope here.
 The scope defined by a method begins with its opening curly brace. However, if that method has
parameters, they too are included within the method’s scope.
 As a general rule, variables declared inside a scope are not visible (that is, accessible) to code
that is defined outside that scope. Thus, when you declare a variable within a scope, you are
localizing that variable and protecting it from unauthorized access and/or modification.
 Indeed, the scope rules provide the foundation for encapsulation. Scopes can be nested.

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIRMVIT


 For example, each time you create a block of code, you are creating a new, nested scope.
 When this occurs, the outer scope encloses the inner scope.
 This means that objects declared in the outer scope will be visible to code within the inner
scope.
 However, the reverse is not true. Objects declared within the inner scope will not be visible
outside it.
 Variables are created when their scope is entered, and destroyed when their scope is left.
 This means that a variable will not hold its value once it has gone out of scope.
 Therefore, variables declared within a method will not hold their values between calls to
that method. Also, a variable declared within a block will lose its value when the block is
left.
 Thus, the lifetime of a variable is confined to its scope.

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIRMVIT


Demonstration of scope of variables
class Scope
{
public static void main(String args[])
{
int x=10, i; // x and i are local to main() x and y: 10
if(x == 10) 20
{ x is 40
int y = 20; // y is local to this block a is 3
[Link]("x and y: " + x + " " + y);
a is 3
x = y * 2;
a is 3
}
// y = 100; // y cannot be accessed here
[Link]("x is " + x);
for(i=0;i<3;i++)
{
int a=3; // a is local to this block 1st iteration → a=3 → prints 3 → then a++ makes it 4 → but loop ends,
[Link]("a is " + a); variable destroyed.
a++;
} 2nd iteration → new a=3 created again → prints 3.
}
} 3rd iteration → new a=3 created again → prints 3.

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIRMVIT


 Note that, variable a is declared within the scope of for loop.
 Hence, each time the loop gets executed, variable a is created newly and there is no effect of a++ for next
iteration.
 NOTE:
 In Java, same variable name cannot be used in nested scopes.
 That is, the following code snippet generates error.
class Test
{
public static void main(String args[])
{
int x=3;
{
}
}
}
int x=5;
//error!! (Note that, having same variable name in nested scopes is VALID in C/C++).

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIRMVIT


Type Conversion and Casting
 It is quite common in a program to assign value of one type to a variable of
another type.
 If two types are compatible, Java performs implicit type conversion.
 For example, int to long is always possible. But, whenever the types at two
sides of an assignment operator are not compatible, then Java will not do
the conversion implicitly.
 For that, we need to go for explicit type conversion or type casting.
 Java’s Automatic Conversions
 When one type of data is assigned to another type of variable, an
automatic type conversion will take place if the following two conditions
are met:
1. The two types are compatible.
2. The destination type is larger than the source type.

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIRMVIT


 When these two conditions are met, a widening conversion takes
place.
 For example, the int type is always large enough to hold all valid
byte values, so no explicit cast statement is required.
 For widening conversions, the numeric types, including integer and
floating-point types, are compatible with each other.
 However, there are no automatic conversions from the numeric types
to char or boolean. Also, char and boolean are not compatible with
each other.
 As mentioned earlier, Java also performs an automatic type
conversion when storing a literal integer constant into variables of
type byte, short, long, or char.

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIRMVIT


Casting Incompatible Types
 if you want to assign an int value to a byte variable?
 This conversion will not be performed automatically, because a byte is smaller than an int.
 This kind of conversion is sometimes called a narrowing conversion, since you are explicitly making the value
narrower so that it will fit into the target type.
 To create a conversion between two incompatible types, we must use a cast. A cast is simply an explicit type
conversion.
 It has this general form:
(target-type) value
 Here, target-type specifies the desired type to convert the specified value to. For example,
int a;
byte b;
b = (byte) a;
 When a floating-point value is assigned to an integer type, the fractional component is lost.
 And such conversion is called as truncation (narrowing).
 If the size of the whole number component is too large to fit into the target integer type, then that value will
be reduced modulo the target type’s range. Following program illustrates various situations of explicit casting.

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIRMVIT


Illustration of type conversion
class Conversion
{
public static void main(String args[]) Conversion of int to byte.
{
i and b 257 1
byte b;
int i = 257;
Conversion of double to int.
double d = 323.142;
d and i 323.142 323
[Link]("\nConversion of int to byte.");
Conversion of double to byte.
b = (byte) i;
[Link]("i and b " + i + " " + b);
d and b 323.142 67

[Link]("\nConversion of double to int.");


i = (int) d;
[Link]("d and i " + d + " " + i);
257 → 1 because narrowing int to byte wraps around
(257 % 256 = 1).
[Link]("\nConversion of double to byte.");
323.142 → 323 because casting double to int truncates
b = (byte) d;
the decimal part.
[Link]("d and b " + d + " " + b);
323.142 → 67 because first 323.142 becomes 323, then
}
}
323 % 256 = 67.

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIRMVIT


Automatic Type promotion in Expression
 Apart from assignments, type conversion may happen in expressions also. In an arithmetic
expression involving more than one operator, some intermediate operation may exceed the size
of either of the operands. For example,
byte x=25, y=80, z=50;
int p= x*y/z ;
 Here, the result of operation x*y is 4000 and it exceeds the range of both the operands i.e. byte
(-128 to +127). In such a situation, Java promotes byte, short and char operands to int That is,
the operation x*y is performed using int but not byte and hence, the result 4000 is valid.
 On the other hand, the automatic type conversions may cause error. For example,
byte x=10;
byte y= x *3; //causes error!!!

 Here, the result of x *3 is 30, and is well within the range of byte. But, for performing this
operation, the operands are automatically converted to byte and the value 30 is treated as of int
type. Thus, assigning an int to byte is not possible, which generates an error. To avoid such
problems, we should use type casting.
That is,
byte x=10;
byte y=(byte) (x *3); //results 30

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIRMVIT


Type Promotion Rules

 Java defines several type promotion rules that apply


to expressions. They are as follows:
 All byte, short, and char values are promoted to int.
 If one operand is a long, the whole expression is
promoted to long.
 If one operand is a float, the entire expression is
promoted to float.
 If any of the operands is double, the result is double.

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIRMVIT


Demonstration of type promotions
class TypePromo
{
public static void main(String args[]) result = 626.7784146484375
{
byte b = 42; Let’s look closely at the type promotions that occur in this
char c = 'a'; line from the program: double result = (f * b) + (i / c) - (d *
short s = 1024; s); In the first sub-expression, f * b, b is promoted to a float
int i = 50000; and the result of the sub-expression is float. Next, in the
sub-expression i / c, c is promoted to int, and the result is of
float f = 5.67f;
type int. Then, in d * s, the value of s is promoted to double,
double d = .1234; and the type of the sub-expression is double. Finally, these
double result = (f * b) + (i / c) - (d * s); three intermediate values, float, int, and double, are
[Link]("result = " + result); considered. The outcome of float plus an int is a float. Then
the resultant float minus the last double is promoted to
}
double, which is the type for the final result of the
} expression.

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIRMVIT

You might also like