CS1007: Object Oriented Design and Programming in Java. Lecture #2 Sept 8 Shlomo Hershkop Announcements

Similar documents
Objectives. Problem Solving. Introduction. An overview of object-oriented concepts. Programming and programming languages An introduction to Java

Chapter. Focus of the Course. Object-Oriented Software Development. program design, implementation, and testing

Chapter 1. Introduction

2 rd class Department of Programming. OOP with Java Programming

Object-Oriented Design & Patterns

CompSci 125 Lecture 02

COMP 202 Java in one week

3. Java - Language Constructs I

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

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

Java language. Part 1. Java fundamentals. Yevhen Berkunskyi, NUoS

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

A Java program contains at least one class definition.

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Program Fundamentals

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

ECE 122 Engineering Problem Solving with Java

For the course, we will be using JCreator as the IDE (Integrated Development Environment).

Java Programming. Atul Prakash

Java is a high-level programming language originally developed by Sun Microsystems and released in Java runs on a variety of

Packages & Random and Math Classes

CSCI 2101 Java Style Guide

COMP 202 Java in one week

An overview of Java, Data types and variables

Course Outline. Introduction to java

CSC 1214: Object-Oriented Programming

Building Java Programs. Introduction to Programming and Simple Java Programs

Object Oriented Programming and Design in Java. Session 2 Instructor: Bert Huang

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

Full file at

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

1 Shyam sir JAVA Notes

Chapter 2. Elementary Programming

Pace University. Fundamental Concepts of CS121 1

Welcome to CSE 142! Zorah Fung University of Washington, Spring Building Java Programs Chapter 1 Lecture 1: Introduction; Basic Java Programs

PROGRAMMING FUNDAMENTALS

MP 3 A Lexer for MiniJava

Programming in C++ 4. The lexical basis of C++

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

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

Introduction to Programming Using Java (98-388)

JAVA Ch. 4. Variables and Constants Lawrenceville Press

Identifiers. Identifiers are the words a programmer uses in a program Some identifiers are already defined. Some are made up by the programmer:

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

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

Introduction to C# Applications

3. Java - Language Constructs I

DM550 Introduction to Programming part 2. Jan Baumbach.

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

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Introduction to CS102

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

Tokens, Expressions and Control Structures

JOSE LUIS JUAREZ VIVEROS com) has a. non-transferable license to use this Student Guide

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

JAVA REVIEW cs2420 Introduction to Algorithms and Data Structures Spring 2015

Programming Lecture 3

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Welcome to CSE 142! Whitaker Brand. University of Washington, Winter 2018

CSCI 253. Outline. Background. George Blankenship 1

Elementary Programming

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

JAVA: A Primer. By: Amrita Rajagopal

CS 231 Data Structures and Algorithms, Fall 2016

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

last time in cs recitations. computer commands. today s topics.

CSE 142 Su 04 Computer Programming 1 - Java. Objects

BLM2031 Structured Programming. Zeyneb KURT

Games Course, summer Introduction to Java. Frédéric Haziza

Software and Programming 1

CS 61B Discussion 5: Inheritance II Fall 2014

Getting started with Java

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

Basic Types, Variables, Literals, Constants

The Java Language Rules And Tools 3

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1

Building Java Programs. Chapter 1: Introduction to Java Programming

Objectives of CS 230. Java portability. Why ADTs? 8/18/14

This course supports the assessment for Scripting and Programming Applications. The course covers 4 competencies and represents 4 competency units.

Java Fundamentals p. 1 The Origins of Java p. 2 How Java Relates to C and C++ p. 3 How Java Relates to C# p. 4 Java's Contribution to the Internet p.

9 Working with the Java Class Library

The MaSH Programming Language At the Statements Level

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

Selected Java Topics

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

The Sun s Java Certification and its Possible Role in the Joint Teaching Material

Basics of Java Programming

CS3157: Advanced Programming. Outline

Outline. Object Oriented Programming. Course goals. Staff. Course resources. Assignments. Course organization Introduction Java overview Autumn 2003

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

COMP 202. Java in one week

printf( Please enter another number: ); scanf( %d, &num2);

Software Design and Analysis for Engineers

Announcements. Java Review. More Announcements. Today. Assembly Language. Machine Language

CS3157: Advanced Programming. Outline

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Transcription:

CS1007: Object Oriented Design and Programming in Java Lecture #2 Sept 8 Shlomo Hershkop shlomo@cs.columbia.edu Announcements Class website updated Homework assignments will be posted Sept 9. TA: Edward Ishak Amrita Rajagopal Unix review cources offered by CUIT Check courseworks tomorrow for office hours survey. Let me know asap if you can not log in. 1

252 engineering Friday Sept 9 10-12, 1-3, 3-5pm Monday Sept 12 5-7pm Wed Sept 14 5-7pm Friday 16 19, 21 Unix classes Outline Review of Java basics. Writing classes in Java. Types Object reference vs. Object values Reading Today: Chapter 1 Next: Chapter 1, homework 0 (non-credit) 2

