Навигация
 
  •  Главная
•  Программирование
•  Веб-программирование
•  Заработок в сети
•  Продвижение сайта
•  Дизайн
 
 
 
 
 
 
 
 
 
 
 
   
 
 
 
 
 
 
Навигация
 
  •  Главная
•  Форум
•  Доска объявлений
•  Биржа труда
•  О нас
 
 
 
     
  •   Программисты.kz » Программирование » Java » Уроки Java » Simple Data Types, Operators, and Variables  

      Реклама на сайте:
Голосуй за Programmers.kz

  Simple Data Types, Operators, and Variables  
    |   18-12-2009, 17:27   |   Опубликовал: КазКиберГетик  : 208  
 

Java Unit 3

Simple Data Types, Operators, and Variables

3.1  Data Types, Variable Declaration and Initialization

3.2   Assignment and the Relationship Between Numeric Types

3.3  Assignment and Simple Arithmetic

3.4  The Math Class

3.5  The String Class

3.6  Using the MyTerminalIO Class

3.1  Data Types, Variable Declaration and Initialization

            These are some of the simple numeric data types:

int                 for integers

long              for large integers

float            for single precision floating point values

double         for double precision floating point values

            There are other numeric types, but none that are needed immediately.  For most purposes it is sufficient to be able to use int and double.  Learning about long and float gives a more complete understanding of Java.

When actually writing numeric values in a program no commas can be used.  Any value shown with a decimal point, such as 3.0, will be treated as a floating point value, not an integral value.  Exponential notation also exists for handling very large or very small values, but it will not be covered in these notes.

            The type “double” illustrates the pitfalls of case sensitivity in Java.  There is also a system supplied class “Double”.  If you mistakenly use a capital letter when giving the variable type in a declaration you will have problems in your code which will lead to mysterious errors.  It is extremely difficult to locate the source of the problem when it is simply the difference between a capital and a small “d” in one line of code.    

            Variables are containers for values.  In effect, when a variable is declared, a certain amount of space is set aside in the computer’s memory in order to store a value of that type.  The following rules and recommendations apply to variables:

  1. They have to be typed.
  2. Ideally, they should be initialized to some concrete value.
  3. They should be given a descriptive name.
  4. Their names have to follow these rules:

a.       They may contain letters, digits, the $ sign, and the underscore (_).

b.      They can’t start with a digit.

c.       No variable can have the same name as a Java keyword.

d.      They are case sensitive.

e.       They cannot have blank spaces in them.

Rule 4.c is a little unfair for someone just learning Java.  It is not possible to know all of the keywords in advance.  These notes use the following approach to avoiding keywords or supplied class names:  The names of many things written by the author start with “my”.  “double” is a keyword, for example, but “mydouble” is not.  Therefore “mydouble” is an acceptable name for a variable.

Recall that class names have to start with a capital letter.  Syntactically, variable names are allowed to start with a capital letter, but this should not be done.  This way there is no chance of confusing variables and classes.  In the previous chapter the idea of an object reference was introduced.  Although not a simple data type, it should be noted that the declaration of a type and the assignment of a value mean that the object reference functions as a variable.  It is especially important to use naming conventions that allow you to distinguish between classes and instances of those classes.  Just like variables, the names of object references should also not be capitalized.

To make a variable name descriptive, quite often it is desirable to use compound words.  Even though this requires more typing, the code is easier to understand and shorter explanatory comments are possible if the naming conventions are clear.  Syntactically permissible compounds might take the following forms:

payRate, pay_rate, payrate, etc.

The dash is not allowed in variable names because the compiler would interpret it as a minus sign or subtraction.

It is good practice to declare or declare and initialize variables at the beginning of the block of code where they are used.  Some examples follow.  The declarations that include initialization are preliminary examples of how to assign values to variables. 

double pay_rate;

double tax_rate = .05;

int days_in_a_week;

int weeks_in_a_year = 52;

