MODULE 02: BASIC COMPUTATION IN JAVA

Similar documents
DATA TYPES AND EXPRESSIONS

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

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

Variables and data types

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

Primitive Types. Four integer types: Two floating-point types: One character type: One boolean type: byte short int (most common) long

Basic Computation. Chapter 2

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language

Full file at

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

Full file at

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

Basics of Java Programming

COMP Primitive and Class Types. Yi Hong May 14, 2015

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

1.1 Your First Program

PROGRAMMING STYLE. Fundamentals of Computer Science I

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

Program Fundamentals

Basic Computation. Chapter 2

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

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

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

Zheng-Liang Lu Java Programming 45 / 79

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

Lecture 2: Intro to Java

Chapter 2: Data and Expressions

1.1 Your First Program

CMPT 125: Lecture 3 Data and Expressions

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

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

Chapter 3: Operators, Expressions and Type Conversion

Building Java Programs

CIS133J. Working with Numbers in Java

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

Building Java Programs

Declaration and Memory

ECE 122 Engineering Problem Solving with Java

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

A Java program contains at least one class definition.

CS 112 Introduction to Programming

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

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

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

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

Visual C# Instructor s Manual Table of Contents

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. A Guide to this Instructor s Manual:

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

Reserved Words and Identifiers

Eng. Mohammed S. Abdualal

Getting started with Java

Chapter 2: Data and Expressions

1.1 Your First Program

1 Introduction Java, the beginning Java Virtual Machine A First Program BlueJ Raspberry Pi...

Chapter 2: Data and Expressions

1.1 Your First Program

Java Bytecode (binary file)

What did we talk about last time? Examples switch statements

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

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Object-Oriented Programming

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

COMP 110 Introduction to Programming. What did we discuss?

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

Two Types of Types. Primitive Types in Java. Using Primitive Variables. Class #07: Java Primitives. Integer types.

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

CS112 Lecture: Primitive Types, Operators, Strings

Course PJL. Arithmetic Operations

Types and Expressions. Chapter 3

Basic Operations jgrasp debugger Writing Programs & Checkstyle

Chapter 2 Elementary Programming

Calculations, Formatting and Conversions

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

9/5/2018. Overview. The C Programming Language. Transitioning to C from Python. Why C? Hello, world! Programming in C

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

Chapter 1 Introduction to java

4 Programming Fundamentals. Introduction to Programming 1 1

C/C++ Programming for Engineers: Working with Integer Variables

egrapher Language Reference Manual

1.1 Your First Program

Lecture 2: Intro to Java

Chapter 2: Using Data

CONDITIONAL EXECUTION

The C Programming Language. (with material from Dr. Bin Ren, William & Mary Computer Science)

Chapter 2: Using Data

The C++ Language. Arizona State University 1

Basics of Java Programming variables, assignment, and input

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

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

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

Chapter 2 Primitive Data Types and Operations. Objectives

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

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

CS313D: ADVANCED PROGRAMMING LANGUAGE

Building Java Programs

JAVA OPERATORS GENERAL

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

JAVA Programming Fundamentals

Algorithms and Programming I. Lecture#12 Spring 2015

C++ Programming: From Problem Analysis to Program Design, Third Edition

Transcription:

MODULE 02: BASIC COMPUTATION IN JAVA

Outline Variables Naming Conventions Data Types Primitive Data Types Review: int, double New: boolean, char The String Class Type Conversion Expressions Assignment Mathematical Boolean Sequential Execution

Variables Variables store data such as numbers and letters. Think of them as places to store data. They are implemented as memory locations. The data stored in a variable is called its value. The value is stored in the memory location. Its value can be changed. In Java, we always have to declare (define) a variable before we can use it x

Variables: Naming Convention A variable's name should suggest its use e.g. taxrate Begin with lowercase, uppercase each new word int totalwidgets; Called lower camel case

Data Types A primitive type is used for simple, non-decomposable values such as an individual number or individual character. int, double, and char are primitive types. A class type is used for a class of objects and has both data and methods. "Java is fun" is a value of class type String DEFINITION A data type is a set of values and the legal operations on those values.

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 int integer values 42 1234 double floating-point values 9.95 3.0e8 char characters 'a', 'b', '!', '2' compare add, subtract, multiply, divide, remainder, compare, increment, decrement add, subtract, multiply, divide, compare String sequence of characters boolean truth values true false "Hello world!" "I love this!" concatenate and, or, not 6

Data Types: Integers Addition: + Subtraction: - Multiplication: * Division: / Careful! Remainder is discarded in result e.g. 23/5 = 4 Remainder: % Remainder is the result e.g. 23%5 = 3 Comparision: Greater then, greater than or equal:>, >= Less than, less than or equal: <, <= Equal: == Not equal:!= Increment, Decrement: ++, -- Java built-in type what it stores example values int integer values 42 1234 operations add, subtract, multiply, divide, remainder, compare, increment, decrement

Data Types: Floating Point Numbers Addition: + Subtraction: - Multiplication: * Division: / With floating point numbers, the remainder is part of the result e.g. 23.0/5.0 = 4.6 Comparision: Greater then, greater than or equal:>, >= Less than, less than or equal: <, <= Don t use == or!= to test for equality Because of the way numbers are stored, what appears to be an equal floating point number is not exactly the same Java built-in type what it stores example values operations double floating-point values 9.95 3.0e8 add, subtract, multiply, divide, compare

Data Types: Characters Comparision: Greater then, greater than or equal:>, >= Less than, less than or equal: <, <= Equal: == Not equal:!= Java built-in type what it stores example values operations char characters 'a', 'b', '!', '2' compare

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 10