Status Should have plans on acquiring the text Should have tested your cunix access Should have seen the class website Cunix accounts, will be used for homework submissions CS accounts are useful for working in the clic lab and accessing the cs departments resources. www.cs.columbia.edu/~crf/accounts Suggestions Working outside of CUNIX: Setup correct version of java Use IDE Save often Don t forget to test on cunix Working on CUNIX Don t telnet Putty: available from acis Work in the labs 3

Class background There is a wide variety of both JAVA and programming skills We will do a super fast overview of JAVA basics before starting the meat and potatoes of the course. Please bear with me. Java Program Structure In the Java programming language: A program is made up of one or more classes A class contains one or more methods A method contains program statements A Java application always contains a method called main 4

Java Program A Java program contains at least one class definition. public class Hello { public static void main(string[] args) { System.out.println("Hello, world!") ; } } This code defines a class named Hello. The definition of Hello must be in a file Hello.java. The method main is the code that runs when you call `java Hello'. Java Program Structure // comments about the class public class Hello { class header class body } Comments can be placed almost anywhere 10 5

Java Program Structure // comments about the class public class Hello { // comments about the method public static void main (String[] args) { } method body method header } 11 Comments Comments in a program are called inline documentation They should be included to explain the purpose of the program and describe processing steps They do not affect how a program works, they are simply ignored. Java comments can take three forms: // this comment runs to the end of the line /* this comment runs to the terminating symbol, even across line breaks */ /** this is a javadoc comment */ 12 6

Identifiers Elements in a program are identified by some name. In Java, identifiers: Always start with a letter. Can include letters, digits, underscore (` ') and the dollar sign symbol ($). Must be different from any Java reserved words (or keywords). Often we use special identifiers called reserved words that already have a predefined meaning in the language Keywords that we've seen so far include: public, static, class and void. Reserved Words The Java reserved words: abstract else boolean enum break extends byte false case final catch finally char float class for const goto continue if default implements do import double instanceof int interface long native new null package private protected public return short static strictfp super switch synchronized this throw throws transient true try void volatile while 14 7

Case counts Identifiers and keywords in Java are case sensitive. In other words, capitalization matters. Keywords are always in lowercase. The following identifiers are all different: SHLOMO shlomo SHlomO Bad idea: use all those in one program. WHY? Spaces We use the word whitespace to describe blanks, tabs and newline characters. The Java compiler ignores whitespace except when it is used to separate words. E.g.: y=m*x+b;total=total+y; Is the same as: y = m*x + b ; total = total + y ; Which is easier to read? Does anyone know the diffence between DOS and UNIX linebreaks? (hint: fixcrlf) 8

Types The values a variable can take on and the operations we can perform on them is determined by its type. Java has the following type categories: Booleans Characters Integers Floating Points References to Objects Integers The java integer type represents both positive and negative integers. An n-bit integer x, can represent the range: n 1 n 1 byte 8 bits short 16 bits int 32 bits long 64 bits 2 x 2 9

Integer Literal A integer value or literal can be specified in decimal, hex, or octal (base 8) Decimal is a regular number which doesn t start with zero Hex literals start with 0x (0x1F = 31 base10) Octal literals start with just zero (072 = 58 base10) Integer literals are by default of type int A long literal ends with L If an int is small enough to fit into a short, it will be automatically converted, else you need to cast. In general extra bits are thrown away (not always good). Floating Point Type Floating point are used to represent the real numbers, i.e. fractional numbers 0.345 = 3.45 X 10 10

Program Development The mechanics of developing a program include several activities 1. Skip design 2. writing the program in a specific programming language (such as Java) 3. translating the program into a form that the computer can execute 4. investigating and fixing various types of errors that can occur 5. Go back and design correctly Software tools can be used to help with all parts of this process Development Environments There are many programs that support the development of Java software, including: Sun Java Development Kit (JDK) Sun NetBeans IBM Eclipse Borland JBuilder MetroWerks CodeWarrior Monash BlueJ Though the details of these environments differ, the basic compilation and execution process is essentially the same 11

Syntax and Semantics The syntax rules of a language define how we can put together symbols, reserved words, and identifiers to make a valid program The semantics of a program statement define what that statement means (its purpose or role in a program) A program that is syntactically correct is not necessarily logically (semantically) correct A program will always do what we tell it to do, not what we meant to tell it to do 23 Errors A program can have three types of errors The compiler will find syntax errors and other basic problems (compile-time errors) If compile-time errors exist, an executable version of the program is not created A problem can occur during program execution, such as trying to divide by zero, which causes a program to terminate abnormally (run-time errors) A program may run, but produce incorrect results, perhaps using an incorrect formula (logical errors) 24 12

Basic Program Development Edit and save program errors errors Compile program Execute program and evaluate results Problem Solving The purpose of writing a program is to solve a problem Solving a problem consists of multiple activities: Understand the problem Design a solution Consider alternatives and refine the solution Implement the solution Test the solution These activities are not purely linear they overlap and interact 13

