How Data Types and Operators Work in Java?

How Data Types and Operators Work in Java?At the foundation of any programming language are its data types and operators, and Java is no exception.

These elements define the limits of a language and determine the kind of tasks to which it can be applied.

Fortunately, Java supports a rich assortment of both data types and operators, making it suitable for any type of programming.

DammnnBlockedUnblockFollowFollowingApr 10google.

com/imagesData types and operators are a large subject.

We will begin here with an examination of Java’s foundational data types and its most commonly used operator.

We will also take a closer look at variables and examine the expression.

Data types are especially important in Java because it is a strongly typed language.

This means that all operations are type checked by the compiler for type compatibility.

Illegal operations will not be compiled.

Thus, strong type checking helps prevent error and enhance reliability.

To enable strong type checking, all variables, expressions, and values have a type.

There is no concept of a type-less variable.

Furthermore, the type of value determines what operations are allowed on it.

An operation allowed on one type might not be allowed on another.

Java Primitive TypeJava contains two general categories of built-in data types: object-oriented and non-object oriented.

Java’s object-oriented types are defined by classes, and a discussion of classes is deferred until later.

However, at the core of Java are eight primitive types of data.

The term primitive is used here to indicate that these types are not objects in an object-oriented sense, but rather, normal binary values.

These primitive types are not objects because of efficiency concerns.

All of Java’s other data types are constructed from these primitive types.

Primitive data types:-booleanbytechardoublefloatintlongshortJava strictly specifies a range and behaviour for each primitive type, which all implementation of the Java Virtual Machine must support.

Because of Java’s portability requirement, Java is uncompromising on this account.

IntegersJava defines four integer types: byte, short, int and long, which are down here:byte 8 bitsshort 16 bitsint 32 bitslong 64 bitsAll of the integer types are signed positive and negative values.

Java does not support unsigned integers.

The most commonly used integer type is int.

Variable of type int it often employed to control loops, to index arrays, and to perform general purpose integer math.

When you need an integer that has a range greater than int, use long.

The smallest integer type is a byte.

Variables of type byte are especially useful when working with raw binary data that may not be directly compatible with Java’s other built-in types.

The short type creates a short integer.

Variables of type short are appropriate when you don’t need the larger range offered by int.

Floating-Point TypesThe floating-point types can represent numbers that have fractional components.

There are two kinds of floating-point types, float and double, which represent single and double precision numbers, respectively.

Type float is 32 bits wide and types double are 64 bits wide.

Of the two, double is the most commonly used because all of the math functions in Java’s class library use double values.

For example, the sqrt() method returns a double value that is the square root of its double argument.

sqrt() can be used to compute the length of the hypotenuse, given the length of the two opposite sides:import java.

math.

*;/** * This is made by saurav for damnn on medium * using pythagorean theorem to find the length of hypotenuse */public class PythaforeanTheorem { public static void main(String [] args) { double x, y, z; x = 3; y = 4; z = Math.

sqrt(x*x + y*y); System.

out.

println("Hypotenuse is " + z); }}The output of this program will be:Hypotenuse is 5.

0CharactersIn Java, character are not 8-bit quantities like they are in many other computer languages.

Instead, Java uses Unicode.

Unicode defines a character set that can represent all of the characters found in all human languages.

In Java, char is an unsigned 16-bit type having a range of 0 to 65,536.

The standard 8 bit ASCII character set is a subset of Unicode and ranges from 0 to 127.

Thus, the ASCII character is still valid Java characters.

A character variable can be assigned a value by enclosing the character in a single quote.

For example:char ch;ch = 'x';You can output a char value using a println() statement.

For example, this line outputs the value in ch:System.

out.

println("This is ch: " + ch);Since char is an unsigned 16-bit type, it is possible to perform various arithmetic manipulation on a char variable.

