A First Look At Java. Didactic Module 13 Programming Languages - EEL670 1

Similar documents
Full file at

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Introduction to Programming Using Java (98-388)

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Values and Variables 1 / 30

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

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

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Lecture Set 4: More About Methods and More About Operators

A First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Lecture Set 4: More About Methods and More About Operators

Java Primer 1: Types, Classes and Operators

JAVA Programming Fundamentals

Chapter 3: Operators, Expressions and Type Conversion

Memory Management. Didactic Module 14 Programming Languages - EEL670 1

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

Operators in java Operator operands.

CS 231 Data Structures and Algorithms, Fall 2016

Primitive Data Types: Intro

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

Program Fundamentals

Basics of Java Programming

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

A Java program contains at least one class definition.

4 Programming Fundamentals. Introduction to Programming 1 1

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

Java Identifiers, Data Types & Variables

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Course Outline. Introduction to java

3. Java - Language Constructs I

Java+- Language Reference Manual

CS11 Java. Fall Lecture 1

Object-Oriented Programming

C++ Programming: From Problem Analysis to Program Design, Third Edition

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language

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

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

Operators and Expressions

Java Bytecode (binary file)

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Programming with Java

CS109A ML Notes for the Week of 1/16/96. Using ML. ML can be used as an interactive language. We. shall use a version running under UNIX, called

Getting started with Java

1007 Imperative Programming Part II

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

CSC 1214: Object-Oriented Programming

Chapter 7 Expressions and Assignment statements

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

Chapter 2: Using Data

PROGRAMMING FUNDAMENTALS

Objectives. In this chapter, you will:

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

Java Programming Fundamentals. Visit for more.

DATA TYPES AND EXPRESSIONS

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

More Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements

Operators. Java operators are classified into three categories:

MODULE 02: BASIC COMPUTATION IN JAVA

Memory Management. Chapter Fourteen Modern Programming Languages, 2nd ed. 1

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

Prof. Navrati Saxena TA: Rochak Sachan

Chapter 2: Basic Elements of Java

Java Basic Programming Constructs

3. Convert 2E from hexadecimal to decimal. 4. Convert from binary to hexadecimal

Full file at

CS 11 java track: lecture 1

Absolute C++ Walter Savitch

EMBEDDED SYSTEMS PROGRAMMING Language Basics

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

Flow Control. CSC215 Lecture

Chapter 7. Expressions and Assignment Statements ISBN

Java Programming. Atul Prakash

Software II: Principles of Programming Languages. Why Expressions?

Chapter 1 Introduction to java

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline

Lecture Set 2: Starting Java

Chapter 7. Expressions and Assignment Statements

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

Lecture Set 2: Starting Java

CMPT 125: Lecture 3 Data and Expressions

Scientific Computing

Programming Lecture 3

UNIT- 3 Introduction to C++

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

Java Notes. 10th ICSE. Saravanan Ganesh

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

CS Week 5. Jim Williams, PhD

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

Lecture 3. Lecture

CS 106 Introduction to Computer Science I

More Programming Constructs -- Introduction

Chapter 4 Defining Classes I

Transcription:

A First Look At Java Didactic Module 13 Programming Languages - EEL670 1

Outline Thinking about objects Simple expressions and statements Class definitions About references and pointers Getting started with a Java language system Didactic Module 13 Programming Languages - EEL670 2

Example Colored points on the screen What data goes into making one? Coordinates Color What should a point be able to do? Move itself Report its position Didactic Module 13 Programming Languages - EEL670 3

My x: 5 My y: 20 My color: black Things I can do: move report x report y My x: 20 My y: 10 My color: dark grey Things I can do: move report x report y My x: 17 My y: 25 My color: light grey Things I can do: move report x report y Didactic Module 13 Programming Languages - EEL670 4

Java Terminology Each point is an object Each includes three fields Each has three methods Each is an instance of the same class My x: 10 My y: 50 My color: black Things I can do: move report x report y Didactic Module 13 Programming Languages - EEL670 5

Object-Oriented Style Solve problems using objects: little bundles of data that know how to do things to themselves Not the computer knows how to move the point, but rather the point knows how to move itself Object-oriented languages make this way of thinking and programming easier Didactic Module 13 Programming Languages - EEL670 6

