Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Similar documents
Building Java Programs

Building Java Programs

Building Java Programs

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

Basics of Java Programming

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

Topic 4 Expressions and variables

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

Declaration and Memory

COMP Primitive and Class Types. Yi Hong May 14, 2015

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

What we will do today Explain and look at examples of. Programs that examine data. Data types. Topic 4. variables. expressions. assignment statements

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Lecture 2: Operations and Data Types

Full file at

Full file at

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

Chapter 2: Data and Expressions

Basic Operations jgrasp debugger Writing Programs & Checkstyle

Building Java Programs Chapter 2

Chapter 2: Data and Expressions

Program Fundamentals

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

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

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

1.00 Lecture 4. Promotion

CIS133J. Working with Numbers in Java

Elementary Programming

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

CMPT 125: Lecture 3 Data and Expressions

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

4 Programming Fundamentals. Introduction to Programming 1 1

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

3. Java - Language Constructs I

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

Building Java Programs Chapter 2. bug. Primitive Data and Definite Loops. Copyright (c) Pearson All rights reserved. Software Flaw.

Building Java Programs Chapter 2

LECTURE 3 C++ Basics Part 2

Chapter 2: Data and Expressions

ECE 122 Engineering Problem Solving with Java

Zheng-Liang Lu Java Programming 45 / 79

Datatypes, Variables, and Operations

Primitive Data, Variables, and Expressions; Simple Conditional Execution

DATA TYPES AND EXPRESSIONS

Object-Oriented Programming

MODULE 02: BASIC COMPUTATION IN JAVA

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Getting started with Java

CS313D: ADVANCED PROGRAMMING LANGUAGE

Computational Expression

CSE 142, Summer 2015

CSE 142, Summer 2014

Visual C# Instructor s Manual Table of Contents

Introduction to Computer Programming

Chapter 2: Overview of C++

JAVA Programming Fundamentals

CS 112 Introduction to Programming

Admin. CS 112 Introduction to Programming. Recap: Java Static Methods. Recap: Decomposition Example. Recap: Static Method Example

Lecture 3 Tao Wang 1

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

UNIT- 3 Introduction to C++

Chapter 2: Using Data

CS 106 Introduction to Computer Science I

CEN 414 Java Programming

Ex: If you use a program to record sales, you will want to remember data:

Java Notes. 10th ICSE. Saravanan Ganesh

Chapter 2 Elementary Programming

Primitive Types. Four integer types: Two floating-point types: One character type: One boolean type: byte short int (most common) long

CS 112 Introduction to Programming

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language

Objectives. In this chapter, you will:

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Chapter 2 Primitive Data Types and Operations. Objectives

Chapter 2 Working with Data Types and Operators

Chapter 2: Using Data

COMP 110 Introduction to Programming. What did we discuss?

Programming with Java

Chapter 2. Elementary Programming

CIS 110: Introduction to Computer Programming

Outline. Performing Computations. Outline (cont) Expressions in C. Some Expression Formats. Types for Operands

Values, Variables, Types & Arithmetic Expressions. Agenda

Differentiate Between Keywords and Identifiers

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators

Chapter 2: Using Data

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

AP Computer Science A

Chapter 2: Basic Elements of C++

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

Basic Computation. Chapter 2

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

Chapter 02: Using Data

Lesson 02 Data Types and Statements. MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

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

A Java program contains at least one class definition.

Sir Muhammad Naveed. Arslan Ahmed Shaad ( ) Muhammad Bilal ( )

DEPARTMENT OF MATHS, MJ COLLEGE

Professor: Sana Odeh Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators

Transcription:

Data and Variables Data Types Expressions Operators Precedence String Concatenation Variables Declaration Assignment Shorthand operators

Review class All code in a java file is written in a class public class <ClassName> {.. } Static methods public static void <methodname> () {.. } Made up of statements; Used in procedural programming Decompose large tasks into smaller subtasks Create a method for each unique subtask to eliminate redundancy Errors Syntax (won t compile) Runtime (won t run) Logic (incorrect result) Identifiers Must begin with a letter, underscore, or $ Must contain only letters, digits, underscores, or $ Can not be a Java keyword/reserved word

Data Types Java is a strongly typed language. Each piece of data has a specific type Java supports two categories of data types Primitive data Objects (covered later)

Primitive Data Types Integer (Whole Number) Java keywords for Integer Types int (4 bytes) byte (1 byte) short (2 bytes) long (8 bytes) We will use the int type minimum value -2,147,483,648 maximum value 2,147,483,647 Examples: 0, 35, +148, -250

Primitive Data Types (cont.) Real (Floating point, Decimal) Java keywords for Real Number Types double (8 bytes) (double precision) float (4 bytes) We will use the double type minimum value 4.94065645841246544e-324 maximum value 1.79769313486231570e+308 Examples: 23..03-5.5 10.0583 34e-20

