Week 3: Basic Operations

Slides:



Advertisements
Similar presentations
Escape Sequences \n newline \t tab \b backspace \r carriage return
Advertisements

Introduction to Computing Concepts Note Set 7. Overview Variables Data Types Basic Arithmetic Expressions ▫ Arithmetic.
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
Week 2: Primitive Data Types 1.  Programming in Java  Everything goes inside a class  The main() method is the starting point for executing instructions.
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
ECE122 L3: Expression Evaluation February 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
String Escape Sequences
Week 2 - Friday.  What did we talk about last time?  Data representation  Binary numbers  Types  int  boolean  double  char  String.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Week 3 - Wednesday.  What did we talk about last time?  Math methods  Lab 2.
CSC Programming I Lecture 5 August 30, 2002.
Week 2 - Wednesday.  What did we talk about last time?  Data representation  Binary numbers  Types  int  boolean  double  char  String.
Week 2 - Friday.  What did we talk about last time?  Using Scanner to get input  Basic math operations.
5 BASIC CONCEPTS OF ANY PROGRAMMING LANGUAGE Let’s get started …
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
1 CS 177 Week 3 Recitation Slides Basic Math Operations, Booleans, and Character Operations.
Chapter 2 Variables.
COMP Primitive and Class Types Yi Hong May 14, 2015.
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
COMP 110: Spring Announcements Lab 1 due Wednesday at Noon Assignment 1 available on website Online drop date is today.
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Week 3 - Monday.  What did we talk about last time?  Using Scanner to get input  Basic math operations  Lab 2.
© 2004 Pearson Addison-Wesley. All rights reserved August 27, 2007 Primitive Data Types ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
CS 106A, Lecture 4 Introduction to Java
Week 2 - Wednesday CS 121.
Chapter 2 Variables.
Week 4 - Friday CS 121.
Week 3 - Wednesday CS 121.
Topics Designing a Program Input, Processing, and Output
Expressions.
Introduction to Computer Science / Procedural – 67130
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
Debugging and Random Numbers
Multiple variables can be created in one declaration
Variables and Primative Types
Primitive Data, Variables, Loops (Maybe)
Fundamental of Java Programming Basics of Java Programming
Type Conversion, Constants, and the String Object
CS 177 Week 3 Recitation Slides
Introduction to C++ Programming
Building Java Programs
Building Java Programs
Chapter 2 Variables.
Introduction to Primitive Data types
Building Java Programs Chapter 2
Building Java Programs
Building Java Programs
Topics Designing a Program Input, Processing, and Output
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Topics Designing a Program Input, Processing, and Output
Introduction to Primitives
Fundamental OOP Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Introduction to Primitives
In this class, we will cover:
Primitive Types and Expressions
Unit 3: Variables in Java
Building Java Programs Chapter 2
Chapter 2 Variables.
Building Java Programs
Introduction to Primitive Data types
Week 3 - Friday COMP 1600.
Building Java Programs
Presentation transcript:

Week 3: Basic Operations CS 177

What did we talk about last week? Data representation Built-in types int double boolean char String Literals Declaration of variables Assignment

Basic operations In Java, each data type has a set of basic operations you are allowed to perform It is not possible to define new operations or change how the operations behave Some programming languages allow this, but not Java

Operations for each type We are going to consider the basic operations for numerical types: int double

The + Operator for int Use the + operator to add two ints together int a; int b; a = 5 + 6; // a contains 11 b = a + 3; // b contains 14 a + b; // not allowed, does nothing a = a + 1; // a contains 12, and b?

Shortcuts Some expressions are used so often that Java gives us a short cut x = x + y; can be written x += y; x = x + 1; can be written x++; int x; x = 6; // x contains 6 x += 4; // x contains 10 x++; // x contains 11

The - Operator for int Exactly like + except performs subtraction int a; int b; a = 6 - 5; // a contains 1 b = 3 - a; // b contains 2 a -= 10; // shortcut for a = a – 10; a--; // shortcut for a = a – 1;

The * Operator for int The * operator performs multiplication int a; int b; a = 5 * 6; // a contains 30 b = a * 3; // b contains 90 a *= 2; // shortcut for a = a * 2;