Java Class Definitions: A Peek public class Point { private int x,y; private Color mycolor; field definitions } public int currentx() { return x; } public int currenty() { return y; } public void move(int newx, int newy) { x = newx; y = newy; } method definitions Didactic Module 13 Programming Languages - EEL670 7

Outline Thinking about objects Simple expressions and statements Class definitions About references and pointers Getting started with a Java language system Didactic Module 13 Programming Languages - EEL670 8

Primitive Types We Will Use int: -2 31..2 31-1, written the usual way char: 0..2 16-1, written 'a', '\n', etc., using the Unicode character set double: IEEE 64-bit standard, written in decimal (1.2) or scientific (1.2e-5, 1e3) boolean: true and false Oddities: void and null Didactic Module 13 Programming Languages - EEL670 9

Primitive Types We Won t Use byte: -2 7..2 7-1 short: -2 15..2 15-1 long: -2 63..2 63-1, written with trailing L float: IEEE 32-bit standard, written with trailing F (1.2e-5, 1e3) Didactic Module 13 Programming Languages - EEL670 10

Constructed Types Constructed types are all reference types: they are references to objects Any class name, like Point Any interface name (following classes) Any array type, like Point[] or int[] (following classes) Didactic Module 13 Programming Languages - EEL670 11

Strings Predefined but not primitive: a class String A string of characters enclosed in doublequotes works like a string constant But it is actually an instance of the String class, and object containing the given string of characters Didactic Module 13 Programming Languages - EEL670 12

A String Object "Hello there" My data: Hello there My length: 11 Things I can do: report my length report my ith char make an uppercase version of myself etc. Didactic Module 13 Programming Languages - EEL670 13

Numeric Operators int: +, -, *, /, %, unary Java Expression Value 1+2*3 7 15/7 2 15%7 1 -(5*5) -25 double: +, -, *, /, unary Java Expression Value 13.0*2.0 26.0 15.0/7.0 2.142857142857143 Didactic Module 13 Programming Languages - EEL670 14

Concatenation The + operator has special overloading and coercion behavior for the class String Java Expression Value "123"+"456" "123456" "The answer is " + 4 "The answer is 4" "" + (1.0/3.0) "0.3333333333333333" 1+"2" "12" "1"+2+3 "123" 1+2+"3" "33" Didactic Module 13 Programming Languages - EEL670 15

Comparisons The usual comparison operators <, <=, >=, and >, on numeric types Equality == and inequality!= on any type, including double (unlike ML) Java Expression Value 1<=2 true 1==2 false true!=false true Didactic Module 13 Programming Languages - EEL670 16

Boolean Operators && and, short-circuiting, like ML s andalso and orelse!, like ML s not a?b:c, like ML s if a then b else c Java Expression Value 1<=2 && 2<=3 true 1<2 1>2 true 1<2? 3 : 4 3 Didactic Module 13 Programming Languages - EEL670 17

Operators With Side Effects An operator has a side effect if it changes something in the program environment, like the value of a variable or array element In ML, and in Java so far, we have seen only pure operators no side effects Now: Java operators with side effects Didactic Module 13 Programming Languages - EEL670 18

Assignment a=b: changes a to make it equal to b Assignment is an important part of what makes a language imperative Didactic Module 13 Programming Languages - EEL670 19

Rvalues and Lvalues Why does a=1 make sense, but not 1=a? Expressions on the right must have a value: a, 1, a+1, f() (unless void), etc. Expressions on the left must have memory locations: a or d[2], but not 1 or a+1 These two attributes of an expression are sometimes called the rvalue and the lvalue Didactic Module 13 Programming Languages - EEL670 20