Primitive Data Types (cont.) Character (Single Character) Java keyword for Character Type char (2 bytes) Enclosed in single quotes Examples: a & X 8 Use escape sequence for Single Quote \ Backslash \\

Primitive Data Types (cont.) boolean (Logical Values) Java keyword boolean Only two different values (Java keywords) true false Covered Later

Practice Which of the following are legal int literals? 5. -1 22 7 1.5-6875309 10.0 2.3

Practice What primitive data type would you use to store a person s middle initial? number of people in class? cost of lunch? distance to class? number of siblings a person has? your grade in a class?

Expressions Expression A simple value or a set of operations that produces a value. Evaluation The process of obtaining the value of an expression. Expressions have values, statements do not. Two types Arithmetic Boolean (covered later)

Expressions (cont.) A simple value or a set of operations that produce a value Literal Value 42-365 0 +9812 28.9 0.24 207. 0.0 -.98 true false a m X! \\ \ Operations: combining values (5 * 6) + 32 Use expressions in print statements System.out.println(4); System.out.println(2 + 2);

Arithmetic Operators and Operands Operators: indicate the operation to be performed Addition (+) (5 + 2) Subtraction (-) (5-2) Multiplication (*) (5 * 2) Division ( / ) (5 / 2) (5.0 / 2.0) Remainder (mod) (%) (5 % 2) Operands: values used in the expression Literal Expression (3 + 2) * (6 / 2)

Division Integer Division - result is an integer, the remainder is dropped (truncation). examples: 22 / 4 = 5 116 / 5 = 23 Floating Point Division normal division. examples: 22.0 / 4. = 5.5 116.0 / 5.0 = 23.2

Remainder (Mod) % - The remainder operator Returns the remainder of division examples: 22 % 4 = 2 22. % 4.0 = 2.0 5.2 % 2.4 = 0.4 1 % 5 = 1 0 % 5 = 0 5 % 0 = undefined (runtime error) Useful applications Testing for even/odd (number % 2 = 0 means even) Extract final digit (number % 10)

Precedence Precedence The order of evaluating expressions Multiplication, Division, and Modulo take precedence over Addition and Subtraction. Unary operators (+, -) (pos, neg) take precedence over all 5 operators. Within same level of precedence, evaluate from left to right Override precedence with parentheses.

Precedence Examples 8 * 4 / 10 + (4 + 2) * 5 % 2 46 % 8 * 2 / 7 + 11 / 4 * 3

Mixing Types Promotion: a copy of a value is converted to a higher type. Does not lose information about the value Integer to a double Result of operation between integer and double is a double (integer is promoted to a double to perform the operation) 6.4 + 8 = 14.4 Casting: a copy of a value is converted to another type Double to integer Loses the fraction part Requires a cast put the name of the type you want in parentheses in front of the value you want to cast (int) 5.62 (result is 5) (int) 5.0 / 2.0 (result is 5 / 2.0 = 2.5) (int) (5.0 / 2.0) (result is 2)

More Casting Only casts value immediately following cast For example: 23 / 2 = 11 (double) 23 / 2 = 11.5 (23. / 2, 23 / 2., 23. / 2.) (double) (23 / 2) = 11.0 Example of when we may want to use casting: We have some books that are 0.15 feet wide and we want to know how many of them will fit in a bookshelf that is 2.5 feet wide. Then, 2.5 / 0.15 = 16.666 books. How are we going to put 2/3 of a book on the shelf? Instead, we need to see how many whole books can fit on the shelf: (int) (2.5 / 0.15) = 16

String Concatenation Combining several strings into a single string, or combining a string with other data into a new, longer string Addition operator (+) Result of adding a String literal and a primitive data type is a String literal (primitive type is promoted to a String literal to perform the operation) Examples: "hello" + 42 is "hello42" 1 + "abc" + 2 is "1abc2" "abc" + 1 + 2 is "abc12" 1 + 2 + "abc" is "3abc" "abc" + 9 * 3 is "abc27" "12" + 3 is "123"

Expression Practice Consider the data type in the answers. For example, 5 (an int) is totally different from 5.0 (a double) 5.5 + 2 / 3 2 + 3.5 * -2 5 * 10 / 5.0 + 3 * (int) 2.5 / 10 8 + 4 + "3" + 4 + 10 / 2 + "6" + (7 + 8)

In-Class Exercise 1. 2 * 3-4 % 2 / 2 + 10 / (double)(10 / 4) 2. 42 % 6 + 35 / 5 % 4-16. / (12 % 8) 3. (int) 5.0 / 2.0 + (4 + 6) / 5 * 2 4. 3 * (5-3) + 3-3 * 2 5. 9 / 2.0-2 - 10 / (int) (5 * 0.5) 6. "1" + 2 / 3 + "four" + 5 % 6 + 7 + (8 + 9)