Data Types: Strings (of Characters) Concatentation: + e.g. Hello + World becomes HelloWorld If you want a space in there, you need to put it in the string Either: Hello + World Or: Hello + World Any number of strings can be concatenated using the + operator. Java built-in type what it stores example values operations String sequence of characters "Hello world!" "I love this!" concatenate

Concatenating Strings and Integers String data type A sequence of characters Double quote around the characters Concatenation using the + operator String firstname = Michele"; String lastname = "Van Dyne"; String fullname = firstname + " " + lastname; String favnumber = "42"; System.out.println(fullName + "'s favorite number is " + favnumber); Michele Van Dyne's favorite number is 42 12

String Methods An object of the String class stores data consisting of a sequence of characters. Objects have methods as well as data Recall a data type is a set of values and the operations allowed on those values For numeric data types, these are mathematical operations For class data types, these operations are its methods

The Method length() The method length() returns an int. You can use a call to method length() anywhere an int can be used. int count = command.length(); System.out.println("Length is " + command.length()); count = command.length() + 3;

String Indices Positions start with 0, not 1. The 'J' in "Java is fun." is in position 0 A position is referred to an index. The 'f' in "Java is fun." is at index 8.

Data Types: Boolean / Logical And: &&, & If both arguments are true, result is true, otherwise false Or:, If any argument is true, result is true, otherwise false Not:! If argument is true, result is false and vice versa Boolean variables should suggest a true/false value Choose names such as ispositive or systemsareok. Avoid names such as numbersign or systemstatus. Java built-in type what it stores example values operations boolean truth values true false and, or, not

Booleans boolean data type 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 17

Data Types: Constants Literal expressions such as 42, 3.7, or 'y' are called constants. Integer constants can be preceded by a + or - sign, but cannot contain commas. Floating-point constants can be written With digits after a decimal point or Using e notation. Constants All upper case, use _ between words double SPEED_LIGHT = 3.0e8;

Creating and Initializing a Primitive Variable byte x = 7; x primitive value x 011010101010100101010101110101010101010101010111010101 000101010101010111101010101010101010101001001101010101 010010101010110000001110101010101011101010100010101010 101011110101010101010101010100100110101010101001010101 011101010101010101010101110101010001010101010101111010 101010101010101010010011010101010100101010101110101010 101010101010111010101000101010101010111101010101010101 010101001001101010101010010101010111010101010101010101 19

Changing the Value of a Primitive Variable byte x = 7; x = x + 1; x primitive value x 011010101010100101010101110101010101010101010111010101 000101010101010111101010101010101010101001001101010101 010010101010110000010000101010101011101010100010101010 101011110101010101010101010100100110101010101001010101 011101010101010101010101110101010001010101010101111010 101010101010101010010011010101010100101010101110101010 101010101010111010101000101010101010111101010101010101 010101001001101010101010010101010111010101010101010101 20

Mathematical Expressions: Parentheses and Precedence Parentheses can communicate the order in which arithmetic operations are performed examples: (cost + tax) * discount (cost + (tax * discount) Without parentheses, an expressions is evaluated according to the rules of precedence.

Precedence Rules When binary operators have equal precedence, the operator on the left acts before the operator(s) on the right.

Boolean Expressions: 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 23

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 24

Creating and Initializing a Primitive Variable byte x = 7; x = x + 1; short y = 7; x primitive values y x y 011010101010100101010101110101010101010101010111010101 000101010101010111101010101010101010101001001101010101 010010101010110000010000101010101011101010100010101010 101011110101010101010101010100100110101010101001010101 011101000000000000011101110101010001010101010101111010 101010101010101010010011010101010100101010101110101010 101010101010111010101000101010101010111101010101010101 010101001001101010101010010101010111010101010101010101 25

You can't put a big cup into a small one You may know 7 can fit in a byte, but compiler doesn't! byte x = 7; x = x + 1; short y = 7; x = y; x primitive values y x y 011010101010100101010101110101010101010101010111010101 000101010101010111101010101010101010101001001101010101 010010101010110000010000101010101011101010100010101010 101011110101010101010101010100100110101010101001010101 011101000000000000011101110101010001010101010101111010 101010101010101010010011010101010100101010101110101010 101010101010111010101000101010101010111101010101010101 010101001001101010101010010101010111010101010101010101 26

Assignment Compatibilities Java is said to be strongly typed. You can't, for example, assign a floating point value to a variable declared to store an integer. Sometimes conversions between numbers are possible. doublevariable = 7; is possible even if doublevariable is of type double, for example.

Assignment Compatibilities A value of one type can be assigned to a variable of any type further to the right byte --> short --> int --> long --> float --> double But not to a variable of any type further to the left. This is called automatic type conversion You can assign a value of type char to a variable of type int.

Type Casting A type cast temporarily changes the value of a variable from the declared type to some other type. For example, double distance; distance = 9.0; int points; points = (int)distance; Illegal without (int) The value of (int)distance is 9, The value of distance, both before and after the cast, is 9.0. Any nonzero value to the right of the decimal point is truncated rather than rounded.

Type Conversion Java is strongly typed 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; ^ 30

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 31

Type Conversion Automatic conversion Numeric types: 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 32

Type Conversion Automatic 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! 33

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 34

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 static method expression resulting type resulting value (int) 3.14159 Math.round(3.6) 2 * 3.0 2 * (int) 3.0 (int) 2 * 3.0 35

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 36

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) 37

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) 38

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" 39

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" 40

Comments The best programs are self-documenting. Clean style Well-chosen names Comments are written into a program as needed to explain the program. They are useful to the programmer, but they are ignored by the compiler. // comment to end of line /* multi-line comment /* /** * javadoc comment */

Summary Variables Naming Conventions Data Types Primitive Data Types Review: int, double New: boolean, char The String Class Type Conversion Expressions Assignment Mathematical Boolean Sequential Execution