21 December 2021 Review of Previous Lesson State
21 December 2021 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 0 - 3. 1
21 December 2021 Strings 2
21 December 2021 LEARNING OBJECTIVE Explain the relationship between a class and an object. Identify, using its signature, the correct constructor being called. For String class: a. Create String objects. b. Call String methods. Compare object references using boolean expressions in program code. For algorithms in the context of a particular specification that involves String objects: • Identify standard algorithms. • Modify standard algorithms. • Develop an algorithm. 3
21 December 2021 ESSENTIAL KNOWLEDGE Data types can be categorized as either primitive or reference. A class is the formal implementation, or blueprint, of the attributes and behaviors of an object. A class contains a constructor that is invoked to create objects. Constructors are used to set the initial state of an object. An object is a specific instance of a class with defined attributes. An object’s behavior refers to what the object can do (or what can be done to it) and is defined by methods. Every object is created using the keyword new followed by a call to a class’s constructor. A parameter is a value that is passed into a constructor. These are often referred to as actual parameters. Constructors have the same name as the class. 4
21 December 2021 ESSENTIAL KNOWLEDGE When no constructor is written, Java provides a no-argument constructor, and the instance variables are set to default values. The parameter list, in the header of a constructor, lists the types of the values that are passed and their variable names. These are often referred to as formal parameters. The memory associated with a variable of a reference type holds an object reference value which is the memory address of the referenced object. Non-static methods are called through objects of the class. The dot operator is used along with the object name to call non-static methods. The keyword null is a special value used to indicate that a reference is not associated with any object. Constructors should include initial values for all instance variables. The actual parameters passed to a constructor must be compatible with the types identified in the formal parameter list. 5
21 December 2021 ESSENTIAL KNOWLEDGE A signature consists of the constructor name and the parameter list. A method signature for a method with parameters consists of the method name and the ordered list of parameter types. A method signature for a method without parameters consists of the method name and an empty parameter list. Methods are said to be overloaded when there are multiple methods with the same name but a different signature. Constructors are said to be overloaded when there are multiple constructors with the same name but a different signature. A class contains constructors that are invoked to create objects. Values provided in the parameter list need to correspond to the order and type in the method signature. 6
21 December 2021 ESSENTIAL KNOWLEDGE Application program interfaces (APIs) and libraries simplify complex programming tasks. Existing classes and class libraries can be utilized as appropriate to create objects. Documentation for APIs and libraries are essential to understanding the attributes and behaviors of an object of a class. Classes in the APIs and libraries are grouped into packages. The String class is part of the java. lang package. Classes in the java. lang package are available by default. A string literal is enclosed in double quotes. String objects can be created by using string literals or by calling the String class constructor. String objects are immutable, meaning that String methods do not change the String object. 7
21 December 2021 ESSENTIAL KNOWLEDGE Two object references are considered aliases when they both reference the same object. Object reference values can be compared, using == and !=, to identify aliases. A class hierarchy can be developed by putting common attributes and behaviors of related classes into a single class called a superclass. Classes that extend a superclass, called subclasses, can draw upon the existing attributes and behaviors of the superclass without repeating these in the code. Extending a subclass from a superclass creates an “is-a” relationship from the subclass to the superclass. When a class S “is-a” class T, T is referred to as a superclass, and S is referred to as a subclass. The keyword extends is used to establish an inheritance relationship between a subclass and a superclass. A class can extend only one superclass. 8
21 December 2021 ESSENTIAL KNOWLEDGE The keyword public affects the access of classes, data, constructors, and methods. A void method does not return a value. Its header contains the keyword void before the method name. Method overriding occurs when a public method in a subclass has the same method signature as a public method in the superclass. A subclass is usually designed to have modified (overridden) or additional methods. The Object class is the superclass of all other classes in Java. Utilize the Object class through inheritance. Often classes have their own equals method, which can be used to determine whether two objects of the class are equivalent. Using a null reference to call a method or access an instance variable causes a Null. Pointer. Exception to be thrown. A reference value can be compared with null, using == or !=, to determine if the reference actually references an object. 9
21 December 2021 ESSENTIAL KNOWLEDGE Primitive values can be concatenated with a String object. This causes implicit conversion of the values to String objects can be concatenated using the + or += operator, resulting in a new String object. Autoboxing is the automatic conversion that the Java compiler makes between primitive types and their corresponding object wrapper classes. This includes converting an int to an Integer and a double to a Double. The Integer class and Double class are part of the java. lang package. The Java compiler applies autoboxing when a primitive value is: • Assigned to a variable of the corresponding wrapper class. Unboxing is the automatic conversion that the Java compiler makes from the wrapper class to the primitive type. This includes converting an Integer to an int and a Double to a double. 10
21 December 2021 ESSENTIAL KNOWLEDGE Subclasses of Object often override the to. String method with class specific implementations. If System. out. print or System. out. println is passed an object, that object’s to. String method is called, and the returned String is printed. A String object can be concatenated with an object reference, which implicitly calls the referenced object’s to. String method. The Java compiler applies unboxing when a wrapper class object is: • Assigned to a variable of the corresponding primitive type. A String object has index values from 0 to length – 1. Attempting to access indices outside this range will result in an Index. Out. Of. Bounds. Exception. There are standard algorithms that utilize String traversals to: • Find if one or more substrings has a particular property • Determine the number of substrings that meet specific criteria • Create a new string with the characters reversed 11
21 December 2021 Java Quick Reference - Accessible methods from the Java library that may be included in the exam Class Constructors and Methods Explanation String(String str) String Class Constructs a new String object that represents the same sequence of characters as str int length() String substring(int from, int to) Returns the number of characters in a String object Returns the substring beginning at index from and ending at index to - 1 String substring(int from) Returns substring(from, length()) int index. Of(String str) Returns the index of the first occurrence of str; - 1 if not found 12
21 December 2021 Java Quick Reference - Accessible methods from the Java library that may be included in the exam Class Constructors and Methods Explanation String Class boolean equals(String other) Returns true if this is equal to other; returns false otherwise int compare. To(String other) Returns a value <0 if this is less than other; returns zero if this is equal to other; returns a value >0 if this is greater than other 13
21 December 2021 Java Quick Reference - Accessible methods from the Java library that may be included in the exam Class Constructors and Methods Explanation Integer Class Integer(int value) Constructs a new Integer object that represents the specified int value int. Value() Returns the value of this Integer as an int Class Constructors and Methods Explanation Double(double value) Double Class Constructs a new Double object that represents the specified double value double. Value() Returns the value of this Double as a double 14
Java Quick Reference 21 December 2021 - Accessible methods from the Java library that may be included in the exam Object Class boolean equals(String other) String to. String() 15
21 December 2021 Programming Paradigms • Methods of programming. 16
21 December 2021 Two divisions of data in Java 17
Primitives 21 December 2021 • “Fundamental components that are used to create other, larger parts. “ • A programmer cannot 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. 18
Primitives 21 December 2021 • Advantages: • 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”. • Please NOTE that converting Integers to Strings is NOT a simple matter! You learned in the Conversion unit that numbers are held in binary for arithmetic but these have to be converted to ASCII code for String representation for display. 19
21 December 2021 Objects • Advantages: • 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. 20
21 December 2021 Primitives & Objects (crude) Analogy • Primitive: • Nuts & Bolts • Object: • Whole machine. 21
21 December 2021 Object Orientated Programming Paradigm (OOP) enables modelling of the real world by basing itself on: Examples of classes of realworld 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. . . 22
21 December 2021 Examples of Object Orientated Programming Paradigm (OOP) Languages • Java, C++, C#, Python, PHP, Java. Script, Ruby, Perl, Object Pascal, Objective-C, Dart, Swift, Scala, Common Lisp, MATLAB, and Smalltalk. • Contain software objects which exist entirely within a computer system and interact with other software objects. 23
21 December 2021 Class • A template/blueprint/instructions/factory/plan for objects. • Has 4 characteristics: 1. State/Properties/Attribute/Data Members/Instance Variables/Fields (optional): • Characteristics / data each object created from it (instances of a class) will have (may change over the course of the object’s ‘lifetime’). • All objects of the same class will have the same types of data (although the values of the data will be different from object to object). • e. g. • animal: length, eats, number of legs, etc… • bank account: balance, interest rate, daily withdrawal limit, etc… • pen: name, colour, etc. 24
21 December 2021 Class • Has 4 characteristics: 2. Constructor/s (NOT optional): • A template/blueprint/instructions/factory/plan for creating objects. • Every class has at least one constructor which, when called, can create/initialise/set up an object. • May or may not require certain ‘actual parameters’ to be passed to it. • e. g. size, colour, etc…. • It does not by itself create any objects, it is only a set of instructions to create an object. • Object creation has to be specifically requested before an object is created – see later. 25
21 December 2021 Class • Has 4 characteristics: 3. Behaviour/Methods/Mini Programs (optional): • Sets of instructions on how to use an object. • Sets of instructions that describe how an object will behave and / or how to use it. • e. g. https: //en. wikipedia. org/wiki/Animal 26
21 December 2021 Class • Has 4 characteristics: 4. Has an address: • The address in RAM where the 1 st byte (beginning) of the object is stored. 27
21 December 2021 Class • The name of the class is the data type of any objects created from it (or sub-classes – see later). • Many classes are pre-defined in Java (standard classes). • A programmer can invent new classes to meet the particular needs of a program. 28
Objects: 21 December 2021 • Are the instances (results) of a class created by following the constructor description contained in its class (or sub-classes – see later). • 4 characteristics: 1. optional members 2. 3. Constructor/s (NOT optional): • A template/blueprint/instructions/factory/plan for creating objects. • May or may not require certain ‘actual parameters’ to be passed to it. • e. g. size, colour, etc…. Can have values of states/properties/attribute/data members/instance variables/fields: • The data that each object has as part of itself 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: actual balance, interest rate, daily withdrawal limit, etc… • pen: name is Reynolds, colour is white etc. Can run behaviour/methods/mini programs: What states are required and possible behaviours are set by the class (or classes - see later) it comes from. • Functionality of an object (it can do things and can have things done to it) such as the • e. g. • animal: the sound it produces, • bank account: deposit, withdraw etc. • pen: writing 4. • Whether the objects ‘have’ these behaviours is arguable as the code for them is written in their class/es (see later). Has an address: • The address in RAM where the 1 st byte (beginning) of the object is stored. After a program stops running, any created objects no longer exist. Objects are created at and exist during Run Time only. 29
Difference between Class & Objects ? 21 December 2021 30
21 December 2021 class Chair { // 3 characteristics: // 1. Properties / instance variables int height; Object: chair 1 int num. Legs; // More properties could be listed. // 2. Constructor height = 0. 5 Chair (…, …) { /* Code to create a chair. Typically, initialise the instance variables with the ‘actual parameters’ given to the constructor. */ // 3. Methods: public void sit (…, …. ) { // More methods could be listed. /* Code to describe how to use a chair e. g. how much weight it can support, etc … */ } } num. Legs = 4 3 characteristics: 1. Values of properties / instance variables 2. Methods (from its class): • sit (e. g. can be sat on & support a certain amount of weight) 3. An address (location in memory) 31
To create/instantiate/construct an object: 21 December 2021 Standard Java formatting dictates that it begins with a capital letter and for multiple words use capitals 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. 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 2 nd word to begin each word. Name • 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. 32
Ways to declare & assign a reference variable Some constructors may require certain information called “actual” parameters / arguments written inside the brackets in a specific order separated by , . 1. 21 December 2021 null/nothing Class. Name ref. Var. Name = new Construc. Name ( ); // This is the standard way shown on the previous slide. • 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. 2. Class. Name ref. Var. Name; // Declares a reference variable & the class of the object it will later refer to but no object is created. 3. Class. Name ref. Var. Name. One, variable. Name. Two, …; 4. // Declares multiple reference variables, potentially referring to objects of the same class but no objects are created. …. ref. Variable. Name = new Construc. Name( ); // For methods 2 & 3 only after lines like these will object/s be created. ref. Var. Name. One = new Construc. Name( ); Class. Name ref. Var. Name. One = new Construc. Name ( ), variable. Name. Two = new Construc. Name ( ) ; /* Declares multiple reference variables, constructs new objects of the same class and their references are assigned to the variables. */ 33
21 December 2021 Types of Constructors 34
21 December 2021 Default constructor • 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 My. Class { public static void main (String args[]) { …. . ; } …. } public class My. Class { My. Class() { } JAVAC } public static void main (String args[]) { …. . ; } …. 35
21 December 2021 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, sets any instance variables (properties) to default values, 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 call the constructor/s of any parent class/es – see later. 36
21 December 2021 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. 37
no-arg Constructor 21 December 2021 • 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. 38
21 December 2021 Parameterized Constructor • Constructor with arguments (“actual” parameters). • Formal parameters • Declarations in the constructor’s or method's header. • Actual parameters • Values/Variables passed at the point of invocation (when called). • Some people use the word "arguments" instead of "actual parameters“ and just "parameters" for "formal parameters". Caller Constructor copies data actual parameters / arguments formal parameters 39
Objects 21 December 2021 • 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) 40
What is the object? 21 December 2021 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 ‘variable 1’, 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 ‘variable 1’. “ • rather than: • "The object variable 1. . . " • 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. 41
Dot Notation 21 December 2021 • The way variables and methods are accessed/called/invoked. • Non-Static methods: • object. Reference. member. Of. Object • object. Reference. variable. Name • object. Reference. method. Name() If parameters are required, they should be listed here according to the method’s signature – see later. 42
21 December 2021 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. 43
Parameterized Constructor Example 1 21 December 2021 Dante asks why data cannot go into emp. Id & emp. Name directly? Why do they have to be stored in id & name 1 st? • A parameterized constructor with 2 parameters id and name. • While creating the objects obj 1 and obj 2 2 arguments have been passed so that this constructor gets invoked after creation of obj 1 and obj 2. • Passing = sending to or from • • 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 emp. Id & emp. Name don’t exist. The Heap obj 1 reference Employee h ot ole ec s on T emp. Id = 10245 emp. Name = “Chaitanya” 44
Parameterized Constructor Example 1 21 December 2021 Output: ? 45
Parameterized Constructor Example 1 Instance 1 a. Variables ? “Formal” Parameter 2. ? Variables Reference 3. ? Variables “Actual” Parameter 4. ? Variables/arguments 21 December 2021 • Declared without the static keyword and outside any 1 b. ? method/constructor declarations. • Their values are instance/object specific. • If declared with Static then they would be associated with the class & so the same value for all instances of a class. 46
21 December 2021 Signature • In the Java programming language, a signature is the method/constructor name and the number, type and order of its parameters. • method. Or. Constructor. Name(parameters) {. . . }; • e. g. do. Something(int y, int x); do. Something(int x, int y); do. Something(double x, int y); do. Something(int x, double y); Signature: do. Something (int int) What their signatures and they only thetheir same? Sameare signature (variable names not are important, types). Signature: do. Something (int int) Signature: do. Something (double, int) What. Different are their and are they the same? andsignatures distinct signatures. Signature: do. Something (int, double) When methods have the same name or there are multiple constructors but with different signatures then they are said to be ‘Overloaded’. ? 47
Parameterized Constructor Example 2 • 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. 21 December 2021 no-arg Output: ? 48
Parameterized Constructor Example 3 21 December 2021 Output: • ? A compilation error. • The statement Example 3 myobj = new Example 3() invokes a default constructor which this program does not have and as no int argument has been supplied it does not match the signature of the existing single constructor. • 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. 49
Parameterized Constructor Example 4 21 December 2021 Output: no-arg ? error. • A compilation • You cannot have multiple constructors (or methods) with the same signature. • The signatures of the 2 nd & 3 rd constructors signature is: Why ? • Example 2 (int) • The names of the parameters are different but they are not part of a signature. • What do you think would happen Java allowed multiple constructors (or methods) with the ? same signature? • Java would have no idea which constructor or method to use. ? 50
21 December 2021 Application Program Interfaces (APIs) and Libraries • A library of available prewritten packages, classes, and interfaces with their respective methods, fields and constructors which simplify complex programming tasks. • Similar to a user interface, which facilitates interaction between humans and computers, an API serves as a software program interface facilitating interaction. • Documentation for APIs and libraries are essential to understanding the attributes and behaviors of an object of a class. • https: //docs. oracle. com/javase/8/docs/api/ 51
21 December 2021 Package • A group of classes, interfaces and other packages. package. Name { classes …. } • APIs are grouped into packages or classes which sometimes need to be imported into a program before their classes can be used. • e. g. • See importing the Scanner class later. • See the String class next. • Packages can be written inside packages as sub packages. https: //beginnersbook. com/2013/03/packages-in-java/ 52
21 December 2021 String • Is a sequence of characters/sequence of char values. • The String class is part of the java. lang package but does not need to be explicitly mentioned as all classes in java. lang are automatically imported. • 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). 53
21 December 2021 Strings Treatment • 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. 54
21 December 2021 String Construction • A String can be constructed by either: • 1. Directly assigning a string literal to a String reference - just like a primitive. • e. g. String str 1 = “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. • e. g. String str 2 = new String("Hello"); // Explicit construction via new 55
String Literals - Java String Pool 21 December 2021 1. Directly assigning a string literal to a String reference - just like a primitive. e. g. String s 1 = “Hello"; // Implicit construction via string literal String s 2 = “Hello"; // Implicit construction via string literal String s 3 = “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. 56
21 December 2021 String Object - Heap 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 s 4 = new String(“Hello"); // Explicit construction via new String s 5 = 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. 57
s 1 == s 2; // true True / False ? s 1 == s 3; // false / False ? True s 1 == “Cat”; //True true / False ? s 3 == “Cat”; //True false / False ? s 3 reference Basic Conclusion: Don’t use == to compare strings! ces) “Cat” “Dog” eren String s 3 = new String (“Cat”); s 2 reference != (ref String s 2 = “Cat”; Java Heap == String s 1 = “Cat”; s 1 reference != String - Issue with == 21 December 2021 String pool “Cat” • Remember that variables of objects are references so == with 2 objects checks if they relate to the same object known as aliases (in this case, literal strings), the contents are irrelevant. • See the later slides for the solution to this but 1 st we need to cover a few more OOP concepts. • Other examples of this issue can be found on slides 90 & 110. 58
21 December 2021 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. 59
Inheritance 21 December 2021 Java Syntax: To inherit a class we use extends keyword. 60
21 December 2021 Syntax: Inheritance in Java • To inherit a class we use extends keyword. Here class A is a child class and class B is a parent class A extends B { } 61
Reminder 21 December 2021 • 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. ? 62
Reminder • void: 21 December 2021 ? • States that a method does not return anything. 63
Inheritance Example 21 December 2021 ‘designation & the does() method are not defined in the Math. Teacher class, so Why is ‘designation’ part of a Math. Teacher object? How is the does() method accessible via a Math. Teacher object? Output: ? • If, as in this case, the constructor doesn’t set them. ole To the console Note: • As the programmer has not written a constructor for the Math. Teacher class, Javac will insert a default constructor. • A default constructor does nothing you “see” but it may call the constructor/s of any parent class/es. • After that any instance variables will be initialised as specified (those of any parent classes 1 st). Cons The Heap Maths. Teacher obj reference designation = “Teacher” college = “Beginnersbook” main. Subject = “Maths” 64
21 December 2021 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 65
21 December 2021 Rules for Method Overriding 1. The argument list (signature) should be exactly the same as that of the overridden method. 2. The return type should be the same or a subtype of the return type declared in the original overridden method in the superclass. 3. If a method cannot be inherited, then it cannot be overridden. 4. 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. 5. Constructors cannot be overridden. 66
21 December 2021 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. 67
21 December 2021 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. 68
21 December 2021 boolean equals(Object other) s 1 reference String s 3 = new String (“Cat”); s 1. equals(s 2); //True true / False ? s 1. equals(s 3); //True true / False ? s 1. equals(“Cat”); // true / False ? True s 3. equals(“Cat”); // true / False ? True == == s 3 reference nces) != (refere String s 2 = “Cat”; s 2 reference != String s 1 = “Cat”; Java Heap “Cat” “Dog” String pool “Cat” Conclusion: Don’t use == to compare strings! Use the equals method!!! 69
Reminder 21 December 2021 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 “Trycatch” blocks but this is not required in AP Computer Science (CS). 70
21 December 2021 Null Pointer Exception String string 1 = null; String string 2 = "abc"; System. out. println(string 1. equals(string 2)); Output: ? Exception in thread "main" java. lang. Null. Pointer. Exception at …. Null. Pointer. Exception 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. 71
21 December 2021 Null Pointer Exception Solution 1 • String comparison with literals String string 1 = null; System. out. println("abc". equals(string 1)); 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. 72
21 December 2021 Null Pointer Exception Solution 2 • Check if the Strings are null before any comparisons. String string 1 = null; String string 2 = "abc"; if (string 1 != null && string 2 != null) { System. out. println(string 1. equals(string 2)); } else { System. out. println("At least 1 of the strings is null so they can’t be compared"); } 73
Reference Variable Reused 21 December 2021 • 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. 74
21 December 2021 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. 75
21 December 2021 Types of Operator in Java 1. 2. 3. 4. 5. 6. 7. 8. 9. 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. 76
7. Concatenation 21 December 2021 • 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) 77
Concatenation 21 December 2021 e. g. int answer. Choice = ? ; System. out. println("You answered: " + answer. Choice + ". Please try again. "); • If answer. Choice = 4 then the following would be printed to the console: You answered: 4. Please try again. What happened here? 78
21 December 2021 Concatenation int answer. Choice = ? ; System. out. println("You answered: " + answer. Choice + ". Please try again. "); • If answer. Choice = 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)? Please NOTE that converting Integers to Strings is NOT a simple matter! You learned in the Conversion unit that numbers are held in binary for arithmetic but these have to be converted to ASCII code for String representation for display. int 00000100 = 4 ASCII 00110100 = 4 1. Autoboxing 2. to. String ? See next slides for explanations. 79
Autoboxing & Wrapper Classes • Autoboxing: Note: new Integer will give you deprecation warnings in versions of Java above version 8. Either ignore the warnings or change to Java 8. In Jdoodle: • The automatic creation of an corresponding object wrapper classes object by JAVAC from primitive types. • Integer(int value) & Double(double value) • e. g. Integer num. Integer = new Integer (20); • 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 to. String (see later). 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? 21 December 2021 Note that primitives consist of lower case letters only, objects start with a capital letter. Primitive type Corresponding Wrapper class int double boolean Integer Double Boolean Note: new Integer will give you deprecation warnings in versions of Java above version 8. Either ignore the warnings or change to Java 8. In Jdoodle: 80
String to. String() Note: new Integer will give you deprecation warnings in versions of Java above version 8. Either ignore the warnings or change to Java 8. In Jdoodle: 21 December 2021 • 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 to. String() method which every pre-defined Java class, overrides. • Note: to. String() 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 to. String() method which Java uses to tell it what to display. Output: Integer num. Integer = new Integer(65); String Integer to. String(): 65 Double num. Double = new Double(65. 3); object Double to. String(): 65. 3 Boolean answer = new Boolean (true); ? true Boolean to. String(): String string 1 = "abc"; String to. String(): abc System. out. println("Integer to. String(): " + num. Integer. to. String()); System. out. println("Double to. String(): " + num. Double. to. String()); System. out. println("Boolean to. String(): " + answer. to. String()); System. out. println("String to. String(): " + string 1. to. String()); 81
String to. String() 21 December 2021 Note: new Integer will give you deprecation warnings in versions of Java above version 8. Either ignore the warnings or change to Java 8. In Jdoodle: • Please NOTE that converting Integers to Strings is NOT a simple matter! You learned in the Conversion unit that numbers are held in binary for arithmetic but these have to be converted to ASCII code for String representation for display. • What do you think will happen if we do NOT explicitly invoke the to. String method? Integer num. Integer = new Integer(65); Double num. Double = new Double(65. 3); Boolean answer = new Boolean (true); String string 1 = "abc"; System. out. println("Integer to. String(): " + num. Integer); System. out. println("Double to. String(): " + num. Double); System. out. println("Boolean to. String(): " + answer); System. out. println("String to. String(): " + string 1); Output: Integer to. String(): 65 Double to. String(): 65. 3 Boolean to. String(): true String to. String(): abc ? Note: to. String() is automatically invoked when an object is ‘printed’ even if it is not explicitly invoked e. g. num. Integer. to. String() 82
String to. String() 21 December 2021 Note: new Integer will give you deprecation warnings in versions of Java above version 8. Either ignore the warnings or change to Java 8. In Jdoodle: int. Num = 65; double. Num = 65. 3; boolean answer = true; System. out. println("Integer to. String(): " + int. Num); System. out. println("Double to. String(): " + double. Num); System. out. println("Boolean to. String(): " + answer); Output: Integer to. String(): 65 Double to. String(): 65. 3 Boolean to. String(): 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 83
21 December 2021 Auto Boxing & automatic invocation of to. String() int. Num = 65; Note: new Integer will give you deprecation warnings in versions of Java above version 8. Either ignore the warnings or change to Java 8. In Jdoodle: System. out. println("Integer to. String(): " + Integer(int. Num). to. String()); This happened ‘automatically’ on the previous slide, hence ‘auto boxing’. double. Num = 65. 3; to. String() is also automatically invoked when an object is ‘printed’ even if it is not explicitly invoked System. out. println("Integer to. String(): " + Double(double. Num). to. String()); = The red code above is automatically added by Javac on compilation if it is not written. int. Num = 65; System. out. println("Integer to. String(): " + int. Num); double. Num = 65. 3; System. out. println("Integer to. String(): " + double. Num); 84
21 December 2021 Converting to String Process Summary e. g. Integer(int). to. String() primitive data type autoboxing corresponding wrapper object e. g. int e. g. Integer to. String method String object Note: new Integer will give you deprecation warnings in versions of Java above version 8. Either ignore the warnings or change to Java 8. In Jdoodle: 85
Unboxing Note: new Integer will give you deprecation warnings in versions of Java above version 8. Either ignore the warnings or change to Java 8. In Jdoodle: 21 December 2021 • int. Value() & double. Value() • Used to unbox and retrieve a primitive type value (int/double values) from their Integer/Double wrapper class objects. Integer num. Integer = new Integer (65); int. Num = num. Integer. int. Value(); // int. Num is now = 65 • However, this can be done automatically by the Java compiler and is therefore called ‘(auto) Unboxing’. Integer num. Integer = new Integer (65); int. Num = num. Integer; // int. Num is now = 65 Note: strangely the term “auto” is not traditionally used with the term “unboxing” so “unboxing” on its own is generally understood to mean “(auto)unboxing”, if we unbox using a wrapper class method like int. Value() or double. Value(), we can say “manually unboxing” to emphasise the manual nature that unboxing has been performed. /* int. Num is now = 65 & has been ‘unboxed’: the primitive type value has automatically been retrieved by the Java compiler from its wrapper class object. */ corresponding wrapper object e. g. Integer unboxing primitive data type e. g. int 86
Storing primitive data types in a String variable? 21 December 2021 Will the following lines compile and run? int x = 10; String str; str == x; x; ✘ str /* Auto Boxing in this situation does not happen & the last line will not compile: ‘Integer cannot be converted to String’. */ int x = 10; String str = “”; str += += x; x; ✔ str // Auto Boxing only occurs with the + operator and below are other variations of this. String str; str x; ✔ str == “” “” ++ x; str “Text”+ +x; x; ✔ str == “Text” Continued on the next slide. 87
Storing wrapper class data types in a String reference variable? 21 December 2021 /* Or, of course, we can use wrapper classes but statements without the + operator or to. String() written explicitly, will not compile (e. g. for the example below str = x ✘ */ Integer x = new Integer (10); String str; str = x. to. String(); ? // or str = “”? + x // or str = “Text ? ” + x; String str = “”; str ? += x; 88
String to. String() Note: new Integer will give you deprecation warnings in versions of Java above version 8. Either ignore the warnings or change to Java 8. In Jdoodle: 21 December 2021 • To simply convert a variable to a String for display, you can use: Integer num. Integer = new Integer (65); System. out. println(num. Integer); ? • But to store a variable in a string variable: Integer num. Integer = new Integer (65); String integer. To. String = num. Integer; /* Javac compile the line Will the will codenot above compile andabove, run? stating “incompatible types: …. cannot be converted to String”. = num. Integer. to. String() must be used (or +=). */ • Also note that all objects inherit the to. String() method of the Object class if a programmer defined object is displayed and it’s class does not override the to. String() 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 to. String() 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. http: //www. dummies. com/programming/java/use-javas-tostring-method/ 89
Operator Precedence Rules • 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 / 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 • 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. 21 December 2021 Operator Associativity unary pre-increment/decrement ++ -+ - (logical) ! not associative cast () right to left multiplicative */% left to right string concatenation + additive +- left to right relational < <= > >= not associative equality == != left to right logical && left to right logical || left to right assignment = += -= *= /= %= right to left 90
21 December 2021 Reminder: String - Issue with ==! String str = "a"; str += "b"; System. out. println(str); // Prints “ab”. System. out. println(str == "ab"); // false What is printed even str = “ab”! would bethough printed? • Conclusion: • Don’t use == to compare strings! • Use the equals ? method!!! Java Heap “a” “b” “ab” String Pool “ab” System. out. println(str. equals("ab“)); ? • Or to avoid a Null. Pointer. Exception: ? System. out. println(“ab”. equals(str)); • Other examples of this issue can be found on slides 57 & 110. 91
Changing the value of a Wrapper Class Object 21 December 2021 • The values of Wrapper Class Objects are actually immutable! ? • Wrapper Classes have no methods to change the value they have wrapped. Integer num. Integer = new Integer (12); ? num. Integer = new Integer (10); num. Integer There is no reference to this object so it is now marked as garbage! ? 12 10 Note: new Integer will give you deprecation warnings in versions of Java above version 8. Either ignore the warnings or change to Java 8. In Jdoodle: 92
Rewrite the following code so that it doesn’t use primitive data type variables (e. g. no int or double variables), autoboxing, implicit use of to. String or (auto) unboxing. 21 December 2021 int x = 10; int y = 25; int z = x + y; System. out. println("Sum of x + y = " + z); Note: new Integer will give you deprecation warnings in versions of Java above version 8. Either ignore the warnings or change to Java 8. In Jdoodle: 93
Previous code written so that it doesn’t use primitive data type variables, autoboxing, implicit use of to. String or (auto) unboxing. 21 December 2021 Integer x = new Integer (10); Integer y = new Integer (25); Integer z = new Integer (x. int. Value() + y. int. Value()); System. out. println("Sum of x + y = " + z. to. String()); Note: new Integer will give you deprecation warnings in versions of Java above version 8. Either ignore the warnings or change to Java 8. In Jdoodle: 94
Rewrite the following code so that it doesn’t use primitive data type variables (e. g. no int or double variable), autoboxing, implicit use of to. String or (auto) unboxing. 21 December 2021 int num. Of. Melons = 12; int capacity = 5; double melon. Contain; melon. Contain = num. Of. Melons / (double) capacity; System. out. println("Number of boxes needed: " + melon. Contain); Note: new Integer will give you deprecation warnings in versions of Java above version 8. Either ignore the warnings or change to Java 8. In Jdoodle: 95
Previous code written so that it doesn’t use primitive data type variables, autoboxing, implicit use of to. String or (auto) unboxing. 21 December 2021 Integer num. Of. Melons = new Integer (12); Integer capacity = new Integer (5); Double melon. Contain; melon. Contain = new Double(num. Of. Melons. int. Value()/(double)capacity. int. Value()); System. out. println("Number of boxes needed: " + melon. Contain. to. String()); Note: new Integer will give you deprecation warnings in versions of Java above version 8. Either ignore the warnings or change to Java 8. In Jdoodle: 96
21 December 2021 int length() • Used for finding out the length of a String. • Counts the number of characters in a String including the white spaces and returns the count. Output: ? 97
21 December 2021 String substring() Method 98
21 December 2021 String substring(int from, int to) • Returns the substring starting from the given index(begin. Index) till the specified index - 1 (end. Index - 1). • e. g. "Chaitanya". substring(2, 5) would return "ait". ? • It throws String. Index. Out. Of. Bounds. Exception if: 1. begin. Index or end. Index < 0 2. begin. Index or end. Index ? > last index of the String 3. end. Index < begin. Index Does substring change the original string? NO, the substring() method of a String object creates a new object (one object is creating another). 99
21 December 2021 String substring(int from) • Returns the substring starting from the specified index(begin. Index) 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". length = 7 • This method throws String. Index. Out. Of. Bounds. Exception if begin. Index is: 1. Less than zero (begin. Index<0). 2. Greater than the length? of String (> length of String). Note: this 1 parameter substring() method still uses 2 parameters as it has to know where to stop, the difference is that Java automatically uses the length of the String as the 2 nd parameter (i. e. last index position + 1). String substring(int from, String. length()); // The length of the string is automatically used as the 2 nd parameter, if you do not specify a 2 nd parameter. 100
21 December 2021 String substring() Method example public class Sub. String. Example{ public static void main(String args[]) { String str = "quick brown fox jumps over the lazy dog"; System. out. println("Substring starting from index 15 to last index: ") ; System. out. println(str. substring(15)); System. out. println("Substring starting from index 15 and ending at 19: "); System. out. println(str. substring(15, 20)); } } Output: ? 101
21 December 2021 Strings are immutable public class Imm. Demo { 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. 102
21 December 2021 String str = "abcdea"; String letter; int counta = 0; for (int i = 0 ; i <= str. length() ; i++) { letter = str. substring(i, i + 1); if (letter == "a") Output: counta++; } ? System. out. println(counta); 103
21 December 2021 Off-By-One Error String str = "abcdea"; String letter; int counta = 0; for (int i = 0 ; i <= str. length() ; i++) { letter = str. substring(i, i + 1); if (letter == "a") Output: counta++; String. Index. Out. Of. Bounds. Exception } System. out. println(counta); This is a common error and is always worth a mark in a FRQ exam. 104
21 December 2021 Off-By-One Error Solved String str = "abcdea"; String letter; int counta = 0; for (int i = 0 ; i < str. length() ; i++) { letter = str. substring(i, i + 1); if (letter == "a") counta++; } System. out. println(counta); Output: ? 105
21 December 2021 == String str = "abcdea"; String letter; int counta = 0; for (int i = 0 ; i < str. length() ; i++) { letter = str. substring(i, i + 1); if (letter == "a") Output: counta++; 0 } letter == “a” will never return true, System. out. println(counta); even if letter does actually refer to“a”. 106
21 December 2021 equals String str = "abcdea"; String letter; int counta = 0; for (int i = 0 ; i < str. length() ; i++) { letter = str. substring(i, i + 1); if (letter. equals("a“)) counta++; } System. out. println(counta); Output: 2 107
21 December 2021 Off-By-One Error String str = "abcdea"; String letter; int counta = 0; for (int i = 0 ; i < str. length() ; i++) { letter = str. substring(i, i + 2); if (letter. equals("ab“)) counta++; } System. out. println(counta); Output: ? 108
Off-By-One Error 21 December 2021 String str = "abcdea"; String letter; int counta = 0; str. length() ; i++) { for (int i = 0 ; i < str. length() letter = str. substring(i, ii ++ 22); if (letter. equals("ab“)) Output: counta++; } String. Index. Out. Of. Bounds. Exception System. out. println(counta); As ‘i + 2’ is now being used in the loop, i must stop before i < str. length - 1. Make sure you look out for this! 109
21 December 2021 Off-By-One Error Solved String str = "abcdea"; String letter; int counta = 0; for (int i = 0 ; i < str. length() - 1 ; i++) { letter = str. substring(i, i + 2); if (letter. equals("ab“)) counta++; } System. out. println(counta); Output: 1 110
int index. Of(String str) 21 December 2021 • Returns the index of the specified char/substring in a particular String. • Returns -1 if the specified char/substring is not found in the particular String. Output: ? 111
21 December 2021 int index. Of(String str) 112
21 December 2021 Quirky Issue when referring to the end of a String with substring String str 1 = “a dog thinks its owner is god, a cat thinks it is god"; String str 2 = "god"; Output: int i = str 1. index. Of(str 2); What is strange about this parameter? while (i >= 0) { str 1 = str 1. substring(0, i) + str 1. substring( i + str 2. length() ); i = str 1. index. Of(str 2); Because str 2 = “god” is at the end of str 1, this parameter will at some point become 1 more than the last index of str 1 (str 1. length). } This index position does not exist so you would be forgiven for thinking that this will System. out. println(str 1); ? ? result in a String. Index. Out. Bounds exception BUT IT DOESN’T. Java allows this even though nothing is there, it just returns nothing (null). This is due to the fact that the 2 nd parameter of the 2 parameter substring method refers to the index position of this parameter – 1, so Java allows this on the 1 st parameter. If you went any further though, a String. Index. Out. Bounds exception would occur. 113
21 December 2021 int compare. To(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. 114
21 December 2021 int compare. To(String other) Output: ? 115
21 December 2021 Methods to read data input by a user 1. Scanner class 2. Buffered. Reader class 3. Console • I will cover only the 1 st method as this is the more popular method (for the other methods, check the following link: • https: //www. geeksforgeeks. org/ways-to-read-input-from-console-in-java/ 116
1. Scanner class 21 December 2021 • 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 1 st 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: Object Name Constructor Must be the same name as the Class Name. • Scanner scan = new Scanner(System. in); Class Name Keyword Parameter required 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 2 nd word to begin each word. Note that it is also possible to avoid importing the Scanner class by writing java. util. Scanner each time you need the Scanner class. 117
21 December 2021 1. 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: Object Name int num = scan. next. Int(); 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. next. Int(); Method next. Boolean() next. Byte() next. Double() next. Float() next. Int() next. Line() next. Long() next. Short() next(). char. At(0) 118
21 December 2021 Example program to read data of various types using Scanner class. 119
21 December 2021 Reminder: String - Issue with ==! Scanner scan = new Scanner(System. in) String input. String = scan. Line(); if (input. String == “…”) // Will return true!!! true? Will never this ever • Conclusion: • Don’t use == to compare strings! • Use the equals ? method!!! if (input. String. equals(“…”)) ? Or to avoid a Null. Pointer. Exception: ? if (“…”. equals(input. String)) • Other examples of this issuecan be found on slides 57 & 90. 120
21 December 2021 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. next. Line() method is used after another. next method. • A new line character is a String, so a String. next. Line() 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. next. Line(); //To ‘consume’ (collect) the previous new line character but not assign it to any variable. 121
21 December 2021 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? It is possible I may not actually ask for these comments especially if most of the class have previously attended an ‘Intro to Computer Science ‘ course. Please listen to my instructions in class for details. Special note: This does not mean you will not be asked for any comments at all, only that you may not be asked for the comments above, please see the details of each individual program for the specific comments needed for a particular program. 122
21 December 2021 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). 123
21 December 2021 Garage • A garage is having software produced to calculate the bills for its customers. The garage enters details of a job. Duration 01: 09 02: 52 04: 13 Parts $17. 07 $29. 27 $43. 15 Please note that some comments are required (see the last slide for details). • 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. 124
21 December 2021 Garage • Write this program. • 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. Note that the flowchart is using pseudocode variable naming rules, please don’t forget to use Java variable naming rules in your Java code. 125
Garage • Hints: 21 December 2021 Please note that you are expected to write this program in the way hinted at here, as it uses all the methods on your syllabus. Look for the colon : using the index. Of method to find its position. Use the substring method to extract the numbers on the right of : as minutes. Use the substring method to extract the numbers on the left of : 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 and ints are primitive data types), so use the compare. To 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 1 st digit. • Solution: Extract each digit separately, if there are 2 digits then the 1 st digit is worth *10 and then + the 2 nd digit. • For minutes, things are fairly simple as there always 2 digits, but for hours there is no limit. Solution: Loop from the end of the hours string & move back, multiplying by increasing powers 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 = 31 -59 then add …. . See the next slide for required comments. 126
Garage Note: new Integer will give you deprecation warnings in versions of Java above version 8. Either ignore the warnings or change to Java 8. In Jdoodle: 21 December 2021 • Please submit 2 versions • You may submit 1 version with all of the below if you wish but 2 versions will allow you separate the complexity of the program itself from the concept comments asked for below. 1. Basically as ‘normal’, so uses autoboxing (no wrapper classes) and implicit to. String(). • With a comment on, before or after a specific line explaining that autoboxing occurs on this line and exactly where, why and what is happening. 2. Has at least one occasion of the following: a) A wrapper class variable reference. b) Implicit use of to. String(). c) Explicit use of to. String(). d) (auto) Unboxing • All occasions of each of the above must be commented on before or after their lines explaining exactly where, why and what is happening. 127
21 December 2021 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‘. 128
21 December 2021 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. • 07 129
21 December 2021 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. 130
21 December 2021 Grade yourself • Grade yourself on the vocabulary and learning objectives of the presentation. 131
- Slides: 131