int hours_in_a_day, minutes_in_an_hour;

As noted above, the declaration of a variable sets aside memory space for a value.  If the variable is not initialized, the value of the variable will be whatever is in that memory space when the program is in use.  Initialization is a good habit since you don’t want calculations to depend on values that result from random system conditions.  The compiler will try to warn you about variables that have not had values assigned to them.  However, to avoid errors later, it can be helpful to initialize variables to suitable default values.

It is possible to declare constants.  This is the syntax for initializing a variable to a given value that cannot be changed later on in the program:

final int WEEKS_IN_A_YEAR = 52;

            Unless you are traveling from planet to planet, the number of weeks in a year does not change.  With a declaration of “final”, after the first assignment, any subsequent assignment to the variable will result in a compiler error.  It is customary to use all capital letters when declaring constants.  This is one exception to the rule that variable names should not begin with a capital letter.

3.2  Assignment and the Relationship Between Numeric Types

Assuming that a variable has been declared, it can be assigned a value.  In a typical program, the sequence might be as follows:

int myinteger;     /*  declaration  */

myinteger = 7;     /*  assignment  */

The Java language uses the single “=” sign as the assignment operator.  The value that occurs on the right hand side of the operator is stored in the memory location designated by the variable name on the left hand side.

A problem arises when the value on the right is not of the same type as the variable on the left.  In some cases the system automatically converts the value on the right to the type of the variable on the left.  In other cases the assignment is syntactically invalid.  If the data type of the value on the right cannot contain more information than the data type on the left, then the assignment is allowed.  Automatic conversion will occur.  If however, the data type on the right can contain more information than the one on the left, such an automatic conversion could lead to the loss of information.  This is not automatically allowed.

In general:

An integer can be stored in a long.

A float can be stored in a double.

An integer or a long can be stored in either a float or a double.

A long can’t be stored in an integer.

A double can’t be stored in a float.

Neither a float nor a double can be stored in either an integer or a long because any information to the right of the decimal place would be lost.

Given these type declarations:

double tax_rate = .05;

int weeks_in_a_year = 52;

Here are two simple examples of what is and is not allowed:

tax_rate = weeks_in_a_year;  /*  valid  */

weeks_in_a_year = tax_rate;  /*  not valid  */

The invalid statement is now modified with syntax that makes it valid.  This new syntax is called casting and it explicitly causes the conversion of one type to another:

weeks_in_a_year = (int) tax_rate;

The value on the right is cast to the type on the left by putting the desired type in parentheses in front of the quantity on the right.  This is required of the programmer because it functions like a contract.  When casting, the programmer is taking responsibility for anything that might be lost due to the fact that the type on the left cannot hold all of the information on the right.  When going from a floating point type to an integer type, casting results in truncation.  Rounding does not occur, and all data to the right of the decimal point is lost.  Here is an illustration:

double tax_rate = .05;

int weeks_in_a_year = 52;

weeks_in_a_year = (int) tax_rate;

Everything to the right of the decimal place in tax_rate is lost and the end result is that weeks_in_a_year contains the integer value 0.

3.3  Assignment and Simple Arithmetic

            One way of understanding variables is that they are containers which can be used more than once and can hold different values at different times during program execution.  Variables are commonly used to store the results of arithmetic operations and an assignment statement is the place for doing arithmetic operations in a program.

            The simple arithmetic operators are +, -, *, and /, with () for grouping.  Unless the order of operations is changed by parentheses, multiplication and division are performed before addition and subtraction.  All else being equal, operations are performed in order from left to right.

            Arithmetic may include both variables and numeric values.  Given such declarations as these:

int myinteger1 = 10;

int myinteger2 = 20;

int myinteger3 = 30;

double mydouble1 = 10.0;

double mydouble2 = 20.0;

double mydouble3 = 30.0;

            The following statements are valid:

myinteger = 4 + myinteger3;

