Presentation is loading. Please wait.

Presentation is loading. Please wait.

Review of Previous Lesson

Similar presentations


Presentation on theme: "Review of Previous Lesson"— Presentation transcript:

1 Review of Previous Lesson
04/07/2019 Review of Previous Lesson State as many Vocabulary words and Learning Objectives that you remember from the last lesson as you can. Remember to grade yourself from

2 04/07/2019 Strings

3 Language Features and other Testable Topics
04/07/2019 Tested in the AP CS A Exam Notes Not tested in the AP CS A Exam, but potentially relevant/useful String concatenation: + 5 (char) Object Comparison object identity (==, !=) vs. object equality (equals), String compareTo Input 6 Scanner Exceptions NullPointerException IndexOutOfBoundsException Variables parameter variables, instance variables,

4 Language Features and other Testable Topics
04/07/2019 Tested in the AP CS A Exam Notes Not tested in the AP CS A Exam, but potentially relevant/useful Methods static, non-static, method signatures, overloading, overriding, parameter passing 10 Classes new, visibility (public) 13, 14 Inheritance Understand inheritance hierarchies. Packages import packageName.className Miscellaneous OOP “is-a” relationship, null, this

5 Language Features and other Testable Topics
04/07/2019 Tested in the AP CS A Exam Notes Not tested in the AP CS A Exam, but potentially relevant/useful Classes new, visibility (public), 14 Standard Java Library Object, Integer, Double, String 18 autoboxing

6 Language Features and other Testable Topics
04/07/2019 Notes: 5. String concatenation + is part of the AP Java subset. Students are expected to know that concatenation converts numbers to strings. 6. User input is not included in the AP Java subset. There are many possible ways for supplying user input: e.g., by reading from a Scanner, reading from a stream (such as a file or a URL), or from a dialog box. There are advantages and disadvantages to the various approaches. The exam does not prescribe any one approach. Instead, if reading input is necessary, it will be indicated in a way similar to the following: double x = /* call to a method that reads a floating-point number */; or double x = ...; // read user input

7 Language Features and other Testable Topics
04/07/2019 Notes: 10. Students are required to understand when the use of static methods is appropriate. In the exam, static methods are always invoked through a class (explicitly or implicitly), never an object (i.e., ClassName.staticMethod( ) or staticMethod( ), not obj.staticMethod()). 14. Students are expected to extend classes. Students are also expected to have knowledge of inheritance that includes understanding the concept of (the) method (of) overriding. Students are expected to implement their own subclasses. 18. Students are expected to know a subset of the constants and methods of the listed Standard Java Library classes and interfaces. Those constants and methods are enumerated in the Java Quick Reference (Appendix B). See next slide.

8 Java Quick Reference (Appendix B)
04/07/2019 Java Quick Reference (Appendix B) class java.lang.Object boolean equals(Object other) String toString() class java.lang.String int length() String substring(int from, int to) // returns the substring beginning at from // and ending at to-1 String substring(int from) // returns substring(from, length()) int indexOf(String str) // returns the index of the first occurrence of str; // returns -1 if not found int compareTo(String other) // returns a value < 0 if this is less than other // returns a value = 0 if this is equal to other // returns a value > 0 if this is greater than other

9 Java Quick Reference (Appendix B)
04/07/2019 Java Quick Reference (Appendix B) class java.lang.Integer Integer(int value) int intValue () class java.lang.Double Double(double value) double doubleValue()

10 Programming Paradigms
04/07/2019 Programming Paradigms Methods of programming.

11 Two divisions of data in Java
04/07/2019 Two divisions of data in Java

12 04/07/2019 Primitives “Fundamental components that are used to create other, larger parts.“ A programmer can not create new primitive data types. Are not objects. An object needs a class, methods and other information (metadata) attached to the object in addition to the raw value being held. This needs much more memory allocation and computer resources to process. The designers of Java decided to retain primitive types in an object-oriented language, instead of making everything an object, so as to improve the performance of the language. If you visit its memory location you will find the value of the variable.

13 Primitives Advantages: Disadvantages: 04/07/2019 fixed memory sizes
use little memory fast access Disadvantages: Can’t be null (it has to have a value) so have to initialise to a “rogue” value such 0 or -1, but this can be misleading (e.g. for temperatures 0 & -1 could be possible temperatures, for exam marks 0 is a possible mark). Java is an OOP and primitives are the only non-object exceptions, so many programmers argue that primitives hinder Java from being purely OOP. Due to the above many data structures expect objects and so won’t accept primitives. As they are not objects they only store values, they do not possess methods (see later for examples) or the ability to convert to a String (which you will see later is an object) e.g. int 123 to “123”

