Data Types, Variables, and Arithmetic Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by.

Slides:



Advertisements
Similar presentations
CSci 1130 Intro to Programming in Java
Advertisements

DATA TYPES, VARIABLES, ARITHMETIC. Variables A variable is a “named container” that holds a value. A name for a spot in the computer’s memory This value.
1 CS1001 Lecture Overview Java Programming Java 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.
10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
Introduction to Programming with Java, for Beginners Primitive Types Expressions Statements Variables Strings.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
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.
Aalborg Media Lab 21-Jun-15 Software Design Lecture 2 “ Data and Expressions”
Lecture 4 Types & Expressions COMP1681 / SE15 Introduction to Programming.
Program Elements We can now examine the core elements of programming (as implemented in Java) We focuse on: data types variable declaration and use, constants.
Slides prepared by Rose Williams, Binghamton University Chapter 1 Getting Started 1.2 Expressions and Assignment Statement.
Chapter 3 Numerical Data. Topics Variables Numeric data types Assignment Expressions.
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Java Methods. Topics  Declaring fields vs. local variables  Primitive data types  Strings  Compound Assignment  Conversions from one value to another.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Sahar Mosleh California State University San MarcosPage 1 A for loop can contain multiple initialization actions separated with commas Caution must be.
Chapter 2: Using Data.
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 Syntax and Style JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin, Gary Litvin,
Assignment Statements Operator Precedence. ICS111-Java Programming Blanca Polo 2 Assignment, not Equals  An assignment statement changes the value of.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Java Programming: From Problem Analysis to Program Design, 5e Chapter 2 Basic Elements of Java.
November 1, 2015ICS102: Expressions & Assignment 1 Expressions and Assignment.
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.
Data Types, Variables, and Arithmetic JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin,
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
Chapter 2 Variables.
Mathematical Calculations in Java Mrs. C. Furman.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
Programming in Java (COP 2250) Lecture 4 Chengyong Yang Fall, 2005.
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
CMSC 202 Java Primer 1. July 24, 2007 Copyright © 2008 Pearson Addison-Wesley 2 A Sample Java Application.
Java-02 Basic Concepts Review concepts and examine how java handles them.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
ICS102 Lecture 1 : Expressions and Assignment King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer.
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.
The Essentials of a Java Program JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin,
© 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
Java Primer 1: Types, Classes and Operators
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
Multiple variables can be created in one declaration
Assignment and Arithmetic expressions
Java Programming: From Problem Analysis to Program Design, 4e
Escape Sequences What if we wanted to print the quote character?
Chapter 2: Basic Elements of Java
Chapter 2 Variables.
Unit 6 - Variables - Fundamental Data Types
Expressions and Assignment
CS2011 Introduction to Programming I Elementary Programming
CS1001 Lecture 14.
Primitive Types and Expressions
Chapter 2 Variables.
Just Enough Java 17-May-19.
Presentation transcript:

Data Types, Variables, and Arithmetic Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved. int chapter = 6;

6-2 Objectives: Discuss primitive data types Learn how to declare fields and local variables Learn about arithmetic operators, compound assignment operators, and increment / decrement operators Discuss common mistakes in arithmetic

6-3 Variables A variable is a “named container” that holds a value. q = q; means:  1. Read the current value of q  2. Subtract it from 100  3. Move the result back into q count 5 mov ax,q mov bx,100 sub bx,ax mov q,bx

6-4 Variables (cont’d) Variables can be of different data types: int, char, double, boolean, etc. Variables can hold objects; then the type is the class of the object. The programmer gives names to variables. Names of variables usually start with a lowercase letter.

6-5 Variables (cont’d) A variable must be declared before it can be used: int count; double x, y; JButton go; Walker amy; String firstName; Type Name(s)

6-6 Variables (cont’d) The assignment operator = sets the variable’s value: count = 5; x = 0; go = new JButton("Go"); firstName = args[0];

6-7 Variables (cont’d) A variable can be initialized in its declaration: int count = 5; JButton go = new JButton("Go"); String firstName = args[0];

6-8 Variables: Scope Each variable has a scope — the area in the source code where it is “visible.” If you use a variable outside its scope, the compiler reports a syntax error. Variables can have the same name when their scopes do not overlap. { int k =...;... } for (int k =...) {... }

6-9 Fields Fields are declared outside all constructors and methods. Fields are usually grouped together, either at the top or at the bottom of the class. The scope of a field is the whole class.

6-10 Fields (cont’d) public class SomeClass { } Fields Constructors and methods Scope public class SomeClass { } Fields Constructors and methods Scope Or:

6-11 Local Variables Local variables are declared inside a constructor or a method. Local variables lose their values and are destroyed once the constructor or the method is exited. The scope of a local variable is from its declaration down to the closing brace of the block in which it is declared.