Variables Variable A memory location with a name and a type that stores a value. Declaration A request to set aside a new variable with a given type and name. <type> <name>; Variablenames are identifiers Style guidelines: start with lowercase letter, capitalize each subsequent word Examples int age; double weight; char firstinitial;

Variable Assignment Assignment Giving a value to a variable. A value is assigned to a variable using an assignment statement: <variable> = <expression>; Equalsign (=) is the operator for assignment The value of the expression on the right-hand side of the assignment is stored in the variable on the left-hand side of the assignment and is the result of the assignment operation Examples double height = 70; double weight = 195; double bmi = weight / (height * weight) * 703; char firstinitial = M ;

Initialization Giving a variable an initial value is known as the initialization of the variable int age; age = 35; //uninitialized //now initialized

Declaration/Assignment Variations //declare and assign a value to //a variable in one statement <type> <name> = <expression>; int value = 10; int answer = 5 * 6; //declare multiple variables of //the same type in one statement <type> <name1>, <name2>,, <name3>; int value, answer; int number = 5, sum; int age1 = 5, age2 = 8;

Practice Which of the following choices is the correct syntax for declaring a real number variable named grade and initializing its value to 4.0? 1. 4.0 = grade; 2. double grade = 4.0; 3. grade = double 4.0; 4. 4.0 = double grade; 5. int grade = 4.0;

Variables (cont.) Changing the value of a variable using assignment : What will the values of x, y, and z be after the following statements are executed? int x = 3, y = 7, z; z = x + y; x = x + 2; x = y 5; y = z x;

Variables (cont.) Changing the value of a variable using a shorthand method: Special Assignment Operators that increment or decrement a value by a set amount Standard Assignment x = x + 1; y = y 7; z = z * 2; a = a / 3; Shorthand Assignment x += 1; y -= 7; z *= 2; a /= 3;

Variables (cont.) Changing the value of a variable using increment/decrement (++/--) operators Increment a value by 1 i++; ++i; (post increment) (pre increment) Decrement a value by 1 i--; --i; (post decrement) (pre decrement) Post versions evaluate to the older (original) value evaluate using current value of i, then increment i Pre versions evaluate to the new (final) value increment i, then evaluate using new i

Pre/Post Increment/Decrement Examples What are the values of age1, age2, age3, and years after the following statements are executed? int age1 = 21; int age2 = 50; int years; int age3 = age2 age1++; years = ++age1 + age2--; years++;

Common Syntax errors A variable can't be used until it is assigned a value. int x; System.out.println(x); // ERROR: x has no value You may not declare the same variable twice. int x; int x; // ERROR: x already exists int x = 3; int x = 5; // ERROR: x already exists

Printing an expression or variable value Use + to print a String and an expression value on one line System.out.println("Grade: " + (95.1 + 71.9) / 2); Output: Grade: 83.5 System.out.println("Grade: " + (95.1 + 71.9) + 2); Output: Grade: 167.02 Use + to print a String and a variable's value on one line. double grade = (95.1 + 71.9 + 82.6) / 3.0; System.out.println("Your grade was " + grade); Output: Your grade was 83.2 int students = 11 + 17 + 4 + 19 + 14; System.out.println("There are " + students + " students in the course."); Output: There are 65 students in the course.

Practice What does the following program output? public class Variables { public static void main(string[] args) { int num1, num2, num3; num1 = 4; num2 = 12; num3 = num1; num2 /= 3; num1 = num2++ + 4; num3 += num1; int num4 = --num1; num4++; System.out.print("num1 = " + --num1 + "\nnum2 = " + ++num2 + "\nnum3 = " + num3++); System.out.println(" num4 = " + num4--); } }

In-Class Assignment Meadowdale Dairy Farm sells organic brown eggs to local customers. They charge $3.25 for a dozen eggs, or 45 cents for individual eggs that are not part of a dozen. Write a class that includes a variable for the number of eggs in the order and assign the value 27 to this variable. Calculate and display the amount owed with a full explanation as follows: You ordered 27 eggs. That s 2 dozen at $3.25 per dozen and 3 loose eggs at 45 cents each for a total of $7.85. Save the class as Eggs.java.

In-Class Assignment Write a class that calculates and displays the conversion of an integer variable storing a number of dollars into currency denominations 20s, 10s, 5s, and 1s. Assign the value of 57 to the variable. Print the resulting conversion as shown below (the output values must be calculated, not printed out using literal values). Output: $57 converts to: 2 20s, 1 10s, 1 5s, and 2 1s. Save the class as Dollars.java.