mydouble = mydouble2 * mydouble3;

            Questions of type conversion also occur with arithmetic.  In some cases it is possible to mix the types of operands without trouble.  In other cases problems can result.  For example, the following statement is valid:

mydouble1 = myinteger1 – mydouble2;

            Why can an integer and a double variable be combined without trouble?  Automatic type conversion happens on the right.  When mixing types, all are promoted to the type present which can hold the most information.  In other words, myinteger1 is treated as a double, the result is a double, and this can be stored in mydouble1.

The following statement is not valid:

myinteger1 = myinteger2 / mydouble1;

            The results on the right are promoted to a double, but this cannot be stored in an integer variable.  In general, the best rule is not to rely on automatic conversion.  When in doubt, explicitly cast all variables to the type you want in the arithmetic statements where they occur.

            Another question to consider is the result of the following:

myinteger1 = myinteger2 / myinteger3;

            Division potentially leads to an answer with a fractional part.  However, when integers are divided in Java, only the whole part of the answer is kept.  In other words, the result is a truncated integer value, and it is correct to store it in another integer variable.

It is also possible to obtain the remainder of integer division.  The arithmetic symbol for this operation is “%” and is known as the modulus operator.  In the following example the value 10 would be assigned to myinteger1, the remainder upon dividing 30 by 20.

myinteger1 = myinteger3 % myinteger2;

            Part of the power of variables is that they can be assigned new values that depend on their current values.  In other words, the following statements are valid:

myinteger1 = myinteger1 + 1;

mydouble1 = mydouble1 - 5.0;

            Such incrementing and decrementing operations are so common that a shorthand syntax exists for them.  The statements shown below are equivalent statements to the ones above, respectively. 

myinteger1++;

mydouble1 -= 5.0;

            Two minus signs can be substituted for the two plus signs to decrement by one.  Changing the single minus sign in the second statement to a plus sign will change the operation to incrementing by a floating point value of 5.0.

            There are a few remaining loose ends to tie up concerning simple arithmetic.  Although not recommended, from previous material it is probably apparent that a variable can be declared when needed.  Thus, a statement such as this is syntactically acceptable:

int myinteger4 = myinteger2 + myinteger3;

            Aside from the lack of foresight evident in such programming, this practice is the cause of another type of error.  If instead of declaring all needed variables once at the top you are in the habit of declaring them as you go, you are liable to declare the same variable more than one time.  This is a syntax error.

            It is also possible to do arithmetic inside of print statements.  Assuming that the variables have been declared and assigned values, this is a valid statement:

            myterminal.println(myinteger + myinteger2);

            This also shows lack of foresight and it has the shortcoming that the result of the arithmetic is not available for future use since it has not been saved in another variable.

            There is one final, important observation to make about arithmetic in Java.  As with the vast majority of languages, numeric values in Java are internally stored as binary numbers.  The results of some decimal arithmetic may not have exact representations in binary.  Some languages try to make life more convenient by showing result values in a form that the user might expect.  Java takes the approach of showing the user the exact value as manipulated in the program.  When doing simple arithmetic and expecting a result of 0.5, for example, you may find that your output shows a value such as 0.49999999.  You should not be surprised.  There are ways of explicitly formatting output so that you see the value 0.5 instead, but they are not covered in these notes.  It is simply necessary to keep in mind that Java tells no lies on this account.

3.4  The Math Class 

            The Java system makes available many math constants and functions.  It does this by means of a class named Math.  For complete information on this class and what it contains, refer to the Java API documentation.  In this section a subset of these features will be discussed which illustrate the characteristics of the class.  First of all, to make use of the class in a program, do the following at the top:

