Variables and Assignments CSC 121 Spring 2017 Howard Rosenthal

Similar documents
Variables and Assignments CSC 121 Fall 2015 Howard Rosenthal

Variables and Assignments CSC 121 Fall 2014 Howard Rosenthal

Expressions, Data Types, Formatted Printing, Scanning CSC 123 Fall 2018 Howard Rosenthal

Programming with Java

A+ Computer Science -

Chapter 2. Elementary Programming

Computational Expression

Chapter 2 ELEMENTARY PROGRAMMING

A+ Computer Science -

Chapter 2 Elementary Programming

Computational Expression

Fundamentals of Programming Data Types & Methods

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

ECE 122 Engineering Problem Solving with Java

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

Input. Scanner keyboard = new Scanner(System.in); String name;

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

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

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

A variable is a name for a location in memory A variable must be declared

St. Edmund Preparatory High School Brooklyn, NY

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Full file at

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

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

Peer Instruction 1. Elementary Programming

ing execution. That way, new results can be computed each time the Class The Scanner

CEN 414 Java Programming

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

Data Conversion & Scanner Class

Reading Input from Text File

Introduction to Java Unit 1. Using BlueJ to Write Programs

Basic Computation. Chapter 2

The for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming

Chapter 2 Elementary Programming

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

A Quick and Dirty Overview of Java and. Java Programming

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

Chapter 2 Primitive Data Types and Operations

Using Classes and Objects Chapters 3 Creating Objects Section 3.1 The String Class Section 3.2 The Scanner Class Section 2.6

Arrays and Lists CSC 121 Fall 2014 Howard Rosenthal

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

Chapter 2: Data and Expressions

We now start exploring some key elements of the Java programming language and ways of performing I/O

Java Classes: Math, Integer A C S L E C T U R E 8

Chapter 2 Primitive Data Types and Operations. Objectives

Computer Science 210 Data Structures Siena College Fall Topic Notes: Methods

Java Coding 3. Over & over again!

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

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

Elementary Programming. CSE 114, Computer Science 1 Stony Brook University

Basic Computation. Chapter 2

Primitive Data Types: Intro

Elementary Programming

Methods CSC 121 Spring 2017 Howard Rosenthal

AP Computer Science Unit 1. Writing Programs Using BlueJ

Programming Exercise 7: Static Methods

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Basics of Java Programming

Methods CSC 121 Fall 2016 Howard Rosenthal

Chapter 2 Elementary Programming. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.

Repetition CSC 121 Fall 2014 Howard Rosenthal

Basic Programming Elements

Darrell Bethea May 25, 2011

AP Computer Science Unit 1. Writing Programs Using BlueJ

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

Chapter 2: Data and Expressions

Important Java terminology

Lecture Set 2: Starting Java

Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal

JAVA Ch. 4. Variables and Constants Lawrenceville Press

Motivations. Chapter 2: Elementary Programming 8/24/18. Introducing Programming with an Example. Trace a Program Execution. Trace a Program Execution

Chapter. Let's explore some other fundamental programming concepts

Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4

Arrays and Lists CSC 121 Fall 2015 Howard Rosenthal

Project 1. Java Data types and input/output 1/17/2014. Primitive data types (2) Primitive data types in Java

Lecture Set 2: Starting Java

H212 Introduction to Software Systems Honors

Computer Programming, I. Laboratory Manual. Experiment #3. Selections

Lecture 8 " INPUT " Instructor: Craig Duckett

STUDENT LESSON A7 Simple I/O

Object Oriented Programming. Java-Lecture 1

AP Computer Science A

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

Introduction to Computer Programming

Objects and Classes 1: Encapsulation, Strings and Things CSC 121 Fall 2014 Howard Rosenthal

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

data_type variable_name = value; Here value is optional because in java, you can declare the variable first and then later assign the value to it.

Loops and Expression Types

Classes and Objects Part 1

