CHAPTER 5 VARIABLES AND OTHER BASIC ELEMENTS IN JAVA PROGRAMS (C) KARI LAITINEN

Similar documents
CHAPTER 5 VARIABLES AND OTHER BASIC ELEMENTS IN JAVA PROGRAMS

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

CHAPTER 7 ARRAYS: SETS OF SIMILAR DATA ITEMS

3. Java - Language Constructs I

Full file at

Program Fundamentals

Programming Lecture 3

Bits, Words, and Integers

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Visual C# Instructor s Manual Table of Contents

COMP 202 Java in one week

Programming for Engineers Introduction to C

Variables and Literals

3. Simple Types, Variables, and Constants

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

Accelerating Information Technology Innovation

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

Introduction to C# Applications

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

CS102: Variables and Expressions

The Java Language Rules And Tools 3

JAVA Programming Fundamentals

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

printf( Please enter another number: ); scanf( %d, &num2);

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

CHAPTER 6 DECISIONS AND REPETITIONS: BASIC ACTIVITIES IN PROGRAMS

CPS122 Lecture: From Python to Java last revised January 4, Objectives:

Fundamental of Programming (C)

BASIC ELEMENTS OF A COMPUTER PROGRAM

3. Java - Language Constructs I

Basics of Java Programming

DEPARTMENT OF MATHS, MJ COLLEGE

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

Java Programming Fundamentals. Visit for more.

Programming in C++ 4. The lexical basis of C++

Lecture 2: Variables and Operators. AITI Nigeria Summer 2012 University of Lagos.

