CISC-124. Dog.java looks like this. I have added some explanatory comments in the code, and more explanation after the code listing.

Similar documents
Java Identifiers, Data Types & Variables

Programming with Java

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

CISC-124. This week we continued to look at some aspects of Java and how they relate to building reliable software.

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

CHAPTER 7 OBJECTS AND CLASSES

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

1B1b Classes in Java Part I

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

Mr. Monroe s Guide to Mastering Java Syntax

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable?

CISC-124. Passing Parameters. A Java method cannot change the value of any of the arguments passed to its parameters.

Java Fall 2018 Margaret Reid-Miller

VARIABLES AND TYPES CITS1001

CS 231 Data Structures and Algorithms, Fall 2016

Computational Expression

Notes on Chapter Three

Fundamentals of Programming Data Types & Methods

Enumerated Types. CSE 114, Computer Science 1 Stony Brook University

PROGRAMMING FUNDAMENTALS

Final Exam Practice. Partial credit will be awarded.

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

Software Practice 1 Basic Grammar

Midterms Save the Dates!

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

Ticket Machine Project(s)

Simple Java Reference

CHAPTER 7 OBJECTS AND CLASSES

CS 251 Intermediate Programming Java Basics

Fall 2017 CISC124 9/16/2017

1007 Imperative Programming Part II

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

data_type variable_name = value; Here value is optional because in java, you can declare the variable first and then later assign the value to it.

Introduction to Programming Using Java (98-388)

CSE 142 Su 04 Computer Programming 1 - Java. Objects

Two Types of Types. Primitive Types in Java. Using Primitive Variables. Class #07: Java Primitives. Integer types.

Units 0 to 4 Groovy: Introduction upto Arrays Revision Guide

Controls Structure for Repetition

Lecture 12. Data Types and Strings

COMP 202 Java in one week

H212 Introduction to Software Systems Honors

Java Classes & Primitive Types

CMPSCI 187: Programming With Data Structures. Lecture 6: The StringLog ADT David Mix Barrington 17 September 2012

Java Bytecode (binary file)

Week 3 Classes and Objects

Software and Programming 1

Getting started with Java

C++ for Java Programmers

APCS Semester #1 Final Exam Practice Problems

Java Classes & Primitive Types

Introduction to Java

CS 106 Introduction to Computer Science I

Full file at

Java Programming Fundamentals - Day Instructor: Jason Yoon Website:

Lecture Set 2: Starting Java

Introduction to Python

Midterms Save the Dates!

Lecture Set 2: Starting Java

Pointers, Arrays and Parameters

Following is the general form of a typical decision making structure found in most of the programming languages:

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Decisions, Decisions, Decisions. GEEN163 Introduction to Computer Programming

Object Oriented Programming. Java-Lecture 6 - Arrays

Software and Programming 1

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

Introduction to Java & Fundamental Data Types

CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall Office hours:

a) Answer all questions. b) Write your answers in the space provided. c) Show all calculations where applicable.

CS 113 PRACTICE FINAL

CS 1331 Exam 1 ANSWER KEY

Bjarne Stroustrup. creator of C++

Java+- Language Reference Manual

Michele Van Dyne Museum 204B CSCI 136: Fundamentals of Computer Science II, Spring

COE318 Lecture Notes Week 4 (Sept 26, 2011)

Recitation 3 Class and Objects

Decisions in Java IF Statements

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Topic 4 Expressions and variables

CS121/IS223. Object Reference Variables. Dr Olly Gotel

An Introduction to Processing

Brief Summary of Java

} Each object in a Java program has an identifier (name) } This includes:

Chapter 2 Elementary Programming

CEN 414 Java Programming

COMP-202: Foundations of Programming. Lecture 8: for Loops, Nested Loops and Arrays Jackie Cheung, Winter 2016

Basics of Java Programming

CS 1331 Exam 1. Fall Failure to properly fill in the information on this page will result in a deduction of up to 5 points from your exam score.

Datatypes, Variables, and Operations

CS260 Intro to Java & Android 03.Java Language Basics

Timing for Interfaces and Abstract Classes

Array. Array Declaration:

Activity 3: Data Types

About this exam review

COMP 401 Midterm. Tuesday, Oct 18, pm-3:15pm. Instructions

