A very simple program. Week 2: variables & expressions. Declaring variables. Assignments: examples. Initialising variables. Assignments: pattern

Similar documents
Datatypes, Variables, and Operations

CS313D: ADVANCED PROGRAMMING LANGUAGE

Program Fundamentals

CEN 414 Java Programming

Chapter 2 Elementary Programming

Chapter 2 Primitive Data Types and Operations. Objectives

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

3. Java - Language Constructs I

Advanced Computer Programming

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

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

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

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

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

Chapter 2. Elementary Programming

Chapter 2 ELEMENTARY PROGRAMMING

PRIMITIVE VARIABLES. CS302 Introduction to Programming University of Wisconsin Madison Lecture 3. By Matthew Bernstein

Data Types and the while Statement

Full file at

Basics of Java Programming

Chapter 2 Primitive Data Types and Operations

Visual C# Instructor s Manual Table of Contents

JAVA OPERATORS GENERAL

DATA TYPES AND EXPRESSIONS

Zheng-Liang Lu Java Programming 45 / 79

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

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

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

A Java program contains at least one class definition.

Algorithms and Programming I. Lecture#12 Spring 2015

Building Java Programs

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Programming with Java

Values and Variables 1 / 30

JAVA Programming Fundamentals

Operators in java Operator operands.

A First Program - Greeting.cpp

CMPT 125: Lecture 3 Data and Expressions

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

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

Chapter 2 Elementary Programming

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

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

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

Building Java Programs

Motivations 9/14/2010. Introducing Programming with an Example. Chapter 2 Elementary Programming. Objectives

1.00 Lecture 4. Promotion

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

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

Simple Java Reference

JAVA Programming Concepts

Object-Oriented Programming

Elementary Programming

Lecture Set 4: More About Methods and More About Operators

Building Java Programs

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

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

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

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

Topic 4 Expressions and variables

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

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

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

Java+- Language Reference Manual

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

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

CS2141 Software Development using C/C++ C++ Basics

Fundamentals of Programming Data Types & Methods

Lesson 3: Accepting User Input and Using Different Methods for Output

Getting started with Java

Software and Programming 1

BASIC ELEMENTS OF A COMPUTER PROGRAM

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

Exercise 4: Loops, Arrays and Files

Guide for The C Programming Language Chapter 1. Q1. Explain the structure of a C program Answer: Structure of the C program is shown below:

Structured Programming Using C++ Lecture 2 : Introduction to the C++ Language. Dr. Amal Khalifa. Lecture Contents:

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Variables and literals

Chapter 2: Data and Expressions

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

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

Example: Tax year 2000

Reserved Words and Identifiers

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

Chapter 2: Basic Elements of C++

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

Values, Variables, Types & Arithmetic Expressions. Agenda

Lecture Set 4: More About Methods and More About Operators

CS 106 Introduction to Computer Science I

Fundamental of Programming (C)

COMP 202 Java in one week

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

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.

Chapter 2 Primitive Data Types and Operations

COMP-202: Foundations of Programming

Chapter 1 Introduction to java

Chapter 2: Data and Expressions

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

Define a method vs. calling a method. Chapter Goals. Contents 1/21/13

Chapter 2: Using Data

Transcription:

School of Computer Science, University of Birmingham. Java Lecture notes. M. D. Ryan. September 2001. A very simple program Week 2: variables & expressions Variables, assignments, expressions, and types. /* a program to print Hello, World on the screen */ public class Hello { public static void main(string[] args) { String greeting; greeting = "Hello, World!\n"; System.out.print(greeting); Declaring variables Variables must be declared before they are used. The general pattern is: type variable ; Examples: int x1 ; double total ; String greeting ; Assignments: examples x = 1; // Assign 1 to x; radius = 1.0; // Assign 1.0 to radius; y = y + 1; total = tenners * 10 + total; total = total * 1.065; area = radius*radius*3.14; a = 'A'; name = "Mark Ryan"; Assignments: pattern General pattern is variable = expression ; Variable names must start with a letter, and can contain numbers, but cannot contain special symbols like +, *. A variable cannot be a Java reserved word, such as public or class. Variables should have meaningful names. Initialising variables It s good practice to initialise variables at the same time as declaring them, as in double radius = 1.0; int total = tenners * 10 + fivers * 5 double area = radius*radius*3.14; char a = 'A'; String name = "Mark Ryan"; 1

Another simple program public class Money1 { public static void main(string[] args) { int pounds = 8; int fivers = 4; int tenners = 3; double total = tenners * 10 + fivers * 5 + pounds * 1; System.out.println(total); // now let s add 6% interest total = total * 1.06; System.out.println(total); Order of evaluation The difference between total = price1 + (price2 * 2) and total = (price1 + price2) * 2 What if we just write total = price1 + price2 * 2? * has higher precedence than + and -. / has higher precedence than + and -. * and / have equal precedence, so 10/5*3 is evaluated left to right. Similarly, + and - have equal precedence. Exercise Answer public class Money2 { public static void main(string[] args) { double invstmt = 1000; System.out.println("Initial investment " + invstmt); invstmt = invstmt * 1.06; System.out.println("Investment after 1 yr " + invstmt); public class Money2 { public static void main(string[] args) { double invstmt = 1000; System.out.println( Initial investment + invstmt); invstmt = invstmt * 1.06 * 1.06; invstmt = invstmt + 10; System.out.println( Investment after 2 yrs (including bonus) + invstmt); Modify this program so that instead of calculating the value of the investment after 1 year. it calculates the value of the investment after 2 years, and adds a bonus of 10, and then prints the result. Some numeric types f type values size range byte integer -128 to 127 short integer -32768 to 32767 int integer -2147483648 to 2147483647 long integer -9223372036854774808 to 9223372036854774808 float real ±3.4 e38 to ±1.4 e-45 9 decimal place precision double real ±1.7 e308 to ±4.9 e-324 18 decimal place precision Respecting types In an expression, we must make sure that we use operations which take values of the type we give them. For example: 2+3 is OK 25.25 - "Mark Ryan" is not OK, because you cannot subtract a string from a double. The compiler will complain. 2.0 + 5 is OK, because the int 5 is converted to a double 2* a is OK, because the character is converted to an integer (its ascii value). 2

Respecting types 2 The variable we assign to must be the right type to take the expression. E.g., if total is an int, then (a) total = 2 + 5; (b) total = 2.45 * 7.63; is OK is not OK If total is a double, then both are OK; in (a), Java will implicitly convert the int to a double. Assignment compatibilities You can assign a value of any type to a variable of a type that appears further down the list: byte short int long float double E.g., you can assign from an int to a double. Finding the unifying type In an expression like 2 * (3.5+7) /1.23 Java will find a type that includes the values it encounters in evaluating the expression. In this case, the result of the expression is a double. Literals A literal whole number (like 34) is considered an int. A literal number with digits after the decimal point (like 53.82) is considered a double. You can make it a float by adding f after it (e.g., 53.82f). Casting To assign from a double to an int, we have to tell Java to get rid of the extra information. We do this by type casting. For example, double price = 2.75; int pounds; pounds = (int) price; results in pounds being 2. Casting precedence Consider what happens if total is 13.75, in each of the following: int pennies = (int) (total * 100) int pennies = ((int) total) * 100 Question: What if we write int pennies = (int) total * 100 Answer: a type cast has highest precedence (i.e. applies to the smallest subexpression possible.) 3

Shortcut operators Operator Example Equivalent += i+=8 i = i+8 -= f-=8.0 f = f-8.0 *= i*=8 i = i*8 /= i/=8 i = i/8 %= i%=8 i = i%8 Increment and decrement operators x = 1; y = 1 + x++; y = 1 + ++x; y = 1 + x--; y = 1 + --x; Increment and decrement operator examples common code int n = 3; int m = 4; int result; What will be the value of m and result after : (a) result = n * ++m; (b) result = n * m++; (c) result = n * --m; (d) result = n * m--; result m 15 5 12 5 9 3 12 3 Program Gotcha: integer division Result int a=6; double t = a/b; System.out.println(t); 0 double a=6.0; double t = a/b; System.out.println(t); 0.75 integer division, again. The boolean data type Program Result boolean switchdown, bulbpresent, lightson; int a=6; double t = (double) (a/b); System.out.println(t); 0 int a=6; double t = ((double)a)/b; System.out.println(t); 0.75 switchdown = true; bulbpresent = false; lightson = switchdown && bulbpresent; // results in false bulbpresent = true; lightson = switchdown && bulbpresent; // results in true daytime = false; cansee = daytime lightson; 4

Some operations on numbers yield values of boolean type. int myvalue = 24; int yourvalue = 32; boolean win = myvalue > yourvalue; boolean draw = myvalue == yourvalue; note: = is the assignment operator; is the comparison relation. boolean lightson = switchdown && (voltage >= 150); Order of evaluation We saw that in total = price1 + price2 * 2; * has higher precedence than +. And in int pennies = (int) total * 100; (type) has higher precedence than *. You can, of course, use brackets to override the precedence: e.g., int pennies = (int) (total * 100); Operator precedence Casting ++, -- *, /, % +, - <, <=, >, => ==,!=; && =, +=, -=, *=, /=, %= Constants static final datatype CONST = value; static final double PI = 3.14159; static final int SIZE = 3; Character data type char letter = 'A'; char letter = '\u000a'; char numchar = '4'; Calling methods In an expression, you can also use function calls, or method calls as they are known in Java. E.g., int n = (int)math.round(100*f); f = Math.sqrt(f); Procedure calls, also called method calls in Java: System.out.println(name5); 5

Naming conventions Variables and method names: Use lowercase. If the name consists of several words, concatenate all in one, use lowercase for the first word, and capitalize the first letter of each subsequent word in the name. For example, the variables radius and area, and the method computearea. Naming conventions, cont. Class names: Capitalize the first letter of each word in the name. For example, the class name PoundsAndPence. Constants: Capitalize all letters in constants. For example, the constant PI. Reading a string from the keyboard Reading an int from the keyboard import java.io.*; //Using the input/output classes import java.io.*; //Using the input/output classes public class Fred { public static void main(string[ ] args) { // `reader' gets characters from the keyboard BufferedReader reader = new BufferedReader( new InputStreamReader(System.in) ); String str=""; System.out.print("Please enter a string: "); try { str = reader.readline(); // read a string catch(ioexception e) { // do nothing on exception System.out.println( "You typed + str + ". ); public class Fred { public static void main(string[ ] args) { // `reader' gets characters from the keyboard BufferedReader reader = new BufferedReader( new InputStreamReader(System.in) ); int x=0; String str=""; System.out.print("Please enter a number: "); try { str = reader.readline(); // read a string x = Integer.parseInt(str); //Convert it to integer catch(ioexception e) { System.out.println( "You typed + x + ". ); Temperature exercise To convert that program into the temperature example, - copy and rename it - instead of System.out.println( "You typed + x + ". ); we put something like double c = (5/9)*(x-32); System.out.println( In Celsius, the temperature is + c + ". ); Random number exercise Let s solve a related problem: obtain a random integer in the range -10 to 10, inclusive. (Is that an even distribution across the range?) What about this problem: in a car simulation program, I want to create cars with random colours in, say, {blue, green, red, yellow with three times as many blue as green, and half as many red/yellow as green. 6