import java.lang.Math;

            The Math class contains certain mathematical constants such as pi and e.  These constants can be used in your programs using the names Math.PI and Math.E.  The variable names are capitalized because they’re constants.  Assuming that the variables area and radius have been declared and a value has been assigned to radius, here is an example of the use of one of these constants:

     area = Math.PI * radius * radius;

            In this example the name of the class is followed by a dot, which is followed by the name of the variable.  Although it is contained in the Math class, the variable is available for use in a program without making use of a method to obtain it.  Such a variable is called a static variable, which differs from the instance variables mentioned earlier.  More details on static variables will be given later.

            It is also important to observe that the class is used without constructing an instance of it.  The variables in the Math class are available for use without having an object in existence.  A class may serve as a model for the creation of objects, but it may also serve as a container for useful things.  The Math class exists only as a container, and the constants are some of the useful things it contains. 

            The Math class also contains higher mathematical operators, such as the trigonometric functions, etc.  Several will be used as examples here.  Just like with the mathematical constants, It is not necessary for there to be an instance of the Math class in order to use its methods.  Such methods are referred to as static methods.

            In the previous examples of making method calls, the model was:

            object.method(parameters);

            When using static methods there is no object to call the method on.  All information which goes into the method goes in as parameters, and a return value is expected in order to capture the result.  The model is:

            return_value = Class_name.method(parameters);

            The return_value variable has to be correctly typed to match what the method will return and the parameters also have to agree with the types expected by the method.  Here are schematics of some of the functions.  Notice that the schematic begins with a declaration of the type of the return value, and the parameters are declared with their types inside the parentheses.

double exp(double x)

This returns e raised to the x power, ex.

            double pow(double x, double y)

            This returns x raised to the y power, xy.

            double log(double x)

            This returns the natural logarithm of x, ln x.

            double sqrt(double x)

            This returns the square root of x.

            double abs(double x)

            This returns the absolute value of x, |x|.

            Assuming that the Math class is available for use and the rest of the program is in place here is a fragment illustrating the use of one of these methods.  :

     double somevalue = 3.2;

     double resultvalue;

     resultvalue = Math.sqrt(somevalue);

            A mistake that you might be tempted to make might be something along these lines:

     resultvalue = somevalue.sqrt();  //  No!  No!  No!

            This is wrong on two counts:  Math class methods cannot be called on objects; the thing you want to operate on has to be passed in as a parameter;  Also, somevalue is a variable, not an object, and it is not possible to call a method on a variable.

            Here is another illustration of the use of one of these methods, writing this familiar formula in Java code:  A = πr2.

area = Math.PI * Math.pow(radius, 2.0);

            Keep in mind that these methods are black boxes.  The user just has to know how to use them, not how they work.  You can find out the required types of the parameters and the types of the return values in the Java API documentation.  You will not find the code there.

3.5 The String Class

            Strings are sequences of characters that are treated together as a group.  They are among the most commonly manipulated data items, along with simple numeric variables.  We have already encountered string constants.  Anything enclosed in double quotes is a string, so the following is a string constant:

“Hello World”

            In Java there is a String class.  It is possible to construct instances of this class and obtain references to them.  Because strings are so commonly used, and because the double quotes are so closely associated with them, there is a special syntax for constructing strings.  Here is an example:

String mystring = “Hello World”;

Or:

String mystring;

mystring = “Hello World”;

            In other words, it is not necessary to make use of the keyword new in order to create an instance of a string.  The reference to the string can now be used in the following way, for example, with the expected results:

     myterminal.println(mystring);

            Once it has been declared, the reference, like a variable, can be re-used.  In other words, it is now possible to do the following to mystring:

            mystring = “A new string”;

            We initially saw this model for calling methods on objects:

     object.method(parameters);

            Then we saw this model for making use of static methods:

     return_value = Class.method(parameters);

            Since String is a class, it has methods associated with it.  One useful method allows you to find out the number of characters in a string object at any given time.  The following illustrates its use:

     int stringlength;

     stringlength = mystring.length();

            This shows that methods called on objects can also return values.  In this example the value returned depends entirely on the object the method is called on.  No parameters are needed inside the parentheses.  This is an example of a method that returns the contents of some instance variable maintained inside the object.  More generally, method calls on objects that return values may also take parameters.  This will be explored in more detail later.  This is the general model for these of calls:

     return_value = object.method(parameters);

            Although not immediately apparent, the String class has a special characteristic.  If you examined all of the methods of the class, you would not find any that allowed you to modify a string.  You can obtain information about a string object, you can obtain its contents, and you can cause the string reference to refer to a new string, but you cannot change the string itself.  This property is referred to as immutability.

            In Java, the individual characters in a string can be identified numerically by their position, starting at the left beginning with 0.  This is illustrated below:

String mystring = “Hello”;

Hello

01234

            The String class has a method that returns a reference to a selected portion of the string.  It takes two integer parameters.  The first parameter tells the starting position of the substring of interest in the string.  The second parameter tells the position immediately past the last character of interest.  Here is an example illustrating its use:

     String anotherstring;

     anotherstring = mystring.substring(0, 4);

     myterminal.println(anotherstring);

     Hell

            The model for this method can be given as:

     other_string = some_string.substring(start, past_end);

            Notice that the method does not trim the original string.  It remains unchanged.  The method returns a reference to the desired substring, which can be captured in another named string reference.

            In addition to selecting substrings from strings, it is possible to put more than one string together.  This is called concatenation.  In fact, we have already seen it.  When doing output, it was possible to do something like this:

     myterminal.println(“Hello” + “ “ + “World”);

            The parameters in that call are simply string constants, and the “+” sign is serving as the symbol for concatenation of strings.  As a result, it should be no surprise that the following sequence of actions is possible with the expected results.

     String mystring1, mystring2, mystring3, mystring4;

     mystring2 = “Hello”;

     mystring3 = “ “;

     mystring4 = “World”;

     mystring1 = mystring2 + mystring3 + mystring4;

     myterminal.println(mystring1);

            Also as seen in output, when doing concatenation it is possible to mix strings and numerical values.  You can do this:

     myterminal.println(“The result is:  “ + 27);

            The following sequence of actions gives the same result:

     int result = 27;

     String mystring = “The result is:  “;

     String anotherstring = mystring + result;

     myterminal.println(anotherstring);

            When shown as a parameter to the println() method, the “+” sign appears to be a punctuation mark, like a comma.  However, it is an operator, but with a special characteristic.  When used only on numeric types, it does addition.  When used only on strings, it does concatenation.  When used on a mixture of numeric types and strings, it converts the numeric types to strings and does concatenation.  The fact that the same operator does different things depending on what its operands are is referred to as overloading.  This topic will come up again later on.

            Because the “+” works in this way you can convert numeric values to strings in general.  A pair of double quotes with nothing between them (not even a space) is referred to as the empty string.  If you concatenate this with any numeric variable, the result is a string containing only the sequence of symbols that represented the value.  In other words, the following sequence would give the result shown:

     double mydouble = 3.75;

     String mystring = “” + mydouble;

     String mystring2 = mystring.substring(2, 3);

     myterminal.println(“The digit in the 10ths place

 is:  “ + mystring2);

     The digit in the 10ths place is:  7

            As mentioned earlier, there are classes with the names Integer and Double.  Like the Math class, these classes contain useful methods.  For example, it is possible to convert numbers without using the trick given above.  The following illustrates the idea:

     import java.lang.Double;

     …

     double mydouble = 3.75;

     String mystring = Double.toString(mydouble);

            The toString() method converts a numeric value into a string containing the number.

            These Integer and Double classes also contain methods that allow you to turn the contents of strings into numeric values, assuming the strings contain sequences of symbols which form valid numbers.  Here is an example:

     import java.lang.Integer;

     …

     String mystring = “375”;

     int myinteger = Integer.parseInt(mystring);

There are similar classes for numeric types other than int and double.  They all contain similar methods, allowing conversion to and from strings and numeric variables, as well as other methods.  Details can be found in the Java API documentation.