Text User Interfaces. Keyboard IO plus

CS110: PROGRAMMING LANGUAGE I

3. Java - Language Constructs I

AP Computer Science Unit 1. Programs

method method public class Temperature { public static void main(string[] args) { // your code here } new

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

CS 251 Intermediate Programming Java Basics

Lesson 7 Part 2 Flags

Over and Over Again GEEN163

Transcription:

Variables and Assignments CSC 121 Spring 2017 Howard Rosenthal

Lesson Goals Understand variables Understand how to declare and use variables in Java Programs Learn how to formulate assignment statements Learn how to read in data from a terminal Creating your first object Using the Scanner object for interactive input Compatibility and casting 2

What is a Variable A variable (either primitive or a reference) is a named memory location capable of storing data of a specified type Variables indicate logical, not physical addresses Those are taken care of in the JVM and the OS Variables in Java always have a specific data type Variables must always be declared before they can be used Remember that a data type is a scheme for using bit patterns to represent a value or a reference. Think of a variable as a little box made of one or more bytes that can hold a value using a particular data type. double Cost_of_Home 128,695.22 3

What is a Variable (2) A declaration of a variable is made if a program requires a named variable of a particular type Three things happen The variable is named with an identifier The amount of space required for the variable is defined How the bits in that space are interpreted is defined The value of a variable is always its last declared or assigned value in a program public class Example1_CH3 { public static void main ( String [] args ) { long payamount; //the declaration of the variable payamount = 123; // variable assignment System.out.println("The variable payamount contains: " + payamount); payamount = -8976; // variable reassignment System.out.println("The variable payamount contains: " + payamount); } } 4

Declaring Variables Variables must be declared before they are used Basic syntax: Type name1, name2, name3 ; Example: double dinner_bill, creditbalance, moneyinbank;//three variables of type double Variables can be explicitly initialized when they are declared short rent = 75; double milkprice_half = 1.99; boolean testimony = true; Can t do multiple assignments at once when declaring variables int x=y=z=0; // Incorrect syntax int x,y,z=60; // only z is initialized int x=60, y=60, z=60; //all three are initialized Don t try to assign a value that that is illegal short big_number = 250000; This gives an error why? 5

Naming Variables Use only the characters 'a' through 'z', 'A' through 'Z', '0' through '9', character '_', and character '$'. Just like any other identifier A variable name cannot contain the space character. Do not start with a digit. A variable can be any length. Java is case sensitive. Upper and lower case count as different characters. SUM and Sum are different identifiers. A variable name cannot be a reserved word. Don t use the same name twice, even as different types it will generate an error during compilation Programmers should follow the good practice of creating meaningful identifier names that self-describe an item's purpose. Meaningful names make programs easier to maintain. userage, housesquarefeet, and numitemsonshelves. Good practice minimizes use of abbreviations in identifiers except for well-known ones like num in numpassengers. Abbreviations make programs harder to read and can also lead to confusion, such as if a chiropractor application involves number of messages and number of massages, and one is abbreviated nummsgs (which is it?). 6

Assigning Variables Assignment statements look like this: variablename = expression ; //The equal sign = is the assignment operator variablename is the name of a variable that has been declared previously in the program. Remember: An expression is a combination of literals, operators, variable names, and parentheses used to calculate a value must be syntactically correct Assignment is accomplished in two steps: Evaluate the expression Store the value in the variable which appears to the left of the = sign Examples (assuming variable has been previously declared): total = 3 + 5; // total =8 price = 34.56; tax = price*0.05; //tax = 1.728 While you can t do a multiple assignment in a declaration statement, you can do multiple assignments once the variables have been declared: int x,y,z; //declaration of the variables x=y=z=0; // works as an assignment statement provided the variables have been declared previously these work right to left int x=y=z=3; // This will generate a syntax error because you are first declaring the variables here x=y=z=14+5; // First calculate the value of the expression, then do the assignments 7

Assigning Variables (2) What does the following program fragment write? int value = 5; System.out.println("value is: " + value ); value = value + 10; System.out.println("value is: " + value ); 8

Assigning Variables (3) Primitive variables must be initialized before they are used They aren t given a default value They are typically initialized by reading in a value You can also explicitly initialize in the code int value; value = value + 10; // this gives an error as value wasn t initialized 9

final Variables final variables are really constants They are assigned a value that doesn t change final double PI = 3.14159; final int PERFECT = 100; final variables are by convention written with all capitals 10

An Example of a Simple Program (1) The Fibonacci sequence is 1,1,2,3,5,8,13,21,34,55. The next number is the sum of the previous two numbers. Pseudocode for printing Fibonacci series up to 50 Set the low number =1 Set the high number equal to 1 Print the low Start of Loop check that high is less than 50 Print the high Set the high equal to the low+high Set the low equal to the high -low Repeat loop 11

An Example of a Simple Program (2) public class Fibonacci { // Print out the Fibonacci sequence for values < 50 public static void main(string[] args) { int lo = 1; int hi = 1; System.out.println(lo); while (hi < 50) { System.out.println(hi); hi = lo + hi; // new hi lo = hi - lo; /* new lo is (sum - old lo) i.e., the old hi */ } } } Note: We are using a while construct that is formally introduced in Chapter 5 Note: also look at Fibonacci2.java 12

Obtaining Input Data Using Scanner Scanner is a class. You must include the following statement to use the class to create a Scanner object: import java.util.scanner; or import java.util.*; You are importing a class with all it s methods that can then be used to create objects Declare a Scanner object variable and create an object: Scanner scannername = new Scanner (System.in); new means you are creating a new object new is a reserved word System.in is a variable that tell the Java program that this input stream is coming from the keyboard You can now access seven types of primitive input: byte, short, int, long, double, float and boolean using predefined methods associated with object A Scanner object doesn t read characters We will learn a way around this when we study the String object The scannername is just another variable name 13

There are 7 Input Methods Available For PrimiQve Data Types ScannerName.nextByte() ScannerName.nextShort() ScannerName.nextInt() ScannerName.nextLong() ScannerName.nextDouble() ScannerName.nextFloat() ScannerName.nextBoolean() Note: the type names are capitalized in these methods Note: There is no way to directly input a char with a Scanner object What you are looking at above is the standard way objects access methods: objectname.method(par1, par2, ) - There are no parameters required for the Scanner methods 14

Each Scanner Object Is Created From The Scanner Class keyboard Name0f input file (System.in) Constructor used to create object Methods nextbyte() nextshort() nextint() nextlong() nextfloat() nextdouble() nextboolean() next() nextline() hasnext() o 0 0 15

An Example Showing Scanner Usage import java.util.scanner; public class ScannerUsage { public static void main(string [] args) { Scanner keyboard = new Scanner(System.in); // Creates a new Scanner called keyboard System.out.println("Enter an integer of type int"); int n1 = keyboard.nextint(); System.out.println("Enter an integer of type byte"); byte b1 = keyboard.nextbyte(); float f1; double d1; long l1; short s1; boolean bn1; } } System.out.println("Enter a floating point of type float"); f1 = keyboard.nextfloat(); System.out.println("Enter a floating point of type double and Enter an integer of type long"); d1 = keyboard.nextdouble(); l1 = keyboard.nextlong(); System.out.println("Enter an integer of short int and Enter boolean value"); s1 = keyboard.nextshort(); bn1 = keyboard.nextboolean(); System.out.println("n1 = " + n1 +"\nb1 = " + b1 + "\nf1 = " + f1 + "\nd1 = " + d1); System.out.println("l1 = " + l1 +"\ns1 = " + s1 + "\nbn1 = " + bn1); 16

An PracQcal Example Using Scanner import java.util.scanner; // Make the Scanner class available. public class Interest2WithScanner { public static void main(string[] args) { Scanner keyboard = new Scanner( System.in ); // Create the Scanner. double principal; // The value of the investment. double rate; // The annual interest rate. double interest; // The interest earned during the year. System.out.print("Enter the initial investment: "); principal = keyboard.nextdouble(); System.out.print("Enter the annual interest rate "); rate = keyboard.nextdouble(); rate = rate/100; interest = principal * rate; // Compute this year's interest. principal = principal + interest; // Add it to principal. System.out.print("The value of the investment after one year is $"); System.out.println(principal); // } } // end of class Interest2withScanner 17

CasQng (1) The value of a smaller numerical type may be assigned to a higher numerical data type automatically Do you know the order? Casting down must be done explicitly Example: int natural, bigger; double odds, othernumber; odds = 20.3; natural = 5; othernumber = (int)(odds)*natural; bigger = (int)othernumber; System.out.println(otherNumber); //prints 100.0 System.out.println(bigger); //prints 100 othernumber = odds*natural; bigger = (int)othernumber; System.out.println(otherNumber); //prints 101.5 System.out.println(bigger); //prints 101 18

CasQng (2) Remember that float is a special case that always requires casting if you are assigning a floating point number to a float variable float x = 15.0; //This creates an error float y = (float)15.0; //This is proper explicit casting float z = 15; //Implicit casting 19

CasQng (3) Character data may be assigned to any of the types short, int, long, double or float When this happens the ASCII/Unicode value is assigned to the numerical value double x = A ; System.out.print(x); The output is 65.0 Why? However, char chm = A ; System.out.println(chm); The output is A 20

Shortcuts Operator Shortcut For += x+=10 x=x+10 -= x-=10 x=x-10 *= x*=10 x=x*10 /= x/=10 x=x/10 %= x%=10 x=x%10 21

Prefix and PosTix for IncremenQng and DecremenQng There are two mechanisms for adding or subtracting 1 from a variable ++number; //prefix form for adding 1 to number --number; //prefix form for subtracting 1 from number number++; //postfix form for adding 1 to number number--; //postfix form for subtracting 1 from number What s the difference? In assignment statements prefix action takes effect before the assignment In assignment statements postfix action takes effect after the assignment 22

Prefix and PosTix for IncremenQng and DecremenQng (2) Prefix Incrementing int number =5,result; result = 3*(++number); System.out.println(result); 18 System.out.println(number); 6 Postfix Incrementing int number =5,result; result = 3*(number++); System.out.println(result); 15 System.out.println(number); 6 Use postscript incrementing carefully, it can be confusing However, it is very useful when dealing with loops 23

Prefix and PosTix for IncremenQng and DecremenQng (3) Here is what happens in a postfix in prior example result = 3*(number++); a. A hidden temp = number; b. number = number +1; c. result = 3*temp; What is the value printed in the following example; int number =10; number = number++; System.out.println(number); 24

Programming Exercise Class (1) Calculate The Product. Write a program that reads in four integers and prints their product. 25

Programming Exercise Class (2) Exercise 4. Area Write a program that prompts a user for the dimensions (double) of a room in feet (length, width, height) and calculates and prints out the total area of the floor, ceiling and walls. 26

Programming Exercise Lab (1) Exercise 11. Running Sums Write a program that accepts ten integers n1, n2, n3,. n10 and prints a running sum that is, your program should display ten sums: n1, n1+n2, n1+n2+n3 and so on. For example, if the input is 3, 28, 5, 8, 9, 10, 12, 2, 1, -19 then the output is 3 31 36 44 53 63 75 77 78 59 27

10. Larger or Smaller Programming Exercise Lab (2) Write a program that accepts 5 integers, and for each integer following the first, prints true or false depending on whether or not that integer is greater than the previous one. This program can be written more simply after we complete chapter 4. 28