Upgrade to Pro — share decks privately, control downloads, hide ads and more …

M250 Unit 3 Subsection 2 & 3 - Variable identifiers and expressions (13)

Matt
January 13, 2020

M250 Unit 3 Subsection 2 & 3 - Variable identifiers and expressions (13)

Matt

January 13, 2020
Tweet

More Decks by Matt

Other Decks in Education

Transcript

  1. Instances variables Whenever we’ve talked about an object so far

    we’ve said it has behaviour and attributes that are both defined in its class. Both are implemented in different ways in the class. We’ll talk about how attributes are implemented here and how behaviour is implemented in the next unit. The attributes of an object are implemented by instance variables within its class.
  2. So remember how Frog objects have the attributes position and

    colour? Well if we opened up the Frog class we would see that there are two instance variables declared there: position and colour. Instance variables can be of primitive or reference type. - position is a primitive type instance variable because it is defined as being of the primitive type int. - colour is a reference type instance variable because it is defined as being of reference type OUColour.
  3. When we talk about an object’s attributes we are indeed

    referring to its characteristics. But these characteristics have to actually be defined within the class, and this is done so by declaring the appropriate instance variables. As we dive further into the code of a class we’ll tend to use the term ‘attribute’ less and ‘instance variable’ more. But just bear in mind that they are essentially synonymous.
  4. Identifier naming rules There are certain rules for what we

    can call an identifier. They must: • Begin with an uppercase or a lowercase letter, an underscore, or a dollar character. (Note that variable identifiers begin with a lowercase letter by convention, but the compiler won’t stop you if you don’t follow this rule.) • Any characters other than the first can also contain a letter of any case, the dollar sign/underscore and also numbers. But keep in mind the camelcase convention of variable identifiers, and remember that we name class identifiers as starting with an uppercase letter.
  5. An identifier cannot: • Contain any character other than a

    letter, number, or ($ or _). So something like a+frog is not a valid identifier. • Begin with a number. • Contain spaces. So a frog is not a valid identifier. • Be keywords, such as new or class. • Be the reserved literal values true, false, or null. Also by M250 convention we follow all the above rules and: • We don’t use dollar or underscore signs in identifiers.
  6. Expressions An expression is a collection of values that evaluate

    to a single value. For example, 2+5 is an expression which evaluates to 7. Also, 22 is an expression which evaluates, quite simply, to 22. Expressions can involve primitive data types, or reference types (or both).
  7. Operators and operands An operator is used in an expression

    to define how values are evaluated. + and – are two obvious operators, but there are more and they don’t all just apply to arithmetic. An operator is used with one or more operands. So in the expression 5+3: • + is the operator • 5 & 3 are the operands
  8. Some operators use two operands, like the plus operator, and

    these are called binary operators. Some operators use only one operand, and these are called unary operators. For example, -7 is a unary operator. The operand is 7 and the operator is - This evaluates to negative 7, or the literal -7 (Note that if the expression was 7-3 then the - operator would work as a binary operator because it has two operands.)
  9. Arithmetic operators All arithmetic expressions follow the BIDMAS rules of

    mathematics. We can use arithmetic operators on integer and floating-point types. The arithmetic operators are: • + (addition) • - (subtraction or negation) • * (multiplication) • / (division) • % (remainder)
  10. Addition, subtraction, and multiplication operators work exactly how you would

    expect. When it comes to division we need to address integer division. In Java, an expression like 5 / 2 will evaluate to 2 and not 2.5 like you might expect. If both of the operands are values of type int, then division will simply count how many times the second number fits into the first number exactly. So 2 goes into 5 twice. It doesn’t matter that we have 1 left over, it just counts how the exact fits of the integers. This is called integer division. If we wanted a precise answer then we’d need to make at least one of the operands a floating-point literal. So 5.0 / 2 would evaluate to 2.5. Integer division can be useful but it can cause unexpected problems so we must be aware of it.
  11. % operator The remainder operator is also called the modulus

    operator. It gives the remainder of the first operand divided by the second. So 6 % 4 will evaluate to 2, because 4 fits into 6 once and there is 2 left over as a remainder. And 3.5 % 3 will evaluate to 0.5, because 3 fits into 3.5 once and there is 0.5 left over as a remainder. Also 10 % 5 evaluates to 0, because 5 fits into 10 an exact number of times so there is 0 left over as a remainder. With this operator we can check if any number is even. If x is some number, and x % 2 evaluates to 0, then we know that x is divisible by 2 and so it must be even. This strategy can be quite useful more often than you think, so it would be useful to remember.
  12. Comparison operators Comparison operators evaluate to either true or false.

    So they evaluate to a boolean value. We use them often to compare numbers. • == (equals to / equality operator) – E.g. 5==5 evaluates to true because 5 is equal to 5, but 6==7 evaluates to false. • != (not equals to / inequality operator) – E.g. 5!=6 evaluates to true because 5 is not equal to 6, but 5!=5 evaluates to false. • < (less than) – E.g. 6<7 evaluates to true because 6 is less than 7, but 7<2 evaluates to false. • <= (less than or equal to) – E.g. 10<=10 evaluates to true because 10 is indeed less than or equal to 10. • > (greater than) – E.g. 5>1 evaluates to true. • >= (greater than or equal to) – E.g. 5>=6 evaluates to false.
  13. The comparison operators split into two types: The equality operators

    are those that check for equality or lack thereof: • == • != The relational operators are the ones that check the relation between operands: • < • <= • > • >=
  14. A super-common type of mistake is when we mix up

    = with ==. = is the assignment operator. We use it to assign a value to a variable. E.g. x=5 means ‘let x equal 5’. == is the equal-to comparison operator. We use it to compare two values. E.g. x==5 means ‘does x equal 5?’ If your code doesn’t work, check these!
  15. As well as comparing integer operands we can also compare

    floating-point operands with expressions such as: 3.5 < 1 or 3.1415 == 22/7. Note that in the second example we used another expression, 22/7, as an operand. This expression is termed a sub-expression, and the bigger expression that is made up of sub-expressions is called a compound expression. Sub-expressions can even be composed of more sub-expressions. E.g.: 0 <= (12*(5-1) + 6) Its sensible to use brackets in a sub-expression, even when they aren’t mathematically needed, in order to make things clearer.
  16. We can also compare char values with the comparison operators.

    char values actually have numerical values arranged in alphabet order. So an expression such as ‘a’ < ‘z’ will evaluate to true, because a is less than z. Beware that some char values look like numbers but are indeed actually characters and not numerical. ‘3’ for example (in single-quotes) is not the same thing as the int value 3. Trying to do arithmetic with a char literal when you think it is an integer literal will result in unexpected problems. E.g. 5+’0’ doesn’t make any sense. 5+0 does.
  17. The equality operator used with reference type variables We can

    use reference variables as the operands of the equality operator ==. Doing this means the expression will: • Evaluate to true if both reference variable hold reference to the same object • Evaluate to false if they don’t This is an important point to touch on. Two or more reference variables can reference the same object, and sending a message to either of them will affect the object in the same way.
  18. For example, Frog kermit = new Frog(); Frog gribbit =

    kermit; System.out.println(kermit == gribbit); This will print out “true”. In the first line we created a new Frog object and stored a reference to this object in the variable kermit of type Frog. In the second line we created the variable gribbit of type Frog and assigned to it the reference held in kermit. So now both gribbit and kermit refer to the same object. The third line evaluates to true because kermit and gribbit refer to the exact same object. Hence true is printed.
  19. Don’t get caught out with strings Strings are weird in

    Java, but they are not primitive data types at all! We can see that from the capitalisation of String when we declare String objects. However, say we have two reference variables of type String: String test1 = “Hello”; String test2 = “Hello”; The expression test1 == test2 will evaluate to true. You might be surprised, because we just said that the equality sign used with reference variables just checks if they hold reference to the same object. But here, the object is the String “Hello”, and the two variables that hold a reference to this object are test1, and test2. So test1 == test2 evaluates to true. We go over this concept in unit 9. Just remember, if we try to create a string object that holds the exact same characters in the exact same order, then we don’t actually create this a second object – we just assign another reference variable to it. This is seen above. Because the String object “Hello” already exists, the second line of code just assign test2 to reference this object as well as test1.
  20. equals() We’ll get into WHY we do this in unit

    9, but to check if two strings are the same sentence we shouldn’t use the == operator like I just said we could. Instead we should use the message equals(). So “Hello world”.equals(“Hello World”) would return true, because each has the same characters in the same order. However if the variable sentence was the String “abc”, then the message expression sentence.equals(“abcd”) would return false, because the two strings aren’t the same.
  21. Logical operators The logical operators are used only with boolean

    values. There are three: • && (logical and) • || (logical or) • ! (not)
  22. • && evaluates to true if strictly both operands evaluate

    to true. • || evaluates to true if at least one of the operands evaluates to true. • ! evaluates to the opposite value of its operand. That is, it negates it. The table on page 115 of book 1 does an excellent job of providing examples for these. Remember that an operand can be made up an expression: (5+2) < 3 || ‘d’ == ‘d’ evaluates to true. Firstly, the sub-expression (5+2) < 3 evaluates to false, because 5+2 = 7 and this is not less than 3. The sub-expression ‘d’ == ‘d’ evaluates to true, because the primitive variable ‘d’ does indeed equal ‘d’. Because the expression uses the logical or operator, only one of these operands need to evaluate to true. And as the second operand did indeed evaluate to true, the entire expression evaluates to true.
  23. Expressions with objects/reference variables Most operators aren’t really used with

    reference variables. We assign objects to reference variables using the assignment operator = And as said the equality operator == checks if two variables are referencing the same object, and the inequality operator != checks if they aren’t. But we don’t have expressions like kermit <= gribbit where kermit and gribbit are two Frog objects because it wouldn’t make sense. How can an object be less than or equal to another? It can’t.
  24. Remember that the code written when sending an object a

    message is called a message-send, and that sometimes a message-send returns a message answer. E.g. kermit.getPosition() returns an int value (representing kermit’s position) as a message answer. Any message-send that results in a message-answer is called a message expression. We can think of a message expression as any other type of expression. And a message expression evaluates to the returned value. So kermit.getPosition() is therefore a message-expression that evaluates to a number. If kermit was at position 5, then the message-expression would evaluate to 5. We can use message expressions with operators. Say we wanted to check if kermit’s position is greater than 5. We would write the expression: kermit.getPosition() > 5; The operand on the left-hand side is a message expression that evaluates to kermit’s position. The operand on the right-hand side is a int expressionl that quite simply evaluates to 5. The comparison operator > will then compare them and return true or false, depending on whether kermit’s position is greater than 5 or not.
  25. Some extra information: If you have a relational operator and

    you want to swap the sides that the operands are on then you need to reverse the sign. For example: x <= y is the same as y >= x because, since we swapped the sides the operands were on AND flipped the sign. But 3<4 is not the same as 3>4 because we didn’t flip the sign when we swapped the sides.
  26. So we’ve seen that message-expressions can used in different ways:

    • They may be assigned to a variable. E.g. int currentPosition = kermit.getPosition() • The returned answer can be used as the argument of another message: E.g. gribbit.setPosition(kermit.getPosition()) • They can be used as an operand in an expression: E.g. kermit.getPosition() > 5
  27. Strings A lot of classes are provided by Java and

    are general-purpose - for use in a large range of applications. The String class is one of these. A String object is a collection of char values arranged in a certain order. For example, the string “Hello” is made up of the char literals ‘H’, ‘e’, ‘l’, ‘l’, and ‘o’ in that order. Remember that a string is enclosed in double-quotes whereas char values are enclosed in single-quotes. This means,for example, that “a” is a String whereas ‘a’ is a char.
  28. When we talk about strings and char values being “enclosed”

    by single and double quotes, what we’re actually saying is that they are delimited by them. A delimiter tells the compiler where a certain section of code begins or ends. For example: • ; marks the end of a statement • { } mark the start and end of statement blocks (as we’ll see in the next unit) • “ and ‘ mark the start and end of strings and char values. But what if we wanted to use the delimiter as a character? For example, what if we wanted a string to include the bracket character { ? Then we’d need to use an escape sequence. In Java the escape sequence is the backwards-slash \ and it is placed before the delimiter character we want to include in order to tell the compiler “I know this next character has a specific meaning to you, but I want you to just treat it as just another character this time”. E.g. String test = “Look at this semicolon \; isn’t it cool?”; Would print “Look at this semicolon ; isn’t it cool?” Because we use the escape sequence before the delimiter, the semi-colon, it is treated as just another character and not as the symbol for terminating a statement.
  29. Strings are objects so they can receive messages. For example,

    toUpperCase() is a message that can be sent to a string. It takes a string argument and changes all of the letters of that argument to uppercase and then returns this value as a String. So it is also a message-expression because it returns a value!
  30. Concatenation Often we want to join two Strings together as

    one. The + sign when used with String operands becomes the concatenation operator and the expression evaluates to the combined Strings. “Hello” + “world” evaluates to “Helloworld”. Note the lack of a space in between the words. If we wanted it we’d need to manually put it in, either after “Hello” or before “world”.
  31. Also note that the concatenation operator + looks the same

    as the addition operator + The compiler decides which one to use based on the operands surrounding it. If the operands are numeric then a numerical addition is done, and if they are strings than a concatenation is done. An important point to note is that only one of the operands needs to be a string for the + sign to be interpreted as the concatenation operator. So, an expression like: 99 + “ red balloons” evaluates to the string “99 red balloons”, because even though 99 is an int value, the other operand is a string, so the int literal 99 is automatically converted to the string “99” and then concatenation occurs. This is also true if one operand is a string and the other is a double, char, or boolean. They are all converted to a string and then concatenated with the other string. In contrast an expression like 5.3 + 1.5 would just evaluate to 6.8, because neither operand is a string so the + sign is interpreted as the addition operator.
  32. println() and print() To print the value of an expression

    as output we can use two statements: • System.out.println(); • System.out.print(); The first will print the statement on its own separate line and the second will just print it next to whatever was last outputted. Within the brackets we include an expression. This could be a string, a number, or even a message expression like kermit.getPosition(). The evaluation of that expression -- that is -- the single value that the expression is reduced to -- will be printed. So for example System.out.println(kermit.getPosition()); will print out the position of kermit, because kermit.getPosition() is a message expression that evaluates to an int value, and this value forms the argument of the println() message.
  33. “12” + 34 evaluates to the string “1234” because one

    of the operands is a String object, so the int value 34 is converted a string. And now because there are two Strings on either side of the + sign it is interpreted as the concatenation operator and the two strings are therefore concatenated.