For example, consider the following program:/** * made by damnn */public class demo { public static void main(String [] args) { char ch; ch = 'x'; System.

out.

println("ch contains: " + ch); ch++; System.

out.

println("ch after incrementation: " + ch); ch = 90; System.

out.

println("ch is now: " + ch); }}The output of the following program is:ch contains: xch after incrementation: ych is now: ZIn the program, ch is first given the value X.

Next, ch is incremented.

This results in ch containing Y, the next character in the ASCII sequence.

Next, ch is assigned the value, 90, which is the ASCII value that corresponds to the letter z.

Since the ASCII character set occupies the first 127 values in the Unicode character set, all the old tricks that you may have used with a character in other languages will work in Java, too.

The Boolean TypeThe boolean type represents true/false values.

Java defines the values true and false using the reserved words true or false.

Thus, a variable or expression of type boolean will be one of these two values.

Here is a program that demonstrates the boolean type:The output of this program will be:b is falseb is trueThis is executed.

10 > 2-0 isfalseThere are three things to notice about this BooDemo.

java.

First, as you can see, when a boolean value is an output by println(), “true” or “false” is displayed.

Second, the value of a boolean variable is sufficient, by itself, to control the if statement.

There is no need to write an if statement like this:if (b == true).

.

Third, the outcome of a relational operator, such as <, is a boolean value.

This is why the expression 10 > 20 displays the value “false”.

Further, the extra set of parentheses around 10 > 20 is necessary because the + operator has higher precedence than the >.

LiteralsIn Java, literals refer to fixed values that are represented in their human-readable form.

For example, the number 100 is literal.

Literals are also commonly called constants.

For the most part, literals, and their usage are so intuitive that they have been used in one form or another by all the preceding sample programs.

“Java literals can be of any of the primitive data types.

The way each literal is represented depends upon its types because character constants are enclosed in single quotes.

For example, ‘a’ and ‘%’ are both character constants.

”Integer literals are specified as a number without fractional components.

For example, 10 and -100 are integer literals.

Floating point literals require the use of the decimal point followed by the number’s fractional components.

For example, 11.

123 is a floating point literal.

Java also allows you to use scientific notation for floating point numbers.

By default, floating point literals are of type double.

To specify a float literal append on F or f to the constant.

Although integer literals create an int value by default, they can still be assigned to variables of type char, byte, or short as long as the value being assigned can be represented by the target type.

An integer literal can always be assigned to a long variable.

Hexadecimal, Octal and Binary LiteralsAs you may know, in programming it is sometimes easier to use a number system based on 8 or 16 instead of 10.

The number system based on 8 is called octal, and it uses the digit 0 through 7.

In octal, the number 10 is the same as 8 in decimal.

The base 16 number systems is called hexadecimal and uses the digits 0 through 9 plus the letters A through F, which stands for 10,11,12,13,14 and 15.

As a point of interest, Java also allows hexadecimal floating-point literals, but they are seldom used.

For example, the hexadecimal number 10 is 16 in decimal.

Because of the frequency with which these two number systems are used, Java allows you to specify integer literals in hexadecimal or octal instead of decimal.

A hexadecimal literal must begin with 0x or 0X.

An octal literal begins with a zero.

Here are some examples:hex = 0xFF; // 255 in decimalCharacter Escape SequencesEnclosing character constants in single quotes works for most printing characters, but a few characters, such as the carriage return, pose a special problem when a text editor is used.

In addition, certain other characters, such as the single and double quotes, have special meaning in Java, so you cannot use them directly.

For these reasons, Java provides special escape sequences, sometimes referred to as backlash character constants.

These sequences are used in place of the characters that they represent.

