Data types, declarations, and expressions in Java.

Slides:



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

Chapter 3: Expressions and Interactivity. Outline cin object Mathematical expressions Type Conversion and Some coding styles.
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.
CS 1400 Chapter 2 sections 1, 2, 4 – 6, 8,
10-Jun-15 Introduction to Primitives. 2 Overview Today we will discuss: The eight primitive types, especially int and double Declaring the types of variables.
1 Fundamental Data types Overview l Primitive Data Types l Variable declaration l Arithmetical Operations l Expressions l Assignment statement l Increment.
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
1 Chapter 3 Arithmetic Expressions. 2 Chapter 3 Topics l Overview of Java Data Types l Numeric Data Types l Declarations for Numeric Expressions l Simple.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3: Numeric Data *Variables *Numeric data.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Expressions and Operators Program Style.
1 Fundamental Data Types. 2 Outline  Primitive Data Types  Variable declaration  Numbers and Constants  Arithmetic Operators  Arithmetic Operator.
CS180 Recitation 3. Lecture: Overflow byte b; b = 127; b += 1; System.out.println("b is" + b); b is -128 byte b; b = 128; //will not compile! b went out.
Chapter 3 Numerical Data. Topics Variables Numeric data types Assignment Expressions.
Expressions An expression is a sequence of operands and operators that reduces to a single value expression operator operand An operator is a language-specific.
1 Data types, operations, and expressions Continued l Overview l Assignment statement l Increment and Decrement operators l Short hand operators l The.
Performing Computations C provides operators that can be applied to calculate expressions: example: tax is 8.5% of the total sale expression: tax =
What is a variable?  A variable holds data in memory so the program may use that data, or store results.  Variables have a data type. int, boolean, char,
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
Expressions and Interactivity Chapter 3. 2 The cin Object Standard input object Like cout, requires iostream file Used to read input from keyboard Often.
EG280 - CS for Engineers Chapter 2, Introduction to C Part I Topics: Program structure Constants and variables Assignment Statements Standard input and.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
Operaciones y Variables
Copyright © 2003 Pearson Education, Inc. Slide 2-1 Problem Solving with Java™ Second Edition Elliot Koffman and Ursula Wolz Copyright © 2003 Pearson Education,
 Value, Variable and Data Type  Type Conversion  Arithmetic Expression Evaluation  Scope of variable.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
