Week 6: Review. Java is Case Sensitive

Similar documents
Variables of class Type. Week 8. Variables of class Type, Cont. A simple class:

Introduction to Programming Using Java (98-388)

Fall 2017 CISC124 10/1/2017

5/24/2006. Last Time. Announcements. Today. Method Overloading. Method Overloading - Cont. Method Overloading - Cont. (Midterm Exam!

Fall 2017 CISC124 9/27/2017

Program Fundamentals

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

Index COPYRIGHTED MATERIAL

3. Java - Language Constructs I

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Java Primer 1: Types, Classes and Operators

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

CSC 1214: Object-Oriented Programming

CSC Web Programming. Introduction to JavaScript

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

CS313D: ADVANCED PROGRAMMING LANGUAGE

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Basics of Java Programming

AP Computer Science A

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

CS260 Intro to Java & Android 03.Java Language Basics

1 Shyam sir JAVA Notes

Lecture 2: Variables and Operators. AITI Nigeria Summer 2012 University of Lagos.

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

Fall 2017 CISC124 9/16/2017

Operators and Expressions

HUDSONVILLE HIGH SCHOOL COURSE FRAMEWORK

Visual C# Instructor s Manual Table of Contents

Computer Components. Software{ User Programs. Operating System. Hardware

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

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

Accelerating Information Technology Innovation

Chapter 2: Using Data

3. Java - Language Constructs I

Language Fundamentals Summary

Computer Components. Software{ User Programs. Operating System. Hardware

Object-Oriented Programming

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

Chapter 2. Elementary Programming

A variable is a name for a location in memory A variable must be declared

Java Review. Fundamentals of Computer Science

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

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments

CMPT 125: Lecture 3 Data and Expressions

Java Identifiers. Java Language Essentials. Java Keywords. Java Applications have Class. Slide Set 2: Java Essentials. Copyright 2012 R.M.

Chapter 6 Introduction to Defining Classes

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

COMP Primitive and Class Types. Yi Hong May 14, 2015

Fundamental Java Syntax Summary Sheet for CISC124, Fall Java is Case - Sensitive!

c) And last but not least, there are javadoc comments. See Weiss.

Full file at

The Warhol Language Reference Manual

CS 231 Data Structures and Algorithms, Fall 2016

Fundamental Java Syntax Summary Sheet for CISC101, Spring Java is Case - Sensitive!

Mr. Monroe s Guide to Mastering Java Syntax

Pace University. Fundamental Concepts of CS121 1

Java Basic Datatypees

Language Reference Manual simplicity

The Java language has a wide variety of modifiers, including the following:

Full file at

JAVA Programming Fundamentals

Points To Remember for SCJP

6.096 Introduction to C++ January (IAP) 2009

Cellular Automata Language (CAL) Language Reference Manual

boolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Operators. Java operators are classified into three categories:

Chapter 2 Elementary Programming

Client-Side Web Technologies. JavaScript Part I

Declaration and Memory

Tools : The Java Compiler. The Java Interpreter. The Java Debugger

Chapter 3: Operators, Expressions and Type Conversion

Zheng-Liang Lu Java Programming 45 / 79

Chapter 2: Data and Expressions

Values and Variables 1 / 30

CS 106 Introduction to Computer Science I

Getting started with Java

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

5/23/2015. Core Java Syllabus. VikRam ShaRma

CS112 Lecture: Working with Numbers

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

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java

CSC Java Programming, Fall Java Data Types and Control Constructs

Object Oriented Programming with Java

Computer Science II (20073) Week 1: Review and Inheritance

JAVA Ch. 4. Variables and Constants Lawrenceville Press

Chapter 2: Using Data

egrapher Language Reference Manual

Datatypes, Variables, and Operations

The MaSH Programming Language At the Statements Level

Programming Lecture 3

Chapter 2: Using Data

Exam 1 Prep. Dr. Demetrios Glinos University of Central Florida. COP3330 Object Oriented Programming

Java Notes. 10th ICSE. Saravanan Ganesh

Transcription:

Week 6: Review Java Language Elements: special characters, reserved keywords, variables, operators & expressions, syntax, objects, scoping, Robot world 7 will be used on the midterm. Java is Case Sensitive Special Characters // in line comment. /* */ block comment. ; end of line, in for loop syntax. { code block. dot : used to list a member of an object., comma : separates parameters or arguments in a list, values in an array. ( ) encloses parameter lists, used in syntax of conditionals and loops. used to enclose String literals. used to enclose char literals. [] used in array definitions. APSC142 - Prof.McLeod 1

Reserved Keywords (Can t be used as variable names) Used in APSC142, so far: boolean, byte, char, class, do, double, else, final, float, for, if, int, long, new, private, public, return, short, static, void, while You should know what these mean and where they are used! Other keywords: abstract, break, case, catch, continue, default, extends, finally, implements, import, instanceof, interface, native, null, package, protected, super, switch, synchronized, this, throw, throws, try (Underlined keywords will be discussed later in course) APSC142 - Prof.McLeod 2

Variables - Primitive Types Integral Types: byte, short, int, long, char For byte, from -128 to 127, inclusive For short, from -32768 to 32767, inclusive Forint, from -2147483648 to 2147483647, inclusive For long, from -9223372036854775808 to 9223372036854775807, inclusive For char, from '\u0000' to '\uffff' inclusive, that is, from 0 to 65535. A variable of the char type represents a Unicode character. Can also be represented as a or 8, etc. Floating Point Types: float, double For float, (4 bytes) roughly ±1.4 x 10-45 to ±3.4 x 10 38 to 8 significant digits. For double, (8 bytes) roughly ±4.9 x 10-324 to ±1.7 x 10 308 to 17 significant digits. APSC142 - Prof.McLeod 3

Variables - Types (Cont.) Boolean Types: boolean is either true or false. String is an object, not a primitive type. class is an object. (Arrays are objects.) APSC142 - Prof.McLeod 4

Variable Declaration & Naming Rules Variables must be declared before they are used. Variable names cannot start with a number, but otherwise can use a..z, A..Z, 0..9 and _. No spaces in variable names. Convention is that variables start with a lower case letter. Constants are all in upper case. Method names start with a lower case letter. Class names start with an upper case letter. Use descriptive variable names! Variables are usually nouns. Declaration examples: int numstudents; boolean studentisasleep; int numeggsindozen = 12; int icounter, jcounter, kcounter; double bigarea = 1.2e23; APSC142 - Prof.McLeod 5

Variable Declaration - Constants & Scoping The keyword final is used to declare constants: final int NUMSCREENROWS = 25; Hint: usually initialize after declaration. Variables declared within a method are local in scope to that method. You don t use private or public or static. Variables declared at the same level as methods within a class are called attributes must be declared public or private and can be static. Examples: public static int numstudents = 50; private final double R = 0.08206; public means the attribute can be changed. private attributes cannot be viewed or changed. static attributes occupy the same memory location for each child object. APSC142 - Prof.McLeod 6

Expressions - Operators Listed in order of operator precedence: () (parentheses). ( dot operator) ++ (increment) -- (decrement) + (unary plus) - (unary minus)! (boolean not ) (type) (type cast) * (multiplication) / (division) % (modulus) + (addition or concatenation) - (subtraction) < (boolean less than ) <= ( less than or equal to ) > ( greater than ) APSC142 - Prof.McLeod 7

Expressions - Operators (Cont.) >= ( greater than or equal to ) == ( equal to, don t use with String s!)!= ( not equal to ) && (boolean and ) (boolean or ) = (assign) += (add and assign) -= (subtract and assign) *= (multiply and assign) /= (divide and assign) %= (modulo and assign) Example: amount *= 25; is the same as: amount = amount * 25; You should know what all these operators do, and in what order they are processed. APSC142 - Prof.McLeod 8

Expressions - (Cont.) Expressions can contain operators, variables and literal values. Literals are things like north, 2, 1e-4, true, etc. Watch out for integer division!: 2.0 / 5.0 evaluates to 0.4. 2/5 is 0. Type casting: Any integer type can be implicitly changed into a float or double type. You must cast types to go in the other direction. For example: (int)4.8 evaluates to 4. The double value 4.8 has been cast to an int type. Note that casting truncates, not rounds. APSC142 - Prof.McLeod 9

Conditionals - if Statements Simple if statement syntax: if ( boolean_expression ) statement_when_true; else statement_when_false; With statement blocks: if ( boolean_expression ) { block_of_code_when_true else { block_of_code_when_false Note that else part is optional. APSC142 - Prof.McLeod 10

Conditionals - if Statements (Cont.) Branching if statement: if ( boolean_expression ) { block_of_code_when_true else if ( boolean_expression2 ) { block_of_code_when_2_true else if ( boolean_expression3 ) { block_of_code_when_3_true else if ( boolean_expression4 ) { block_of_code_when_4_true. else { block_of_code_when_all_are_false if statement is ended when one condition is true, no other branches are tested. Note that else part is optional. APSC142 - Prof.McLeod 11

Conditionals -switch Statement switch ( controlling_expression ) { (etc.) case case_label1: statement; statement; break; case case_label2: statement; statement; break; case case_label3: statement; statement; break; default: statement; statement; break; Note: case_label s are constants of same type as controlling_expression. APSC142 - Prof.McLeod 12

Loops Loops execute a block of instructions until a given condition becomes false. Three kinds of loops: while, do while, for. while loop syntax: while ( boolean_expression ) { block_of_code Loop executes until boolean_expression evaluates to false. Note, if boolean_expression is false to start with, loop will not execute at all. do while loop syntax: do { block_of_code while ( boolean_expression ); This loop will execute at least once. APSC142 - Prof.McLeod 13

Loops Cont. for loop syntax: for ( initialization; boolean_expression; update) { block_of_code Example: int sumnumbers = 0; for (int i=1; i <= 20; i++) { sumnumbers = sumnumbers + i; System.out.println(sumNumbers); Hint: Avoid using declarations inside loops. Watch out for infinite loops!! APSC142 - Prof.McLeod 14

String literals: String Class Press <enter> to continue. String variable declaration: String teststuff; or: String teststuff = A testing string. ; String concatenation ( addition ): String teststuff = Hello ; System.out.println(testStuff + to me! ); Would print the following to the DOS window: Hello to me! Note that including another type in a String concatenation calls an implicit tostring method. So, in: System.out.println( I am + 2); the number 2 is converted to a String before being concatenated. The digits given after a decimal point in a float or double type variable can be impressive! APSC142 - Prof.McLeod 15

String Class, Cont. A String variable is an object, so it has methods as well as a value. String methods include: length() equals(otherstring) equalsignorecase(otherstring) tolowercase() touppercase() trim() charat(position) substring(start) substring(start, End) indexof(searchstring) APSC142 - Prof.McLeod 16

Examples: String Class, Cont. int i; boolean abool; char achar; String teststuff = A testing string. ; i = teststuff.length(); // i is 17 abool = teststuff.equals( a testing string. ); // abool is false abool = teststuff.equalsignorecase( A TESTING STRING. ); // abool is true achar = teststuff.charat(2); // achar is t i = teststuff.indexof( test ); // i is 2 APSC142 - Prof.McLeod 17

Escape Characters: String Class, Cont. \ Double quote \ Single quote \\ Backslash \n Go to beginning of next line \r Go to beginning of current line \t Tab character For example: String teststuff = Line1\nLine2 ; System.out.println(testStuff); Would print the following to the DOS window: Line1 Line2 APSC142 - Prof.McLeod 18

Defining Methods Classes are containers for attributes and methods called encapsulation. Attributes and methods are members of a class. Attributes or instance variables hold data, methods do things. When a child object is created, it inherits all the attributes and methods of the parent object. For example: Robot BagOBolts = new Robot(); BagOBolts, the child object, inherits all the attributes and methods defined in the parent Robot class (ie. Defined in the Robot.java file). APSC142 - Prof.McLeod 19

Defining Methods Cont. Example (in first Robot.java file): public class Robot { //***********attributes********** public int row; public int column; public String direction; //************methods************ public void move() { // lines of code here public void turn() { // lines of code here public void printlocation() { // lines of code here // end of class Robot APSC142 - Prof.McLeod 20

Defining Methods Cont. Syntax: Scope Optional_static Return_type Method_name(Parameter_list) { Lines_of_code Scope is either public or private. public means that the method is available to other objects. The use of private allows for information hiding. Optional_static is the optional keyword static (Talk about later ) Return_type is either void, or a type such as int or double, etc. or a defined object such as String. void is used when the method does not return anything. If void is not used, then there must be at least one return statement in the method. APSC142 - Prof.McLeod 21

Defining Methods Cont. Method_name is whatever you want follow variable naming restrictions. Be descriptive (a verb). Parameter_list provides a means of passing values, or parameters, into a method. It is optional. It can consist of one or many parameters, separated by commas. Each parameter type must be declared in the parameter list. Examples of methods: public void PrintHello() { System.out.println( Hello ); public void PrintHelloName(String yourname) { System.out.println( Hello + yourname); APSC142 - Prof.McLeod 22

More Examples: Defining Methods Cont. public void PrintAvg(int a, int b) { System.out.println((a + b) / 2); public double Average(double a, double b) { return (a + b) / 2; public int Lowest(int a, int b) { if (a <= b) return a; else return b; Note that return can be used in a void method to end the method at the return statement rather than at the end of the code. APSC142 - Prof.McLeod 23

Defining Methods Cont. Scoping of variables and methods the use of public and private. Can declare variables inside a method: public double Average(double a, double b) { double holdaverage = (a + b) /2; return holdaverage; holdaverage is a local variable to the method. It is not defined or accessible outside the method. Instance variables (or attributes) declared in a class, at the same level as the methods, can be used by any method in the class. If an instance variable is declared public it is also available to objects outside the class as a member of the class. If the variable is declared private it can only be used within the class. If an method is declared public it is also available to objects outside the class as a member of the class. If the method is declared private it can only be used within the class. APSC142 - Prof.McLeod 24

Defining Methods Cont. If the static keyword is used in a method definition inside a class, it allows that method to be used without first having to instantiate the class. For example: String Junk = SavitchIn.readLine(); readline() is a public static method defined in the SavitchIn class. APSC142 - Prof.McLeod 25

Method Overloading A method can have the same name in many different classes. Overloading is when a method name is used more than once in the same class. The rule is that no two methods with the same name within a class, can have the same number and/or types of parameters in the method declarations. The method signatures must be different. Why bother? Allows the user to call a method without requiring him to supply values for all the parameters. Allows the programmer to keep an old method definition in the class for backwards compatibility. How does it work? Java looks through all methods until the parameters match with what is supplied by the user. If none match, Java tries to convert types in order to get a match. APSC142 - Prof.McLeod 26

Method Overloading Cont. Overloaded (and simplified) move() method in Robot class: // Move the robot a single space in the direction // it is facing. public void move() { if (direction.equalsignorecase("north")) row = row - 1; else if (direction.equalsignorecase("south")) row = row + 1; else if (direction.equalsignorecase("east")) column = column + 1; else if (direction.equalsignorecase("west")) column = column - 1; // end move() method // Moves the robot numofspaces in same direction public void move(int numofspaces) { for (int i=1; i <= numofspaces; i++) move(); // end move(numofspaces) method APSC142 - Prof.McLeod 27

Constructors In older robot versions, for example: Robot ChugAlong = new Robot(); ChugAlong.row = 0; ChugAlong.column = 1; ChugAlong.direction = south ; ChugAlong.numFlares = 20; When using Robot Version 7, you *must* use: Robot ChugAlong = new Robot(0, 1, south, 20); Robot World 7 attributes, constants and arrays are not longer public, they are private - they way they should have been all along! You can no longer use myrobot.row to get at the robot s row. You will need to use the appropriate get method. APSC142 - Prof.McLeod 28

Constructors Cont. Can and should overload constructors. Note that constructor definition cannot contain a return type and does not even have void. A Constructor without parameters is called the default constructor. For example, the Robot() default constructor works to put the robot at the first square from the north-west corner that does not have a wall, faces him east and gives him zero flares. Constructors are called with the new keyword when an object is created. Once an object is created ( instantiated ) then the constructor cannot be called again for that object. So, the only way to change the robot s direction or position is to use the move(), turn(), teleport(), etc. methods. Robot World 7 does not have any set methods for the attributes. APSC142 - Prof.McLeod 29

Constructors Cont. What other reasons are there to use constructors? Suppose we tried to use: Robot BadBoy = new Robot(0, 12, South ); Constructors can check for and compensate for illegal values. For example: // A three-parameter Robot constructor public Robot (int initrow, int initcol, String initdir) { if (initrow < 0) row = 0; else if (initrow > MAX_ROW) row = MAX_ROW; else row = initrow; if (initcol < 0) column = 0; else if (initcol > MAX_COL) column = MAX_COL; else column = initcol; direction = initdir.trim(initdir.tolowercase()); Constructors can also make assumptions and create values for those attributes the user does not supply. APSC142 - Prof.McLeod 30

Mutators and Accessors If class attributes are public, then they can still be directly changed even after the constructor has been run. In order to prevent direct changes to the attributes, make them private. The constructors can still set the attribute values when the object is created, but what if we want to see or set the attribute values later in the program? Mutator or set methods can change attribute values. Accessor, Selector or get methods can provide attribute values. Robot 7 has various get methods, such as getrow(), getcol() and getnumholding(). Robot 7 does not have any set methods. APSC142 - Prof.McLeod 31

Static Methods A public static method can be called without having to create ( instantiate ) an object. For example, all SavitchIn methods are static: String Junk = SavitchIn.readLine(); works. Instead of: SavitchIn readmethods = new SavitchIn(); String Junk = readmethods.readline(); (This also works ) Static methods cannot refer to non-static attributes or non-static methods, without creating an object first. Robot 7 has static get methods: getmaxrow(), getmaxcol(), and numrobots(). So they can be called as in Robot.getMaxRow(). APSC142 - Prof.McLeod 32

Static Variables One aspect is similar to static methods. A public static variable is available without having to create an object. For example, the Math class provides a value for π: double circlearea = Math.PI * radius *radius; Somewhere in the Math class is: public static final double PI = 3.141592653589793; Every object created from the class can refer to the same static variable (also called class variable ). Static variables are called static because they occupy a static area in memory. Normally each object has its own, completely independent copy of the class s attributes in separate memory locations. Robot 7 has a number of private static constants and variables. APSC142 - Prof.McLeod 33