Built-in data types. public static void main(string [] args) logical AND logical OR logical NOT &&! Fundamentals of Computer Science

Similar documents
Built-in data types. logical AND logical OR logical NOT &&! public static void main(string [] args)

Variables and data types

MODULE 02: BASIC COMPUTATION IN JAVA

DATA TYPES AND EXPRESSIONS

CONDITIONAL EXECUTION

1.1 Your First Program

! Widely available. ! Widely used. ! Variety of automatic checks for mistakes in programs. ! Embraces full set of modern abstractions. Caveat.

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

1/16/12. CS 112 Introduction to Programming. A Foundation for Programming. (Spring 2012) Lecture #4: Built-in Types of Data. The Computer s View

Lecture 2: Intro to Java

1.1 Your First Program

CONDITIONAL EXECUTION

1.1 Your First Program

1.1 Your First Program

1.1 Your First Program

1.1 Your First Program! Naive ideal. Natural language instructions.

1.1 Your First Program

Michele Van Dyne Museum 204B CSCI 136: Fundamentals of Computer Science II, Spring

Conditionals, Loops, and Style. Control flow thus far. if statement. Control flow. Common branching statement Evaluate a boolean expression

Conditionals, Loops, and Style

Lecture 2: Intro to Java

1.1 Your First Program

Building Java Programs

Building Java Programs

A human being should be able to change a diaper, plan an invasion, butcher a hog, conn a ship, design a building, write a sonnet, balance accounts,

1.1 Your First Program

Static methods. Not actually a valid Java static method. Fundamentals of Computer Science Keith Vertanen

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

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

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

CSCI 135 Final Fall Problem Points Score Total 100

A foundation for programming. Classes and objects. Overview. Java primitive types. Primitive types Creating your own data types

Inf1-OOP. Textbooks. Who and What. Organizational Issues. Why Java? Course Overview. Hello, World! in Java. Ewan Klein, Perdita Stevens

JAVA Programming Fundamentals

Inf1-OOP. Textbooks. Who and What. Organisational issues. Why Java? Course Overview. Hello, World! in Java

Who and what can help? Inf1-OP. Lecturer: Timothy Hospedales TA: Natalia Zon

Building Java Programs

COMP 110/L Lecture 13. Kyle Dewey

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

Eng. Mohammed S. Abdualal

CSCI 135 Exam #0 Fundamentals of Computer Science I Fall 2013

Lesson 5: Introduction to the Java Basics: Java Arithmetic THEORY. Arithmetic Operators

CIS133J. Working with Numbers in Java

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

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

Program Fundamentals

Inf1-OP. Course Overview. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. February 26, School of Informatics

Zheng-Liang Lu Java Programming 45 / 79

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

Full file at

Topic 4 Expressions and variables

Lecture 2: Operations and Data Types

Full file at

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

Declaration and Memory

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

Visual Programming. Lecture 2: More types, Methods, Conditionals

Getting started with Java

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

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

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

Introduction to Programming Using Java (98-388)