’ — single quote” — Double quote — Backlash
 — Carriage return!. — Newlinef — Form feed  — Horizontal tab — Backspaceddd — Octal constantuxxx — Hexadecimal constantFor example, this assigns ch the tab character:ch = ' ';The next example assigns a single quote to ch:ch = ''';String LiteralsJava supports one other type of literal: the string.

A string is a set of characters enclosed by double quotes.

For example,"this is a thing"is a string.

You have seen the example of strings in many of the println() statements in the preceding sample program.

In addition to normal characters, a string literal can also contain one or more of the escape sequence just described.

For example, consider the following program.

It uses the!.and escape sequence.

/** * made by damnn */public class demo { public static void main(String [] args) { System.

out.

println("First line.Second line"); System.

out.

println("a b c"); System.

out.

println("d e f"); }}The output of the following program is:First lineSecond linea b cd e fYou must not confuse strings with characters.

A character literal represents a single letter of type char.

A string containing only one letter is still a string.

Although strings consists of characters, they are not the same type.

Notice how the.escape sequence is used to generate a new line.

You don’t need to use multiple println() statement to get multiline output.

Just embed.within a longer string at the point where you want the new lines to occur.

Variable is declared using this form of statement,type var-name;where type is the data type of the variable, and var-name is its name.

You can declare a variable of any valid type, including the simple types just described, and every variable will have a type.

Thus, the capabilities of a variable are determined by its type.

For example, a variable of type boolean cannot be used to store floating-point values.

Furthermore, the type of a variable cannot change during its lifetime.

An int variable cannot turn into a char variable, for example.

All variables in Java must be declared prior to their use.

This is necessary because the compiler must know what type of data a variable contains before it can properly compile any statement that uses the variable.

It also enables Java to perform strict type checking.

Initializing a VariableIn general, you must give a variable a value prior to using it.

One way to give a variable value is through an assignment statement, as you have already seen.

Another way is by giving it an initial value when it is declared.

To do this, follow the variable’s name with an equal sign and the value being assigned.

The general form of initialization is down here:int count = 10; // give count an value of 10 which is initial char ch = 'x'; // initialize ch with the letter x float f = 1.

2F; // f is initialized with 1.

2When declaring two or more variables of the same type using a comma-separated list, you can give one or more of those variables an initial value.

For example:int a, b = 8, c = 19, d; // b and c have intializationsDynamic InitializationAlthough the preceding examples have used only constant as initializers, Java allows variables to be initialized dynamically, using an expression valid at the time the variable is declared.

For example, here is a short program that computes the volume of a cylinder given the radius of its base and its height:/** * made by damnn * * calculates the volume of a cylinder given the radius * of its base and its height.

*/public class demo { public static void main(String [] args) { double r = 4, h = 5; double vol = 3.

1416 * r * r * h; System.

out.

println("Volume is: " + vol); }}Here, three local variables — r, h, and vol — are declared.

The first two, r and h, are initialized by constants.

However, vol is initialized dynamically to the volume of the cylinder.

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

Scope and Lifetime of VariablesSo far, all of the variables that we have been using were declared at the start of the main() method.

However, Java allows variables to be declared within any block.

A block is begun with an opening curly brace and ended by a closing curly brace.

A block defines a scope.

Thus, each time you start a new block, you are creating a new scope.

A scope determines what objects are visible to other parts of your program.

It also determines the lifetime of those objects.

Some other computer languages define two general categories of scopes: global and local.

Although supported by Java, these are not the best ways to categorize Java’s scopes.

The most important scopes in Java are those defined by a class and those defined by a method.

A 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 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 or modification.

Indeed, the scope rules provide the foundation for encapsulation.

A scope can be nested.

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.

To understand the nested scope, consider the following program:/** * made by damnn */public class demo { public static void main(String [] args) { int x; // known to all code within main x = 10; if(x == 10) { // a new scope has started.

int y = 20; //this is known only in this block.

// x and y both known here.

System.

out.

println("x and y: " + x + "" + y); x = y * 2; } // y = 100; // in this line y is outside the scope.

// x is still known here.

System.

out.

println("x is " + x); }}As the comments indicate, the variable x is declared at the start of main( )’s scope and is accessible to all subsequent code within main( ).

Within the if block, y is declared.

Since a block defines a scope, y is visible only to other code within its block.

This is why outside of its block, the line y = 100; is commented out.

If you remove the leading comment symbol, a compile-time error will occur, because y is not visible outside of its block.

Within the if block, x can be used because code within a block (that is, a nested scope) has access to variables declared by an enclosing scope.

Within a block, variables can be declared at any point, but are valid only after they are declared.

Thus, if you define a variable at the start of a method, it is available to all of the code within that method.

Conversely, if you declare a variable at the end of a block, it is effectively useless, because no code will have access to it.

Here is another important point to remember: 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.

If a variable declaration includes an initializer, that variable will be reinitialized each time the block in which it is declared is entered.

For example, consider this program:/** * made by damnn * */public class demo { public static void main(String [] args) { int x; for (x = 0; x < 3; x++) { int y = -1; // y is initialized each time block is entered System.

out.

println("y is: " + y); // this always prints -1 y = 100; System.

out.

println("y is now: " + y); } }}The output of this program is:y is: -1y is now: 100y is: -1y is now: 100y is: -1y is now: 100As you can see, y is always reinitialized to -1 each time the inner for loop is entered.

Even though it is subsequently assigned to the value 100, these values are lost.

There is one quirk to Java’s scope rules that may surprise you: although blocks can be nested, no variable declared within an inner scope can have the same name as a variable declared by an enclosing scope.

OperatorsJava provides a rich operator environment.

An operator is a symbol that tells the compiler to perform a specific mathematical or logical manipulation.

Java has four general classes of operators: arithmetic, bitwise, relational, and logical.

Java also defines some additional operators that handle certain special situations.

Arithmetic Operators(+) — Addition(-) — Subtraction(*) — Multiplication(/) — Division(%) — Modulus(++) — Increment( — ) — DecrementIt’s two subtraction sign, but medium adds then up, so they appear as a single hyphen.

The operator +, -, *, and / all work the same way in Java as they do in any other computer languages or in algebra.

These can be applied to any built-in numeric data type.

They can also be used on objects of type char.

Although the actions of arithmetic operators are well known to all readers, a few special situations warrant some explanation.

First, remember that when / is applied to an integer, any remainder will be truncated; for example, 10/3 will equal 3 in integer division.

You can obtain the remainder of this division by using the modulus operator %.

It works in Java the way it does in other languages, it yields the remainder of an integer division.

Consider this program to understand the modulus operator.

/** * made by damnn * */public class demo { public static void main(String [] args) { int iresult, irem; double dresult, drem; iresult = 10/3; irem = 10 % 3; dresult = 10.

0 / 3.

0; drem = 10.

0 % 3.

0; System.

out.

println("result and remainder of 10/3: " + iresult + "" + irem); System.

out.

println("result and remainder of 10/3: " + dresult + "" + drem); }}The output of the program will be:result and remainder of 10/3: 31result and remainder of 10/3: 3.

3333333333333335 1.

0As you can see, the % yields a remainder of 1 for both integer and floating point operations.

Increment and DecrementThe ++ and the — — are Java’s increment and decrement operators.

As you will see, they have some special properties that make them quite interesting.

Now let’s see how they are used and what they do:The increment operator adds 1 to its operand, and the decrement operator subtracts 1.

Therefore:x = x + 1;the above line is same as:x++;and,x = x — 1;is the same asx — — ;Both the increment and decrement operators can either precede or follow the operands.

For example;x = x + 1;this can also be written as;++x; // prefix formor asx++; // postfix formIn the foregoing example, there is no difference whether the increment is applied as a prefix or a postfix.

However, when an increment or decrement is used as part of a larger expression, there is an important difference.

When an increment or decrement operator precedes its operand, Java will perform the corresponding operation prior to obtaining the operand’s value for use by the rest of the expression.

If the operator follows its operand, Java will obtain the operand’s value before incrementing or decrementing it.

Consider the following:x = 10;y = ++x;In this case, y will be set to 11.

However, if the code is written as.

x = 10;y = x++;In this case, y will be set to 10.

In both cases, x is still set to 11; the difference is when it happens.

There are significant advantages in being able to control when the increment or decrement operations take place.

Relational and Logical OperatorsIn the terms relational operators and logical operators, relational refers to the relationships that values can have with one another, and logical refers to the ways in which true and false values can be connected together.

Since the relational operators produce true or false results, they often work with the logical operators.

The relational operators are:-== — equal to!= — not equal to> — greater than< — less than≥ Greater than or equal to≤ Less than or equal toThe logical operators are:-& — AND| — OR^ — XOR|| — Short circuit OR&& — Short circuit and! — NOTThe outcome of the relational and logical operators is a boolean value.

In Java, all objects can be compared for equality or inequality using = = and !=.

However, the comparison operators, <, >, <=, or >=, can be applied only to those types that support an ordering relationship.

Therefore, all of the relational operators can be applied to all numeric types and to type char.

However, values of type boolean can only be compared for equality or inequality, since the true and false values are not ordered.

For example, true > false has no meaning in Java.

For the logical operators, the operands must be of type boolean, and the result of a logical operation is of type boolean.

The logical operators, &, |, ^, and !, support the basic logical operations AND, OR, XOR and NOT.

Short-circuit Logical OperatorsJava supplies special short-circuit versions of its AND and OR logical operators that can be used to produce more efficient code.

To understand why, consider the following.

In an AND operation, if the first operand is false, the outcome is false no matter what value the second operand has.

In an OR operation, if the first operand is true, the outcome of the operation is true no matter what the value of the second operand is.

Thus, in these two cases there is no need to evaluate the second operand.

By not evaluating the second operand, time is saved and more efficient code is produced.

The short-circuit AND operator is &&, and the short-circuit OR operator is ||.

Their normal counterpart is & and |.

The only difference between the normal and short-circuit versions is that the normal operands will always evaluate each operand, but short-circuit versions will evaluate the second operand only when necessary.

Here is a program that demonstrates the short-circuit AND operator.

The program determines whether the value in d is a factor of n.

it does this by performing a modulus operation.

If the remainder of n / d is zero, then d is a factor.

However, since the modulus operation involves a division, the short-circuit form of the AND is used to prevent a divide-by-zero error.

/** * made by damnn * */public class demo { public static void main(String [] args) { int n, d, q; n = 10; d = 2; if (d != 0 && (n %d) == 0) System.

out.

println(d + "is a factor of" + n); d = 0; // now the value of d is 0 // since d is zero, the second operand is not evaluated.

if (d != 0 && (n % d) == 0) System.

out.

println(d + "is a factor of " + n); /* now, lets try the same thing without short-circuit operator.

this will cause a divide by zero error.

*/ if (d != 0 & (n % d) == 0) System.

out.

println(d + "is a factor of" + n); }}To prevent a divide-by-zero, the if statement first checks to see if d is equal to zero.

If it is, the short-circuit AND stops at that point and does not perform the modulus division.

Thus, in the first test, d is 2 and the modulus operation is performed.

The second test fails because d is set to zero, and the modulus operation is skipped, avoiding a divide-by-zero error.

Finally, the normal AND operator is tried.

This causes both operands to be evaluated, which leads to a run-time error when the division by zero occurs.

One last point: The formal specification for Java refers to the short-circuit operators as the conditional-or and the conditional-and operators, but the term “short-circuit” is commonly used.

The Assignment OperatorThe assignment operator is the single equal sign, =.

This Operator works in Java much as it does in any other computer language.

It has this general form:var = expression;Here, the type of var must be compatible with the type of expression.

The assignment operator does have one interesting attribute that you may not be familiar with: it allows you to create a chain of assignment.

For example, consider this fragment:int x, y, z;x = y = z = 100; // set x, y, and z to 100This fragment sets the variable x, y, and z to 100 using a single statement.

This works because the = is an operator that yields the value of the right-hand expression.

Thus, the value of z = 100 is 100, which is then assigned to y, which in turn is assigned to x.

Using a “chain of assignment” is an easy way to set a group of the variable to a common value.

Shorthand AssignmentsJava provides special shorthand assignment operators that simplify the coding of a certain assignment statement.

Let’s begin with an example.

The assignment statement is shown herex = x + 10;can be written, using Java shorthand, as:x += 10;The operator pair += tells the compiler to assign to x the value of x plus.

Here is another example.

The statementx = x — 100;is the same asx -= 100;Both statements assign to x the values of x minus 100.

This shorthand will work for all the binary operators in Java that is, those that require two operands.

The general form of the shorthand isvar op = expression;Thus, the arithmetic and logical shorthand assignment operators are the following:Because these operators combine an operation with an assignment, they are formally referred to as compound assignment operators.

The compound assignment operators provide two benefits.

First, they are more compact than their “longhand” equivalents.

Second, in some cases, they are more efficient.

For these reasons, you will often see the compound assignment operators used in professionally written Java programs.

Type Conversion in AssignmentsIn programming, it is common to assign one type of variable to another.

For example, you might want to assign an int value to a float variable, as shown here:int i;float f;i = 10;f = i; //assign an int to a floatWhen compatible types are mixed in an assignment, the value of the right side is automatically converted to the type of the left side.

Thus, in the preceding fragment, the value in i is converted into a float and then assigned to f.

However, because of Java’s strict type checking, not all types are compatible, and thus, not all type conversions are implicitly allowed.

For example, boolean and int are not compatible.

When one type of data is assigned to another type of variable, automatic type conversion will take place ifThe two types are compatible.

2.

The destination type is larger than the source type.

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, and both int and byte are integer types, so an automatic conversion from byte to int can be applied.

For widening conversions, the numeric types, including integer and floating-point types, are compatible with each other.

For example, the following program is perfectly valid since long to double is a widening conversion that is automatically performed.

/** * made by damnn * */public class demo { public static void main(String [] args) { long l; double d; l = 100123285L; d = l; System.

out.

println("L and D: " + l + "" + d); }}Although there is an automatic conversion from long to double, there is no automatic conversion from double to long, since that is not a widening conversion.

Thus, the following version of the preceding program is invalid.

Casting Incompatible TypesAlthough the automatic type conversions are helpful, they will not fulfil all programming needs because they apply only to widening conversions between compatible types.

For all other cases, you must employ a cast.

A cast is an instruction to the compiler to convert one type into another.

Thus, it requests an explicit type conversion.

A cast has this general form:(target-type) expressionHere, target-type specifies the desired type to convert the specified expression.

For example, if you want to convert the type of the expression x/y to int, you can writedouble x, y;//.

(int) (x / y)Here, even though x and y are of type double, the cast converts the outcome of the expression to int.

The parentheses surrounding x / y are necessary.

Otherwise, the cast to int would apply only to the x and not to the outcome of the division.

The cast is necessary here because there is no automatic conversion from double to int.

When a cast involves a narrowing conversion, information might be lost.

For example, when casting a long into a short, information will be lost if the long’s value is greater than the range of a short because its high-order bits are removed.

When a floating-point value is cast to an integer type, the fractional component will also be lost due to truncation.

For example, if the value 1.

23 is assigned to an integer, the resulting value will simply be 1.

The 0.

23 is lost.

/** * made by damnn * demonstrate casting */public class demo { public static void main(String [] args) { double x, y; byte b; int i; char ch; x = 10.

0; y = 3.

0; i = (int) (x / y); //cast double to int System.

out.

println("Integer outcome of x / y: " + i); i = 100; b = (byte) i; System.

out.

println("value of b: " + b); i = 257; b = (byte) i; System.

out.

println("Value of b: " + b); b = 88; // ASCII code for x ch = (char) b; System.

out.

println("ch: " + ch); }}The output of the program will be:Integer outcome of x / y: 3value of b: 100Value of b: 1ch: XIn the program, the cast of (x / y) to int results in the truncation of the fractional component, and the information is lost.

Next, no loss of information occurs when b is assigned the value 100 because a byte can hold the value 100.

However, when the attempt is made to assign b the value 257, information loss occurs because 257 exceeds a byte’s maximum value.

Finally, no information is lost, but a cast is needed when assigning a byte value to a char.

ExpressionsOperators, variable, and literals are constituents of expressions.

You probably already know the general form of expression from your other programming experience, or from algebra.

However, a few aspects of expressions that I will discuss now.

Type Conversion in ExpressionWithin an expression, it is possible to mix two or more different types of data as long as they are compatible with each other.

For example, you can mix shortand long within an expression because they are both numeric types.

When different types of data are mixed within an expression, they are all converted to the same type.

This is accomplished through the use of Java’s type promotion rule.

First, all char, byte, and short values are promoted to int.

Then, if one operand is a long, the whole expression is promoted to long.

If one operand is a float operand, the entire expression is promoted to float.

If any of the operands is double, the result is double.

It is important to understand that type promotions apply only to the values operated upon when an expression is evaluated.

For example, if the value of a byte variable is promoted to int inside an expression, outside the expression, the variable is still a byte.

Type promotion only affects the evaluation of an expression.

Type promotion can, however, lead to somewhat unexpected results.

For example, when an arithmetic operation involves two-byte values, the following sequence occurs: First, the byte operands are promoted to int.

Then the operation takes place, yielding an int result.

Thus, the outcome of an operation involving two byte values will be an int.

This is not what you might intuitively expect.

Consider the following program:/** * made by damnn * */public class demo { public static void main(String [] args) { byte b; int i; b = 10; i = b * b; // ok, no cast needed b = 10; b = (byte) (b * b); // cast needed.System.

out.

println("i and b: " + i + "" + b); }}Somewhat counterintuitively, no cast is needed when assigning b*b to i, because b is promoted to int when the expression is evaluated.

However, when you try to assign b * b to b, you do need a cast — back to byte.Keep this in mind if you get unexpected type-incompatibility error messages on expressions that would otherwise seem perfectly OK.

This same sort of situation also occurs when performing operations on chars.

For example, in the following fragment, the cast back to char is needed because of the promotion of ch1 and ch2 to int within the expression:char ch1 = 'a', ch2 = 'b';ch1 = (char) (ch1 + ch2);Without the cast, the result of adding ch1 to ch2 would be int, which can’t be assigned to a char.

Casts are not only useful when converting between types in an assignment.

For example, consider the following program.

It uses a cast to double to obtain a fractional component from an otherwise integer division.

/** * made by damnn * */public class demo { public static void main(String [] args) { int i; for (i = 0; i < 5; i++) { System.

out.

println(i + " / 3: " + i / 3); System.

out.

println(i + " / 3 with fractions: " + (double) i /3); System.

out.

println(); } }}The output of the following program is:0 / 3: 00 / 3 with fractions: 0.

01 / 3: 01 / 3 with fractions: 0.

33333333333333332 / 3: 02 / 3 with fractions: 0.

66666666666666663 / 3: 13 / 3 with fractions: 1.

04 / 3: 14 / 3 with fractions: 1.

3333333333333333Spacing and ParenthesesAn expression in Java may have tabs and spaces in it to make it more readable.

For example, the following two expressions are the same, but the second is easier to read:x = 10/y * (127/x);x = 10 / y * (127/x);Parentheses increase the precedence of the operations contained within them, just like in algebra.

Use of redundant or additional parentheses will not cause errors or slow down the execution of the expression.

You are encouraged to use parentheses to make clear the exact order of evaluation, both for yourself and for others who may have to figure out your program later.

For example, which of the following two expressions is easier to read?x = y/3-34*temp+127;x = (y/3) – (34*temp) + 127;.

. More details

Leave a Reply