Lecture 2: Intro to Java

Similar documents
1.1 Your First Program

! Widely available. ! Widely used. ! Variety of automatic checks for mistakes in programs. ! Embraces full set of modern abstractions. Caveat.

1.1 Your First Program

1.1 Your First Program

Lecture 2: Intro to Java

1.1 Your First Program

1.1 Your First Program

1.1 Your First Program

1.1 Your First Program! Naive ideal. Natural language instructions.

1.1 Your First Program

1.1 Your First Program

1/16/12. CS 112 Introduction to Programming. A Foundation for Programming. (Spring 2012) Lecture #4: Built-in Types of Data. The Computer s View

A human being should be able to change a diaper, plan an invasion, butcher a hog, conn a ship, design a building, write a sonnet, balance accounts,

1.1 Your First Program

2.3 Flow Control. Flow-Of-Control. If-Else: Leap Year. If-Else

Inf1-OOP. Textbooks. Who and What. Organizational Issues. Why Java? Course Overview. Hello, World! in Java. Ewan Klein, Perdita Stevens

Inf1-OOP. Textbooks. Who and What. Organisational issues. Why Java? Course Overview. Hello, World! in Java

Built-in data types. logical AND logical OR logical NOT &&! public static void main(string [] args)

Built-in data types. public static void main(string [] args) logical AND logical OR logical NOT &&! Fundamentals of Computer Science

MODULE 02: BASIC COMPUTATION IN JAVA

CS111: PROGRAMMING LANGUAGE II

DATA TYPES AND EXPRESSIONS

1.3 Conditionals and Loops

1.3 Conditionals and Loops

Lecture 3: Loops. While Loops. While Loops: Powers of Two. While Loops: Newton-Raphson Method

CS 112 Introduction to Programming

Program Development. Program Development. A Foundation for Programming. Program Development

3. Conditionals & Loops

3. Conditionals & Loops

3. Conditionals and loops

1.3 Conditionals and Loops. 1.3 Conditionals and Loops. Conditionals and Loops

Lecture 3: Loops. While Loops. While Loops: Newton-Raphson Method. While Loops: Powers of Two

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

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

Variables and data types

Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent

Who and what can help? Inf1-OP. Lecturer: Timothy Hospedales TA: Natalia Zon

Inf1-OP. Course Overview. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. February 26, School of Informatics

I/O (cont) and Program Development. Standard Audio. A Foundation for Programming. Crash Course in Sound

Java Bytecode (binary file)

1.3 Conditionals and Loops

CS 302: Introduction to Programming

CS 11 java track: lecture 1

CS 177 Recitation. Week 1 Intro to Java

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

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

A Foundation for Programming

CONDITIONAL EXECUTION

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

Programming Language Basics

Built-in Types of Data

1. Download the JDK 6, from

Programming Language Concepts: Lecture 2

1.3 Conditionals and Loops

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

CS 112 Introduction to Programming

1.3 Conditionals and Loops

! Sequence of statements that are actually executed in a program. ! Conditionals and loops: enable us to choreograph control flow.

CS 112 Introduction to Programming

Program Fundamentals

Algorithms and Programming I. Lecture#12 Spring 2015

when you call the method, you do not have to know exactly what those instructions are, or even how the object is organized internally

Introduction Basic elements of Java

Administrative Stuff. Inf1-OP. Additional help? Who to contact for help? Course Overview

Module 4: Characters, Strings, and Mathematical Functions

Flow of Control Branching 2. Cheng, Wei COMP May 19, Title

CS125 : Introduction to Computer Science. Lecture Notes #4 Type Checking, Input/Output, and Programming Style

4.1 Performance. Running Time. The Challenge. Scientific Method. Reasons to Analyze Algorithms. Algorithmic Successes

Calculations, Formatting and Conversions

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

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

A PROGRAM IS A SEQUENCE of instructions that a computer can execute to

CONDITIONAL EXECUTION

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

CS110: PROGRAMMING LANGUAGE I

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