Rvalues and Lvalues In most languages, the context decides whether the language will use the rvalue or the lvalue of an expression A few exceptions: Bliss: x :=.y ML: x :=!y (both of type 'a ref) Didactic Module 13 Programming Languages - EEL670 21

More Side Effects Compound assignments Long Java Expression a=a+b a=a-b a=a*b Short Java Expression a+=b a-=b a*=b Increment and decrement Long Java Expression a=a+1 a=a-1 Short Java Expression a++ a-- Didactic Module 13 Programming Languages - EEL670 22

Values And Side Effects Side-effecting expressions have both a value and a side effect Value of x=y is the value of y; side-effect is to change x to have that value Java Expression Value Side Effect a+(x=b)+c the sum of a, b and c changes the value of x, making it equal to b (a=d)+(b=d)+(c=d) three times the value of d changes the values of a, b and c, making them all equal to d a=b=c the value of c changes the values of a and b, making them equal to c Didactic Module 13 Programming Languages - EEL670 23

Pre and Post Values from increment and decrement depend on placement Java Expression Value Side Effect a++ the old value of a adds one to a ++a the new value of a adds one to a a-- the old value of a subtracts one from a --a the new value of a subtracts one from a Didactic Module 13 Programming Languages - EEL670 24

Instance Method Calls Java Expression s.length() s.equals(r) r.equals(s) Value the length of the String s true if s and r are equal, false otherwise same r.touppercase() r.charat(3) r.touppercase().charat(3) A String object that is an uppercase version of the String r the char value in position 3 in the String r (that is, the fourth character) the char value in position 3 in the uppercase version of the String r Didactic Module 13 Programming Languages - EEL670 25

Class Method Calls Class methods define things the class itself knows how to do not objects of the class The class just serves as a labeled namespace Like ordinary function calls in non-objectoriented languages Java Expression Value String.valueOf(1==2) "false" String.valueOf(5*5) "25" String.valueOf(1.0/3.0) "0.3333333333333333" Didactic Module 13 Programming Languages - EEL670 26

Method Call Syntax Three forms: Normal instance method call: <method-call> ::= <reference-expression>.<method-name> (<parameter-list>) Normal class method call <method-call> ::= <class-name>.<method-name> (<parameter-list>) Either kind, from within another method of the same class <method-call> ::= <method-name>(<parameter-list>) Didactic Module 13 Programming Languages - EEL670 27

Object Creation Expressions To create a new object that is an instance of a given class <creation-expression> ::= new <class-name> (<parameter-list>) Parameters are passed to a constructor like a special instance method of the class Java Expression Value new String() a new String of length zero new String(s) new String(chars) a new String that contains a copy of String s a new String that contains the char values from the array Didactic Module 13 Programming Languages - EEL670 28

No Object Destruction Objects are created with new Objects are never explicitly destroyed or deallocated Garbage collection (next class) Didactic Module 13 Programming Languages - EEL670 29

General Operator Info All left-associative, except for assignments 15 precedence levels Some obvious: * higher than + Others less so: < higher than!= Use parentheses to make code readable Many coercions null to any reference type Any value to String for concatenation One reference type to another sometimes (following classes) Didactic Module 13 Programming Languages - EEL670 30

Numeric Coercions Numeric coercions (for our types): char to int before any operator is applied (except string concatenation) int to double for binary ops mixing them Java expression 'a'+'b' 195 1/3 0 value 1/3.0 0.3333333333333333 1/2+0.0 0.0 1/(2+0.0) 0.5 Didactic Module 13 Programming Languages - EEL670 31

Boxing and Unboxing Coercions Preview: Java supports coercions between most of the primitive types (including int, char, double, and boolean), and corresponding predefined reference types (Integer, Character, Double, and Boolean) More about these coercions in following classes Didactic Module 13 Programming Languages - EEL670 32

Statements That s it for expressions Next, statements: Expression statements Compound statements Declaration statements The if statement The while statement The return statement Statements are executed for side effects: an important part of imperative languages Didactic Module 13 Programming Languages - EEL670 33

Expression Statements <expression-statement> ::= <expression> ; Any expression followed by a semicolon Value of the expression, if any, is discarded Java does not allow the expression to be something without side effects, like x==y Java Statement Equivalent Command in English speed = 0; Store a 0 in speed. a++; Increase the value of a by 1. inthered = cost > balance; If cost is greater than balance, set inthered to true, otherwise to false. Didactic Module 13 Programming Languages - EEL670 34

Compound Statements <compound-statement> ::= { <statement-list> } < statement-list> ::= <statement> <statement-list> <empty> Do statements in order Also serves as a block for scoping { } { Java Statement a = 0; b = 1; a++; b++; c++; Equivalent Command in English Store a zero in a, then store a 1 in b. Increment a, then increment b, then increment c. } { } Do nothing. Didactic Module 13 Programming Languages - EEL670 35

Declaration Statements <declaration-statement> ::= <declaration> ; <declaration> ::= <type> <variable-name> <type> <variable-name> = <expression> Block-scoped definition of a variable boolean done = false; Point p; Define a new variable named done of type boolean, and initialize it to false. Define a new variable named p of type Point. (Do not initialize it.) { } int temp = a; a = b; b = temp; Swap the values of the integer variables a and b. Didactic Module 13 Programming Languages - EEL670 36

The if Statement <if-statement> ::= if (<expression>) <statement> if (<expression>) <statement> else <statement> Dangling else resolved in the usual way Java Statement Equivalent Command in English if (i > 0) i--; if (a < b) b -= a; else a -= b; if (reset) { a = b = 0; reset = false; } Decrement i, but only if it is greater than zero. Subtract the smaller of a or b from the larger. If reset is true, zero out a and b and then set reset to false. Didactic Module 13 Programming Languages - EEL670 37

The while Statement <while-statement> ::= while (<expression>) <statement> Evaluate expression; if false do nothing Otherwise execute statement, then repeat Iteration is another hallmark of imperative languages (Note that this iteration would not make sense without side effects, since the value of the expression must change) Java also has do and for loops Didactic Module 13 Programming Languages - EEL670 38

Java Statement Equivalent Command in English while (a<100) a+=5; while (a!=b) if (a < b) b -= a; else a -= b; while (time>0) { simulate(); time--; } while (true) work(); As long as a is less than 100, keep adding 5 to a. Subtract the smaller of a or b from the larger, over and over until they are equal. (This is Euclid's algorithm for finding the GCD of two positive integers.) As long as time is greater than zero, call the simulate method of the current class and then decrement time. Call the work method of the current class over and over, forever. Didactic Module 13 Programming Languages - EEL670 39

The return Statement <return-statement> ::= return <expression>; return; Methods that return a value must execute a return statement of the first form Methods that do not return a value (methods with return type void) may execute a return statement of the second form Didactic Module 13 Programming Languages - EEL670 40

Outline Thinking about objects Simple expressions and statements Class definitions About references and pointers Getting started with a Java language system Didactic Module 13 Programming Languages - EEL670 41

Class Definitions We have enough expressions and statements Now we will use them to make a definition of a class Example: ConsCell, a class for building linked lists of integers like ML s int list type Didactic Module 13 Programming Languages - EEL670 42

/** * A ConsCell is an element in a linked list of * ints. */ public class ConsCell { private int head; // the first item in the list private ConsCell tail; // rest of the list, or null /** * Construct a new ConsCell given its head and tail. * @param h the int contents of this cell * @param t the next ConsCell in the list, or null */ public ConsCell(int h, ConsCell t) { } head = h; tail = t; Note comment forms, public and private, field definitions. Note constructor definition: access specifier, class name, parameter list, compound statement Didactic Module 13 Programming Languages - EEL670 43

/** * Accessor for the head of this ConsCell. * @return the int contents of this cell */ public int gethead() { return head; } /** * Accessor for the tail of this ConsCell. * @return the next ConsCell in the list, or null */ public ConsCell gettail() { return tail; } Note method definitions: access specifier, return type, method name, parameter list, compound statement Didactic Module 13 Programming Languages - EEL670 44

} /** * Mutator for the tail of this ConsCell. * @param t the new tail for this cell */ public void settail(conscell t) { tail = t; } Note: this mutator gives a way to ask a ConsCell to change its own tail link. (Not like anything we did with lists in ML!) This method is useful for some of the exercises at the end of the chapter. Didactic Module 13 Programming Languages - EEL670 45

val a = []; val b = 2::a; val c = 1::b; Using ConsCell ConsCell a = null; ConsCell b = new ConsCell(2,a); ConsCell c = new ConsCell(1,b); Like consing up a list in ML But a Java list should be object-oriented: where ML applies :: to a list, our Java list should be able to cons onto itself And where ML applies length to a list, Java lists should compute their own length So we can t use null for the empty list Didactic Module 13 Programming Languages - EEL670 46

/** * An IntList is a list of ints. */ public class IntList { private ConsCell start; // list head, or null /** * Construct a new IntList given its first ConsCell. * @param s the first ConsCell in the list, or null */ public IntList(ConsCell s) { start = s; } An IntList contains a reference to a list of ConsCell objects, which will be null if the list is empty Didactic Module 13 Programming Languages - EEL670 47

/** * Cons the given element h onto us and return the * resulting IntList. * @param h the head int for the new list * @return the IntList with head h, and us as tail */ public IntList cons (int h) { return new IntList(new ConsCell(h,start)); } An IntList knows how to cons things onto itself. It does not change, but it returns a new IntList with the new element at the front. Didactic Module 13 Programming Languages - EEL670 48

} /** * Get our length. * @return our int length */ public int length() { int len = 0; ConsCell cell = start; while (cell!= null) { // while not at end of list len++; cell = cell.gettail(); } return len; } An IntList knows how to compute its length Didactic Module 13 Programming Languages - EEL670 49

Using IntList ML: val a = nil; val b = 2::a; val c = 1::b; val x = (length a) + (length b) + (length c); Java: IntList a = new IntList(null); IntList b = a.cons(2); IntList c = b.cons(1); int x = a.length() + b.length() + c.length(); Didactic Module 13 Programming Languages - EEL670 50

Outline Thinking about objects Simple expressions and statements Class definitions About references and pointers Getting started with a Java language system Didactic Module 13 Programming Languages - EEL670 51

What Is A Reference? A reference is a value that uniquely identifies a particular object public IntList(ConsCell s) { start = s; } What gets passed to the IntList constructor is not an object it is a reference to an object What gets stored in start is not a copy of an object it is a reference to an object, and no copy of the object is made Didactic Module 13 Programming Languages - EEL670 52

Pointers If you have been using a language like C or C++, there is an easy way to think about references: a reference is a pointer That is, a reference is the address of the object in memory Java language systems can implement references this way Didactic Module 13 Programming Languages - EEL670 53

But I Thought It is sometimes said that Java is like C++ without pointers True from a certain point of view C and C++ expose the address nature of pointers (e.g. in pointer arithmetic) Java programs can t tell how references are implemented: they are just values that uniquely identify a particular object Didactic Module 13 Programming Languages - EEL670 54

C++ Comparison A C++ variable can hold an object or a pointer to an object. There are two selectors: a->x selects method or field x when a is a pointer to an object a.x selects x when a is an object A Java variable cannot hold an object, only a reference to an object. Only one selector: a.x selects x when a is a reference to an object Didactic Module 13 Programming Languages - EEL670 55

Comparison C++ IntList* p; p = new IntList(0); p->length(); p = q; IntList p(0); p.length(); p = q; Equivalent Java IntList p; p = new IntList(null); p.length(); p = q; No equivalent. Didactic Module 13 Programming Languages - EEL670 56

Outline Thinking about objects Simple expressions and statements Class definitions About references and pointers Getting started with a Java language system Didactic Module 13 Programming Languages - EEL670 57

Text Output A predefined object: System.out Two methods: print(x) to print x, and println(x) to print x and start a new line Overloaded for all parameter types System.out.println("Hello there"); System.out.print(1.2); Didactic Module 13 Programming Languages - EEL670 58

Printing An IntList /** * Print ourself to System.out. */ public void print() { System.out.print("["); ConsCell a = start; while (a!= null) { System.out.print(a.getHead()); a = a.gettail(); if (a!= null) System.out.print(","); } System.out.println("]"); } Added to the IntList class definition, this method gives an IntList the ability to print itself out Didactic Module 13 Programming Languages - EEL670 59

The main Method A class can have a main method like this: public static void main(string[] args) { } This will be used as the starting point when the class is run as an application Keyword static makes this a class method; use sparingly! Didactic Module 13 Programming Languages - EEL670 60

A Driver Class public class Driver { public static void main(string[] args) { IntList a = new IntList(null); IntList b = a.cons(2); IntList c = b.cons(1); int x = a.length() + b.length() + c.length(); a.print(); b.print(); c.print(); System.out.println(x); } } Didactic Module 13 Programming Languages - EEL670 61

Compiling The Program Three classes to compile, in three files: ConsCell.java, IntList.java, and Driver.java (File name = class name plus.java watch capitalization!) Compile with the command javac They can be done one at a time Or, javac Driver.java gets them all Didactic Module 13 Programming Languages - EEL670 62

Running The Program Compiler produces.class files Use the Java launcher (java command) to run the main method in a.class file C:\demo>java Driver [] [2] [1,2] 3 Didactic Module 13 Programming Languages - EEL670 63