1 class Lecture2 { 2 3 "Elementray Programming" / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch.

JAVA OPERATORS GENERAL

Lecture #6-7 Methods

What did we talk about last time? Examples switch statements

CS 112 Introduction to Programming

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

More on methods and variables. Fundamentals of Computer Science Keith Vertanen

Java Basic Programming Constructs

17 Statement: assignment statement: assigning an expression value 18 Age next year 19 Type: String: conversion: from int 21 Age next year 22 The full

CS111: PROGRAMMING LANGUAGE II

Basics of Java Programming

1. Download the JDK 6, from

Hello World. n Variables store information. n You can think of them like boxes. n They hold values. n The value of a variable is its current contents

CLASSES AND OBJECTS. Fundamentals of Computer Science I

Chapter 3 Selections. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

CS 61B Data Structures and Programming Methodology. June David Sun

CS 302: Introduction to Programming

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

Review for Test 1 (Chapter 1-5)

CMPT 125: Lecture 3 Data and Expressions

Data Structure and Programming Languages

CSC 1214: Object-Oriented Programming

CLASSES AND OBJECTS. Fundamentals of Computer Science I

Operators and Expressions

Primitive Data, Variables, and Expressions; Simple Conditional Execution

Classes and objects. Chapter 2: Head First Java: 2 nd Edi4on, K. Sierra, B. Bates

The Math Class. Using various math class methods. Formatting the values.

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

CS 177 Spring 2010 Exam I

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

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

Building Java Programs Chapter 2

Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

Java Programming Fundamentals. Visit for more.

Building Java Programs Chapter 2

Chapter 3 Selection Statements

Calculations, Formatting and Conversions

Transcription:

Built-in data types logical AND logical OR logical NOT &&! public static void main(string [] args) Fundamentals of Computer Science

Variables Overview Allows us to store and compute on data For now we'll be using basic Java data types String, int, double, boolean, char Variables in Java must be declared including type! Converting between different basic types Types of errors Runtime, compile Random numbers Allow us to simulate random events Needed for loops assignment 2

Variables Variables and data types Stores information your program needs Each has a unique name Each has a specific type Java built-in type what it stores example values operations String sequence of characters "Hello world!" "I love this!" concatenate char characters 'a', 'b', '!' compare int integer values 42 1234 double floating-point values 9.95 3.0e8 boolean truth values true false add, subtract, multiply, divide, remainder add, subtract, multiply, divide and, or, not 3

int a; a = 10; int b; b = 7; int c = a + b; Some definitions Declaration statement I'm going to need an integer and let's call it a NOTE: in Java you are required to declare a variable before using it! Variable name Whenever I say a, I mean the value stored in a Literal I want the value 10 Assignment statement Variable b gets the literal value 7 = in CS is not the same as = in math! Combined declaration and assignment Make me an integer variable called c and assign it the value obtained by adding together a and b 4

String data type Text A sequence of characters Double quote around the characters Concatenation using the + operator String firstname = "Keith"; String lastname = "Vertanen"; String fullname = firstname + " " + lastname; String favnumber = "42"; System.out.println(fullName + "'s favorite number is " + favnumber); Keith Vertanen's favorite number is 42 5

Characters char data type Holds a single character Single apostrophe, e.g. 'a', 'z' public class CharExample public static void main(string [] args) char ch1 = 'y'; char ch2 = 'o'; String result = "" + ch1; result = result + ch2; result = result + ch2; result = result + ch2; Double quotes with nothing in between, an empty String } } System.out.println(result); % java CharExample yooo 6

int data type Integers An integer value between -2 31 and +2 31-1 Between -2,147,483,648 and 2,147,483,647 Operations: add subtract multiply divide remainder + - * / % example result comment 10 + 7 17 10-7 3 Watch out for this! / is integer division if both sides are integers! 10 * 7 70 10 / 7 1 integer division, no fractional part 10 % 7 3 remainder after dividing by 7 10 / 0 runtime error, you can't divide an integer by 0! 7

int data type Integers Normal rules of mathematical precedence e.g. multiplication/division before addition/subtraction Use ()'s to force a different order of calculation example result comment 10 + 7 * 2 24 multiplication comes before addition (10 + 7) * 2 34 ()'s force addition to occur first 10 / 7 + 2 3 integer division result is 1 which is added to 2 10-7 - 2 1 (10-7) - 2 1 10 - (7-2) 5 8

double data type Floating-point numbers Floating-point number (as specified by IEEE 754) Operations: add subtract multiply divide + - * / example result 9.95 + 2.99 12.94 1.0-2.0-1.0 1.0 / 2.0 0.5 1.0 / 3.0 0.3333333333333333 1.0 / 0.0 Infinity 0.0 / 123.45 0.0 0.0 / 0.0 NaN 9

boolean data type Either true or false Booleans Controls logic and flow of control in programs Operations: logical AND logical OR logical NOT &&! Note: two symbols for logical AND and OR, not one! 10

boolean data type Booleans logical AND logical OR logical NOT &&!!a Is a set to false? a && b Are both a and b set to true? a b Is either a or b (or both) set to true? a!a true false false true a b a && b a b false false false false false true false true true false false true true true true true 11

