IS2104_1_2_Fundamentals of Java.pdf
Document Details
Uploaded by Deleted User
Tags
Related
Full Transcript
Fundamentals of Java IS2104: Rapid Application Development Roshan Abeyweera ([email protected]) Objectives This lesson will review the following topics: Java Primitives Strings Logical and Relational Operators Conditional Statements Program Control Object Classes Constructor...
Fundamentals of Java IS2104: Rapid Application Development Roshan Abeyweera ([email protected]) Objectives This lesson will review the following topics: Java Primitives Strings Logical and Relational Operators Conditional Statements Program Control Object Classes Constructor and Method Overloading Inheritance 2 Primitive Data Types Java has eight primitive data types that store data during a program's operation. Primitive data types are a special group of data types that do not use the keyword new when initialized 3 Primitive Data Types Java creates primitives as automatic variables that are not references and are stored in stack memory with the name of the variable Primitive Data Types and Non-Primitive Data References Types Stack Memory Heap Memory The most common primitive types used in this course are int(integers) and double(decimals) 4 Primitive Data Types 5 Primitive Data Types 6 Declaring Variables and using Literals The keyword new is not used when initializing a variable primitive type Instead, a literal value should be assigned to each variable upon initialization A literal can be any number, text, or other information that represents a value E.g. 7 Task 1 : Declaring Variables and Using Literals 1. Create a class named VarTest 2. Create the following 3 uninitialized variables: int iNum; char cVal; Boolean bVal; 3. Display all the values to the console 4. Update your code to assign the following iNum = 25 cVal = B bVal = true 5. Display all the values to the console 8 Variables and Literals Suggested Solution 9 Strings A String is an object that contains a sequence of characters Declaring and instantiating a String is much like any other object variable However, there are differences: They can be instantiated without using the new keyword. Once instantiated, they are final and cannot be changed String objects come with their own set of methods 10 Task 2 : String Operations 1. Create a class named StringOperations 2. Create 3 string variables (str1, str2, str3) str1 should be initialized to “Hello” str2 should be initialized with your first name str3 should not be initialized with a value 11 String Operations Suggested Solution 12 String Operations Task Continued 3. Assign a value to str3 that joins the literal value “You are “ to the name held in str2 4. Display a welcome message to the screen that states “Welcome: “ and the value held in str3 5. Display a substring of str3 beginning with character 0, up to, but not including character 5 6. Display str2 in uppercase 13 String Operations Suggested Solution 14 String Operations You should never compare the value of Strings by using the == method (equals equals) that you use with primitive data types This is because the == operator only compares the contents of stack memory and therefore only compares the String references, not the String values 15 String Operations When comparing Strings there are different methods that you can use. The two ways of doing this are the compareTo() method and the equals() method Your options are: compareTo(String str) compareToIgnoreCase(String str) OR equals(Object obj) equalsIgnoreCase(String str) 16 String Operations Method: s1.compareTo(s2); Should be used when trying to find the lexicographical order of two strings Returns an integer If s1 is less than s2, an int< 0 is returned If s1 is equal to s2, 0 is returned If s1 is larger than s2, an int> 0 is returned There is also an option that allows you to ignore the case of the Strings 17 String Operations Method: s1.equals(s2) Should be used when you only wish to find if the two strings are equal Returns a boolean value If true is returned, s1 equals to s2 If false is returned, s1 not equal to s2 18 String Operations Task Continued 8. Use a comparison method to determine if the values of str1 and str2 are the same If they are not, display the information that gives you the lexicographical order of the two strings 9. Display the values that tell us whether two Strings are the same The order is not important 19 String Operations Suggested Solution 20 Console Input To read input that the user has entered into the console, use the Java class Scanner. You will have to use an import statement to access the class java.util.Scanner import java.util.Scanner; To initialize a Scanner, write: Scanner sc = new Scanner(System.in); You should explore the scanner class in more depth. You will see there are many methods for reading different types from the console 21 Console Input To accept different data types from the console, use: To read a single String value: String textInput = sc.next(); To read a line of text: String multiTextInput = sc.nextLine(); To read the next integer: int numValue = sc.nextInt(); To read the next double: double doubleValue = sc.nextDouble(); 22 Console Input Task 1. Create a class named InputVariables 2. Create a Scanner object named in 3. Create an initialized variable for each primitive data type 23 Console Input Suggested Solution 24 Console Input Task 4. Prompt for and read in a value for each variable using the Scanner. Use a print statement to create a prompt that resembles the following: Please enter a Boolean value: 5. Display the values for each variable that was entered in the console by using a println statement boolean value: true Close the scanner when you no longer need it 25 Console Input Suggested Solution 26 Console Input Suggested Solution 27 Relational Operators Java has six relational operators used to test primitive or literal numerical values Relational operators are used to evaluate if-else and loop conditions 28 Logic Operators Java has three logic operators used to combine boolean expressions into complex tests Understanding boolean logic is fundamental to programming 29 If Conditional Statement To build an if-else statement, remember the following rules: An if-else statement needs a boolean condition or method that is tested for true/false For example: If( x==5 ) If(y >= 17 ) If(s1.equals(s2)) 30 Conditional Statement Task 1. Create a class named AgeChecker 2. Read in an integer value for the user age from the console 3. Combine an if/else statement with a greater than relational operator to display “You are an adult” if the age is 21 or over, or “You are not an adult” if the age is less than 21 31 Conditional Statement Suggested Solution 32 Conditional Statement Task You need to be both 21 or over and have a driving license to hire a car 4. Read in a character value to identify if the user holds a current driving license Accept ‘y’ for yes and ‘n’ for no, assume that the input will be in the correct format 33 Conditional Statement Suggested Solution 34 Conditional Statement Task 5. Add a logical operator to the if/else statement so that if you are 21 or over and have a driving license, you can hire a car, the output should be: “You are an adult and can hire a car” or Test it with the following “You are not an adult, so cannot hire a car” values: 18, n 21,n 17,y 25,y 35 Conditional Statement Suggested Solution 36 Conditional Statement Task 2 1. Create a class called ValueChecker 2. Prompt for and read in an integer value 3. If the number is 7, then display “That’s lucky!” 4. If the number is 13, then display “That’s unlucky!” 5. If the number is anything else then display “That number is neither lucky nor unlucky!” 37 Conditional Statement Task 2 Suggested Solution 38 Loops - While With a while loop, Java uses the syntax: Similar to if statements, the while loop parameters can be boolean types or can equate to a boolean value Conditional statements (, =, !=, ==) equate to Boolean values. - Examples: while ( num1 < num2 ) while( isTrue ) while( n != 0) 39 Loops – do-while With a do-while loop, Java uses the syntax: The do-while loop: Is a post-test loop Is a modified while loop that allows the program to run through the loop once before testing the boolean condition Continues until the condition becomes false If you do not allow for a change in the condition, both the while loop and do-while loops will run forever as an infinite loop 40 Loops - for With a for loop, Java uses the syntax: The for loop repeats code a pre-set number of times The syntax of a for loop contains three parts: Initializing the loop counter (inti=0;) Conditional statement, or stopping condition (i< timesToRun;) Updating the counter (going to the next value(i++)) Think of i as a counter starting at 0 and incrementing until the value of i fails the stopping condition 41 Loops Task 1. Open the ValueChecker class in your IDE 2. Use a do-while loop so the program will continually ask the user for lucky numbers and display the results to the console 3. The program should terminate when the user enters a 0 (zero) as the value 4. No message should be displayed if a 0 value is entered 42 Loops Suggested Solution 43 Array An array is an collection of values of the same data type stored in a container object Length of the array is set when the array is declared Array examples: The address elements range from 0 to length – 1 44 Array Task A program is required to store a range of unique values! 1. Create a class called UniqueNumbers 2. Create a five(05) element integer array called numbers 3. Create the following four(04) variables: integer value called num, initialized to 0 that stores the user input Integer value called numValues, initialized to 0 that stores the number of valid entries Boolean value called valid, initialized to true that flags whether the number is unique or not Scanner object called in 45 Array Suggested Solution 46 Array Task Continued 4. Use a while loop to create a control structure that will continually execute until the number of values entered exceeds the size of the array 5. Use a nested do while loop to ask the user for a valid unique value 6. Use a nested for loop to check that the entered value does not already exist in the numbers array 7. If a valid number has been entered, add it to the numbers array 8. Use the numValuesvariable for the array index 9. Increment the numValuesvariable 47 Array Suggested Solution Continued 48 Array Task Continued 10. When the array has been filled with unique values, close the Scanner object 11. Use an enhanced for loop to display the contents of the numbers array to the console 49 Array Suggested Solution Continued 50 Object Classes Are classes that define objects to be used in a driver class Can be found in the Java API, or created by you Examples: Animal Circle String Student 51 Student Class Example Package Statement Class Declaration Instance Fields (Variables) Constructor Methods 52 Instance Fields An instance field is a variable declared within the class for which every object of the class will hold its own value Instance fields are declared within the class but outside of the methods Instance fields should be made private and accessed through a getter method 53 Access Modifiers Access modifiers specify accessibility to changing variables, methods, and classes There are four access modifiers in Java: Fields are typically private and methods public, but this is not always the case 54 Object Classes and Instance Field Task 1. Create a project called animalShop 2. Create a class called Dog that does not have a main method 3. Include the following instance fields in the dog class: String name String breed String barkNoice – “Woof” double weight 55 Object/Instance Fields Suggested Solution 56 Constructor A constructor is a method that creates an object In Java, constructors are methods with the same name as their class, used to create an instance of an object Constructors are invoked using the new keyword You can declare more than one constructor in a class declaration as long as they have different signatures 57 Constructor Example of creating an object using Student constructor: Student stu = new Student(); The constructor call is at the end of the statement and must include arguments that match the parameter list of the constructor If you do not declare a constructor, Java will provide a default (blank) constructor for you When you declare your own constructor, the default one provided by Java will no longer be available 58 Overloading Constructors Constructors assign initial values to instance variables of a class Constructors inside a class are declared as methods Overloading a constructor means having more than one constructor with the same name However, the number of arguments would be different, and/or the data types of the arguments would differ 59 Constructors with Parameters A constructor with parameters is used when you want to initialize the fields to values other than the default values To instantiate a Student instance using the constructor with parameters, write: Student stu = new Student("Zina","3003456"); 60 Object/Instance Fields Task Continued 4. Create a constructor that creates a dog object using parameters for the name, breed, and weight fields. Assign the instance fields to these values 5. Create a second constructor that accepts values for all instance fields as parameters and assigns the corresponding fields to those values 61 Object/Instance Fields Suggested Solution 62 Components of a Method A method signature is the name and parameters. Return type: This identifies what type of object, if any, will be returned when the method is invoked (called) If nothing will be returned, the return type is declared as void Method name: Used to make a call to the method 63 Components of a Method Parameter(s): The programmer may choose to include parameters depending on the purpose and function of the method Parameters can be of any primitive or type of object, but the parameter type used when calling the method must match the parameter type specified in the method definition Name of the Return Type Parameters Method 64 Class Methods Every class can have a set of methods associated with it, which allows functionality for the class Accessor method - Often called “getter” method - Returns the value of a specific instance variable Mutator method - Often called “setter” method - Changes or sets the value of a specific instance variable Functional method - Returns or performs some sort of functionality for the class 65 Accessor Methods Accessor methods access and return the value of a specific instance field of the class Non-void return type corresponds to the data type of the instance field you are accessing Includes a return statement Usually have no parameters 66 Mutator Methods Mutator methods set or modify the value of a specified instance field of the class Have a void return type Parameter has a type that corresponds to the type of the instance field being set 67 Functional Methods Functional methods perform a function or behavior for the class Can have either void or non-void return type Parameters are optional and used depending on what is needed for the method's function 68 Object/Instance Fields Task Continued 6. Create Accessor and Mutator (getter and setter) methods for the following fields: name Breed Weight 7. Don’t create one for the barkNoice field 69 Object/ Instance Fields Suggested Solution 70 Object/Instance Fields Suggested Solution 71 Object/Instance Fields Task Continued 8. Add a functional method called bark that will display the value of the barkNoise field to the console 72 Object/Instance Fields Suggested Solution 73 Overloading Methods Just as you used overloading when you created your constructors, you can also overload methods (behaviors) An overloaded method must have a different method signature The number of parameters must be different The type of parameters must be different The number or order of the parameter types must be different The name of the parameters are not part of the method signature 74 Object/Instance Fields Task Continued 9. Add an overloaded functional method called bark that will accept a String parameter for the noise the dog will make when it barks 75 Object/Instance Fields Suggested Solution 76 Main Method To run a Java program, you must define a main method in a Driver Class The main method is automatically called when the class is called Example: 77 Object/Instance Fields Task Continued 10. Create a class called AnimalTester that contains a main method 11. Create a dog1 object using the three (03) parameter constructor 12. Create a dog2 object using the four (04) parameter constructor 78 Object/Instance Fields Suggested Solution 79 Object/Instance Fields Task Continued Create method calls for both dog objects so that all of their information is displayed to screen 13. Use the instance field getter methods to produce the following output: Dog name : Bailey Dog breed : Boerboel Bark noise : arf-arf Dog weight : 80.2 80 Object/Instance Fields Suggested Solution 81 Superclass versus Subclass Classes can derive from or evolve out of parent classes, which means they contain the same methods and fields as their parents but can be considered a more specialized form of their parent classes The difference between a subclass and a superclass is as follows: 82 Superclass versus Subclass Superclasses: Contain methods and fields that are passed down to all of their subclasses Subclasses: Inherit methods and fields from their superclasses May define additional methods or fields that the superclass does not have May redefine (override) methods inherited from the superclass 83 extends Keyword In Java, you have the choice of which class you want to inherit from by using the keyword extends The keyword extends allows you to designate the superclass that has methods you want to inherit, or whose methods and data you want to extend For example, to inherit methods from the Shape class, use extends when the Rectangle class is created 84 More About Inheritance Inheritance is a one-way street Subclasses inherit from superclasses, but superclasses cannot access or inherit methods and data from their subclasses This is just like how parents don't inherit genetic traits like hair color or eye color from their children A student has access to the name field in the superclass but the Person class has no knowledge of the Student’s average mark 85 Object: The highest Superclass Every superclass implicitly extends the class Object Object: Is considered the highest and most general component of any hierarchy. It is the only class that does not have a superclass. Contains very general methods which every class inherits The Java API has more information on the object class: https://docs.oracle.com/javase/10/docs/api/java/lang/Object.html Java supports only single inheritance. That means that it can only extend one class, and not multiple classes. 86 Encapsulation Encapsulation is a fundamental concept in object oriented programming Encapsulation means to enclose something into a capsule or container, such as putting a letter in an envelope In object-oriented programming, encapsulation encloses, or wraps, the internal workings of a Java instance/object 87 How Encapsulation Works private data fields are hidden from the user of the object public methods can provide access to the private data, but methods hide the implementation Encapsulating your data prevents it from being modified by the user or other classes so that the data is not corrupted 88 Object/Instance Fields Task Continued 14. The animal shop now wants also to stock fish in their shop, the software will have to be updated to reflect this. You will have to create an Animal class (superclass) and a Fish class (subclass, same as Dog) 15. They would like to store all their animals’ colors. All animals must have their color stored 16. You cannot store any fish objects in your system unless all of the required values have been provided. Create a fish constructor that reflects this 89 Object/Instance Fields Task Continued 17. Identify the common fields/methods and place them in the superclass. The fields/methods that are specific to each animal type (dog, fish) should be placed in the appropriate class 18. Display both the fish and dog values on the console 19. A fish can be either a cold or heated water variety 20. Update your driver class to create these objects: 90 Object/Instance Fields Suggested Solution 91 Object/Instance Fields Suggested Solution 92 Object/Instance Fields Suggested Solution 93 Object/Instance Fields Suggested Solution 94 Terminology Key terms used in this lesson included: Java Primitives Strings Logical and Relational Operators Conditional Statements Program Control Object Classes Constructor and Method Overloading Inheritance Encapsulation 95 Summary In this lesson, you have learned how to: Use Java Primitives Use of Strings Use of Logical and Relational Operators Use Conditional Statements Use Program Control Understand Object Classes Understand Constructor and Method Overloading Understand Inheritance Understand Encapsulation 96 References Slides adopted by: 97