3.6  Using the MyTerminalIO Class

            You have already seen the MyTerminalIO class used to do output.  Now you will see how it can be used for input.  If input is expected from a user during a program run, it is necessary to print out a prompt requesting the input.  The MyTerminalIO class has three methods for taking in input, getString(), getInt(), and getDouble().  There are versions of these methods that do not take parameters.  With these versions it is necessary to call println() or print() in order to produce the prompt before calling the input methods.  These methods bring up a dialog box on the screen where the input of the required type can be typed.  When you hit the enter key, they return the reference or value to the program, where it can be captured in a named reference or variable.

Here is a short program illustrating the use of the input methods without parameters:

public class TestInput1

{

  public static void main(String[] args)

  {

    MyTerminalIO myterminal = new MyTerminalIO();

    myterminal.println("Enter a string:");

    String mystring = myterminal.getString();

    myterminal.println("Enter an integer:");

    int myinteger = myterminal.getInt();

    myterminal.println("Enter a double:");

    double mydouble = myterminal.getDouble();

  }

}

            There are also versions of the input methods that take parameters.  The parameter is the prompt string.  If you use these versions of the methods, it is not necessary to print out the prompt in advance.  It will appear in the input dialog box and will be automatically echoed in the area where the program’s actions are recorded.

Here is a short program illustrating the use of the input methods with parameters:

public class TestInput2

{

  public static void main(String[] args)

  {

    MyTerminalIO myterminal = new MyTerminalIO();

    String mystring = myterminal.getString("Enter a string:");

    int myinteger = myterminal.getInt("Enter an integer:");

    double mydouble = myterminal.getDouble("Enter a double:");

  }

}


Download MyTerminalIO class

Author: Kirk Scott

Look official permission!


Ключевые теги: Variables, Operators, Types, Simple, Уроки Java
 
 
 
Уважаемый посетитель, Вы зашли на сайт как незарегистрированный пользователь. Мы рекомендуем Вам зарегистрироваться либо войти на сайт под своим именем.

Обсудить на форуме


Другие статьи по теме:


 
 
 (голосов: 0)
 

  Информация  
     
  Посетители, находящиеся в группе Гости, не могут оставлять комментарии в данной новости.  


 
 
Вход на сайт
 
логин :
пароль :
Напомнить пароль?
Вы не зарегистрированы? Регистрация здесь
 


Наш опрос
   


Статистика
  Всего на сайте: 17
Гостей: 9
Пользователи: - отсутствуют
Роботы: crawl Bot, Yandex Bot, Yandex Bot, StackRambler, MSN Bot

 


Олимпиады
  2010/09/15 - 21:00, Ср Member SRM 482
Начало: 2010/09/15 - 21:00, Ср Длительность: 1 ч 35 м

2010/09/25 - 22:00, Сб SRM 483
Начало: 2010/09/25 - 22:00, Сб Длительность: 1 ч 35 м

2010/10/06 - 07:00, Ср SRM 484
Начало: 2010/10/06 - 07:00, Ср Длительность: 1 ч 35 м

2010/10/21 - 17:00, Чт Member SRM 485
Начало: 2010/10/21 - 17:00, Чт Длительность: 1 ч 35 м

2010/10/26 - 21:00, Втр SRM 486
Начало: 2010/10/26 - 21:00, Втр Длительность: 1 ч 35 м

 


Партнёры
 
Freeway.kz
Образование в Казахстане и за рубежом: Uchi.kz
Benchmark.kz - компьютерный портал
wWw.informatik.kz
Информационный портал Hi-Tech
 


Реклама
 
 


 
 
 
 
Главная страница   |   Регистрация   |   Добавить новость   |   Правила сайта   |   Статистика   |   Обратная связь
Copyright © 2009 КазКиберГетик & AlexanderMS . Все права защищены...
Made in DLETemplates.Com and by КазКиберГетик © 2009 for programmers.kz. Modifications by КазКиберГетик
  Rambler's Top100