1 / 49

CS 177

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

stamos
Download Presentation

CS 177

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Week 3: Basic Operations CS 177

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

  3. 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

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

  5. 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?

  6. 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

  7. 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;

  8. 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;

  9. 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;

  10. 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;

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

  12. Conversion example • If you run 26 miles, how many feet is that? • feet = 26 * 5280;

  13. 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;

  14. 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

  15. 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

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

  17. 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;

  18. 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;

  19. 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;

  20. 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)

  21. 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

  22. 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

  23. 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

  24. 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 );

  25. 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

  26. Other Math methods

  27. 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

  28. The ! Operator • The NOT operator • Changes a true into a false or a false into a true

  29. The && Operator • The AND operator • It gives back true only if both things being combined are true

  30. The || Operator • The OR operator • It gives back true if either or both things being combined are true

  31. 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

  32. 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

  33. 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’

  34. 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

  35. 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

  36. 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”

  37. 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”

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

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

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

  41. 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

  42. 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!

  43. 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”

  44. 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!

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

  46. 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);

  47. 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);

  48. 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

  49. 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

More Related