Problem Solving The key to designing a solution is breaking it down into manageable pieces When writing software, we design separate pieces that are responsible for certain parts of the solution An object-oriented approach lends itself to this kind of solution decomposition We will dissect our solutions into pieces called objects and classes Object-Oriented Programming Java is an object-oriented programming language As the term implies, an object is a fundamental entity in a Java program Objects can be used effectively to represent real-world entities We try to define all our data as objects, and define programs to work on those objects For instance, an object might represent a particular employee in a company Each employee object handles the processing and data management related to that employee 14

Objects An object has: state - descriptive characteristics behaviors - what it can do (or what can be done to it) The state of a bank account includes its current balance The behaviors associated with a bank account include the ability to make deposits and withdrawals Note that the behavior of an object might change its state 29 Reusability OOP encourages the design of reusable components Vehicle as a general definition Mini-van as a more specific object Public class minivan{ String manufacturer; String model; int year; Color color; } 15

Classes An object is defined by a class A class is the blueprint of an object The class uses methods to define the behaviors of the object The class that contains the main method of a Java program represents the entire program A class represents a concept, and an object represents the embodiment of that concept Multiple objects can be created from the same class Instantiating Once we define a class we create an instance of the class. The constructor method is responsible for initializing the object new creates an instance 16

null null refers to no object Uninitialized objects Explicit assignment Can assign null to object variable: worldgreeter = null; Can test whether reference is null if (worldgreeter == null)... Dereferencing null causes NullPointerException this Refers to implicit parameter of method call Example: Equality testing public boolean equals(greeter other) { if (this == other) return true; return name.equals(other.name); } Example: Constructor public Greeter(String name) { this.name = name; } 17

Objects and Classes A class (the concept) An object (the realization) Bank Account John s Bank Account Balance: $5,257 Multiple objects from the same class Bill s Bank Account Balance: $1,245,069 Mary s Bank Account Balance: $16,833 Inheritance One class can be used to derive another via inheritance Classes can be organized into hierarchies Account Charge Account Bank Account Savings Account Checking Account 18

Java Objects Construct new objects with new operator new Greeter("World") Can invoke method on newly constructed object new Greeter("World").sayHello() More common: store object reference in object variable Greeter worldgreeter = new Greeter("World"); Then invoke method on variable: String greeting = worldgreeter.sayhello(); References A variable is a location in memory int x; x= 234; minivan mycar; mycar = new minivan(.) x mycar 234 ref Honda Odyssey 2000 Red 19

Difference References Create new variable y int y = x; Create another minivan instance minivan other = mycar; x y mycar other 234 234 ref ref Honda Odyssey 2000 Red Difference II Other.year = 2005; Surprise! x y mycar other 234 234 ref ref Honda Odyssey 2005 Red 20

Why? Any ideas why we would want to create object using references? References Object variable holds a reference Greeter worldgreeter = new Greeter("World"); Can have multiple references to the same object Greeter anothergreeter = worldgreeter; After applying mutator method, all references access modified object anothergreeter.setname("dave"); worldgreeter.sayhello() //returns "Hello, Dave!" 21

Parameter Passing Java uses "call by value": Method receives copy of parameter value Copy of object reference lets method modify object public void copynameto(greeter other) { other.name = this.name; } Greeter worldgreeter = new Greeter("World"); Greeter davegreeter = new Greeter("Dave"); worldgreeter.copynameto(davegreeter); No reference passing No Reference Parameters Java has no "call by reference" public void copylengthto(int n) { n = name.length(); } public void copygreeterto(greeter other) { other = new Greeter(name); } Neither call has any effect after the method returns int length = 0; worldgreeter.copylengthto(length); // length still 0 worldgreeter.copygreeterto(davegreeter) // davegreeter unchanged 22

Java packages Collection of similar classes Package names are dot-separated identifier sequences java.util javax.swing com.sun.misc edu.columbia.cs.robotics Unique package names: start with reverse domain name Must match directory structure package statement to top of file Class without package name is in "default package Full name of class = package name + class name java.util.string Importing Packages Tedious to use full class names import allows you to use short class name import java.util.scanner;... Scanner a; // i.e. java.util.scanner Can import all classes from a package import java.util.*; 23

Command Line Arguments public static void main(string[] args) args, is an array of string. The elements of args are the command line arguments using in running this class. Java testprogram t Moo=boo out.txt 0: -t 1: -Moo=boo 2: out.txt Two dimensional arrays You can create an array of any object, including arrays An array of an array is a two dimensional array public class TicTacToe{ public static final int EMPTY = 0; public static final int x = 1; public static final int y = 2; private int[][] board = { {EMPTY, EMPTY, EMPTY}, {EMPTY, EMPTY, EMPTY}, {EMPTY, EMPTY, EMPTY} } 24

Two dimensions You can also initialize the inner array as a separate call. Doesn t have to be congruous memory locations int [][]example = new int[5][]; for (int i=0;i<5;i++){ example[i] = new int[i+1]; } Multiple dimensions No reason cant create 4,5,6 dimension arrays Gets hard to manage Think about another way of representing the data Often creating an object is a better approach 25

Next Class Read Chapter 1 Download and try Homework 0 Get up to speed on Java Read old notes Dig out reference text 26