6-12 Local Variables (cont’d) public class SomeClass {... public SomeType SomeMethod (...) { }... } Scope Local variable declared

6-13 Variables (cont’d) Use local variables whenever appropriate; never use fields where local variables should be used. Give prominent names to fields, so that they are different from local variables. Use the same name for local variables that are used in similar ways in different methods (for example, x, y for coordinates, count for a counter, i, k for indices, etc.).

6-14 Variables (cont’d) Common mistakes: public void someMethod (...) { int x = 0;... int x = 5; // should be: x = 5;... Variable declared twice within the same scope — syntax error

6-15 Variables (cont’d) Common mistakes: private double radius;... public Circle (...) // constructor { double radius = 5;... Declares a local variable radius; the value of the field radius remains 0.0

6-16 Primitive Data Types int double char boolean byte short long float Used in Java Methods

6-17 Strings String is not a primitive data type Strings work like any other objects, with two exceptions:  Strings in double quotes are recognized as literal constants  + and += concatenate strings (or a string and a number or an object, which is converted into a string) "Catch " + 22"Catch 22"

6-18 Literal Constants 'A', '+', '\n', '\t' - 99, 2010, , , 8.,.5 “coin.gif", "1776", "y", "\n" new line tab char int double String

6-19 Symbolic Constants Symbolic constants are initialized final variables: private final int stepLength = 48; private static final int BUFFER_SIZE = 1024; public static final int PIXELS_PER_INCH = 6;

6-20 Why Symbolic Constants? Easy to change the value throughout the program, if necessary Easy to change into a variable More readable, self-documenting code Additional data type checking by the compiler

6-21 Arithmetic Operators: +, -, /, *, % The precedence of operators and parentheses is the same as in algebra m % n means the remainder when m is divided by n (for example, 17 % 5 is 2; 2 % 8 is 2) % has the same rank as / and * Same-rank binary operators are performed in order from left to right

6-22 Arithmetic (cont’d) The type of the result is determined by the types of the operands, not their values; this rule applies to all intermediate results in expressions. If one operand is an int and another is a double, the result is a double; if both operands are ints, the result is an int.

6-23 Arithmetic (cont’d) Caution: if a and b are ints, then a / b is truncated to an int… 17 / 5 gives 3 3 / 4 gives 0 …even if you assign the result to a double: double ratio = 2 / 3; The double type of the result doesn’t help: ratio still gets the value 0.0.

6-24 Arithmetic (cont’d) To get the correct double result, use double constants or the cast operator: double ratio = 2.0 / 3; double ratio = 2 / 3.0; int m =..., n =...; double factor = (double)m / (double)n; double factor = (double)m / n; double r2 = n / 2.0; Casts

6-25 Arithmetic (cont’d) A cast to int can be useful: int ptsOnDie = (int)(Math.random() * 6) + 1; int miles = (int)(km * ); Returns a double Converts kilometers to miles, rounded to the nearest integer

6-26 Arithmetic (cont’d) Caution: the range for ints is from to (about - 2·10 9 to 2·10 9 ) Overflow is not detected by the Java compiler or interpreter: n = 8 10^n = n! = n = 9 10^n = n! = n = 10 10^n = n! = n = 11 10^n = n! = n = 12 10^n = n! = n = 13 10^n = n! = n = 14 10^n = n! =

6-27 Arithmetic (cont’d) Compound assignment operators: a = a + b; a += b; a = a - b; a - = b; a = a * b; a *= b; a = a / b; a /= b; a = a % b; a %= b; Increment and decrement operators: a = a + 1; a++; a = a - 1; a -- ; Do not use these in larger expressions

6-28 From Numbers to Strings The easiest way to convert x into a string is to concatenate x with an empty string: String s = x + ""; The same rules apply to System.out.print(x) 'A' Math.PI "A" "123" " - 1" "0.1" "3.14" " " Empty string

6-29 From Objects to Strings The toString method is called: public class Fraction { private int num, denom;... public String toString () { return num + "/" + denom; } Fraction f = new Fraction (2, 3); System.out. println (f) ; Output: 2/3 f.toString() is called automatically

6-30 Review: What is a variable? What is the type of a variable that holds an object? What is meant by the scope of a variable? What is the scope of a field? What is the scope of a local variable?

6-31 Review (cont’d): Is it OK to give the same name to variables in different methods? Is it OK to give the same name to a field and to a local variable of the same class? What is the range for ints? When is a cast to double used?

6-32 Review (cont’d): Given double dF = 68.0; double dC = 5 / 9 * (dF - 32); what is the value of dC? When is a cast to int used? Should compound assignment operators be avoided?