Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

Similar documents
Midterms Save the Dates!

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

Midterms Save the Dates!

Midterms Save the Dates!

Midterms Save the Dates!

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

COMP 202 Java in one week

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Program Fundamentals

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

ECE 122 Engineering Problem Solving with Java

Computer Components. Software{ User Programs. Operating System. Hardware

An overview of Java, Data types and variables

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

CSC 1214: Object-Oriented Programming

Building Java Programs. Introduction to Programming and Simple Java Programs

PeerWise Study. Midterms Save the Dates! University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Constants Using Classes and Objects

2 rd class Department of Programming. OOP with Java Programming

Welcome to CSE 142! Zorah Fung University of Washington, Spring Building Java Programs Chapter 1 Lecture 1: Introduction; Basic Java Programs

Midterms Save the Dates!

Midterms Save the Dates!

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

3. Java - Language Constructs I

Full file at

CompSci 125 Lecture 02

CS11 Java. Fall Lecture 1

Using Classes and Objects. Lecture 7. Midterms Save the Dates! Extra Credit Survey

Objectives. Problem Solving. Introduction. An overview of object-oriented concepts. Programming and programming languages An introduction to Java

Lecture 2: Variables and Operators. AITI Nigeria Summer 2012 University of Lagos.

Welcome to CSE 142! Whitaker Brand. University of Washington, Winter 2018

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

Accelerating Information Technology Innovation

Midterms Save the Dates!

DM550 Introduction to Programming part 2. Jan Baumbach.

Chapter. Focus of the Course. Object-Oriented Software Development. program design, implementation, and testing

Programming Lecture 3

Computer Components. Software{ User Programs. Operating System. Hardware

Midterms Save the Dates!

Pace University. Fundamental Concepts of CS121 1

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Midterms Save the Dates!

Survey #2. Variable Scope. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings. Scope Static.

Lecture 1: Basic Java Syntax

Getting started with Java

CS 11 java track: lecture 1

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Java Programming. Atul Prakash

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

The Java Language Rules And Tools 3

Java Bytecode (binary file)

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Final Exam. Programming Assignment 3. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

Basics of Java Programming

CS 231 Data Structures and Algorithms, Fall 2016

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

Fall 2017 CISC124 9/16/2017

CS 251 Intermediate Programming Java Basics

Enums. In this article from my free Java 8 course, I will talk about the enum. Enums are constant values that can never be changed.

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner

CS121/IS223. Object Reference Variables. Dr Olly Gotel

Procedures, Parameters, Values and Variables. Steven R. Bagley

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

Chapter 2. Elementary Programming

Java language. Part 1. Java fundamentals. Yevhen Berkunskyi, NUoS

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

CS 177 Week 15 Recitation Slides. Review

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

The Java Language The Java Language Reference (2 nd ed.) is the defining document for the Java language. Most beginning programming students expect

For the course, we will be using JCreator as the IDE (Integrated Development Environment).

CS 106 Introduction to Computer Science I

! This week: Chapter 6 all ( ) ! Formal parameter: in declaration of class. ! Actual parameter: passed in when method is called

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

Computational Expression

JOSE LUIS JUAREZ VIVEROS com) has a. non-transferable license to use this Student Guide

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Oct Decision Structures cont d

Introduction to C# Applications

Java Identifiers. Java Language Essentials. Java Keywords. Java Applications have Class. Slide Set 2: Java Essentials. Copyright 2012 R.M.

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

Entering the world of Javatar

QUIZ. What is wrong with this code that uses default arguments?

Final Exam. Programming Assignment 3. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

Darrell Bethea May 25, 2011

BM214E Object Oriented Programming Lecture 4

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner

Software and Programming 1

Lecture Set 4: More About Methods and More About Operators

Lesson 1. Introduction to Programming OBJECTIVES

Lab # 2. For today s lab:

Survey #2. Teen Talk Barbie TM Reloaded. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu Partially Filled Arrays ArrayLists

Programming with Java

7/8/10 KEY CONCEPTS. Problem COMP 10 EXPLORING COMPUTER SCIENCE. Algorithm. Lecture 2 Variables, Types, and Programs. Program PROBLEM SOLVING

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner

Building Java Programs. Chapter 1: Introduction to Java Programming

University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner

Tokens, Expressions and Control Structures

McGill University School of Computer Science COMP-202A Introduction to Computing 1

public class Foo { private int var; public int Method1() { // var accessible anywhere here } public int MethodN() {

Transcription:

University of British Columbia CPSC 111, Intro to Computation Alan J. Hu Writing a Simple Java Program Intro to Variables Readings Your textbook is Big Java (3rd Ed). This Week s Reading: Ch 2.1-2.5, Ch 4.1-4.2. Lecture 3 Some slides borrowed from Kurt Eiselt and Steve Wolfman. Some learning goals from Beth Simon. Labs and Tutorials Labs and tutorials start this week! You MUST be enrolled in a lab section. If the lab sections you need are full, go to ICICS Room 201 and see a Computer Science undergrad advisor! Learning Goals By the end of the next several lectures you will be able to Apply with basic competence simple programming constructs such as sequential execution, variable typing and declaration, naming, algebraic operations, operation precedence. Create programs which translate explicit English problem statements (an algorithm) into short series of sequential Java instructions. Learning Goals By the end of class today you will be able to Trace and explain the execution of a small set of Java instructions ordered one-by-one, in sequence. Describe the Java rules for identifiers and reserved words. Recognize legal and illegal identifiers. Explain what a variable is, and what a variable declaration does. Declare Java variables of type int. Recognize and write simple assignment statements. Trace the execution of a sequence of simple assignment statements. Last Time We looked at how Java programs get compiled (javac) into a.class file, which we then interpret (java). We looked at the building blocks of a Java program: white space, comments, strings, identifiers, numbers, curly braces, operators We ran and experimented with a simple Java program. 1

A Simple Java Program Our first Java program. /* Traditionally, one s first program in a new language prints out Hello, World! */ class HelloTester public static void main(string[ ] args) System.out.println( Hello, World! ); Multiple Statements class HelloTester public static void main(string[] args) System.out.println( Hello, World! ); System.out.print( I am feeling chatty ); System.out.println( today. ); Another Example public class ManyOreos System.out.println("Feed me more Oreos!"); I'm being sloppy. You'll learn better ways to do this later. javax.swing.joptionpane.showmessagedialog (null,"give me a cookie!"); javax.swing.joptionpane.showmessagedialog (null,"i want cookie!"); javax.swing.joptionpane.showmessagedialog (null,"cookie!!!!"); Remember the Program Counter Program Counter was the special part of a processor that points to the instruction to execute. Fetch-Decode-Execute: one instruction at a time. Java works the same way. You can use your finger to point to where you are in your program. Even expert programmers do this sometimes! More on public class Oreo System.out.println ("Feed me more Oreos!"); Words we use when writing programs are called identifiers except those inside the quotes 2

Sample Java Application Program public class Oreo System.out.println ("Feed me more Oreos!"); Kurt made up identifier Oreo Sample Java Application Program public class Oreo System.out.println ("Feed me more Oreos!"); Other programmers chose identifiers System, out, and println They wrote printing program. Part of huge library of useful programs that comes with Java By using the right identifier, we find what we want. Sample Java Application Program public class Oreo System.out.println ("Feed me more Oreos!"); Special identifiers in Java called reserved words don t use them in other ways Reserved Words Get familiar with these (Appendix G) But you don t need to memorize all 52 for exam abstract do if private throw boolean double implements protected throws break else import public transient byte enum instanceof return true case extends int short try catch false interface static void char final long strictfp volatile class finally native super while const float new switch continue for null synchronized default goto package this Identifier must Start with a letter and be followed by Zero or more letters and/or digits Digits are 0 through 9. Letters are the 26 lowercase letters in English alphabet the 26 uppercase letters in English alphabet plus the $ and _ also alphabetic characters from other languages Identifier must Start with a letter and be followed by Zero or more letters and/or digits Digits are 0 through 9. Letters are the 26 characters in English alphabet both uppercase and lowercase plus the $ and _ also alphabetic characters from other languages Which of the following are not valid identifiers? username user_name $cash 2ndName first name user.age _note_ note2 3

Identifier must Start with a letter and be followed by Zero or more letters and/or digits Digits are 0 through 9. Letters are the 26 characters in English alphabet both uppercase and lowercase plus the $ and _ also alphabetic characters from other languages Which of the following are not valid identifiers? username user_name $cash 2ndName first name user.age _note_ note2 Java is case sensitive Oreo oreo OREO 0reo are all different identifiers, so be careful common source of errors in programming Java is case sensitive Oreo oreo OREO 0reo are all different identifiers, so be careful common source of errors in programming are these all valid identifiers? Creating identifiers in your Java programs Remember other people read what you create Make identifiers meaningful and descriptive for both you and them No limit to how many characters you can put in your identifiers but don t get carried away public class ReallyLongNamesWillDriveYouCrazyIfYouGoOverboard System.out.println ("Enough already!"); Laws versus Customs/Conventions In real life, some things are illegal: murder, shoplifting, running stop signs, etc. Other things are legal, but social norms dictate that we don t do them, because life is better for everyone if we agree to follow the rules: cutting in line, talking on your cell phone in class/movie/concert, being rude, etc. Java has conventions, too. Rules for identifiers are like laws: If you break them, the compiler won t let your program compile: E.g.,: 3am is not a legal identifier. Java also has conventions. These are the normal way Java programmers do things. It s good to follow them. E.g.,: CamelCase: Makes it easier to read. Don t start identifiers with $ or _ We ll learn more as the course goes on 4

Questions? Who cares about identifiers? are used in Java to name things (to identify them). Why do we name things? Who cares about identifiers? are used in Java to name things (to identify them). Why do we name things? To make it easy to refer to them. In computer programming, a fundamental trick is to name a chunk of memory, so you can store data there and find it easily. Memory and Example of a high-level instruction Tells computer to go to main memory and find value stored in location called b go to main memory and find value stored in location called c add those two values together store result in memory in location called a Great! But... in reality, locations in memory are not actually called things like a, b, and c. Memory Recap Memory: series of locations, each having a unique address, used to store programs and data When data is stored in a memory location, previously stored data is overwritten and destroyed Each memory location stores one byte (8 bits) of data 5802 5803 5804 5805 5806 5807 10110101 Data values are stored in memory locations more than one location may be used if the data is large. Address* *For total accuracy, these addresses should be binary numbers, but you get the idea, no? Memory and So what s with the a, b, and c? Machine language uses actual addresses for memory locations High-level languages easier Avoid having to remember actual addresses Invent meaningful identifiers giving names to memory locations where important information is stored payrate and hoursworked vs. 5802 and 5806 Easier to remember and a whole lot less confusing! 5

Memory and : Variables Variable: name for location in memory where data is stored A little like variables in algebra class payrate, hoursworked, a, b, and c are all variables Variable names begin with lower case letters Java convention, not compiler/syntax requirement Variable may be name of single byte in memory or may refer to a block of many bytes More about this later Programming With Variables Test.java Author: Kurt Our first use of variables! public class Test System.out.print ("The answer is "); System.out.println (a); Programming With Variables (Shorthand) Programming With Variables Test.java Author: Kurt Our first use of variables! public class Test Let s give it a try... Test.java Author: Kurt Our first use of variables! public class Test Let s give it a try... b and c cannot be found! need to assign values Programming With Variables: Take 2 Programming With Variables: Take 2 Test2.java Author: Kurt Our second use of variables! public class Test2 b = 3; c = 5; Test2.java Author: Kurt Our second use of variables! public class Test2 b = 3; c = 5; Now what? such a lazy computer, still can t find symbols... 6

: Now What? Data Types Java requires that we tell it what kind of data it is working with b c 00000011 00000101 memory For every variable, we have to declare a data type Java language provides eight primitive data types i.e. simple, fundamental Java doesn t know : how to interpret the contents of the memory location are they integers? characters from the keyboard? shades of gray? or... For more complicated things, can use data types created by others provided to us through the Java libraries that we invent More soon - for now, let s stay with the primitives We want a, b, and c to be integers. Here s how we do it... Programming With Variables: Take 3 Test3.java Author: Kurt Our third use of variables! public class Test3 int a; these int b; are int c; variable declarations b = 3; c = 5; Variable Declaration variable declaration is instruction to compiler reserve block of main memory large enough to store data type specified in declaration variable name is specified by identifier syntax: typename variablename; Assignment Test3.java Author: Kurt Our third use of variables! public class Test3 int a; int b; int c; b = 3; these c = 5; are assignment statements Assignment Statements Assignment statement assigns value to variable Assignment statement is identifier followed by assignment operator (=) followed by expression followed by semicolon (;) b = 3; c = 8; weekly_pay = pay_rate * hours_worked; Note that = is not a test for equality! 7

Assignment Statements Java first computes value on right side Then assigns value to variable given on left side x = 4 + 7; what s in x? Old value will be overwritten if variable was assigned before x = 2 + 1; what s in x now? Note that = is not a test for equality! Assignment is a new concept in CS versus math. Fetch-decode-execute Dynamic. Something happens. x = x + 1; Read = as gets (short for gets assigned the value ). Assignment Statements Here s an occasional point of confusion: Assignment Statements Here s an occasional point of confusion: Find out! Experiments are easy to do in CS Assignment Statements Here s an occasional point of confusion: Variable values on left of = are clobbered Variable values on right of = are unchanged copy of value assigned to a also assigned to b but that doesn t change value assigned to a Assignment Statements Here s an occasional point of confusion: Memory locations a and b are distinct value of a at that point assigned to b changing a later does not affect previous copy 8

a: b: a: 7 b: a: 7 b: 7 a: 7 b: 7 a: 7 8 b: 7 a: 7 8 b: 7 9

Or, draw little boxes with values in them. a = 7; b = a; a=?, b=? Or, draw little boxes with values in them. a = 7; b = a; a=?, b=? a=7, b=? Questions? Or, draw little boxes with values in them. a = 7; b = a; a=?, b=? a=7, b=? a=7, b=7 10