Computer Components. Software{ User Programs. Operating System. Hardware

CS112 Lecture: Working with Numbers

Expressions and Casting

APPENDIX A: SUMMARY OF IMPORTANT JAVA FEATURES

Memory Addressing, Binary, and Hexadecimal Review

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. A Guide to this Instructor s Manual:

2 rd class Department of Programming. OOP with Java Programming

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

C++ Data Types. 1 Simple C++ Data Types 2. 3 Numeric Types Integers (whole numbers) Decimal Numbers... 5

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Data Types and Variables in C language

2 nd Week Lecture Notes

Variables and Constants

Java Identifiers. Java Language Essentials. Java Keywords. Java Applications have Class. Slide Set 2: Java Essentials. Copyright 2012 R.M.

Variables and Data Representation

Chapter 2 Elementary Programming

Chapter 2: Data and Expressions

Java Programming. Atul Prakash

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Expressions and Casting. Data Manipulation. Simple Program 11/5/2013

IT 374 C# and Applications/ IT695 C# Data Structures

CPS122 Lecture: From Python to Java

Final Labs and Tutors

C++ Programming: From Problem Analysis to Program Design, Third Edition

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Variables and Constants

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Variables. Data Types.

Chapter 2. Data Representation in Computer Systems

Computer System and programming in C

Computer Components. Software{ User Programs. Operating System. Hardware

C: How to Program. Week /Mar/05

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

A Java program contains at least one class definition.

Language Fundamentals Summary

CS 142 Style Guide Grading and Details

An overview of Java, Data types and variables

14.3 Handling files as binary files

Slide Set 2. for ENCM 335 in Fall Steve Norman, PhD, PEng

Chapter 3: Operators, Expressions and Type Conversion

Lecture 3. Input, Output and Data Types

Maciej Sobieraj. Lecture 1

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Objectives. In this chapter, you will:

The C++ Language. Arizona State University 1

Basic Operations jgrasp debugger Writing Programs & Checkstyle

2.2 Syntax Definition

CMPT 125: Lecture 3 Data and Expressions

Course Outline. Introduction to java

These are reserved words of the C language. For example int, float, if, else, for, while etc.

Getting started with Java

3 The Building Blocks: Data Types, Literals, and Variables

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

MP 3 A Lexer for MiniJava

LESSON 2 VARIABLES, OPERATORS, EXPRESSIONS, AND USER INPUT

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

The MaSH Programming Language At the Statements Level

Transcription:

CHAPTER 5 VARIABLES AND OTHER BASIC ELEMENTS IN JAVA PROGRAMS (C) KARI LAITINEN WWW.NATURALPROGRAMMING.COM Now, finally, we really begin studying computer programming with the Java language. Variables are important elements in computer programs, and they are needed in almost every computer program. In this chapter we shall study different types of variables and use the variables in simple arithmetic computations. We shall also explore names and keywords which are very basic elements in source programs. This chapter, as well as the following chapters, introduce many examples of Java source programs for you to study. A source program is a textual description of what the computer should do when the compiled version of the source program is executed by a computer. The source programs that you will see in this chapter contain variable definitions followed by executable program statements, action statements, which do something with the variables. The general structure of the programs is the following: class ClassName public static void main( String[] not_used ) Variable definitions. Action statements that modify and print the contents of the variables that were defined above. As was already discussed in Chapter 2, the structure of our fist programs is such that a static method named main() contains the action statements of the program, and the main() method is written inside a class definition. At this phase, we do not attempt to profoundly understand the meaning of the class definition. We ll just try to figure out how the internal statements of method main() operate. These are sample pages from Kari Laitinen s forthcoming book "A Natural Introduction to Computer Programming with Java". More information at www.naturalprogramming.com

98 Chapter 5: Variables and other basic elements in Java programs (c) Kari Laitinen www.naturalprogramming.com 5.1 Integer variables (int, short, long, byte, char) A variable in a source program is a basic program element that can be used to store numerical values. The value of a variable usually changes when the program is being executed. When we define a variable in a program, we actually reserve a few bytes of computer's main memory to be used for a special purpose. The following is an example of a variable definition: int integer_from_keyboard ; The above source program line means that four bytes (32 bits) of memory are reserved to store an integer that will be read from the keyboard. Integers are whole numbers that have no decimal point. Integers can be positive or negative. Variables of type int are said to be 32-bit variables because they occupy four bytes in the main memory of the computer. A variable always has a type, such as int which is an abbreviation of the word "integer". The programmer, the person who writes the variable definitions in a program, must give a unique name to each variable. In the definition above, the name of the variable is integer_from_keyboard. Variable definitions, like all Java statements, must be terminated with a semicolon ;. Program Game.java, presented as a program description on the following page opening, is an example program where two variables of type int are defined and used. The program is an extremely simple computer game. Unfortunately it is not a fair game because the user of the program will always lose. The program always wins by presenting an integer that is one larger than the number given by the user of the program. A source program like Game.java is a text file in a computer's hard disk memory before it is compiled. When the source program Game.java is compiled, we get a file named Game.class which is an executable version of the program. The compiler is a computer tool that can convert a source program into executable form. The compiler reads and processes a source program file in the same order in which it is written. While compiling program Game.java, the compiler sees first the variable definitions and reserves main memory for the variables. Then it transforms the remaining statements, the action statements, to numerical instructions to be processed during program execution. The action statements in a source program describe the activities a computer performs when the executable version of a source program is run by a computer. The action statements of a program are executed in an order that corresponds with the order in which the statements are written in the source program. In the case of the program Game.java, the computer will perform the following activities: First it asks the user to enter an integer from the keyboard. Then it reads the integer from the keyboard and stores it in variable integer_- from_keyboard. Then it calculates a value that is one larger than the user-given integer and stores that value in variable one_larger_integer. In the end, it displays the values of both variables and informs the user that the computer won the game. There are four action statements in Game.java. Each statement is terminated with a semicolon ;. The variable definitions in the beginning are also statements, but they are not action statements. Variable definitions just reserve memory to store information.

5.1 Integer variables (int, short, long, byte, char) 99 Although the memory space that is reserved for an int variable is rather large, 4 bytes, there are always limitations how big values can be stored in an int variable. A 4- byte int variable can store values in the ranges -2,147,483,648,..., -1, 0, 1,..., 2,147,483,647 (decimal numbering system) -800000,..., -1, 0, 1,..., 7FFFFFFFH (hexadecimal numbering system) A 4-byte int can thus store 4,294,967,296 (1000000) different values. To demonstrate the difficulties that arise when the storage capacity of an int variable is exceeded, program Game.java is also executed with too great an input value in the program description. As the computer uses 4-byte int variables, and it tries to increment the value 2,147,483,647, it results in number -2,147,483,648 and not in 2,147,483,648. To explain this strange behavior of the program, we must remember that the memories of computers can contain only non-negative binary numbers. Negative numbers are represented so that some positive values stored in memory are considered as negative numbers. For example, the value 2,147,483,648 is treated as -2,147,483,648. The values that can be contained in 4-byte int variables have the following meanings: VALUE IN MEMORY MEANING IN PROGRAM 2,147,483,648 (800000) -2,147,483,648 2,147,483,649 (80000001H) -2,147,483,647 2,147,483,650 (80000002H) -2,147,483,646.... 4,294,967,294 (FFFFFFFEH) -2 4,294,967,295 (FFFFFFFFH) -1 0 0 1 1.... 2,147,483,646 (7FFFFFFEH) 2,147,483,646 2,147,483,647 (7FFFFFFFH) 2,147,483,647 Figure 5-1 shows how a 4-byte integer variable looks like when it is in the main memory of a computer. Those four bytes are reserved from somewhere in the main memory. We do not need to know the exact memory address. We only need to know that there are four contiguous memory locations., We can imagine that the main memory of the computer is a long list of single-byte memory cells, and each byte has a unique address. A 32-bit int variable reserves four bytes. There are many bytes preceding and following the variable in the memory. 1 1 0 1 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 D2H 04H In personal computers and many other computers, the four bytes of an int variable are organized so that the least significant byte, which stores the 8 least significant bits of the number, is in a memory location that has the smallest numerical address. The three other bytes are in subsequent memory locations. Figure 5-1. Value 1234, 4D2H, stored in a 4-byte int variable in a computer s main memory.

100 Chapter 5: Variables and other basic elements in Java programs (c) Kari Laitinen www.naturalprogramming.com This line is not actually part of the program. This is a comment line that gives documentary information to the reader of the program. A double slash // marks the beginning of a comment line. The compiler ignores the double slash and the text that follows it on the same line. In Java programs, this kind of definition must be placed inside the parentheses after the method name main. This definition resembles a variable definition, but actually it is not a variable definition. The name of the "variable" here is not_used simply because it is not used in the program. When we will later use this "variable" in a program, it will be given a more meaningful name. // Game.java (c) Kari Laitinen class Game public static void main( String[] not_used ) int integer_from_keyboard ; int one_larger_integer ; Here two integer variables are defined. The names of the variables are integer_from_keyboard and one_larger_integer. The variables are referred to with these names later in the program. System.out.print( "\n This program is a computer game. Please, type in " + "\n an integer in the range 1... 2147483646 : " ) ; integer_from_keyboard = Console.readInt() ; one_larger_integer = integer_from_keyboard + 1 ; System.out.print( "\n You typed in " + integer_from_keyboard + "." + "\n My number is " + one_larger_integer + "." + "\n Sorry, you lost. I won. The game is over.\n") ; This line of source code reads an integer from the keyboard and stores the read integer into variable integer_from_keyboard. The execution of the program stays on this line until the user of the program has entered an integer. This statement is executed so that a method named readint() from a class named Console is used to get the integer value from the keyboard. Texts inside double quote characters " " are strings of characters that will be displayed on the screen. \n among the text means that the text will begin from a new line. \n is said to be the newline character. Game.java - 1.+ A program that implements a simple computer game.

5.1 Integer variables (int, short, long, byte, char) 101 By writing System.out.print(... we invoke a method named print() that prints data to the system s standard output device, the screen. Here, the text that is going to be printed to the screen consists of two strings of characters. These two character strings are concatenated with operator +, and the text is given inside parentheses to the print() method. After this assignment statement has been executed, the value of variable one_larger_integer is one greater than the value stored in integer_from_keyboard. System.out.print( "\n This program is a computer game. Please, type in " + "\n an integer in the range 1... 2147483646 : " ) ; integer_from_keyboard = Console.readInt() ; one_larger_integer = integer_from_keyboard + 1 ; System.out.print( "\n You typed in " + integer_from_keyboard + "." + "\n My number is " + one_larger_integer + "." + "\n Sorry, you lost. I won. The game is over.\n") ; It is possible to output many types of data in a single call to method print(). Here the values of the integer variables are displayed between strings of characters given inside double quotes. Operator + is placed between different types of data. The operator + converts the numerical values stored in the variables to character strings, and joins these numerical strings to the character strings given inside double quotes. A semicolon ; terminates the entire statement. Game.java - 1-1. The action statements of the program. D:\javafiles2>java Game This program is a computer game. Please, type in an integer in the range 1... 2147483646 : 1234 You typed in 1234. My number is 1235. Sorry, you lost. I won. The game is over. D:\javafiles2>java Game This program is a computer game. Please, type in an integer in the range 1... 2147483646 : 2147483647 You typed in 2147483647. My number is -2147483648. Sorry, you lost. I won. The game is over. Game.java - X. In the second execution too large an input value is given to the program.

102 Chapter 5: Variables and other basic elements in Java programs (c) Kari Laitinen www.naturalprogramming.com In addition to variables of type int, Java has other types of integer variables. These variables are sometimes called integral types. Type long is another integer type. Variables of type long occupy 8 bytes (64 bits) of memory. They are thus longer integer variables than variables of type int. If we defined the variables of program Game.java like long integer_from_keyboard ; long one_larger_integer ; the program would work correctly with much larger numbers as it does now. A third integer variable type is short which is a 2-byte, 16-bit, variable. This type may be useful when your program uses only integer values that are smaller than 32,767. If you need to store very many such values, you can save some memory when you use type short instead of type int. In small programs, though, there is no need to use variables of type short because memory is rather abundant in modern computers. A special integer variable type is byte which can be used to store information in 8- bit bytes. A byte variable can store values in the range -128... 127. A variable of type byte occupies a single byte of memory. Variables of type char are 2-byte (16-bit) variables that are used to store 16-bit Unicode character codes. The first 256 Unicodes are the same as the codes in the ASCII coding system. char variables are like integer variables because the used character codes are integer values. However, it is better not to use char variables in situations where integer variables are needed. The integer types int, short, long, etc. will be used when we need to store whole numbers in our computer programs. The most common integer type is int. Integer variables are convenient when we want to count something in our programs. Table 5-1 summarizes the integer types and other variable types in Java. The other variable types will be discussed later in this chapter. Type boolean is a special variable type to define so-called boolean variables. Boolean variables can be given only two values: true and false. We shall study these variables in more detail when we encounter them in some example programs. Exercises with program Game.java Exercise 5-1. Exercise 5-2. Modify the program so that it always loses the game by presenting a number which is one smaller than the number given by the user. With operator - it is possible to perform subtractions in Java. Modify the program so that it prints three numbers that are larger than the number given by the user. For example, if the user types in 144, the program must print 145, 146, and 147.

5.1 Integer variables (int, short, long, byte, char) 103 Table 5-1. Variable types (built-in types) of Java. Type Size Storage capacity int 4 bytes 32 bits -2,147,483,648... 2,147,483,647-800000... 7FFFFFFFH short 2 bytes 16 bits -32,768... 32,767-80... 7FFFH long 8 bytes 64 bits -9,223,372,036,854,775,808... 9,223,372,036,854,775,807-80000000000000... 7FFFFFFFFFFFFFFFH byte 1 byte 8 bits -128... 127-80H... 7FH boolean 1 byte 8 bits a false or true char 2 bytes 16 bits Unicode 0... 65535 float 4 bytes 32 bits Precision: 7 decimal digits Range: +/- 1.5e-45... 3.4e38 b double 8 bytes 64 bits Precision: 15 decimal digits Range: +/- 5.0e-324... 1.7e308 memory address c 4 bytes 32 bits Sufficient for addressing up to 4,294,967,296 bytes (4 gigabytes) of main memory. a. This is a guess because Java books do not usually specify how much memory is needed to store a variable of type boolean. The minimum amount of memory needed to store a boolean value is a single bit, but it is hard for a processor of a computer to allocate memory in single bits. A byte is usually the smallest piece of memory that can be allocated by a processor. The memory for an array of type boolean might, though, be allocated in single bits. b. The ranges that are given here are approximate. c. "memory address" is not a variable type in Java. This row describes how much memory is needed when an object reference is defined. These are sample pages from Kari Laitinen s forthcoming book "A Natural Introduction to Computer Programming with Java". More information at www.naturalprogramming.com

104 Chapter 5: Variables and other basic elements in Java programs (c) Kari Laitinen www.naturalprogramming.com 5.2 Keywords, names, spaces, and newlines Java source programs contain special characters or character pairs such as,, (, ), =, ;, ", \n, and +; and natural-language expressions such as static, void, main, int, System, and integer_from_keyboard. Both the special characters and natural-language expressions are meaningful for the Java compiler. When the compiler starts compiling a Java source program, it reads a text file that contains character codes. Depending on what the compiler reads from the source program file, it creates the corresponding.class file, the result of the compilation process. With the special characters and natural-language expressions we tell the compiler what kind of executable file it should create. Keywords of a programming language are words or abbreviations borrowed from a natural language for special purposes. The compiler of the programming language uses the keywords to detect syntactic structures in source programs. Keywords cannot be used as names in programs. For this reason keywords are called reserved words of the programming language. Java has the following keywords abstract boolean break byte case catch char class const continue default do double else extends final finally float for goto if implements import instanceof int interface long native new null package private protected public return short static super switch synchronized this throw throws transient try void volatile while The keywords will be explained in the following chapters, as we encounter them in example programs. All keywords are listed and discussed briefly in Appendix B. A name in a source program is a natural-language expression invented by the writer of the program. Names are also called symbols or identifiers in programming terminology. Program Game.java contains variable names integer_from_keyboard and one_larger_integer. main() is the name of the main method of the program, print() is the name of the method with which we can write text to the screen, and read- Int() is the name of a method that can read an integer number from the keyboard. Although main and print are not official keywords of Java, they should almost be treated as such because the main method of a Java program must be called main() and print is an official name defined in the standard Java class. (Note that there is a pair of empty parentheses () at the end of the name main. Those parentheses do not belong to the method name. They are just a means to distinguish method names from other names in the body text of this book.) In this book, we use natural names in the source programs. Natural names are such that they consist of natural English words. The name of a variable should describe the purpose of the variable. Natural names with carefully selected words usually fulfil this requirement. Because computer programs are always rather complex, they should be made as easy to read as possible. The use of natural naming makes source programs readable and understandable. The words of a natural name can be joined with underscore characters _ or capitalization can be used to mark the beginning of a new word in a name. In this book, the names of variables are constructed so that the words are joined with underscore characters. Standard Java names like tostring and lastindexof, which we ll encounter later in this book, are constructed by using capitalization, i.e., an uppercase letter starts a new word in a name. Natural names are important for human readers, but compilers treat source programs in a very technical manner. From the compiler s point of view, a name does not necessarily need to be natural. The following are the technical rules for writing a name in Java:

5.2 Keywords, names, spaces, and newlines 105 A name must be a continuous sequence of characters. You may not include spaces, newline characters, or other special characters in a name. (In the body text and text balloons of this book, a name is sometimes hyphenated, i.e., a name continues on the following line. Hyphenation is not, however, allowed in source programs. A name may not continue on the following line in program text.) The first character of a name must be a letter or an underscore _. The characters following the first character must be letters, numbers, or underscores. This means that a number cannot start a name, but numbers are allowed after the first character. According to these rules, all the following variable definitions would be acceptable for a Java compiler: int i ; int xxx ; int some_integer ; int SOME_INTEGER ; int someinteger ; int xx ; int x2 ; Java compiler allows short and abbreviated names, but it is better to use natural names because they increase the readability of programs. Inventing informative natural names is also a means for thinking in the process of program writing. When a compiler detects something illegal in a source program, it displays an error message on the screen. It is also possible to make errors with the names. For example, the definition int 1_larger_integer ; is illegal because a number may not start a name. The definitions int integer from keyboard ; int some-other-integer ; are not acceptable because a name may not contain characters and -. The use of spaces is important in Java programs. There must be at least one space character between a keyword and a name. For example, the variable definition intinteger_from_keyboard ; Although these names contain the same words, all these names are considered different names by the compiler. would result in a compilation error because the compiler could not distinguish keyword int from the variable name. Generally, you do not need spaces between special characters and names, but the use of spaces makes the source code more readable. The two source code lines one_larger_integer=integer_from_keyboard+1; one_larger_integer = integer_from_keyboard + 1 ; are the same in technical sense but the latter is easier to read because of the use of spaces. If you want, you may write more than one space in all those places of a Java program where spaces are allowed. In all those places where a space is allowed, a newline character or a tabulator character is also allowed. There is a newline character at the end of every line of a Java program. When you insert empty lines in a program, you actually insert newline characters into the source program file. When you have a complex statement in a program, it is sometimes necessary to split the statement on several source program lines. The general rule in splitting statements is that you may add a newline character to all those places where a space can be added. This means in practice that names must remain intact when a statement continues on the following line.

106 Chapter 5: Variables and other basic elements in Java programs (c) Kari Laitinen www.naturalprogramming.com 5.3 Floating point variables Integer variables are convenient when we want to count something. But when we want to deal with something related to the real world, integer variables are often not sufficient. To store such values as 3.1416, the value of pi, and 6,378.16, the equatorial radius of the Earth in kilometers, Java has floating point variables. They can be defined by using keywords float or double. Program Miles.java is an example that uses floating point variables of type float. The program asks the user to give a distance in miles, and then converts the given distance to kilometers. Because one mile is 1.6093 kilometers, the program must use floating point variables to make these conversions accurately. An integer variable cannot contain a value which has a decimal point. Floating point variables are based on the idea that every number with a decimal point can be expressed in exponential notation, a notation frequently used by scientists who make calculations with very large or very small numbers. The following are examples of numbers presented in exponential notations (* means multiplication and. is the decimal point) "NORMAL" NOTATION EXPONENTIAL NOTATIONS 2,000,000,000,000 2.0 * 10 12 2.0e12 299,800,000 2.998 * 10 8 2.998e8 0.000,000,123 1.23 * 10-7 1.23e-7 0.000,000,000,002 2.0 * 10-12 2.0e-12 In exponential notation, a number is presented with two parts: a mantissa and an exponent. In the case of the first number above, the mantissa is 2.0 and the exponent is 12. The mantissa indicates "how much" the number is and the exponent tells how many times the mantissa must be multiplied by ten, or divided by ten in the case of negative exponents, to get the "normal" form of the number. The exponential notation is thus based on the fact that every number can be expressed as its "mantissa" times 10 to the power of its "exponent". Here you must again remember that 10 to the power of zero is one. Floating point variables store numbers in exponential notation. The mantissa and exponent are stored separately as binary numbers. A floating point variable of type float occupies 4 bytes of memory, and a variable of type double occupies 8 bytes of memory. The internal structure of floating point variables is rather complex. The Java compiler uses the 32 bits of a float variable so that 8 bits are used to store the exponent, 23 bits are used to store the mantissa, and the remaining 1 bit is used to store the sign (plus or minus). The more precise floating point type double uses more bits for the mantissa and exponent. Usually a programmer does not need to worry about the internal structure of floating point variables. The compiler and the computer ensure that calculations with floating point variables are carried out in a correct manner. If we define a floating point variable like float a_float_variable ; the compiler reserves four bytes of main memory for the variable. When we assign a value for the variable with statement a_float_variable = 12.34F ; the compiler takes care that the floating point literal constant 12.34F is converted to the exponential notation used in float variables, and stores the literal to the reserved four bytes for that notation. Note that letter F must be written at the end of a literal constant of type float.

5.3 Floating point variables 107 Here, keyword float is used to define two single-precision floating point variables. These variables can store numbers with a decimal point. // Miles.java * is the multiplication operator of Java. As one mile is 1.6093 kilometers, miles can be converted to kilometers by multiplying the distance in miles by 1.6093. After this statement has been executed, the contents of variable distance_in_kilometers is 1.6093 times the contents of variable distance_in_miles. Note that the letter F is written after the numerical digits in the literal 1.6093F. That letter indicates that the literal is of type float. class Miles public static void main( String[] not_used ) float distance_in_miles ; float distance_in_kilometers ; System.out.print( "\n This program converts miles to kilometers." + "\n Please, give a distance in miles: " ) ; distance_in_miles = Console.readFloat() ; distance_in_kilometers = 1.6093F * distance_in_miles ; System.out.print( "\n " + distance_in_miles + " miles is " + distance_in_kilometers + " kilometers." ) ; Here the distance in miles is read from the keyboard. The program waits here until the user has typed in the distance. After this statement has been executed the given distance is stored in variable distance_in_miles. This statement prints information to the screen. The values of variables distance_in_miles and distance_in_kilometers are converted to strings of characters, and those strings are printed between the characters that are given inside double quotes. Miles.java - 1. A program that uses floating point variables. D:\javafiles2>java Miles This program converts miles to kilometers. Please, give a distance in miles: 250 250.0 miles is 402.325 kilometers. Miles.java - X. The execution of the program with input value 250.

108 Chapter 5: Variables and other basic elements in Java programs (c) Kari Laitinen www.naturalprogramming.com A programmer must know when to use floating point variables instead of integer variables. Floating point variables are often used when we are dealing with things that can be measured: distances, weights, currencies, temperatures, etc. Integer variables are used in counting. When a floating point variable is used, the programmer needs to select the correct floating point type. The capacities of floating point variables are expressed in Table 5-1. Generally, the type double is used when a high level of precision is required in calculations, but the type float is sufficient for many situations. Do not use tabulator characters in source programs The tabulator character, or "tab", which has the character code 09H, may seem to be useful when you write a computer program with a program editor. You can put a tabulator in all those places where a space is allowed. A tabulator character corresponds to, for example, 4 spaces in the program editor. But the use of tabulator characters causes problems in the long run. If your program editor treats tabulators equal to 4 spaces, your printer may think that they are 8 spaces, and you end up having different kinds of programs on the screen and on paper. Similar problems may occur if you start editing a program with a new program editor. To avoid these kinds of problems, it is better not to use the tabulator character in source programs. It is always possible to use several spaces instead of a tabulator, and most program editors can be configured so that they insert 3 or 4 spaces into the program when the tabulator key is pressed.

5.4 Operators, assignments, and literal constants 109 5.4 Operators, assignments, and literal constants Program Game.java, which we studied earlier, has the following assignment statement one_larger_integer = integer_from_keyboard + 1 ; In this statement the two variable names refer to previously defined variables, 1 is a literal constant, or integer literal, + is the addition operator, = is the assignment operator, and ; terminates the entire statement. All these separate elements of the statement are recognized and processed by the compiler. An assignment statement is executed so that what is on the right side of the assignment operator = is processed first, and then the result is assigned as a value to the left side. When a computer executes the statement above, it first calculates the value of the arithmetic expression integer_from_keyboard + 1 and then it assigns the result as a value to variable one_larger_integer. In an assignment operation only the left side gets a new value. The value of variable integer_- from_keyboard does not change in the above statement. The variable one_larger_integer loses its previous value and gets a new value. We have thus far encountered two arithmetic operators, the addition operator + and the multiplication operator *. A new arithmetic operator, the division operator /, is used in program Distance.java. That program can make conversions from meters to other units of distance. For example, the conversion from meters to light years is made with the assignment statement distance_in_light_years = distance_in_meters / ( 2.99793e8 * 365 * 24 * 3600 ) ; When the computer executes this statement, it performs activities in the following order: It first evaluates the value of the expression 2.99793e8 * 365 * 24 * 3600 because this expression is written inside parentheses. The calculated value is 9.45427e15 which is nearly the correct value of the length of one light year in meters. It divides the contents of the variable distance_in_meters by the calculated value 9.45424e15. The value of distance_in_meters does not change in this operation. The result of the division is stored in the variable distance_in_light_years whose previous contents are overwritten. The previous contents are not important in this case. In addition to arithmetic operators +, *, and /, Java also has the arithmetic operator - to perform subtraction operations. All these operators will be used throughout the book. All Java operators are summarized in Appendix A.

110 Chapter 5: Variables and other basic elements in Java programs (c) Kari Laitinen www.naturalprogramming.com As usual, method main() is written inside a class. Here the name of the class is Distance. At this point of our studies, we write static methods inside class definitions, but we do not pay much attention to the class itself. All values are stored in double-precision floating point variables in this program. It is possible to define several variables of the same type in a long definition statement. In this definition, variable names are separated with commas, and there is only one semicolon ; at the end. When you define variables in this way, you avoid repeating the type keyword, which is double in this case. // Distance.java (c) 2003 Kari Laitinen class Distance public static void main( String[] not_used ) double distance_in_meters, distance_in_kilometers, distance_in_miles, distance_in_yards, distance_in_feet, distance_in_inches ; double distance_in_light_years ; System.out.print( "\n This program converts meters to other units of" + "\n distance. Please, enter a distance in meters: " ) ; distance_in_meters = Console.readDouble() ; distance_in_kilometers = distance_in_meters / 1000.0 ; distance_in_miles = 6.21371e-4 * distance_in_meters ; distance_in_yards = 1.093613 * distance_in_meters ; distance_in_feet = 3.280840 * distance_in_meters ; distance_in_inches = 12 * distance_in_feet ; distance_in_light_years = distance_in_meters / ( 2.99793e8 * 365 * 24 * 3600 ) ; System.out.print( "\n " + distance_in_meters + " meters is: \n" + "\n " + distance_in_kilometers + " kilometers" + "\n " + distance_in_miles + " miles" + "\n " + distance_in_yards + " yards" + "\n " + distance_in_feet + " feet" + "\n " + distance_in_inches + " inches" + "\n " + distance_in_light_years + " light years\n" ) ; Distance.java - 1.+ A program to convert meters to other units of distance.

5.4 Operators, assignments, and literal constants 111 As one meter is 1.093613 yards, you can get the distance in yards simply by multiplying the metric distance by this literal constant. After this statement is executed, the result of the multiplication is stored in distance_in_yards. distance_in_kilometers = distance_in_meters / 1000.0 ; distance_in_miles = 6.21371e-4 * distance_in_meters ; distance_in_yards = 1.093613 * distance_in_meters ; distance_in_feet = 3.280840 * distance_in_meters ; distance_in_inches = 12 * distance_in_feet ; distance_in_light_years = distance_in_meters / ( 2.99793e8 * 365 * 24 * 3600 ) ; This literal constant, which shows the speed of light in meters per second, is a floating point literal written in exponential notation. The same value could be written without the exponent: 299793000. You cannot include any spaces in a literal constant. 2.99793 e8 would be an illegal definition. The calculations inside parentheses are carried out before any other calculations. In this case, the length of one light year is calculated first, before it is used as a divider. In these calculations, 365 means the number of days in a year, 24 is the number of hours in each day, and 3600 is the number of seconds in every hour. Distance.java - 1-1. The assignment statements of the program. D:\javafiles2>java Distance This program converts meters to other units of distance. Please, enter a distance in meters: 40075160 4.007516E7 meters is: 40075.16 kilometers 24901.54224436 miles 4.382671595308E7 yards 1.3148018793439999E8 feet 1.5777622552128E9 inches 4.238841424970174E-9 light years This is the length of the equator of the Earth in meters. Distance.java - X. The program executed with input value 40075160.

112 Chapter 5: Variables and other basic elements in Java programs (c) Kari Laitinen www.naturalprogramming.com Exercises with program Distance.java Exercise 5-3. A light year is the distance which light travels in one year. It is a huge distance. Program Distance.java makes a small mistake when it calculates the length of a light year because it supposes that there are exactly 365 days in a year. A more correct duration for a year is 365 days and 6 hours. Modify program Distance.java so that it calculates a better value for the length of a light year. Remember that those calculations which are inside parentheses are executed first. Exercise 5-4. A furlong is a unit of distance which has been used in some cases in some countries. 1 furlong is exactly 660 feet. Improve program Distance.java so that it prints the distance also in furlongs. These are sample pages from Kari Laitinen s forthcoming book "A Natural Introduction to Computer Programming with Java". More information at www.naturalprogramming.com

5.4 Operators, assignments, and literal constants 113 Programming languages have operators in order to perform various operations in a program. The term "operand" is used to describe the participants of an operation. For example, in the arithmetic operation 1.6093F * distance_in_miles 1.6093F and distance_in_miles are operands to the multiplication operator *. 1.6093F, which is a literal constant of type float, is the left operand. Variable distance_in_miles is the right operand. Operands can be complex expressions such as (2.99793e8 * 365 * 24 * 3600). Complex expressions themselves contain operators and operands. When a complex expression is an operand, the value of the expression is evaluated before it is used as an operand. The numerical values that are used in programs are called literal constants or just literals in the programming terminology. Program Distance.java contains, for example, the literal constants 1000.0 6.21371e-4 1.093613 which are all floating point literals because they include a decimal point. A floating point literal represents a value that can be stored in a floating point variable. Floating point literals should not be assigned as values to integer variables. Integer literals such as 12, 365, and 3600 do not contain a decimal point. Usually it is possible to assign an integer literal as a value to a floating point variable. Sometimes you may need an integer literal that is of type long. Such a literal can be specified by writing letter L in the end of the literal (e.g. 12345678L). As you saw in program Miles.java, a floating point literal must have suffix F or f at the end before it can be assigned to a variable of type float. The world of computers is a binary one. Because hexadecimal numbers are convenient to express binary quantities, numbers stored in integer variables are often expressed as hexadecimal numbers. To assign hexadecimal values to variables, Java provides hexadecimal literals which are written by using the prefix 0x, a zero followed by the letter x. For example, the decimal numbers 10, 255, 258, and 65535 can be written as hexadecimal literals in the following way 0xA 0xFF 0x102 0xFFFF The following two statements are the same from the Java compiler s point of view some_variable = 31 ; some_variable = 0x1F ; The compiler recognizes numerical literals in program text because they start with a numerical character. To make literals different from names, Java has a rule that names may not begin with a numerical character. The letter x in a hexadecimal literal makes the compiler treat the numerical characters as hexadecimal digits. When the compiler reads a literal, it detects the end of the literal when it sees a character which is not a numerical digit. Spaces may not be used inside literals. For example, it would be an error to write mean_distance_to_moon_in_kilometers = 384 400 ; because the compiler would not understand the literal as 384400 but as two separate literals 384 and 400. Although both literals and variables represent information that is processed by the action statements of a program, a literal in a source program is a kind of opposite to a variable. The value of a literal is fixed, while the value of a variable usually changes when a program is being executed. Literals may appear only on the right side of assignment statements. The left side of an assignment statement is a variable in our first example programs.

114 Chapter 5: Variables and other basic elements in Java programs (c) Kari Laitinen www.naturalprogramming.com 5.5 Reading data from the keyboard a first look at strings The programs that have already been presented in this chapter have shown that it is possible to read various values from the keyboard with statements like an_int_variable = Console.readInt() ; a_float_variable = Console.readFloat() ; a_double_variable = Console.readDouble() ; These statements are such that the execution of a program stays on these statements as long as the user has typed in something from the keyboard. After the statements are executed, the variables on the left side of the assignment operator = have got new values. These statement use special methods for reading data from the keyboard. The methods for reading data from the keyboard, readint(), readfloat(), readdouble(), etc., are provided in a class named Console. A method of a class like Console can be invoked (called) by using the dot operator. in the following way ClassName.methodName(... ) ; The dot operator. must be written between the name of the used class and the name of the method. Inside parentheses it is possible to provide information (parameters) that the used (called) method exploits or needs. The Console class is not a standard Java class, but it is very common to use this kind of class in simple Java programs. Therefore, also this book provides a Console class for you to use. The class is stored in the file Console.java, and that file is shown entirely in Appendix E. At this point of your studies you are not supposed to understand everything that is said in Appendix E. In order to use the methods of the Console class, you must have the file Console.java in the same directory (folder) in which you store the Java programs that exploit the Console class. In addition to the above mentioned methods, the Console class provides methods for reading values of types byte, short, long, char, and String. The methods to read these types of values from the keyboard can be used in the following way a_byte_variable = Console.readByte() ; a_short_variable = Console.readShort() ; a_long_variable = Console.readLong() ; a_char_variable = Console.readChar() ; line_of_text = Console.readLine() ; In some cases it is necessary to treat the keyboard input as a hexadecimal string or a binary string, i.e., your program wants to read a hexadecimal number (e.g. 9AF) or a binary number (e.g. 101100) from the keyboard. For these situations, the Console class provides methods readinthexadecimal() and readintbinary(). These methods can be used in the following way an_int_variable = Console.readIntHexadecimal(); an_int_variable = Console.readIntBinary(); Reading information from the keyboard is usually more difficult than writing information to the screen. One problem in an input operation like reading from the keyboard is that the user of the program may type in wrong kind of information. The user may type in letters when he or she should type in numbers, or the user may type in a decimal point when integer values are expected. In these kinds of situations the conversion method usually throws a so-called exception, and the program terminates in a strange way. When this happens your computer screen shows a text in which the word "exception" is mentioned several times. You should not panic in this situation. Later on we will learn to do some-

5.5 Reading data from the keyboard a first look at strings 115 thing to the exceptions. When the various methods of class Console read numerical information from the keyboard, the information is first read in the form of a text line, and then the text line is converted to a suitable form of information. Information from the keyboard comes in the form of single characters, and these characters form a text line that can be converted to a pure numerical value. When there is a statement like integer_from_keyboard = Console.readInt() ; in a program, the statement could be replaced with the more complex statement integer_from_keyboard = Integer.parseInt( Console.readLine() ) ; In the above statement, the method readline() of class Console is first used (called) to read a line of text from the keyboard, and then the parseint() method of the standard class Integer is used to convert the text line to a value of type int. The readint() method of class Console uses this kind of conversion technique when it processes a line of text that it gets from the keyboard. What the Console.readLine() method returns to a program when it reads data from the keyboard, is an object of type String. A String object is a kind of variable that can store a string of characters (sequence of character codes). In the above statement the read text line is not stored anywhere, so it may be difficult to understand how the statement works. The operation of the above statement can be made more concrete if we first define a String object (variable) like String line_of_text ; and replace the above statement with the statements line_of_text = Console.readLine() ; integer_from_keyboard = Integer.parseInt( line_of_text ) ; These two statements work in the same way as the single statement above. You should think that these statements operate from right to left: First the readline() method of class Console reads a line of text from the keyboard, and then the text line is assigned as a value to the String object (variable) line_of_text. Then the text line that is stored in line_of_text is passed to method parseint() of class Integer. Method parseint() converts the text line to a value of type int, and the value is assigned to variable integer_from_keyboard. The method Integer.parseInt() is always available in Java programs because Integer is a standard core Java class. Figure 5-2 explains how numerical information is converted from a sequence of character codes to a binary numerical value when a value of type int is read from the keyboard. Conversions like the one shown in Figure 5-2 are necessary because in a text line that is received from the keyboard the numerical information is in the form of character codes, and in order to calculate with the numerical information it must be in binary form stored in a variable of type int.

116 Chapter 5: Variables and other basic elements in Java programs (c) Kari Laitinen www.naturalprogramming.com The drawing below describes what happens when this statement is executed so that the user of the program types in 556601. This part of the statement, which is inside parentheses, is executed first. The program execution stays here until the user has typed in the number from the keyboard. In this operation, method readline() of class Console is called to read a line of text from the keyboard. integer_from_keyboard = Integer.parseInt( Console.readLine() ) ; After method readline() has done its job, the read line of text is supplied to method parseint() of class Integer. Method parseint() converts the line of text to a 32-bit int value which is later stored to variable integer_from_keyboard. What method readline() gets from the keyboard is a sequence of 16-bit character codes. As we suppose that the user types in number 556601, the input from the keyboard looks like this sequence of bytes. Here the 16-bit character codes are stored in two bytes so that the more significant byte comes after the less significant byte. In each character code, the more significant byte is zero because the values of the character codes are small numbers, less than FFH. When the input from the keyboard is converted, and stored in integer_from_keyboard, it looks like this in the main memory. 556601 is 00087E39H in hexadecimal form. The least significant byte is stored first in the memory. 35H 35H 36H 0035H, code of character 5 0035H, code of character 5 0036H, code of character 6 39H 7EH 08H CONVERSION 36H 30H 31H 0036H, code of character 6 0030H, code of character 0 0031H, code of character 1 Figure 5-2. Reading value 556601, 87E39H, from the keyboard.

5.6 The double role of operator + 117 5.6 The double role of operator + You have certainly learned to use the plus sign + when you have attended mathematics lessons at school. The statements of Java resemble mathematical notations in that the plus sign serves as the addition operator that can be used to write statements like one_larger_integer = integer_from_keyboard + 1 ; sum_of_integers = first_integer + second_integer ; In the case of these statements, the Java compiler detects that the plus sign is used between an integer variable and an integer literal constant, or between two integer variables, and the compiler treats the plus sign as the addition operator. Similarly, the plus sign serves as the addition operator when it is used between floating point variables or between some other program constructs that represent numerical values. The plus sign has, however, also another role in Java. It can be used as a concatenation operator that can concatenate strings of characters. Concatenation means joining two character strings to produce a single longer character string. Concatenation is needed, for example, when you want to produce several lines of text to the screen with a single call to method System.out.print(). In the following statement, method System.out.print() is called so that the string that is printed to the screen is made by concatenating three separate string literals that are written inside double quotes: System.out.print( "\n This is first line." + "\n This is second line." + "\n This is third line." ) ; When the Java compiler processes the above statement, it detects that the plus sign + is used between string literals, and therefore it interprets the plus sign as the concatenation operator and not as the addition operator. In Java, a string literal like "some text" is of type String. The double quote characters are the symbols that make the compiler to distinguish string literals from other program constructs. The double quotes do not belong to the characters of the string literals above. When the concatenation operator + is used between a string literal and a variable, a conversion operation takes place before the concatenation. For example, in the statement System.out.print( "Number is " + some_integer ) ; the concatenation operator is written between the string literal "Number is " and variable some_integer. When this statement is executed, the value of variable some_- integer is first converted to a string of characters, and then the resulting string is joined to the string literal "Number is ". Figure 5-3 describes what happens in the conversion and concatenation operations. Operator + can be used several times in a single statement. How the operator is interpreted by the compiler, depends on what is written to the left side and right side of the operator. Because operator + is left-to-right associative, longer expressions are evaluated so that the leftmost plus sign is applied first. For example, when the expression some_integer + some_integer + "xxxx" + "yyyy" is processed, the leftmost plus sign is first used as an addition operator, and the sum some_integer + some_integer is calculated. Then the other two plus signs are interpreted as concatenation operators, which means that the calculated sum is converted to a string of characters, and the string literals "xxxx" and "yyyy" are joined to the calculated sum.