Comparisons Given two numbers return a boolean operator meaning true example false example == equal 7 == 7 7 == 8!= not equal 7!= 8 7!= 7 < less than 7 < 8 8 < 7 <= less than or equal 7 <= 7 8 <= 7 > greater than 8 > 7 7 > 8 >= greater than or equal 8 >= 2 8 >= 10 Is the sum of a, b and c equal to 0? (a + b + c) == 0 Is grade in the B range? (grade >= 80.0) && (grade < 90.0) Is sumitems an even number? (sumitems % 2) == 0 12

Leap year example Years divisible by 4 but not by 100 leap year Years divisible by 400 leap year public class LeapYear public static void main(string [] args) int year = Integer.parseInt(args[0]); boolean isleapyear; // Leap year if divisible by 4 but not by 100 isleapyear = (year % 4 == 0) && (year % 100!= 0); } } // But also leap year if divisible by 400 isleapyear = isleapyear (year % 400 == 0); System.out.println(isLeapYear); % java LeapYear 2000 true 13

Java is strongly typed Type conversion Helps protect you from mistakes (aka "bugs") public class TypeExample0 public static void main(string [] args) int ordertotal = 0; double costitem = 29.95; ordertotal = costitem * 1.06; System.out.println("total=" + ordertotal); } } % javac TypeExample0.java TypeExample0.java:7: possible loss of precision found : double required: int ordertotal = costitem * 1.06; ^ 14

Type conversion Converting from one type to another: Manually using a cast A cast is accomplished by putting a type inside ()'s Casting to int drops fractional part Does not round! public class TypeExample1 public static void main(string [] args) int ordertotal = 0; double costitem = 29.95; ordertotal = (int) (costitem * 1.06); } } System.out.println("total=" + ordertotal); % java TypeExample1 total=31 15

Automatic conversion Numeric types: Type conversion If no loss of precision automatic promotion public class TypeExample2 public static void main(string [] args) double ordertotal = 0.0; int costitem = 30; ordertotal = costitem * 1.06; System.out.println("total=" + ordertotal); } } % java TypeExample2 total=31.8 16

Automatic conversion Type conversion String concatenation using the + operator converts numeric types to also be a String public class TypeExample3 public static void main(string [] args) double costitem = 29.95; String message = "The widget costs "; message = message + costitem; message = message + "!"; System.out.println(message); } } % java TypeExample3 The widget costs 29.95! 17

args array public static void main(string [] args) Program input comes in as Strings from command line (for now) % java CostCalc bananas 12 0.21 To buy 12 bananas you will need $2.52 identifier meaning value type args[0] 1 st thing on command line after Java class name "bananas" String args[1] 2 nd thing on command line "12" String args[2] 3 rd thing on command line after Java class "0.21" String args.length # of things on command line 3 int 18

Static methods Java has lots of helper methods Things that take value(s) and return a result e.g. Math functions e.g. Type conversion: String int String double e.g. Random number generation For now, we'll stick to static methods Live in some particular Java class e.g. Math, Integer or Double Call using class name followed by dot 19

Converting text to a numeric type method description Integer.parseInt(String a) converts text a into an int Double.parseDouble(String a) convert text a into a double public class CostCalc public static void main(string [] args) String product = args[0]; int qty = Integer.parseInt(args[1]); double cost = Double.parseDouble(args[2]); double total = qty * cost; System.out.print("To buy " + qty); System.out.print(" " + product); System.out.println(" you will need $" + total); } } % java CostCalc elections 2 1e6 To buy 2 elections you will need $2000000.0 20

Different types of errors: runtime runtime error % java CostCalc apples 6-10 To buy 6 apples you will need $-60.0 % java CostCalc apples 6 foo Exception in thread "main" java.lang.numberformatexception: For input string: "foo" at sun.misc.floatingdecimal.readjavaformatstring (FloatingDecimal.java:1222) at java.lang.double.parsedouble(double.java:510) at CostCalc.main(ArgsExample.java:7) % java CostCalc apples 6.1 0.25 Exception in thread "main" java.lang.numberformatexception: For input string: "6.1" at java.lang.numberformatexception.forinputstring (NumberFormatException.java:48) at java.lang.integer.parseint(integer.java:458) at java.lang.integer.parseint(integer.java:499) at CostCalc.main(ArgsExample.java:6) % java CostCalc apples 6.0 0.25 Exception in thread "main" java.lang.numberformatexception: For input string: "6.0" at java.lang.numberformatexception.forinputstring (NumberFormatException.java:48) at java.lang.integer.parseint(integer.java:458) at java.lang.integer.parseint(integer.java:499) at CostCalc.main(ArgsExample.java:6) 21

