Студопедия
Случайная страница | ТОМ-1 | ТОМ-2 | ТОМ-3
АрхитектураБиологияГеографияДругоеИностранные языки
ИнформатикаИсторияКультураЛитератураМатематика
МедицинаМеханикаОбразованиеОхрана трудаПедагогика
ПолитикаПравоПрограммированиеПсихологияРелигия
СоциологияСпортСтроительствоФизикаФилософия
ФинансыХимияЭкологияЭкономикаЭлектроника

Numeric promotions

Student is obliged to write down and run this program by himself | Data in a program (variables and literals) | Operations on data (operators and expressions) | Fundamentals of programming II | Write down and run this program on your computer | Write down and run this program on your computer | Introduction to objects | The first program | Types. Primitive types. | Types of variables. Declarations. |


Читайте также:
  1. Explicit numeric conversions
  2. Numerical control information bar
  3. Продвижение - Promotions

In general, a value of the type B cannot be assigned to a variable of the type A. Thus, the following causes compile-time error:

int a = "PJWSTK";

because the variable a is of the type int, whereas the expression "PJWSTK" is a string literal of the type String.

However, it would be unwise to apply the above rule to numeric types. Variables of numeric types are all numbers, so we would like to treat them similarly regardless of their types.

The modification of the type of a variable is called conversion or promotion (in arithmetical operations).

 

The conversions among primitive types which cannot lead to any loss of information represented by the expression's value are performed implicitly.
For example, to a variable of the type double the value of the type int can be assigned without an error:

int a = 10;
double d = a;

Indeed, values of the type int (integer numbers) can be represented by the values of the type double (real numbers).

Such conversions are called widening primitive conversions, because "narrower" types are converted to "wider" types (able to represent more values).

On the contrary, the assignment:

double d = 10.1;
...
int a = d;

causes compile-time error. The assignment of a real number to an integer results in loss of information about its fractional part.
Such conversions are called narrowing primitive conversions and are possible only when the cast operator is explicitly used. The conversions involving the cast operator are called casting conversions. They must be specified explicitly to tell the compiler that the programmer consciously forces the conversion of types which may lead to loss of information and that it is not an accidental error in the program.

The syntax of the cast operator is:

(type_name) expression

where type_name - the type to which the actual type of expression is converted

 

Thus, the previous example should be written as follows:

double d = 10.9;
...
int a = (int) d;

This form is accepted by the compiler.

It is worth noting that such a conversion may result in loss of precision. The value of the variable a after the assignment is 10. Thus, its fractional part was lost.

Conversions are often performed on characters (of the type char) and their Unicode values (which may occur to be of the type int).
Here is a test program that includes examples of conversions on characters:

public class Char { public static void main(String[] args) { char c = 'a'; int kod = c; System.out.println("Unicode value of " + c + " = " + kod); kod = 77; c = (char) kod; System.out.println("Unicode value of " + c + " = " + kod); // sometimes the widening conversion must be used explicitly System.out.println("Unicode value of " + '*' + " = " + (int) '*'); // the narrowing conversions must always be used explicitly System.out.println("Unicode value of " + (char) 66 + " = " + 66); }}

Unicode value of a = 97
Unicode value of M = 77
Unicode value of * = 42
Unicode value of B = 66

which prints:


The conversions which are applied implicitly to the operands of arithmetic operators are called numeric promotions.

The numeric promotion is the conversion of the operands of a numeric operator to a common type so that an operation can be performed.

 

The question what is the common type answers the following rule:

Binary numeric promotions (for binary operators) are performed as follows:

 

 

Summary

The lecture introduced:

This knowledge enables us to write simple programs performing various calculations correctly.
However, proper declarations of variables and use of literals will become important later when our programs become more complex.

Exercises

  1. Write in Java a program converting temperatures given in Fahrenheit degrees to Celsius. Input data (temperature given in Fahrenheit) should be stored in some variable.
  2. Write a program calculating the cost of purchase of some articles. It should display the overall cost of all articles and each article's share in this cost. An article is characterized by its price and quantity (for example, apples - 1 kg, price for 1 kg - 3 EUR).
  3. Write a program printing Unicode values of characters of some language.


Lecture 6

Objects

Programming in Java deals with objects. The notion of object was introduced in lecture 4. Now we want to describe how objects are represented in Java.


Дата добавления: 2015-11-16; просмотров: 63 | Нарушение авторских прав


<== предыдущая страница | следующая страница ==>
More on operators and expressions| Objects and references

mybiblioteka.su - 2015-2024 год. (0.005 сек.)