CS1150 Principles of Computer Science Arrays

CS 11 java track: lecture 1

Midterms Save the Dates!

COMPUTER APPLICATIONS

Relationship of class to object

Transcription:

CISC-124 20180115 20180116 20180118 We continued our introductory exploration of Java and object-oriented programming by looking at a program that uses two classes. We created a Java file Dog.java and another called AllMyDogs.java. Both of these files are already available on the website but I will include them here as well. Dog.java looks like this. I have added some explanatory comments in the code, and more explanation after the code listing. // 20180115 // RWD public class Dog { // The Dog class has no "main" method. The main method // will be found in the AllMyDogs.java file String name; // Note that this variable is not "static". This means // that each Dog object will have its own copy of the // "name" variable. If this variable is "static" then // all the dogs will have the same name. // constructor for Dog Dog (String n){ // When we create a Dog object, this constructor method is // automatically run. Here we are just using it to assign // the dog's name name = n; } // end constructor

public String getname() { // It is considered bad programming style for // anything outside the Dog class to use direct // access to the attributes of the Dog object. // If access is needed, we create a "getter" // method that will return the value of the // variable, and... return name; } // end getname() public void setname(string n) { //... a "setter" method that will assign // a value to the variable. name = n; } // end setname() } // end class Dog The purpose of Dog.java is simply to define the attributes (variables) that define a Dog, and the methods (functions) that a Dog can execute. Defining the class Dog and including it in a program does not actually create any Dog objects they are only created when we execute a new Dog instruction, which we will see in the AllMyDogs.java file. In this very simple example, the only attribute is name and the only methods are getname and setname. There is one special method included in the class definition the method called Dog is a constructor method. Whenever a Dog object is created, this method is run automatically. We typically use constructor methods to assign values to the attributes of the object being created. Java classes do not have to have constructor methods but they usually do.

Now let s look at the AllMyDogs.java file. // 20180115 // RWD // When we added input to the Collatz program we used a Scanner object. //We had to import the java.util.scanner class to do that // In this program we are going to use Dog objects but we don t have to //import the definition of the Dog object because it is in the same project public class AllMyDogs { // main is in this file because this is the part of the program that actually // does the work public static void main(string[] args) { Dog dog1 = new Dog("Hudson"); // Declare a Dog variable called // dog1, then create a new Dog // object with name = "Hudson", and // connect it to the dog1 variable Dog dog2 = new Dog("Dixie"); Dog dog3 = new Dog("Max"); System.out.println("Dog 1's name is " + dog1.getname()); System.out.println("Dog 2's name is " + dog2.getname()); System.out.println("Dog 3's name is " + dog3.getname()); dog2.setname("marmaduke"); System.out.println("Dog 2's name is " + dog2.getname()); Dog dog4 = dog1; // Declare a new Dog variable called dog4, and assign // it the value of dog1 // This does NOT create a new Dog object - it makes // dog4 an alternative name for the Dog object that // dog1 refers to dog4.setname("clifford"); // So when we change the name of dog4... System.out.println("Dog 1's name is " + dog1.getname()); } // end main } // end class AllMyDogs //... the change shows up when we look at dog1

It s important to understand what happens when we execute a command such as Dog dog1 = new Dog( Hudson ); The word Dog says that we are creating a new variable of type Dog. Then dog1 is the name of the new variable. At this point, there is no Dog attached to this variable. Then new Dog( Hudson ) tells Java to create a new Dog object. The constructor from the Dog class is executed, which assigns Hudson as the name of the just-created Dog. Finally, the = links the variable dog1 to the new Dog whose name is Hudson. What is happening behind the scenes is that the dog1 variable is set up in such a way that it can contain a memory address. When the new Dog object is created, Java allocates a chunk of memory to store all the attributes of the new Dog. The address of that chunk of memory is what gets stored in dog1. So when we say something like dog1.setname( Farley ); what happens is that the memory address stored in dog1 is used to locate the proper chunk of memory, then the setname() method is used to update the name attribute that is stored in that area of memory. When we execute Dog dog4 = dog1; the current value of dog1 is copied to dog4... and since the value of dog1 is a memory address, that is what gets copied. So now dog1 and dog4 both hold the memory address of the same Dog object... which is why calling dog4.setname() changes the result we get from dog1.getname() - dog1 and dog4 are both pointing to the same object. In this simple code sample, we didn t talk too much about public versus private. Normally the attributes of an object are declared private, so they cannot be freely accessed from outside the class. This is part of information hiding which we will talk about a lot in this course. A word about static : notice that the name attribute of the Dog object is not declared static. If it had been declared as static String name; then there would be one variable called name in the Dog class, shared by all the Dog objects. This would have the result that all the dogs would have the same name. You should try this out put the word static in front of the name declaration and see what happens.

Primitive Types Java provides eight types of variables that are not objects which means that they just have values, not attributes or methods. These are: Integer types: byte: this type of integer variable is only allocated 1 byte of memory it can only hold values from -127 to +128 short: allocated 2 bytes of memory int: long: allocated 4 bytes of memory allocated 8 bytes of memory Real Number types: float: allocated 4 bytes of memory Other types: double: allocated 8 bytes of memory boolean: can be true or false char: can hold a single character such as x or & - the character can also be specified in unicode We normally only use four of these: int, double, boolean and char. Note that each primitive type name starts with a lower-case letter this helps us remember that they are not object type names, which usually start with upper-case letters (such as java.util.scanner) Generally, we can assign a value of one numeric type to a variable of a different numeric type if the second type is more general than the first.

We can summarize this in a diagram byte short int long float double which means that a byte value can be assigned to a variable of any type, short values can be assigned to any type except byte, etc. So the following operations are completely legal: byte x = 3; float y = x; short z = 99; long w = z; double u = w; // ha ha, double u = w but this is not: float x = 3; byte y = x; // this looks like an integer, but it is stored // as 3.0 because we are assigning it to a float // variable // fails because byte is more restricted than // float Non-Primitive Types Java provides two standard non-primitive data types: Strings and arrays Strings: we have seen these before, so we already know a bit about them. Notice that String are objects (hence the capital S), but they are so common that Java lets us create them a bit more easily than other objects. When we created a Dog, we had to do something like Dog dog5 = new Dog( Rover ); but to create a String, all we have to do is String astring = A nut for a jar of tuna ; String anotherstring = Borrow, or rob? ; Notice that unlike java.util.scanner, we do not need to import the String class. It is automatically included every time we run a Java program.

Since String is a class, you can expect that it has some predefined methods in fact, the String class has a lot of methods. We will look at two of them here, and I encourage you to look up the class and experiment with some of the methods. One very useful String method is charat(x) which returns the character in position x in the string. char somechar; String yetanotherstring = Mr. Owl ate my metal worm ; somechar = yetanotherstring.charat(5); Now somechar has the value w. (The first position in a String is position 0, the second position is position 1, etc.) Another String method that gets used a lot is length() int howlong = yetanotherstring.length(); Now howlong has the value 25 Exercise: what is wrong with this? char x = astring.charat(astring.length());

String equality can be tested with == (as with primitive types) and also with the String method equals. String astring = Draw evil on no live ward ; String bstring = Draw evil on no live ward ; Now if (astring == bstring) {...} and if (astring.equals(bstring)) {...} do exactly the same thing. Exercise: all of the strings in these examples are palindromes. Use methods in the String class to write a method that will test a String to see if it is a palindrome.

Arrays An array is a structure that allows us to store a collection of values of the same type, each one identified by its position in the collection. Arrays are also objects in Java, but they have a very different syntax for declaring them. An array declaration consists of a type, and a pair of square brackets. For example int[] myarray; boolean[] boolarray; Dog[] lotsofdogs; declares that myarray will be used to refer to an array of integers, boolarray will be an array of booleans, and lotsofdogs will be an array of Dog objects. Creating an array can be done in two ways: 1. by using new and specifying the size of the array. For example (using the array variables defined above) myarray = new int[100]; int x = 7; boolarray = new boolean[x]; lotsofdogs = new Dog[5]; and of course these two steps can be combined, as in double[] somenums = new double[19]; 2. by specifying the set of values to be stored in the array. This is called literal definition or declaration. It used curly braces, like this: String[] week = { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };

The length of an array can be found by using length but unlike Strings, for arrays length is an attribute, not a method. So will not work, but will work just fine. int x = week.length(); int x = week.length;