14 Objects Advantages: Disadvantages: 04/07/2019
Can be null/nothing (it doesn’t have to have a value – like a contact name with no number) so don’t have to initialise to a “rogue” value such 0 or -1. Java is an OOP, so many programmers argue that treating everything as objects fits this idea. Due to the above many data structures expect objects and so won’t accept primitives. As they are objects they possess methods (see later for examples) and the ability to convert to other appropriate data types e.g. “123” to int 123, … Disadvantages: Uses high memory allocations which can vary and computer resources to process (slow). As they can contain raw data along with methods (little programs) and other information (metadata) to process that data.

15 Primitives & Objects (crude) Analogy
04/07/2019 Primitives & Objects (crude) Analogy Primitive: Nuts & Bolts Object: Whole machine.

16 04/07/2019 Object Orientated Programming Paradigm (OOP) enables modelling of the real world by basing itself on: Examples of classes of real-world entities objects like dog, person, car etc… with appropriate variables and methods of using those variables. Actual real-world entities like actual breeds of dogs, names of people, or makes of cars etc...

17 Examples of Object Orientated Programming Paradigm (OOP) Languages
04/07/2019 Examples of Object Orientated Programming Paradigm (OOP) Languages Eiffel, Smalltalk, Java, …. Contain software objects which exist entirely within a computer system and interact with other software objects.

18 Class 04/07/2019 A template/blueprint/instructions/factory/plan for creating and ‘using’ objects. It does not by itself create any objects, it is only a set of instructions to create and use an object. Object creation has to be specifically requested before an object is created – see later. Is the data type of any objects created from it (or sub-classes – see later). A set of instructions that describe how an object will behave (methods – mini programs) and what characteristics (states – see next slide) it must have. e.g. Many classes are pre-defined in Java (standard classes). A programmer can invent new classes to meet the particular needs of a program. Constructor: Every class has at least one constructor method which, when called, can create/initialise/set up an object. May or may not require certain “parameters” to be passed to it. e.g. size, colour, etc….

19 Objects: 04/07/2019 Are the instances (results) of a class created by following the description contained in its class (or sub-classes – see later). Has 3 characteristics: State/Properties/Data Members/Instance Variables/Fields: Data (values) each object (instance of a class) has as part of itself which may change over the course of the object’s ‘lifetime’. All objects of the same class have the same types of data although the values of the data will be different from object to object. e.g. animal: its length, what it eats, number of legs, etc… bank account: balance, interest rate, daily withdrawal limit, etc… pen: name is Reynolds, colour is white etc. Behaviour/Methods/Mini Programs: Functionality of an object (it can do things and can have things done to it) such as the animal: the sound it produces, bank account: deposit, withdraw etc. pen: writing  Address: The address in RAM where the 1st byte (beginning) of the object is stored. members What states and behaviours are required are set by the class (or classes - see later) it comes from. After a program stops running, any created objects no longer exist. Objects are created at and exist during Run Time only.

20 To create/instantiate/construct an object:
04/07/2019 Standard Java formatting dictates that it begins with a capital letter and for multiple words use to begin each word (no spaces are allowed so this makes them more readable). Some constructors may require certain information called “actual” parameters written inside the brackets in a specific order separated by ,. See next slide for variations of this. Name Reference Variable Name Can be anything the programmer chooses but standard Java formatting dictates that they follow the same rules as variable names: begin with a lower case letter and for multiple words use a capital from the 2nd word to begin each word. Must have the same name as the Class Name. Can be considered to be a special type of method. Creates/initialises a newly created object.

21 04/07/2019 Types of Constructors

