Java the UML Way version 2002-04-17 Only to be used in connection with the book "Java the UML Way", by Else Lervik and.

Slides:



Advertisements
Similar presentations
L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
Advertisements

Introduction to C Programming
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
Variables Pepper. Variable A variable –box –holds a certain type of value –value inside the box can change Example –A = 2B+1 –Slope = change in y / change.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Data types and variables
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Chapter 2 Data Types, Declarations, and Displays
Introduction to C Programming
Hello, world! Dissect HelloWorld.java Compile it Run it.
Objectives You should be able to describe: Data Types
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Chapter 2 Primitive Data Types and Operations F Introduce Programming with an Example  The MyInput class F Identifiers, Variables, and Constants F Primitive.
Chapter 4 Variables and Constants. Goals and Objectives 1. Understand simple data types (int, boolean, double). 2. Declare and initialize variables using.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Input, Output, and Processing
Chapter 2: Using Data.
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Java the UML Way version Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
Week 1 Algorithmization and Programming Languages.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 2: Variables & Data Types.
College Board A.P. Computer Science A Topics Program Design - Read and understand a problem's description, purpose, and goals. Procedural Constructs.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
PHY-102 SAPVariables and OperatorsSlide 1 Variables and Operators In this section we will learn how about variables in Java and basic operations one can.
Chapter 2 Variables.
Chapter 4 Literals, Variables and Constants. #Page2 4.1 Literals Any numeric literal starting with 0x specifies that the following is a hexadecimal value.
Java Programming, Second Edition Chapter Two Using Data Within a Program.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
COMP Primitive and Class Types Yi Hong May 14, 2015.
Programming in Java (COP 2250) Lecture 4 Chengyong Yang Fall, 2005.
Data Tonga Institute of Higher Education. Variables Programs need to remember values.  Example: A program that keeps track of sales needs to remember.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
Java the UML Way version Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
COIT29222 Structured Programming 1 COIT29222-Structured Programming Lecture Week 02  Reading: Textbook(4 th Ed.), Chapter 2 Textbook (6 th Ed.), Chapters.
1 Chapter 2: Java Fundamentals cont’d Spring Lory Al Moakar.
1 Week 5 l Primitive Data types l Assignment l Expressions l Documentation & Style Primitive Types, Assignments, and Expressions.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
Introduction to Algorithmic Processes CMPSC 201C Fall 2000.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
Chapter 2 Variables and Constants. Objectives Explain the different integer variable types used in C++. Declare, name, and initialize variables. Use character.
© 2004 Pearson Addison-Wesley. All rights reserved August 27, 2007 Primitive Data Types ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
Java Programming: Guided Learning with Early Objects Chapter 1 Basic Elements of Java.
Chapter 2 Variables.
Chapter 2 Basic Computation
Chapter 2 - Introduction to C Programming
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
Multiple variables can be created in one declaration
Chapter 2 - Introduction to C Programming
Java Programming: From Problem Analysis to Program Design, 4e
IDENTIFIERS CSC 111.
Introduction to C++ Programming
مساق: خوارزميات ومبادئ البرمجة الفصل الدراسي الثاني 2016/2015
Chapter 2 Edited by JJ Shepherd
Chapter 2 Variables.
Expressions and Assignment
Chapter 2: Introduction to C++.
Primitive Types and Expressions
Unit 3: Variables in Java
Chapter 2 Variables.
Chapter 2 Primitive Data Types and Operations
Variables and Constants
Presentation transcript:

Java the UML Way version Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 2 Variables, Data Types, and Expressions The Casepage 2-3 Algorithms and errorspage 4 Test data setpage 5 Statements, blocks and namespage 6 About namespage 7 Variablespage 8-9 Data types for integerspage Data types for decimal numeralspage 12 Data types for boolean values and characterspage 13 A data type for texts: Stringpage 14 Assignments and arithmetical expressionspage 15 Type convertingpage 16-17

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 2, page 2 The Case To renovate an apartment: –How much paint, or wallpaper, will you need for a wall? Or how much flooring? Here: A little program calculating the area of a surface, e.g. a floor or a wall. We'll work with this case throughout the book. At last we'll have a useful program with graphical user interface (Fig. 15.8) Basic questions when solving a programming problem: –Output data: What do we expect to get? What will the program display to the user? –Input data: What has the user to input for the program to produce the given output? In this case: –Output data: the area in square meters –Input data: length and width /* Example Run: Length: 5.8 m Height: 2.4 m The area of the wall is square meters. */ Unfortunately, it is rather difficult to read data into a program in Java. We will postpone this until chapter 3. Instead we will do some simplifications.

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 2, page 3 The Source Code class WallCalculations { public static void main(String[] args) { double length = 5.0; double height = 2.3; double area = length * height; System.out.println("The area of the wall is " + area + " square meters."); } /* Example Run: The area of the wall is 11.5 square meters. */ input data are coded directly into the program, rather than read from the user calculation ouput data 5.0 length 2.3 height 11.5 area Three variables. A variable is a place of storage in the computer's memory. The contents of a variable are interpreted according to the data type. Here the type is a decimal numeral (double). Solve problem no. 2 on page 26.

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 2, page 4 Algorithms and program errors An algorithm is a limited and ordered set of well-defined rules (instructions) for solving a problem. Examples include instruction manuals and cake recipes. Algorithm to calculate the area of a surface: –Input length and height. –Calculate the area according to the formula. –Print out the area. The syntax are rules that the compiler set to our code. The program logics tells us which problems the program solves for us. Program errors: –Syntax error: Words and punctuation are not coded according to the syntax rules.This type of errors are told us by the compiler. –Logical errors: Either we have not programmed the algorithm correct, or the algorithm itself is not correct. The compiler doesn't tell us about these errors. Problem: Create some syntax errors and logical errors in the program at slide 3

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 2, page 5 Test Data A test data set is a set of input and output data whose purpose is to detect logical errors in the program. –Will test the program's outer limits –Test data is seldom realistic data –An example: An archive system for a library has to work for 0 books and for books, as well. Most of the realistic data are somewhere between these limits. –Test data for the Area Program: Data set No. Length Height Expected Result error message Problem: Show how we may test our program with these data sets.

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 2, page 6 class WallCalculations { public static void main(String[] args) { double length = 5.0; double height = 2.3; double area = length * height; System.out.println("The area of the wall is " + area + " square meters."); } Statements, Blocks and Names A statement is an instruction to the computer. It ends with a semicolon. A block is one or more statements surrounded by curly braces {}. The words in a program are either keywords (see Appendix B) or words which are explained to the compiler by declarations. A declaration introduces a new word to the compiler, and it states what it's a name for. In addition to all the declarations that come with Java, we also make our own declarations. Problem: Mark all the blocks, the keywords, the declarations that come with Java, and our own declarations in this well-known program:

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 2, page 7 About Names Syntax: –A name (or identifier) can consist of letters, digits, the underscore character _, and $. –The first character cannot be a digit. –Names cannot include spaces. –Upper- and lower-case letters are distinct characters. –There are no limits on the number of characters in the name. Examples of different valid names: –number, Number, numberOfChildren, student21. Names should evoke immediate associations to the reality the program is modeling.

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 2, page 8 Variables A variable is a place of storage in the computer's memory. A variable contains one value, for example a number or a character. The content of a variable may be changed several times: double price = 14.50; price = 21.70; price = 29.90; A variable declared inside a method is called a local variable. A local variable has to be given a value before it can be used. As a rule the variable gets it's value in the declaration. The variable is initialized. But we may also do it in this way: double price; // this is a declaration without initializing price = 14.50; // here the variable gets it's start value A variable's scope is the part of a program where the declaration is valid. The scope of a local variable is the rest of the block in which it is declared. A variable may have constant content: final double tax = 23.0; final is a modifier; that means it is a keyword that changes the meaning of what follows it. Here the variable gets the property of being non-changeable.

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 2, page 9 Variables, cont. Why do we create a tax variable with constant content instead of just writing the number 23 when we need it? –The name tells the reader more than the number. –If the tax is changed, we only have to change the number in one place, namely the place where the tax variable is declared. –Decimal numerals are the same everywhere. We don't use for example 3.14 one place and in another place. tax is what we call a named constant, while 23 is an anonymous constant or a literal. We make the following recommendations when naming variables: –Use lower case. –Avoid using underscore and $ –If a name is composed of more than one word, every new word should start with a capital letter. For example: numberOfCitiesInBelgium. Solve problems 1 and 2, page 33

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 2, page 10 Data Types for Integers A data type (or just “type”) describes a set of values. We start looking at data types describing integers. Literals: 105, -67, 0, L Variables of integer types: int number = 30; long largeNumber = L; Summary of the integer data types: name no. of bytes range byte 1 [-128, 127] short 2 [ , ] int 4 [ , ] long 8 [ , ] char 2 [0, ]

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 2, page 11 Data Types for Integers, cont. An integer literal starting with the 0 digit is interpreted according to the Base 8 system (the octal system). This is the cause for many strange errors. System.out.println(”Printing 056 gives ” + 056); gives the following printout: Printing 056 gives 46 If we try to store a too large number in an integer variable, we get a compilation error. An example: number = ; However, we do not get an error message if the big number is the result of an integer calculation. What we get is a wrong numerical answer. Division by zero gives an error message, and the program stops.

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 2, page 12 Data Types for Decimal Numerals Literals: 1.25, , 6.7e10 (= 6.7  ), 3.256e-5 (=  ), -4.67F Variables: double number1 = 2.35; float number2 = 2.35f; We have two data types for decimal numerals: –float, 4 bytes, range approx. ±[10-38, 10+38]. The no. of sign digits is approx. 7. –double, 8 bytes, range approx. ±[10-308, ]. The no. of sign digits is approx. 15. The 0.0 value is included in the ranges. Decimal calculations which bring us outside the range, give us an answer. We get Infinity or 0. (This is as opposed to integer calculations, where we get a wrong numerical answer, and no message.) Division by zero gives the Infinity value as the answer. (Integer division by zero gives us an error message and program stop.) The value of the expression 0.0/0.0 is NaN (Not-a-Number). Although we get values as answers, there is no point to continue calculation after we've got values as Infinity and NaN.

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 2, page 13 Data Types for Boolean Values and for Characters A data type for boolean values - boolean –A variable of this type may have true or false as it's value. boolean allWallsArePainted = false; allWallsArePainted = true; A data type for characters - char Literals are surrounded by apostrophes:: ' O ', ' 7 ', ' # ' Variables: char letter = ' A ' ; char digit = ' 4 ' ; Every character has its own code number. – Most programming languages use the ASCII character set. This character set is defined so that each character uses one byte of memory. That means that it can only contain 256 different values. Of these, only the values 0 to 127 are standardized. The other values vary from platform to platform and from country to country. –Java uses the Unicode character set. With two bytes per character at its disposal, it’s possible to store 65,536 different characters. The characters with numbers from 0–127 correspond to the characters with the same numbers in ASCII. Appendix D shows the standardized portion of the ASCII character set. Note the difference between a variable that contains the character '5' (data type char), and one that contains the integer 5 (data type int)

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 2, page 14 A Data Type for Texts: String Literals of this type are surrounded by double quotes: " This is a text " " A " "" Examples: String city = "Trondheim"; String text = "This is four words."; int number = 17; System.out.println("We have " + number + " groups"); String cities = city + " Bergen"; System.out.println(cities); Problem 1: What is printed if this code excerpt is inserted into a program and run? Problem 2: Solve problem 3 page 39. Variables of the String type are called ”text strings”, or only ”strings”. NB! Simple quotes for characters, double quotes for strings.

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 2, page 15 Assignments and Arithmetical Expressions The four basic arithmetical operations + - * / –Multiplication and division have higher priority than addition and subtraction. –If we in a compound expression have more than one operation with the same priority these are interpreted from left to right. –The priority may be overridden by parentheses: –8 + 7 * 2 = 22 (5 + 7) * 5 = / 3.0 *4.0 = / (3.0 * 4.0) = 0.5 –Dividing integers gives no remainder (integer division): 5 / 2 = 2-5 / 2 = -21 / 3 = 0-1 / -3 = 0 The modulo operator % gives only the remainder (this has nothing to do with percent) 3 % 4 = % 2 = % 3 = % -2.2 = -1.1 In program code, the = symbol means assignment. The expression on the right side is calculated, and the result is stored in the variable on the left side. int number = 4; number = number + 8; // after this statement the number variable has the value 12 Solve problems 1 and 3 page 42.

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 2, page 16 Type Converting If the operands in an expression are of different type, the operand belonging to the smallest type is converted to the other data type. One data type is smaller than another data type if the type's range is smaller than the other type's range. Here is the order of the number types (from the largest to the smallest): double, float, long, int, short, byte. An example: double sum = ; int number = 14; double average = sum / number; // calculates /14.0 = Sometimes we need to override the type conversion. One common case is when integer division is performed. An example: int theNumberOfKids = 5; int theNumberOfApples = 23; double applesPerKid = (double) theNumberOfApples / (double) theNumberOfKids; The answer is 4.6. Controlled type conversion is called casting. Question: The example above. What is the result without casting? Note that the content of the variable is not changed by casting. The value is fetched out, and then converted before it is used in the calculation. ”casting”

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 2, page 17 Conversion from Decimal Numerals to Integers Truncating, not rounding Examples: int a = (int) 1.7; // a gets the value 1 int b = (int) ( ); // b gets the value 3 int c = (int) (int) 1.7; // c gets the value 2 Rounding is performed by adding 0.5 to the original value: int a = (int)( ); // a gets the value 2, not 1 as above Solve problems, 1 and 3, page 45.