Data Types, Variables, and Arithmetic JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin,

Slides:



Advertisements
Similar presentations
STRING AN EXAMPLE OF REFERENCE DATA TYPE. 2 Primitive Data Types  The eight Java primitive data types are:  byte  short  int  long  float  double.
Advertisements

CSci 1130 Intro to Programming in Java
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.
Introduction to Computing Concepts Note Set 7. Overview Variables Data Types Basic Arithmetic Expressions ▫ Arithmetic.
1 CS1001 Lecture Overview Java Programming Java Programming.
Primitive Data Types There are a number of common objects we encounter and are treated specially by almost any programming language These are called basic.
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.
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 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
1 Data types, operations, and expressions Overview l Primitive Data Types l Variable declaration l Arithmetical Operations l Expressions.
Aalborg Media Lab 21-Jun-15 Software Design Lecture 2 “ Data and Expressions”
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.
Chapter 3 Numerical Data. Topics Variables Numeric data types Assignment Expressions.
CPS120: Introduction to Computer Science Lecture 8.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
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.
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 Syntax and Style JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin, Gary Litvin,
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
November 1, 2015ICS102: Expressions & Assignment 1 Expressions and Assignment.
Java Classes, Objects, and Events: A Preview JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria.
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.
Java Programming, Second Edition Chapter Two Using Data Within a Program.
COMP Primitive and Class Types Yi Hong May 14, 2015.
Programming in Java (COP 2250) Lecture 4 Chengyong Yang Fall, 2005.
Data Types, Variables, and Arithmetic Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
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?
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.
Inside Class Methods Chapter 4. 4 What are variables? Variables store values within methods and may change value as the method processes data.
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 7: Expressions and Assignment Statements
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
Chapter 7: Expressions and Assignment Statements
Multiple variables can be created in one declaration
Assignment and Arithmetic expressions
Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Character Set Uppercase Alphabets A,
Chapter 2 Variables.
Unit 6 - Variables - Fundamental Data Types
Expressions and Assignment
CS2011 Introduction to Programming I Elementary Programming
Data Types and Expressions
CS1001 Lecture 14.
Primitive Types and Expressions
Chapter 2 Variables.
Just Enough Java 17-May-19.
Data Types and Expressions
Data Types and Expressions
Presentation transcript:

Data Types, Variables, and Arithmetic JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved. TM int chapter = 6;

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

6-3 Variables l A variable is a “named container” that holds a value. q = q; means: 1. Read the current value of q 2. Subtract it from 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) l Variables can be of different data types: int, char, double, boolean, etc. l Variables can hold objects; then the type is the class of the object. l The programmer gives names to variables. l Names usually start with a lowercase letter.

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

6-6 Variables (cont’d) l The assignment operator = sets the variable’s value: l A variable can be initialized in its declaration: count = 5; x = 0; go = new JButton("Go"); firstName = args[0]; Assignments int count = 5; JButton go = new JButton("Go"); String firstName = args[0]; Declarations with initialization

6-7 Variables (cont’d) l Each variable has a scope — the area in the source code where it is “visible.” l If you use a variable outside its scope, the compiler reports a syntax error. l Variables can have the same name. Caution: use only when their scopes do not intersect. { int k;... } { int k;... }

6-8 Fields vs. Local Variables l Fields are declared outside all constructors and methods. l Local variables are declared inside a constructor or a method.

6-9 Fields vs. Local Variables (cont’d) l Fields are usually grouped together, either at the top or at the bottom of the class. l The scope of a field is the whole class.

6-10 Fields public class SomeClass { } Fields Constructors and methods public class SomeClass { } Scope Fields Constructors and methods

6-11 Local Variables l Local variables are declared inside a constructor or a method. l Local variables lose their values and are destroyed once the constructor or the method is exited. l 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 (...) { }... } Local variable declared Local variable Scope

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

6-14 Variables (cont’d) l Common mistakes: public void SomeMethod (...) { int x;... int x = 5; // should be: x = 5;... Variable declared twice — syntax error

6-15 Variables (cont’d) l Common mistakes: private int cubeX;... public SomeClass(...) // constructor { int cubeX = 5; // should be: cubeX = 5;... A field is overridden by a local variable; the value of the field cubeX remains unset

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

6-17 Constants 'A', '+', '\n', '\t' // char - 99, 2010, 0 // int 0.75, , 8.,.5 // double new line tab

6-18 Constants (cont’d) private final int delay = 30; private final double aspectRatio = 0.7; l Symbolic constants are initialized final variables:

6-19 Constants (cont’d) l Why use symbolic constants? –easier to change the value throughout, if necessary –easy to change into a variable –more readable, self-documenting code –additional data type checking

6-20 Arithmetic Operators: +, -, /, *, % l The precedence of operators and parentheses work the same way as in algebra. l m % n means the remainder when m is divided by n (e.g. 17 % 5 is 2). % has the same rank as / and * l Same-rank binary operators are performed in order from left to right.

6-21 Arithmetic (cont’d) l 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. l 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-22 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 l …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-23 Arithmetic (cont’d) l To get the correct double result, use double constants or the cast operator: double ratio = 2.0 / 3; double ratio = 2 / 3.0; double factor = (double) m / (double) n; double factor = m / (double) n; double r2 = k / 2.0; double r2 = (double) k / 2; Casts

6-24 Arithmetic (cont’d) Caution: the range for ints is from to (about - 2·10 9 to 2·10 9 ) l 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-25 Arithmetic (cont’d) l Use 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; l Use increment and decrement operators: a = a + 1; a ++ ; a = a - 1; a -- ; Do not use these in larger expressions

6-26 Ramblecs Case Study l Add a control panel with a speed gauge

6-27 Ramblecs (cont’d) l Now four classes:

6-28 Ramblecs (cont’d) import java.awt.*; import javax.swing.*; public class Ramblecs extends JApplet { private ControlPanel controlpanel; private LetterPanel whiteboard; public void init() { whiteboard = new LetterPanel(); whiteboard.setBackground(Color.white); controlpanel = new ControlPanel(whiteboard); Container c = getContentPane(); c.add(whiteboard, BorderLayout.CENTER); c.add(controlpanel, BorderLayout.EAST); } Ramblecs.java

6-29 Ramblecs (cont’d) /** * Control panel's drawing method */ public void paintComponent(Graphics g) {... // Draw the gauge: int degrees = (int)(180.0 * speed / maxSpeed); g.setColor(Color.blue); g.fillArc(xGauge, yGauge, size, size, 0, 180); // full semicircle g.setColor(Color.red); g.fillArc(xGauge, yGauge, size, size, degrees, degrees); // slice on the left side: // from degrees to } ControlPanel.java

6-30 Review: l What is a variable? l What is the type of variable that holds an object? l What is meant by the scope of a variable? l What is the scope of a field? l What is the scope of a local variable? l Is it OK to give the same name to variables in different methods? l Is it OK to give the same name to a field and to a local variable of the same class?

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