Variables and Assignments CSC 121 Fall 2015 Howard Rosenthal

Similar documents
Variables and Assignments CSC 121 Fall 2014 Howard Rosenthal

Variables and Assignments CSC 121 Spring 2017 Howard Rosenthal

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

Programming with Java

ECE 122 Engineering Problem Solving with Java

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

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

Peer Instruction 1. Elementary Programming

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Computational Expression

JAVA Ch. 4. Variables and Constants Lawrenceville Press

Repetition CSC 121 Fall 2014 Howard Rosenthal

CEN 414 Java Programming

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Arrays and Lists CSC 121 Fall 2014 Howard Rosenthal

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

Full file at

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

Basics of Java Programming

Data Conversion & Scanner Class

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

St. Edmund Preparatory High School Brooklyn, NY

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

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

Chapter 2: Data and Expressions

Methods CSC 121 Fall 2016 Howard Rosenthal

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

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.

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

Introduction to Java Unit 1. Using BlueJ to Write Programs

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

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

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Methods CSC 121 Spring 2017 Howard Rosenthal

Chapter 2 ELEMENTARY PROGRAMMING

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

Java Coding 3. Over & over again!

STUDENT LESSON A7 Simple I/O

Chapter 3: Operators, Expressions and Type Conversion

Basic Operations jgrasp debugger Writing Programs & Checkstyle

Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal

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

Chapter 4 Fundamental Data Types. Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved.

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

Introduction to Computer Programming

Chapter 2. Elementary Programming

Arrays and Lists CSC 121 Fall 2015 Howard Rosenthal

Computational Expression

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

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

Chapter 2 Elementary Programming

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

Chapter 2: Data and Expressions

Basic Computation. Chapter 2

Lesson 7 Part 2 Flags

Getting started with Java

Example: Computing prime numbers

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

Unit 3. Operators. School of Science and Technology INTRODUCTION

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

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

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

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

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

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation.

Basic Programming Elements

Data Types and the while Statement

Big Java. Fifth Edition. Chapter 3 Fundamental Data Types. Cay Horstmann

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

AP Computer Science Unit 1. Writing Programs Using BlueJ

Object-Oriented Programming

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I

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

Chapter 3. Selections

Oct Decision Structures cont d

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java

DATA TYPES AND EXPRESSIONS

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

Elementary Programming

int: integers, no fractional part double: floating-point numbers (double precision) 1, -4, 0 0.5, , 4.3E24, 1E-14

2/9/2012. Chapter Four: Fundamental Data Types. Chapter Goals

Chapter. Let's explore some other fundamental programming concepts

double float char In a method: final typename variablename = expression ;

Basic Computation. Chapter 2

Building Java Programs

Over and Over Again GEEN163

Variables, Types, Operations on Numbers

CSCI 136 Data Structures & Advanced Programming. Fall 2018 Instructors Bill Lenhart & Bill Jannen

More Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements

3. Java - Language Constructs I

Program Fundamentals

Full file at

Computer Science is...

CS 231 Data Structures and Algorithms, Fall 2016

Fall 2017 CISC124 9/16/2017

Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

Introduction to Java Applications

CMPT 125: Lecture 3 Data and Expressions

Transcription:

Variables and Assignments CSC 121 Fall 2015 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 an object) is a named memory location capable of storing data of a specified type Variables indicate logical, not physical addresses Those are taking 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. Cost_of_Home $128,695.22 3

What is a Variable (2) A declaration of a variable is where a program says that it needs a variable 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 } } 4

Declaring Variables Variables must be declared before the are used Basic syntax: Type name1, name2, name3 ; Example: double dinner_bill, credit_balance, money_in_bank; Variables can be explicitly initialized when they are used long 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 '$'. A variable name cannot contain the space character. Do not start with a digit. An identifier 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 can not be a reserved word. Don t use the same name twice, even as different types 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: total = 3 + 5; // total =8 price = 34.56; tax = price*0.05; //tax = 1.728 While you can t do multiple initializations at once, you can do multiple assignments: 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? value = 5; System.out.println("value is: " + value ); value = value + 10; System.out.println("value is: " + value ); 8

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 9

An Example of a Simple Program 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: 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. 10

Obtaining Input Data Using Scanner A Scanner is an object. You must include the following statement to use the 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: 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 the keyboard You can now access seven types of input: byte, short, int, long, double, float and boolean using predefined methods associated with object A Scanner object doesn t read characters The ScannerName is just another identifier 11

There are 7 Input Methods Available ScannerName.nextByte() ScannerName.nextShort() ScannerName.nextInt() ScannerName.nextLong() ScannerName.nextDouble() ScannerName.nextFloat() ScannerName.nextBoolean() What you are looking at above is the standard way objects access methods: objectname.method(par1, par2, ) - There are no parameters required for these methods 12

An 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 13

CasPng (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 14

CasPng (2) 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? 15

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 16

Prefix and PosRix for IncremenPng and DecremenPng 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 take effect before the assignment In assignment statements postfix action take effect after the assignment 17

Prefix and PosRix for IncremenPng and DecremenPng (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 18

Programming Exercise Class (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 19

10. Larger or Smaller Programming Exercise Lab(1) 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 reading chapter 4. 20