22 Default constructor JAVAC 04/07/2019
If you do not implement any constructor in your class, Javac inserts a default constructor into your code on your behalf. You will not find it in your source code (the java file) as it would be inserted into the code during compilation and exists in .class file. This means that class will still have a constructor, it is just that the programmer didn’t write it. public class MyClass { public static void main (String args[]) { MyClass obj = new MyClass(); } …. public class MyClass { MyClass() { } public static void main (String args[]) { MyClass obj = new MyClass(); …. JAVAC

23 04/07/2019 Default Constructor The default constructor does actually do a great deal of work behind the scenes. It works with the Java virtual machine to find main memory for the object, sets up that memory as an object, puts in the variables and methods specified in the class definition, and returns an object reference to your program. All of this is quite complicated, and it is fortunate that you don't have to write code for it. However, none of this is anything you can ‘see’, although the default constructor may except call the constructor/s of any parent class/es – see later.

24 04/07/2019 Parameters Variables/literals (fixed values) passed between (sent to and / or from) methods/constructors. Passing = sending to or from Necessary if the called method or constructor needs a local variable from the calling method.

25 no-arg Constructor Constructor with no arguments/parameters.
04/07/2019 Constructor with no arguments/parameters. Creation/Instantiation is the same as with the default constructor, however the body can have any code unlike default constructor where the body of the constructor is empty. The default and no-arg constructor are not the same, even if you write public Demo() { } in your class Demo it cannot be called the default constructor since you have written the code of it.

26 Parameterized Constructor
04/07/2019 Parameterized Constructor Constructor with arguments (“actual” parameters). Formal parameters Declarations in the method's header. Actual parameters Values/Variables passed at the point of invocation (when called). While the phrases "formal parameter" and "actual parameter" are common, "formal argument" and "actual argument" are not used. This is because "argument" is used mainly to denote "actual parameter". As a result, some people insist that "parameter" can denote only "formal parameter".

27 Object name / reference variable name
Objects 04/07/2019 If you visit the name of the object’s (reference variable name) memory location, unlike the primitive type, you will find a memory address pointing to another location and not the values of variables in object. This memory address points to a location where the details of object and values of variables inside it reside (in an area of memory called “The Heap” – see later). Analogy Object name / reference variable name (contact name) …….. (friend)

28 Object name / reference variable name
What is the object? 04/07/2019 Your friend does not have to use your ‘real name’ in their contact list (they could choose anything). This ‘name’ and ‘you’ are not the same things. Analogy Object name / reference variable name (contact name) …….. (friend) There is no actual object ‘variable1’, only a reference variable of that name. A Java variable never contains an object! So really we should say: "The object referred to by the variable ‘variable1’.“ rather than: "The object variable1... " In fact, every object actually does have a unique ID, which could be said to be the actual object, but this unique ID is only internally visible within the JVM, not to the programs that create and use them.

29 Dot Notation 04/07/2019 The way variables and methods are accessed/called/invoked. Non-Static methods: objectReference.memberOfObject objectReference.variableName objectReference.methodName() If parameters are required, they should listed here according to the method’s signature – see later.

30 Ways to declare & assign a reference variable
04/07/2019 Some constructors may require certain information called “actual” parameters written inside the brackets in a specific order separated by ,. null/nothing ClassName refVarName = new ClassName ( ); // This is the standard way shown earlier. Declares a reference variable & the class of the object. Constructs a new object and a reference to that object is put in the variable. Sometimes parameters are needed when the object is constructed. ClassName refVarName; …. refVariableName = new ClassName( ) ; Declares a reference variable & the class of the object it will later refer to but no object is created. ClassName refVarNameOne, variableNameTwo, …; Declares multiple reference variables, potentially referring to objects of the same class but no objects are created. ClassName refVarNameOne = new ClassName ( ), variableNameTwo = new ClassName ( ) ; Declares multiple reference variables, constructs new objects and their references are assigned to the variables.

31 04/07/2019 this To make sure Javac correctly differentiates between instance and parameter variables of the same name we use the reserved word ‘this’ to show when an identifier refers to an object's instance variable.

32 Parameterized Constructor Example 1
04/07/2019 Dante asks why data cannot go into empId & empName directly? Why do they have to be stored in id & name 1st? When you write down something somebody has told you, where is it between somebody telling you and it ending up on the paper? Answer: Your brain. The header can be thought of as the brain. The constructor needs this information before it can start constructing an object. The header is the setup part, the constructor (or method) has not started until after {. Before starting to construct an object, the instance variables empId & empName don’t exist. A parameterized constructor with 2 parameters id and name. While creating the objects obj1 and obj2 2 arguments have been passed so that this constructor gets invoked after creation of obj1 and obj2. Passing = sending to or from The Heap To the console obj1 Employee reference empId = 10245 empName = “Chaitanya”

33 Parameterized Constructor Example 1
04/07/2019 A parameterized constructor with 2 parameters id and name. While creating the objects obj1 and obj2 2 arguments have been passed so that this constructor gets invoked after creation of obj1 and obj2. Passing = sending to or from Declared without the static keyword and outside any method declarations. Their values are instance/object specific and are not changeable by instances/objects. If declared with Static then they would be associated with the class & so the same value for all instances of a class. Instance Variables “Formal” Parameter Variables Output: ? “Actual” Parameter Variables/arguments Reference Variables

34 04/07/2019 Signature In the Java programming language, a signature is the method/constructor name and the number, type and order of its parameters. methodOrConstructorName(parameters) {...}; e.g. doSomething(int y, int x); doSomething(int x, int y); doSomething(double x, int y); doSomething(int x, double y); Same signature (variable names not important, only their types). Different and distinct signatures.

35 Parameterized Constructor Example 2
04/07/2019 2 constructors, a ‘no-arg’ constructor & a ‘parameterized’ constructor. When we do not pass any parameter while creating the object using new keyword then the ‘no-arg’ constructor is invoked, however when you pass a parameter then ‘parameterized’ constructor that matches with the passed parameters list (matches the signature) gets invoked. Output: ?

36 Parameterized Constructor Example 3
04/07/2019 Output: ? A compilation error. The statement Example3 myobj = new Example3() invokes a default constructor which this program does not have. When a constructor is not written in a class, JAVAC inserts a default constructor into the code, however when any constructor is written (as in this example), then a default constructor is NOT inserted. If the parameterized constructor were removed from the example here then the program would run fine, because then JAVAC would insert a default constructor into the code.

37 String Is a sequence of characters/sequence of char values. e.g.
04/07/2019 String Is a sequence of characters/sequence of char values. e.g. “Hello” is a string of 5 characters. In fact you have been using strings since we started as any “…” creates a string e.g. System.out.println("This is my first program in java"); Is a pre-defined class in Java: As the sequence mentioned above is of any length (the storage space cannot be fixed). Also it is useful to have a number of methods to use on strings (see later for examples).

38 04/07/2019 Strings Receive special treatment in Java, because they are used so frequently in a program. e.g. for (int i = 0; i < 10; i++) { System.out.println("Next iteration"); } If we treat strings as any other object, "Next iteration" would need to be instantiated 10 times. For performance reasons, Java Strings are designed to be in between a primitive and a class. See next slides for the special features.

39 String A String can be constructed by either: 04/07/2019 Or:
1. Directly assigning a string literal to a String reference - just like a primitive. e.g. String str1 = “Hello"; // Implicit construction via string literal Or: 2. Via the "new" operator and constructor, similar to any other classes. However, this is not commonly-used and is not recommended. String str2 = new String("Hello"); // Explicit construction via new

40 String Literals - Java String Pool
04/07/2019 1. Directly assigning a string literal to a String reference - just like a primitive. e.g. String s1 = “Hello"; // Implicit construction via string literal String s2 = “Hello"; // Implicit construction via string literal String s3 = “Hello"; // Implicit construction via string literal String Pool in Java corresponds to an allocation of memory in Java heap memory. It consists of a collection of String objects, which are shared and reused among several String object references for same String content. This can only work if String Objects are immutable (not changeable) as otherwise, all objects which use a String would be affected.

41 String Object - Heap 04/07/2019 2. Via the "new" operator and constructor, similar to any other classes. However, this is not commonly-used and is not recommended. e.g. String s4 = new String(“Hello"); // Explicit construction via new String s5 = new String(“Hello"); // Explicit construction via new String objects created via the new operator and constructor are kept in the heap. Each String object in the heap has its own storage just like any other object. There is no sharing of storage in heap even if two String objects have the same contents.

42 != String - Issue with == True / False ? True / False ? True / False ?
04/07/2019 s1 Java Heap reference String s1 = “Cat”; == s2 “Cat” “Dog” reference String s2 = “Cat”; != String s3 = new String (“Cat”); s3 reference String pool s1 == s2; // true True / False ? Basic Conclusion: Don’t use == to compare strings! s1 == s3; // false “Cat” True / False ? s1 == “Cat”; // true True / False ? s3 == “Cat”; // false True / False ? Remember that variables of objects are references so == with 2 objects checks if they relate to the same object (in this case, literal strings), the contents are irrelevant. See the later slides for the solution to this but 1st we need to cover a few more OOP concepts.

43 04/07/2019 Inheritance The process by which one class acquires the properties and methods of another class. Provides the reusability of code so that a class has to write only the unique features and rest of the common properties and functionalities can be extended from the another class. Child / Sub / Derived Class: The class that extends the features of another class. Parent / Super / Base Class: The class whose properties and functionalities are used(inherited) by another class.

44 Inheritance 04/07/2019 Java Syntax:
To inherit a class we use extends keyword.

45 Syntax: Inheritance in Java
04/07/2019 Syntax: Inheritance in Java To inherit a class we use extends keyword. Here class A is child class and class B is parent class. class A extends B { }

46 Reminder 04/07/2019 ? This keyword is an “access modifier” which specifies the accessibility of what comes next. Keywords = Words special to the language and have defined meanings for that language. Public means it is accessible “everywhere”, what this exactly means is shown by the table below. If we don’t write anything the default accessibility is that it is only visible to other code within the same package.

47 Package A group of classes, interfaces and other packages. 04/07/2019
package packageName { classes …. } Packages or classes in other packages sometimes need to be imported into a program before they can be used. e.g. See importing the Scanner class later. The String class is part of the java.lang package but, as you have seen, this does not need to be explicitly mentioned as all classes in java.lang are automatically imported. Packages can be written inside packages as sub packages.

48 ? Reminder void: States that a method does not return anything.
04/07/2019 void: States that a method does not return anything. ? Continued on next slide.

49 Inheritance Example 04/07/2019 ? Output: Note:
‘designation & the does() method are not defined in the MathTeacher class, so Why is ‘designation’ part of a MathTeacher object? How is the does() method accessible via a MathTeacher object? Output: ? Console Note: As the programmer has not written a constructor for the MathTeacher class, Javac will insert a default constructor. A default constructor does nothing you notice except call the constructor/s of any parent class/es . After that any instance variables will be initialised as specified (those of any parent classes 1st) . If, as in this case, the constructor doesn’t set them. To the console The Heap MathsTeacher obj reference designation = “Teacher” college = “Beginnersbook” mainSubject = “Maths”

50 04/07/2019 Overriding A language feature that allows a subclass or child class to provide a method of the same signature as one in a super/parent class, so that a different more appropriate implementation of a inherited method can be used

51 Rules for Method Overriding
04/07/2019 Rules for Method Overriding The argument list (signature) should be exactly the same as that of the overridden method. The return type should be the same or a subtype of the return type declared in the original overridden method in the superclass. If a method cannot be inherited, then it cannot be overridden. The access specifier for an overriding method can allow more, but not less, access than the overridden method. For example, a protected instance method in the superclass can be made public, but not private, in the subclass. Constructors cannot be overridden.

52 04/07/2019 Object class in Java The Object class is the parent class of all the classes in java by default. In other words, it is the topmost class of java.

53 boolean equals(Object other) & Overriding
04/07/2019 boolean equals(Object other) & Overriding Uses the identity operator ( == ) to determine whether two objects are equal but: In the String class the equals method is overridden to compare the actual contents (i.e. the strings) held in each object.

54 boolean equals(Object other)
04/07/2019 Conclusion: Don’t use == to compare strings! Use the equals method!!! public class EqualsExample1{ public static void main(String args[]){ String str1= new String("Hello"); String str2= new String("Hi"); String str3= new String("Hello"); System.out.println(str1.equals(str2)); System.out.println(str1.equals(str3)); System.out.println(str1.equals("Welcome")); System.out.println(str1.equals("Hello")); System.out.println(str1.equals("hello")); } Output: false true ?

55 04/07/2019 Reminder Exception ? An unwanted event that interrupts the normal flow of the program. System generated error message. Terminates program execution. There are ways to handle exceptions and give a user more friendly and helpful error messages than the system generated ones (which are really directed at programmers), using “Try- catch” blocks but this is not required in AP Computer Science (CS).

56 Null Pointer Exception
04/07/2019 Null Pointer Exception String string1 = null; String string2 = "abc"; System.out.println(string1.equals(string2)); Output: ? Exception in thread "main" java.lang.NullPointerException at …. NullPointerException is thrown when an application attempts to use or access an object reference that has a null value. See the next 2 slides for solutions to this.

57 Null Pointer Exception Solution 1
04/07/2019 Null Pointer Exception Solution 1 String comparison with literals String string1 = null; System.out.println("abc".equals(string1)); If this is a null String then a Null Pointer Exception is thrown. So solution 1: Write a String literal here to make sure it is !Null.

58 Null Pointer Exception Solution 2
04/07/2019 Null Pointer Exception Solution 2 Check if the Strings are null before any comparisons. String string1 = null; String string2 = "abc"; if (string1 != null && string2 != null) { System.out.println(string1.equals(string2)); } else { System.out.println("At least 1 of the strings is null so they can’t be compared"); }

59 Reference Variable Reused
04/07/2019 How many objects were created by the program? 2, 1 for the dog, 1 for the cat. How many reference variables does the program contain? 1, which first refers to the dog, then refers to the cat.

60 04/07/2019 Garbage Collector When "The Calico Cat" object is constructed, what happens to the "The Gingham Dog" object? If no variables refer to an object, there is no way to find it, and it becomes marked as garbage. A part of the JVM called the garbage collector will then return these memory areas to ‘free’ memory so that they can be replaced.

61 Types of Operator in Java
04/07/2019 Types of Operator in Java Basic Arithmetic Operators Assignment Operators Unary +, - Comparison (relational) operators Logical Operators (including Unary !) Unary Auto-increment & Auto-decrement Operators Concatenation Bitwise Operators Ternary Operator Types 1 – 6 have been covered in previous presentations. Type 7 will be covered in this presentation.

62 7. Concatenation 04/07/2019 The + operator, which performs addition on primitives (such as int and double), is overloaded to operate on String objects to perform concatenation for two String operands. It then produces a new string which is the result of the concatenation. Overloaded: Overloading is when two or more methods of a class have the same name but have different parameter lists.  When a method is called, the correct method is picked by matching the actual parameters in the call to the formal parameter lists of the methods (also known as its signature). The + operator is the only Java operator that is internally overloaded. Another example of overloading: There are so many overloaded methods of println: println(String x) println(int x) println(double x) println(boolean x) println(char x) println(Object x)

63 Concatenation e.g. int answerChoice = ?;
04/07/2019 Concatenation e.g. int answerChoice = ?; System.out.println("You answered: " + answerChoice + ". Please try again."); If answerChoice = 4 then the following would be printed to the console: You answered: 4. Please try again. What happened here?

64 04/07/2019 Concatenation int answerChoice = ?; System.out.println("You answered: " + answerChoice + ". Please try again."); If answerChoice = 4 then the following would be printed to the console: You answered: 4. Please try again. This has been displayed in the console as one string (one piece of text), but this value came from an int variable so it must have been converted to a string (text)! How is this possible (as we stated earlier that int is a primitive data type so cannot be converted to a String)? Autoboxing toString See next slides for explanations.

65 Autoboxing & Wrapper Classes
04/07/2019 Note that primitives consist of lower case letters only, objects start with a capital letter. Autoboxing: The automatic conversion by JAVAC between the primitive types and their corresponding object wrapper classes. If the conversion goes the other way, this is called unboxing. So Java automatically converts int variables (for example) to Integer objects for the programmer, so it can now be converted into a String – with toString (see later). Primitive type Corresponding Wrapper class boolean Boolean byte Byte char Character float Float int Integer long Long short Short double Double Think of wrapping up the data with an object, like wrapping up a gift (& unboxing like unwrapping a gift). There is still a problem here, what is it?

66 String toString() 04/07/2019 How does Java know what to display when an Object is ‘printed’? As we have seen, an object consists of instance variables, methods, ID and constructor/s. How does Java decide which of these to display? The Object class (which, as we discussed earlier, is the ultimate ancestor of every Java class) has a toString() method which every pre-defined Java class, overrides. Note: toString() of the object class displays the class name and the address of the object. It returns the string representation of an object when an object is printed for display. It is this toString() method which Java uses to tell it what to display. Integer numInteger = 65; Double numDouble = 65.3; Boolean answer = true; String string1 = "abc"; System.out.println("Integer toString(): " + numInteger); System.out.println("Double toString(): " + numDouble); System.out.println("Boolean toString(): " + answer); System.out.println("String toString(): " + string1); Output: Integer toString(): 65 Double toString(): 65.3 Boolean toString(): true String toString(): abc ? Note: toString() is automatically invoked when an object is ‘printed’ even if it is not explicitly invoked e.g. numInteger.toString()

67 String toString() 04/07/2019 int intNum = 65; double doubleNum = 65.3;
boolean answer = true; System.out.println("Integer toString(): " + intNum); System.out.println("Double toString(): " + doubleNum); System.out.println("Boolean toString(): " + answer); Output: Integer toString(): 65 Double toString(): 65.3 Boolean toString(): true What is the difference between the above & the previous slide? What must have happened here? Answers: Primitive data types are being printed here (on the last slide objects were printed). The primitive must have been autoboxed into their corresponding wrapper objects before being printed. See the next slide

68 Auto Boxing Integer(int value) & Double(double value) 04/07/2019
Used to ‘box’ int/double values into their corresponding wrapper objects Integer/Double. int intNum = 65; System.out.println("Integer toString(): " + Integer(intNum)); double doubleNum = 65.3; System.out.println("Integer toString(): " + Double(doubleNum)); This happened ‘automatically’ on the previous slide, hence ‘auto boxing’.

69 Unboxing int intValue() & double doubleValue() 04/07/2019
Used to ‘unbox’ Integer/Double wrapper objects to their primitive types (int/double values). Integer numInteger = 65; int intNum = numInteger.intValue(); // intNum is now = 65

70 Converting to String Process Summary
04/07/2019 Converting to String Process Summary primitive data type e.g. int autoboxing corresponding wrapper object e.g. Integer toString method String object toString method object String object

71 Storing primitive data types in a String variable?
04/07/2019 int x = 10; String str; str = x; /* Auto Boxing in this situation does not happen & the last line will not compile: ‘Integer cannot be converted to String’. */ String str = “”; str += x; // Auto Boxing only occurs with the + operator and below are other variations of this. str = “” + x; str = “Text” + x; Continued on the next slide.

72 Storing wrapper class data types in a String variable?
04/07/2019 /* Or, of course, we can use wrapper classes but statements without the + operator or toString() written explicitly, will not compile. */ Integer x = 10; String str; str = x.toString(); // or str = “” + x str = “Text ” + x; // or String str = “”; str += x;

73 String toString() 04/07/2019 To simply convert a variable to a String for display, you can use: Integer numInteger = 65; System.out.println(numInteger); But to store a variable in a string variable: String integerToString = numInteger; /* Javac will not compile the line above, stating “incompatible types: …. cannot be converted to String”. = numInteger.toString() must be used.*/ Also note that all objects inherit the toString() method of the Object class if a programmer defined object is displayed and it’s class does not override the toString() method, the name of the object’s class plus its address will be displayed, which is mostly useless to the user or even the programmer. So if objects from a class are to be displayed, the toString() method should be overridden to return any output a programmer wishes it to. Typically this means the values of all instance variables but for programmer defined classes, the programmer is free to decide. We will look at this in more detail in future presentations.

74 Operator Precedence Rules
Associativity unary pre-increment/decrement ++ -- + - (logical) ! not associative cast () right to left multiplicative * / % left to right string concatenation + additive + - relational < <= > >= equality == != logical && || assignment = += -= *= /= %= Most programmers do not memorize these, and even those that do still use parentheses for clarity, so I am not sure why the AP syllabus mentions them. Associativity. When an expression has two operators with the same precedence, the expression is evaluated according to its associativity. e.g. x = y = z = 17 is treated as x = (y = (z = 17)), leaving all 3 variables with the value 17, since the = operator has right-to-left associativity (and an assignment statement evaluates to the value on the right hand side). On the other hand, 72 / 2 / 3 is treated as (72 / 2) / 3 since the / operator has left-to-right associativity. Some operators are not associative: for example, the expressions (x <= y <= z) and x++-- are invalid. Decreasing Precedence

75 int length() Used for finding out the length of a String. 04/07/2019
Counts the number of characters in a String including the white spaces and returns the count. Output: ?

76 String substring() Method
04/07/2019 String substring() Method

77 String substring(int from)
04/07/2019 String substring(int from) Returns the substring starting from the specified index(beginIndex) till the end of the string. The beginning character of a string corresponds to index 0 and the last character corresponds to the index (length of string)-1. e.g. “buttons".substring(2) would return “ttons". This method throws IndexOutOfBoundsException if beginIndex is: Less than zero (beginIndex<0). Greater than the length of String (> length of String). length = 7 Note that the substring() method of a String object creates a new object (one object is creating another).

78 String substring(int from, int to)
04/07/2019 String substring(int from, int to) Returns the substring starting from the given index(beginIndex) till the specified index - 1 (endIndex - 1). e.g. "Chaitanya".substring(2,5) would return "ait". It throws IndexOutOfBoundsException if beginIndex is: Less than zero. beginIndex > endIndex endIndex is greater than the length of String.

79 String substring() Method example
04/07/2019 String substring() Method example Output: ?

80 Strings are immutable ? 04/07/2019
public class ImmDemo { public static void main (String[] args) { String str = new String(“Java strings are immutable!"); str = str.substring( 18 ); System.out.println( str ); } Java strings are immutable! immutable! ? What will now happen to the original string literal “Java strings are immutable!”? It will marked as garbage.

81 int indexOf(String str)
04/07/2019 Returns the index of string str in a particular String. Returns -1 if the specified char/substring is not found in the particular String. Output: ?

82 int compareTo(String other)
04/07/2019 int compareTo(String other) Used for comparing two strings lexicographically. Each character of both the strings is converted into a Unicode value for comparison. If both the strings are equal then this method returns 0 else it returns positive or negative value. The result is positive if the first string is lexicographically greater than the second string else the result would be negative.

83 int compareTo(String other)
04/07/2019 Output: ?

84 Methods to read data input by a user
04/07/2019 Methods to read data input by a user Scanner class BufferedReader class Console I will cover only the 1st method as this is the more popular method (for the other methods, check the following link:

85 Scanner class The Scanner class is used for capturing input,
04/07/2019 The Scanner class is used for capturing input, It is in what is known as the java.util package and needs to be imported into a program, on the 1st line before any classes, before it can be used, with: import java.util.Scanner; We then have to create an object of the Scanner class by passing System.in as parameter, in order to read input provided by a user: Scanner scan = new Scanner(System.in); Object Name Constructor Must be the same name as the Class Name. Class Name Keyword Parameter required Note that it is also possible to avoid importing the Scanner class by writing java.util.Scanner each time you need the Scanner class. Can be anything the programmer chooses but standard Java formatting dictates that they follow the same rules as variable names: begin with a lower case letter and for multiple words use a capital from the 2nd word to begin each word.

86 variable to hold the input
04/07/2019 Scanner class Now we must use one of the methods of the Scanner class that are listed on the right. e.g. To read an integer: int num = scan.nextInt(); Method nextBoolean() nextByte() nextDouble() nextFloat() nextInt() nextLine() nextLong() nextShort() next().charAt(0) Object Name variable to hold the input For Strings (text). e.g. Scanner scan = new Scanner(System.in); System.out.println("Enter a number:"); int num = scan.nextInt();

87 Example program to read data of various types using Scanner class.
04/07/2019 Example program to read data of various types using Scanner class.

88 Warning! if (inputString.equals(“….”)) 04/07/2019
Scanner scan = new Scanner(System.in) String inputString = scan.Line(); if (inputString == “….”) // Will never return true!!! Can you see why? Conclusion: Don’t use == to compare strings! Use the equals method!!! if (inputString.equals(“….”))

89 Consuming the last newline character (enter key) of input
04/07/2019 Consuming the last newline character (enter key) of input None of the .next() methods on the previous slide will consume (use up/collect) the new line character (when a user presses the enter key) a user enters after each input. This only causes a problem if the String .nextLine() method is used after another .next method. A new line character is a String, so a String .nextLine() method will accept a previous new line character as an input. Leaving the user feeling that their input has been ‘skipped’ and the program continues as though the user ‘entered’ a new line. Any other .next method will ignore (not accept) a previous new line character as it is not what it is looking for (e.g. int, double, etc…). So, if a String input is required after another .next() method, use: scan.nextLine(); //To ‘consume’ (collect) the previous new line character but not assign it to any variable.

90 Commenting on String Methods
04/07/2019 Commenting on String Methods For this presentation I will only ask for comments to String Methods. Your comments MUST explain: What does the String Method do? Why does this need to be done? When (after and before what) are you doing this and why does it have to be done there?

91 04/07/2019 Write your own programs: Write your own programs from “scratch”. Of course you should use previous programs for reference, but write your code from “scratch” (do not copy and paste).

92 04/07/2019 ASCII Specification: Allow the user to convert a letter to its corresponding ASCII code and vice versa.

93 Validating a Full Name Specification:
04/07/2019 Validating a Full Name Specification: Ask the user to enter a person’s full name (first name and surname). The program should output suitable messages if: A space has been entered at the beginning of the name. More than one space has been used between the names. A space has been entered at the end of the name.

94 04/07/2019 Search for letter a Write a program that will count the number of letter 'a's in a word. Extension: Adapt the program so that uppercase 'A' to be counted as well as each lower case 'a‘.

95 Search for text Write a program that allows the user to:
04/07/2019 Search for text Write a program that allows the user to: Enter some text (this could be copied and pasted in). Enter a search letter or word (including the word within other words). Outputs the number of times this letter or search word is found. Extension: Adapt the program to offer the user a choice of: 1. Counting whole words and words within other words, as above. 2. Counting whole words only.

96 Garage 04/07/2019 A garage is having software produced to calculate the bills for its customers. The garage enters details of a job. Duration Parts 01:09 $17.07 02:52 $29.27 04:13 $43.15 The software for the garage includes a function which takes HOURS as a string and returns the number of half hours. For example, if the input is “1:30” the output will be 3; if the input is 2:52 the output will be 6. Continued on the next slide.

97 Garage Write this program. 04/07/2019
Please note though that you should use 1 input for the “Duration”, not 2, as even though this would be simpler, it avoids using the “String” functions you need to practise here. Also note that the calculation shown in the flowchart is actually not quite correct! Can you see why? See the next slide for some hints.

98 Garage 04/07/2019 Hints: Look for the colon : using the indexOf method to find its position. Use the substring method to extract the numbers before the : as minutes. Use the substring method to extract the numbers after the : as hours. Note that if you do not include a second number in the substring method function then substring method will extract all numbers from the position you give, to the end. Note that your hours and minutes are still held in Strings and they can’t be converted to ints directly (as Strings are objects are ints are primitive data types), so use the compareTo method to compare them with “0”, the difference between the ASCII codes will be an int (= to the number in the hours & minutes). However, this will only work with single digits, e.g. comparing “51” with “0” will give 5, as it is only looking at the 1st digit. Solution: Extract each digit separately, if there are 2 digits then the 1st digit is worth *10 and then + the 2nd digit. For minutes, things are fairly simple as there are always 2 digits, but for hours there is no limit. Solution: Loop from the end of the hours string & move back, multiplying by multiples of 10 as you go. Note that if the minutes is 0 then do not use the minutes at all (just Hours*2). If Minutes is 1-30 then add …. , if Minutes = then add …. .

99 7/4/2019 Grade yourself Grade yourself on the vocabulary and learning objectives of the presentation.


Download ppt "Review of Previous Lesson"

Similar presentations


Ads by Google