1 Intro to Computer Science I Chapter 2 Fundamental Data Types Java scripting with BeanShell.
Variable Declaration  It is possible to declare multiple variables of the same data type on the same line.  Ex. double hours, rate, total;  Variables.
Chapter 2 part #4 Operator
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 CST 221 OBJECT ORIENTED PROGRAMMING(OOP) ( 2 CREDITS.
1 Do you have a CS account? Primitive types –“ building blocks ” for more complicated types Java is strongly typed –All variables in a Java program must.
Chapter 4 Variables and Constants. Goals and Objectives 1. Understand simple data types (int, boolean, double). 2. Declare and initialize variables using.
Strings & things Introduction to the Java API. The Java API API = Applications Programming Interface –Rich set of predefined classes and objects for use.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
CNG 140 C Programming Lecture Notes 2 Processing and Interactive Input Spring 2007.
CHAPTER 2 PART #4 OPERATOR 2 nd semester King Saud University College of Applied studies and Community Service Csc 1101 By: Asma Alosaimi Edited.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
D-1 University of Washington Computer Programming I Lecture 4: Arithmetic Expressions © 2000 UW CSE.
Data types, expressions & assignment statements. Data types and literal values We have already seen that a string literal is a set of characters enclosed.
Computer Programming TCP1224 Chapter 4 Variables, Constants, and Arithmetic Operators.
CHAPTER 4: CONTROL STRUCTURES - SEQUENCING 10/14/2014 PROBLEM SOLVING & ALGORITHM (DCT 1123)
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
CHAPTER 4 GC 101 Data types. DATA TYPES  For all data, assign a name (identifier) and a data type  Data type tells compiler:  How much memory to allocate.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
Chapter 6 Mathematical Operations. 6.1 Mathematical Expressions In mathematics this expression is valid 0 = -4y + 5 It is invalid in programming Left.
Programming Fundamentals. Overview of Previous Lecture Phases of C++ Environment Program statement Vs Preprocessor directive Whitespaces Comments.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 2A Reading, Processing and Displaying Data (Concepts)
Recap……Last Time [Variables, Data Types and Constants]
Numeric Data Types There are six numeric data types: byte, short, int, long, float, and double. Sample variable declarations: int i, j, k; float numberOne,
Module B - Computation1/61 Module-B-Computation Variables Basic Memory Operations Expressions.
1 Week 5 l Primitive Data types l Assignment l Expressions l Documentation & Style Primitive Types, Assignments, and Expressions.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Chapter 3 Numerical Data. Objectives After you have read and studied this chapter, you should be able to Select proper types for numerical data. Write.
D-1 University of Washington Computer Programming I Lecture 4: Arithmetic Expressions © 2000 UW CSE.
 Most C programs perform calculations using the C arithmetic operators (Fig. 2.9).  Note the use of various special symbols not used in algebra.  The.
Chapter 4: Variables, Constants, and Arithmetic Operators Introduction to Programming with C++ Fourth Edition.
1Object-Oriented Program Development Using C++ Built-in Data Types Data type –Range of values –Set of operations on those values Literal: refers to acceptable.
M105 - Week 2 Chapter 3 Numerical Data 1 Prepared by: M105 Team - AOU - SAB.
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.
Variables, Operators, and Expressions
Chapter 2 Basic Computation
Chapter 4 Assignment Statement
BASIC ELEMENTS OF A COMPUTER PROGRAM
BIL 104E Introduction to Scientific and Engineering Computing
Assignment and Arithmetic expressions
Primitive and Reference Data Values
The Selection Structure
Chapter 3 Assignment Statement
Chapter 2 Basic Computation
Pseudocode and Flowcharts
Numerical Data Types.
Presentation transcript:

Data types, declarations, and expressions in Java

Variables A variable is a named memory location capable of storing data As we have already seen, object variables refer to objects, which are created by instantiating classes with the new operator We can also store data in simple variables, which represent data only, without any associated methods

Data declaration syntax The syntax for the declaration of a variable is: Data type identifier; –“data type” may be the name of a class, as we have seen, or may be one of the simple types, which we’ll see in a moment –“identifier” is a legal Java identifier; the rules for simple variable identifiers are the same as those for object identifiers

Variable declaration: examples For example: int age; // int means integer double cashAmount; // double is a real # We can also declare multiple variables of the same type using a single instruction; for example: int x, y, z; //or int x, y, z; The second way is preferable, because it’s easier to document the purpose of each variable this way.

Numeric data types in Java: integers Data type nameMinimum valueMaximum value byte short-32,76832,767 int-2,147,483,6482,147,483,647 long-9,223,372,036,854,775,8089,223,372,036,854,775,807

Numeric data types in Java: floating-point numbers Data type nameMinimum valueMaximum value float x x double x x

Numeric data types: some notes Most programmers use int for whole numbers and double for real numbers Numeric data types in Java are primitive (non- object) types; this means that a numeric variable is somewhat different from an object: –You don’t use the new operator to initialize a numeric variable – just assign it a value –Memory for a numeric variable is allocated at declaration –Numeric variables actually store values; object names store addresses

Scientific notation and real numbers Both float and double have wide ranges to the values they can represent In order to save space, particularly large or small values are often displayed by default using a variation of scientific notation For example, the value would appear as 2.58 x in conventional notation – as output from a Java program, the number would appear as 2.58e-5 The ‘e’ is for exponent, and can be upper or lowercase

Assignment statements We can store a value in a variable using an assignment statement Assignment statement syntax: variableName = expression; –variableName must be the name of a declared variable –expression must evaluate to an appropriate value for storage within the type of variable specified

Arithmetic expressions An expression is a set of symbols that represents a value An arithmetic expression represents a numeric value Simple expressions are single values; examples: e3 Previously-declared and initialized variables or constants can also be simple expressions

Arithmetic operators in Java Compound expressions are formed by combining simple expressions using arithmetic operators OperationSymbol Addition+ Subtraction- Multiplication* Division/ Modulus%

Arithmetic operations in Java As in algebra, multiplication and division (and modulus, which we’ll look at momentarily) take precedence over addition and subtraction We can form larger expressions by adding more operators and more operands –Parentheses are used to group expressions, using the same rule as in algebra: evaluate the innermost parenthesized expression first, and work your way out through the levels of nesting –The one complication with this is we have only parentheses to group with; you can’t use curly or square brackets, as they have other specific meanings in Java

Examples int x = 4, y = 9, z; z = x + y * 2;// result is 22 z = (x + y) * 2;// result is 26 y = y – 1;// result is 8

Integer division When one real number is divided by another, the result is a real number; for example: double x = 5.2, y = 2.0, z; z = x / y;// result is 2.6 When dividing integers, we get an integer result For example: int x = 4, y = 9, z; z = x / 2;// result is 2 z = y / x;// result is 2, again z = x / y;// result is 0

Integer division There are two ways to divide integers –using the / operator, produces the quotient of the two operands –using the % operator, produces the remainder when the operands are divided. This is called modular division, or modulus (often abbreviated mod). For example: int x = 4, y = 9, z; z = x % 2;// result is 0 z = y % x;// result is 1 z = x % y;// result is 4

Mixed-type expressions A mixed-type expression is one that involves operands of different data types –Like other expressions, such an expression will evaluate to a single result –The data type of that value will be the type of the operand with the highest precision –What this means, for all practical purposes, is that, if an expression that involves both real numbers and whole numbers, the result will be a real number. The numeric promotion that takes place in a mixed-type expression is also known as implicit type casting

Explicit type casting We can perform a deliberate type conversion of an operand or expression through the explicit cast mechanism Explicit casts mean the operand or expression is evaluated as a value of the specified type rather than the type of the actual result The syntax for an explicit cast is: (data type) operand-or- (data type) (expression)

Explicit type casts - examples int x = 2, y = 5; double z; z = (double) y / z;// z = 2.5 z = (double) (y / z);// z = 2.0

Assignment conversion Another kind of implicit conversion can take place when an expression of one type is assigned to a variable of another type For example, an integer can be assigned to a real-number type variable; in this case, an implicit promotion of the integer value occurs

No demotions in assignment conversions In Java we are not allowed to “demote” a higher- precision type value by assigning it to a lower- precision type variable Instead, we must do an explicit type cast. Some examples: int x = 10; double y = x;// this is allowed; y = 10.0 x = y;// error: can’t demote value to int y = y / 3;// y now contains x = (int)y;// allowed; x = 3

Compound arithmetic/assignment operators Previous examples in the notes have included the following statements: y = y + 1; y = y / 3; In each case, the current value of the variable is used to evaluate the expression, and the resulting value is assigned to the variable (erasing the previously-stored value) This type of operation is extremely common; so much so, that Java (like C++ and C before it) provides a set of shorthand operators to perform this type of operation. The table on the next slide illustrates the use and meaning of these operators

Compound arithmetic/assignment operators OperatorUseMeaning +=X += 1;X = X + 1; -=X -= 1;X = X – 1; *=X *= 5;X = X * 5; /=X /= 2;X = X / 2; %=X %= 10;X = X % 10;

Named constants A variable is a named memory location that can hold a value of a specific data type; as we have seen, the value stored at this location can change throughout the execution of a program If we want to maintain a value in a named location, we use the Java keyword final in the declaration and immediately assign the desired value; with this mechanism, we declare a named constant. Some examples: final int LUCKY = 7; final double PI = ; final double LIGHTSPEED = 3.0e10.0 ;

Named constants The name of the constant is used in expressions but cannot be assigned a new value. For example, to calculate the value of variable circleArea using the variable radius and the value , we could write: circleArea = 2 * PI * radius * radius; The use of named constants is considered good programming practice, because it: –eliminates (or at least minimizes) the use of “magic” numbers in a program; it is easier to read code that contains meaningful names –allows a programmer to make global changes in calculations easily

Using named constants: example Suppose, for example, that you are writing a program that involves adding sales tax and subtracting discounts from users’ totals If the tax rate is 5% and the discount rate is 10%, the calculation could look like this: total = total – (total *.1) + ((total *.1) * (1 +.05)); By itself, this isn’t too bad; but suppose there are several places in the program that use these values?

Example continued If, for example, the discount changes to 12%, the programmer who has to maintain the code would have to change the value.1 to.12 everywhere in the program – at least, everywhere that it actually refers to the discount. –The value.1 could very well mean something else in a different expression. –If we use named constants instead, the value has to change in just one place, and there is no ambiguity about what the number means in context; with named constants, the revised code might read: total = total – (total * discount) + ((total * discount) * (1 + taxrate));

Calculations using Java’s Math class The standard Java class Math contains class methods and constants that are useful in performing calculations that go beyond simple arithmetic operations The constants defined in the Math class are Math.PI and Math.E, which are defined values for  and e (the base for natural logs), respectively

Math class methods Math.abs(a): returns the absolute value of its argument (a), which can be of type int, long, float, or double Math.sin(a): returns the sine of its argument, a double value representing an angle in radians; similar trigonometric functions include Math.cos(a) for cosine, Math.tan(a) for tangent, Math.acos(a), Math.asin(a) and Math.atan(a), which provide arccosine, arcsine, and arctangent, respectively

Math class methods Math.toDegrees(a): converts a, a double value representing an angle in radians, to the corresponding value in degrees Math.toRadians(a): converts a, a double value representing an angle in degrees to the corresponding value in radians

Math class methods Math.sqrt(a): returns the square root of a, a value of type double Math.cbrt(a): returns the cube root of a, a value of type double Math.pow(a, b): returns the value of a b Math.log(a): returns the natural log of a, a double value Math.log10(a): returns the log base 10 of a, a double value

Example // computing the roots of a quadratic equation: doublea,// coefficient of x squared b,// coefficient of x c,// 3 rd term in equation x1,// first root x2;// second root // read in values for a, b, and c – not shown here … x1 = (-b + Math.sqrt(Math.pow(b, 2) – (4 * a * c))) / (2 * a); x2 = (-b - Math.sqrt(Math.pow(b, 2) – (4 * a * c))) / (2 * a);