The / Operator for int The / operator performs integer division when used with two ints Not the same as regular division The factional part is dropped, not rounded int a; int b; a = 9; // a contains 9 b = a / 2; // b contains 4 a /= 2; // shortcut for a = a / 2;

The % Operator for int The % operator is the mod operator It returns the remainder after division This operator is a good way to find out if a number is even or odd int a; int b; a = 38; // a contains 38 b = a % 5; // b contains 3 a %= 2; // shortcut for a = a % 2;

Area example Compute the area of a rectangle width Area length area = width * length; width Area length

Conversion example If you run 26 miles, how many feet is that?

The + Operator for double Exactly the same as + for int, except now you can have fractional parts double a; double b; a = 3.14159; // a contains 3.14159 b = a + 2.1; // b contains 5.24159 a += 1.6; // shortcut for a = a + 1.6; a++; // shortcut for a = a + 1.0;

The – and * Operator for double No surprises here They do subtraction and multiplication double a; double b; a = 3.14159; // a contains 3.14159 b = a - 2.1; // b contains 1.04159 a = b * 0.5; // a contains 0.520795

The / Operator for double Unlike int, this division does have fractional parts Can you explain this mystery? double a; double b; a = 9; // a contains 9.0 b = a / 2; // b contains 4.5 b = 9 / 2; // b contains 4.0

Area example Compute the area of a triangle height Area base area = 1.0/2.0 * base * height; height Area base

TF = (9/5)TC + 32 Conversion example Given a temperature in Celsius, what is the equivalent in Fahrenheit? TF = (9/5)TC + 32 tempF = 9.0/5.0 * tempC + 32;

Complex expressions How complex can expressions get? What’s the value of a? 18! int a = 31; int b = 16; int c = 1; int d = 2; a = b + c * d – a / b / d;

Complex expressions Order of operations holds like in math You can use parentheses to clarify or change the precedence Now a is 46 int a = 31; int b = 16; int c = 1; int d = 2; a = (((b + c) * d) – a / b) / d;

Casting You cannot directly store a double value into an int variable However, you can cast the double value to convert it into an int Casting tells the compiler that you want the loss of precision to happen You can always store an int into a double int a = 2.6; // fails! int a = (int)2.6; // succeeds! (a = 2)

Rounding In Java, the conversion of a double into an int does not use rounding As in the case of integer division, the value is always rounded down You can think of this as using the floor function from math If you want to round normally, you can simply add 0.5 before the cast double x = 2.6; int a = (int)(x + 0.5); // rounds

Adding is great, but… There are operations beyond +, -, *, /, and % that you probably want to do with numbers Java has those built-in because the computer can do those directly A number of other operations can be done by calling methods Methods will end up being very important to us later

Methods A method is a collection of Java code that has been packaged up so that you can use it over and over Usually a method will take some input and give some output System.out.println() is an example of a method Using a method (calling a method) always requires parentheses

Method example with sin() The sin() method allows you to find the sine of an angle (in radians) This method is inside the Math class The answer that it gives back is of type double To use it, you might say the following: double value = Math.sin( 2.4 );

result = class.method( input ); Method syntax Unless the method is inside your class, you must supply a class name and a dot If your method takes input, you put it inside the parentheses, if not, you leave them empty result = class.method( input ); You can store the result of the method, as long as the variable matches the type that the method gives back Next, you must give the method name that you are calling

Other Math methods Return type Name Job double sin( double theta ) Find the sine of angle theta cos( double theta ) Find the cosine of angle theta tan( double theta ) Find the tangent of angle theta exp( double a ) Raise e to the power of a (ea) log( double a ) Find the natural log of a pow( double a, double b ) Raise a to the power of b (ab) long round( double a ) Round a to the nearest integer random() Create a random number in [0, 1) sqrt( double a ) Find the square root of a

Operations on booleans The boolean type seems so simple What on earth would we want to do with it? Just like numerical types, we can combine booleans in various ways You might be familiar with these operations if you have taken a course in logic

The ! Operator The NOT operator Changes a true into a false or a false into a true x !x true false

The && Operator The AND operator It gives back true only if both things being combined are true x y x && y true false

The || Operator The OR operator It gives back true if either or both things being combined are true x y x || y true false