Lecture Set 2: Starting Java

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

Introduction to Programming Using Java (98-388)

Getting started with Java

Section 2.2 Your First Program in Java: Printing a Line of Text

Lecture Set 2: Starting Java

Basic Concepts. Computer Science. Programming history Algorithms Pseudo code. Computer - Science Andrew Case 2

CS 231 Data Structures and Algorithms, Fall 2016

4.1 Performance. Running Time. The Challenge. Scientific Method

What did we talk about last time? Examples switch statements

Running Time. Analytic Engine. Charles Babbage (1864) how many times do you have to turn the crank?

Algorithms. Algorithms 1.4 ANALYSIS OF ALGORITHMS

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

Visual Programming. Lecture 2: More types, Methods, Conditionals

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

CSI33 Data Structures

Analysis of Algorithms

CS110D: PROGRAMMING LANGUAGE I

COMP Flow of Control: Branching 2. Yi Hong May 19, 2015

12. Numbers. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Variable Manipulator Driver. Installation and Usage Guide. Revision: 1.0 Date: Monday, July 10, 2017 Authors: Alan Chow

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University

Term 1 Unit 1 Week 1 Worksheet: Output Solution

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s

Transcription:

Why Programming? Lecture 2: Intro to Java Idealized computer. "Please simulate the motion of a system of N heavenly bodies, subject to Newton's laws of motion and gravity." Prepackaged software solutions. Great, if it does exactly what you need. Computer programming. Art of making a computer do what you want. Instead of imagining that our main task is to instruct a computer what to do, let us concentrate rather on explaining to human beings what we want a computer to do. - Donald Knuth Ada Lovelace (left), Analytic Engine (right). Introduction to Computer Science Robert Sedgewick and Kevin Wayne Copyright 2005 http://www.cs.princeton.edu/introcs 2 Languages Why Java? Machine languages. Tedious and error-prone. Natural languages. Ambiguous and hard for computer to parse.! Kids Make Nutritious Snacks.! Milk Drinkers Turn to Powder. Java features.! Widely used.! Widely available.! Embraces full set of modern abstractions.! Variety of automatic checks for mistakes in programs.! Red Tape Holds Up New Bridge.! Police Squad Helps Dog Bite Victim.! Tuna Biting Off Coast of Washington.! Local High School Dropouts Cut in Half. Reference: Rich Pattis High-level programming languages. Acceptable tradeoff. James Gosling http://java.net/jag 3 4

Why Java? A Rich Subset of the Java Language Java features. Types System Math Library! Widely used. int double System.out.println() Math.sin() Math.cos()! Widely available.! Embraces full set of modern abstractions.! Variety of automatic checks for mistakes in programs. long String char boolean Primitive Numeric Types System.out.print() System.out.printf() Parsing Math.log() Math.sqrt() Math.min() Math.abs() Math.exp() Math.pow() Math.max() Math.PI + - * Integer.parseInt() Caveat. No perfect language. / % ++ Double.parseDouble() -- > < Our approach. <= >= == Boolean Punctuation Flow Control! Minimal subset of Java.! Develop general programming skills that are applicable to: C, C++, C#, Python, Matlab, Fortran, Perl, << & >> ^!=! && == { (, ) ; if for do else while String Arrays Objects + "" a[i] class static length() compareto() new public private charat() matches() a.length tostring() equals() new main() 6 7 Programming in Java 1.1 Hello Java Programming in Java.! Create the program by typing it into a text editor, and save it as HelloWorld.java /******************************************* * Prints "Hello, World" * Everyone's first program. *******************************************/ public class HelloWorld { System.out.println("Hello, World"); HelloWorld.java Introduction to Computer Science Robert Sedgewick and Kevin Wayne Copyright 2005 http://www.cs.princeton.edu/introcs 9