Different types of errors: compile time public class CostCalc public static void main(string [] args) String product = args[0]; int qty = args[1]; double cost = args[2]; double total = qty * cost; compile time error System.out.print("To buy " + qty); System.out.print(" " + product); System.out.println(" you will need $" + total); } } % javac CostCalc.java CostCalc.java:6: incompatible types found : java.lang.string required: int int qty = args[1]; ^ CostCalc.java:7: incompatible types found required: double double cost 2 errors : java.lang.string = args[2]; ^ 22

Randomness Simulate roll of two 6-sided dice Generate two random #'s between 1 and 6 Math.random() number in [0, 1.0) e.g. 0.0, 0.312, 0.9999999 0 1 2 3 4 5 6 7 Math.random()*6 number in [0, 6.0) e.g. 0.0, 1.872, 5.9999999 0 1 2 3 4 5 6 7 (Math.random()*6)+1 number in [1, 7.0) e.g. 1.0, 2.872, 6.9999999 0 1 2 3 4 5 6 7 (int)(math.random()*6)+1 number in set 1, 2, 3, 4, 5, 6} e.g. 1, 2, 6 0 1 2 3 4 5 6 7 23

Randomness Simulate roll of two 6-sided dice Generate two random #'s between 1 and 6 public class TwoDice public static void main(string [] args) int dice1 = (int) (Math.random() * 6) + 1; int dice2 = (int) (Math.random() * 6) + 1; int sum = dice1 + dice2; } } System.out.println(dice1 + " + " + dice2 + " = " + sum); % java TwoDice 3 + 4 = 7 % java TwoDice 1 + 6 = 7 % java TwoDice 1 + 1 = 2 24

Type conversion quiz Automatic: no loss of precision int will convert to a double if need be double cannot automatically convert to int Manual: cast or using a method expression resulting type resulting value (int) 3.14159 Math.round(3.6) 2 * 3.0 2 * (int) 3.0 (int) 2 * 3.0 25

Type conversion quiz Automatic: no loss of precision int will convert to a double if need be double cannot automatically convert to int Manual: cast or using a method expression resulting type resulting value (int) 3.14159 int 3 Math.round(3.6) long 4 2 * 3.0 double 6.0 2 * (int) 3.0 int 6 (int) 2 * 3.0 double 6.0 26

String conversion quiz String conversion, using: Integer.parseInt() Double.parseDouble() expression resulting type resulting value Integer.parseInt("30") Double.parseDouble("30") Integer.parseInt("30.1") Double.parseDouble("30.1") Integer.parseInt("$30") Double.parseDouble(3.14) 27

String conversion quiz String conversion, using: Integer.parseInt() Double.parseDouble() expression resulting type resulting value Integer.parseInt("30") int 30 Double.parseDouble("30") double 30.0 Integer.parseInt("30.1") (runtime error, can't parse as int) Double.parseDouble("30.1") double 30.1 Integer.parseInt("$30") Double.parseDouble(3.14) (runtime error, can't parse as int) (compile (runtime error, 3.14 not a String) 28

String concatenation quiz + is addition for numeric types + is concatenation for String type numeric types convert to String if needed Strings never (automatically) go back to number expression resulting type resulting value "testing " + 1 + 2 + 3 "3.1" + 4159 "2" + " + " + "3" 1 + 2 + 3 + "66" 29

String concatenation quiz + is addition for numeric types + is concatenation for String type numeric types convert to String if needed Strings never (automatically) go back to number expression resulting type resulting value "testing " + 1 + 2 + 3 String "testing 123" "3.1" + 4159 String "3.14159" "2" + " + " + "3" String "2 + 3" 1 + 2 + 3 + "66" String "666" 30

Variables Summary Allows us to store and compute on data String, int, double, boolean, char Boolean operators for logic and program flow control (more on this next time!) Type conversion Automatic e.g. int converting itself to a double Explicit via cast or method call Important! Cause of many, many, many software bugs 31