The ^ Operator The XOR operator is what some people mean when they say “or” in English It gives back true if one but not both things are true x y x ^ y true false

Short circuit evaluation In some circumstances, Java doesn’t check the whole expression: (true || (some complicated expression)) Ignores everything after || and gives back true (false && (some complicated expression)) Ignores everything after && and gives back false

What kinds of operations would you expect on chars? Multiplication and division don’t seem to make sense We can increment and decrement a char char letter; letter = ‘f’; // letter contains ‘f’ letter++; // letter contains ‘g’ letter++; // letter contains ‘h’

Sometimes it’s useful to know the number It is possible to convert a char into an int It can often be more useful to get the offset from a starting point int number; number = ‘a’; // letter contains 97 char letter = ‘r’; int number; number = letter - ‘a’ + 1; //number is 18

Escape sequences Remember that we use single quotes to designate a char literal: ‘z’ What if you want to use the apostrophe character ( ‘ )? apostrophe: ‘\’’ What if you want to use characters that can’t be printed, like tab or newline? tab: ‘\t’ newline: ‘\n’ The backslash is a message that a special command called an escape sequence is coming

Concatenation The only operator that we will use directly with Strings is the + (concatenation) operator This operator creates a new String that is the concatenation of the two source Strings As with numerical types, the + operator does not change the two Strings being concatenated String word; word = “tick” + “tock”; // word is “ticktock”

Concatenation with other types Concatenation is a great tool for merging lots of different types into a String Be careful about the order: String word; word = 99 + “ problems”; // word is // “99 problems” String word; word = “love potion #” + 4 + 5; // word is “love potion #45” word = “love potion #” + (4 + 5); // word is “love potion #9”

Strings are objects Objects have data inside of them but also have the ability to do things with methods Among other things, Strings can: Compare themselves with other Strings Report their length Say which character is located at position i Report a substring

String comparison To see if two Strings are identical, use the equals() method: If they are the same (including case), the method equals() will return true If they are not, the method will return false String word1 = “lettuce”; String word2 = “let us”; boolean same = word1.equals(word2); // false

String comparison To see which String goes first in the dictionary, use the compareTo() method: If word1 comes first, value will be a negative number If word2 comes first, value will be a positive number If they are the same, value will be 0 String word1 = “hard work”; String word2 = “success”; int value = word1.compareTo( word2 ); // < 0

String length To find the length of a String, use the length() method: It is possible to have a String of length 0: String word = “a mile long”; int length = word.length(); // length = 11 String nothing = “”; int length = nothing.length(); // length = 0

char at position i To find the char at position i in a String, use the charAt() method: Be careful not to ask for a character out of range: String word = “walnut”; char c = word.charAt(3); // c = ‘n’ String word = “short”; char c = word.charAt(10); // ouch!

Getting a substring To get a substring of a String, use the substring() method: The first int tells which char to start on, the second int says which char to stop before String word1 = “disco fever”; String word2 = word1.substring(3,7); //word2 = “co f”

Classes and objects are useful There are certain things that are difficult to do with the operations we’ve shown you For example, how do you turn a String representation of a number like “847” into the actual int 847? Wrapper classes!

Wrapper classes Each primitive data type in Java has a wrapper class We will focus on 3: Integer Double Character

Integer class The main uses of the Integer class are converting ints to and from Strings To convert a String to an int, use the parseInt() method To convert an int to a String, use the toString() method String number = “345”; int value = Integer.parseInt(number); int value = 543; String number = Integer.toString(value);

Double class The Double class is much like the Integer class To convert a String to a double, use the parseDouble() method To convert a double to a String, use the toString() method String number = “0.4581”; double value = Double.parseDouble(number); double value = 6.0223; String number = Double.toString(value);

Charcter class The Character class is mostly useful for getting information about a particular char For example, you can find out whether a char is a digit, is a letter, is uppercase, or is lowercase by calling the isDigit(), isLetter(), isUpperCase(), or isLowerCase() methods, respectively char c = ‘8’; boolean value = Character.isDigit(c); //true

Where we are headed Next week we will talk about conditional execution if-statements switch-statements Conditionals will allow you to write a program that makes choices With choices, your program can do different things based on input