490 likes | 642 Views
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
E N D
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 inta; 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++; intx; x = 6; // x contains 6 x += 4; // x contains 10 x++; // x contains 11
The - Operator for int • Exactly like + except performs subtraction inta; 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 inta; 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 • Notthe same as regular division • The factional part is dropped, not rounded inta; 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 inta; 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 • area = width * length; width Area length
Conversion example • If you run 26 miles, how many feet is that? • feet = 26 * 5280;
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 • area = 1.0/2.0 * base *height; height Area base
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! inta = 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 inta = 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 inta = 2.6; // fails! inta = (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; inta = (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 );
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
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
The && Operator • The AND operator • It gives back true only if both things being combined are true
The || Operator • The OR operator • It gives back true if either or both things being combined are true
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
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 charletter; 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 intnumber; number = ‘a’; // letter contains 97 char letter = ‘r’; intnumber; 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 Stringword; 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: Stringword; word = 99 + “ problems”;// word is // “99 problems” Stringword; 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 Stringword1 = “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 Stringword1 = “hard work”; • String word2 = “success”; intvalue = 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: Stringword = “a mile long”; int length = word.length(); // length = 11 Stringnothing = “”; 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: Stringword = “walnut”; char c = word.charAt(3); // c = ‘n’ Stringword = “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 Stringword1 = “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 int847? • 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 intto a String, use the toString() method Stringnumber = “345”; int value = Integer.parseInt(number); intvalue = 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 doubleto a String, use the toString() method Stringnumber = “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