Programming in Java Programming in Java Programming in Java.! Create the program by typing it into a text editor, and save it as HelloWorld.java! Compile it by typing at the command line: javac HelloWorld.java Programming in Java.! Create the program by typing it into a text editor, and save it as HelloWorld.java! Compile it by typing at the command line: javac HelloWorld.java! Execute it by typing at the command line: java HelloWorld command prompt % javac HelloWorld.java command prompt % javac HelloWorld.java % java HelloWorld Hello, World This creates a Java bytecode file named: HelloWorld.class 10 11 Programming in Java Hello, World Programming in Java (a slightly more realistic view) 1. Create the program by typing it into a text editor, and save it as MyFancyProgram.java 2. Compile it by typing at the command line: javac MyFancyProgram.java 3. Compiler says: That s not a legal program. 4. Back to step 1 to fix your errors of syntax. Repeat until none left. 5. Execute it by typing at the command line: java MyFancyProgram 6. Result is bizzarely (or subtley) wrong. 7. Back to step 1 to fix your errors of semantics. Repeat, etc. 8. After many attempts you finally get the result you wanted! A few remarks.! Name of class must match name of file.! Comments between /* and */ are ignored by compiler.! Whitespace and indentation is for human readability.! Syntax coloration auto-generated by editor. /******************************************* * Prints "Hello, World" * Everyone's first program. *******************************************/ public class HelloWorld { System.out.println("Hello, World"); HelloWorld.java 12 13

"Primitive" Data Types 1.2 Primitive Types of Data Data type. A set of values and operations defined on those values. Data Type Description Examples Common Operations char character 'A' '@' compare String sequence of characters "Hello World" "CS is fun" concatenate, compare int integer 17 12345 add, subtract, multiply, remainder double floating point number 3.1415 2.17 add, subtract, multiply, divide boolean truth value and, or, not, xor Introduction to Computer Science Robert Sedgewick and Kevin Wayne Copyright 2005 http://www.cs.princeton.edu/introcs 15 Text Ruler Text: the String data type.! A sequence of Unicode characters.! Each character is stored internally as a sequence of 16 bits: 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 1 character '1' in Unicode! Not technically a primitive type, but special language support. Ex. Subdivisions of a ruler. % javac Ruler.java % java Ruler 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 public class Ruler { String ruler1 = "1 "; 1 String ruler2 = ruler1 + "2 " + ruler1; 1 2 1 String ruler3 = ruler2 + "3 " + ruler2; 1 2 1 3 1 2 1 String ruler4 = ruler3 + "4 " + ruler3; String ruler5 = ruler4 + "5 " + ruler4; System.out.println(ruler5); string concatenation 16 17

Integers Integers: the int data type.! Useful when expressing algorithms. -2 31 2 31-1! Set of values: integers between 2147483648 and 2147483647.! Stored internally as a sequence of 32 bits: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 14 10 Integers public class IntOps { int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); int prod = a * b; int quot = a / b; int rem = a % b; System.out.println(a + " * " + b + " = " + prod); System.out.println(a + " / " + b + " = " + quot); System.out.println(a + " % " + b + " = " + rem); % javac IntOps.java % java IntOps 1234 99 1234 * 99 = 122166 1234 / 99 = 12 1234 % 99 = 46 1234 = 12*99 + 46 18 19 Initializing Variables Real Numbers Q. What happens if I forget to initialize the variable a or b?! Java compiler does not allow this.! Caveat: in other languages, variable initialized to arbitrary value. Q. What is default value for Registrar's room assignment variables? 20 Real numbers: the double data type.! Stored internally as a sequence of 64 bits using scientific notation.! Useful in scientific applications.! Ex: solve quadratic equation x 2 + bx + c = 0. public class Quadratic { // read coefficients from command line double b = Double.parseDouble(args[0]); double c = Double.parseDouble(args[1]); // calculate roots double sqroot = Math.sqrt(b*b - 4.0*c); double root1 = (-b + sqroot) / 2.0; double root2 = (-b - sqroot) / 2.0; // print them out System.out.println(root1); System.out.println(root2); roots = "b ± b2 " 4 c 2 22

Command Line Arguments Booleans and Comparisons Command line arguments. A simple method for processing a small amount of user input. % java Quadratic 3.0 2.0 2.0 command line arguments 1.0 x 2 3x + 2 Booleans: the boolean data type.! Set of values: or.! Internally represented as one bit. 0 1! Useful to control logic and flow of a program. Logical Operators Comparison Operators % java Quadratic 1.0 1.0 1.618033988749895 golden ratio -0.6180339887498949 % java Quadratic 1.0 1.0 NaN NaN not a number x 2 x - 1 x 2 + x + 1 a b a && b a b op ==!= < <= Description equal not equal less less or equal 2 == 2 2!= 3 2 < 3 2 <= 3 2 == 3 2!= 2 3 < 2 3 <= 2 % java Quadratic 1.0 hello java.lang.numberformatexception: hello % java Quadratic 1.0 java.lang.arrayindexoutofboundsexception a! a > >= greater greater or equal 3 > 2 3 >= 3 2 > 3 2 >= 3 23 24 Booleans and Comparisons Type Conversion Q. Is a year a leap year? A. Yes if divisible by 400, or divisible by 4 but not 100. public class LeapYear { int year = Integer.parseInt(args[0]); boolean isleapyear; // divisible by 4 but not 100 isleapyear = (year % 4 == 0) && (year % 100!= 0); // or divisible by 400 isleapyear = isleapyear (year % 400 == 0); Type conversion. Convert from one type of data to another.! Automatic: no loss of precision; or with strings.! Explicit: cast; or method. Ex. Generate a pseudo-random number between 0 and N-1.! Math.random() returns a double between 0.0 and 1.0. public class RandomInt { int N = Integer.parseInt(args[0]); double r = Math.random(); int n = (int) (r * N); String to int (method) System.out.println(isLeapYear); % java LeapYear 2004 % java LeapYear 1900 % java LeapYear 2000 25 double to int (cast) int to double (automatic) System.out.println("random integer is: " + n); % java RandomInt 6 3 % java RandomInt 6 0 % java RandomInt 10000 3184 int to String (automatic) 26

Summary A data type is a set of values and operations on those values.! String text processing.! double, int mathematical calculation.! boolean basis for decision making. 2.3 Flow Control Be aware.! Declare type of values.! Convert between types when necessary.! In 1996, Ariane 5 rocket exploded after takeoff because of bad type conversion. 27 Introduction to Computer Science Robert Sedgewick and Kevin Wayne Copyright 2005 http://www.cs.princeton.edu/introcs Flow-Of-Control If-Else Flow-of-control.! Sequence of statements that are actually executed in a program.! Conditionals and loops: enable us to harness power of the computer. The if-else statement is a common branching structure.! Check boolean condition.! If, execute some statements.! Otherwise, execute other statements. boolean 1 statement 1 if (boolean expression) statement1 boolean expression statement 2 statement 3 statement 1 boolean 2 statement 2 else statement2 if-else syntax can be a block of statements statement1 statement2 statement 4 statement 3 straight-line flow-of-control flow-of-control with conditionals and loops if-else flow chart 29 30

If-Else: Leap Year Oblivious Sorting If-else example: print informative text.! Different operation is performed depending on value of variable. if isleapyear is, then print "is a" otherwise, print "isn't a " Sort. Read in 3 integers and rearrange them in ascending order. public class Sort3 { System.out.print(year + " "); int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); int c = Integer.parseInt(args[2]); read in 3 integers swap a and b if (isleapyear) { System.out.print("is a"); else { System.out.print("isn't a"); System.out.println(" leap year"); if (b < a) { int t = b; b = a; a = t; if (c < b) { int t = c; c = b; b = t; if (b < a) { int t = b; b = a; a = t; System.out.println(a + " " + b + " " + c); % java Sort3 9 8 7 7 8 9 Puzzle 1. Sort 4 integers with 5 compare-exchanges. Puzzle 2. Sort 6 integers with 12. % java Sort3 2 1 7 1 2 7 31 32