Lecture 2: Intro to Java

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

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

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/16/12. CS 112 Introduction to Programming. A Foundation for Programming. (Spring 2012) Lecture #4: Built-in Types of Data. The Computer s View

1.1 Your First Program

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

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

DATA TYPES AND EXPRESSIONS

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

MODULE 02: BASIC COMPUTATION IN JAVA

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

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

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

Variables and data types

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

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

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

CS111: PROGRAMMING LANGUAGE II

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

Built-in Types of Data

1. Download the JDK 6, from

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

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

CS 302: Introduction to Programming

Java Bytecode (binary file)

Introduction Basic elements of Java

1.3 Conditionals and Loops

CONDITIONAL EXECUTION

CS 177 Recitation. Week 1 Intro to Java

Program Fundamentals

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

Programming Language Concepts: Lecture 2

3. Conditionals & Loops

Calculations, Formatting and Conversions

CS 11 java track: lecture 1

Module 4: Characters, Strings, and Mathematical Functions

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

1.3 Conditionals and Loops

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)

1.3 Conditionals and Loops

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

3. Conditionals & Loops

3. Conditionals and loops

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

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

CONDITIONAL EXECUTION

CS110: PROGRAMMING LANGUAGE I

Getting started with Java

CS110D: PROGRAMMING LANGUAGE I

Eng. Mohammed S. Abdualal

CSI33 Data Structures

Full file at

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

Introduction to Computer Science Unit 2. Notes

Algorithms and Programming I. Lecture#12 Spring 2015

Lesson 5: Introduction to the Java Basics: Java Arithmetic THEORY. Arithmetic Operators

Programming Language Basics

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

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

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

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

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

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

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

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

What did we talk about last time? Examples switch statements

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

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

Lecture Set 2: Starting Java

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

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

COMP1730/COMP6730 Programming for Scientists. Data: Values, types and expressions.

Lecture Set 2: Starting Java

CMSC131. Introduction to your Introduction to Java. Why Java?

Chapter 4 Mathematical Functions, Characters, and Strings

Introduction to Computer Science Unit 2. Notes

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

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

Branching and Boolean Expressions

More types, Methods, Conditionals. ARCS Lab.

Web Technology for Industrial Engineering 5 September 2002

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

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

Object Oriented Programming Using C++ Mathematics & Computing IET, Katunayake

Getting started with Java

Conditionals, Loops, and Style

Zheng-Liang Lu Java Programming 45 / 79

AP Computer Science. Return values, Math, and double. Copyright 2010 by Pearson Education

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

Transcription:

Why Java? Lecture 2: Intro to Java Java features. Widely available. Widely used. Variety of automatic checks for mistakes in programs. Embraces full set of modern abstractions. 2 Why Java? Why Java? Java features. Widely available. Widely used. Variety of automatic checks for mistakes in programs. Embraces full set of modern abstractions. Java features. Widely available. Widely used. Variety of automatic checks for mistakes in programs. Embraces full set of modern abstractions. Caveat. No perfect language. Caveat. No perfect language. I'm one of the few crazies... who believes it's very possible the Internet has been underhyped instead of overhyped... I predict over the next 90 days Java is going to be like a drug you rub over venture capitalists and they go crazy." -- John Doerr, May 1996 Our approach. Minimal subset of Java. Develop general programming skills that are applicable to C, C++, C#, Python, Matlab, FORTRAN,.... 3 4

A Subset of the Java Language Types System int double System.out.println() long String System.out.print() char System.exit() Primitive Numeric Types Parsing + - * Integer.parseInt() / -- % > ++ < Double.parseDouble() Long.parseLong() <= >= == << >> Boolean & ^!= &&! == Math Library Math.sin() Math.cos() Math.log() Math.exp() Math.sqrt() Math.pow() Math.min() Math.max() Math.abs() Math.PI Punctuation Flow Control { if else ( ) for while, ; do 2.1 Hello Java String Arrays Objects + "" a[i] class static length() compareto() new public private charat() a.length tostring() equals() new main() 5 Programming in Java Programming in Java Programming in Java. 1. 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"); Programming in Java. 1. Create the program by typing it into a text editor, and save it as HelloWorld.java 2. Compile it by typing at the command line: javac HelloWorld.java command prompt % javac HelloWorld.java This creates a Java bytecode file named: HelloWorld.class HelloWorld.java 7 8

Programming in Java Hello, World Programming in Java. 1. Create the program by typing it into a text editor, and save it as HelloWorld.java 2. Compile it by typing at the command line: javac HelloWorld.java 3. Execute it by typing at the command line: java HelloWorld A few remarks. Name of class must match name of file. Comments between /* and */ are ignored by computer. Whitespace and indentation is for human readability. Syntax coloration auto-generated by editor. command prompt % javac HelloWorld.java % java HelloWorld Hello, World /******************************************* * Prints "Hello, World" * Everyone's first program. *******************************************/ public class HelloWorld { System.out.println("Hello, World"); HelloWorld.java 9 10 "Primitive" Data Types 2.2 Primitive Data Types Data type. A set of values. A set of operations on those values. Data Type Description Example Common Operations char String int double boolean character sequence of characters integer floating point number truth value 'A' '@' "Hello, World" "Programming is fun" 17 12345 3.1415 2.17 compare concatenation, compare add, subtract, multiply, multiply, remainder add, subtract, multiply, divide not, and, or 12

String String The String data type. A sequence of characters. Each character internally stored as a sequence of 16 bits: 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 1 '1' in Unicode Not technically a primitive type, but special language support. Ex: generate 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 "; String ruler2 = ruler1 + "2 " + ruler1; String ruler3 = ruler2 + "3 " + ruler2; String ruler4 = ruler3 + "4 " + ruler3; String ruler5 = ruler4 + "5 " + ruler4; System.out.println(ruler5); string concatenation 1 1 2 1 1 2 1 3 1 2 1 13 14 Int The int data type. -2 31 2 31-1 Represents integers between 2147483648 and 2147483647. Internally stored as a sequence of 32 bits: Initializing Variables What happens if I forget to initialize the variable a or b? Java compiler does not allow this. Caveat: in other languages, variable initialized with "random" 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 Useful when expressing algorithms. 14 10 Q. What is the default initialization value for Registrar's room assignment variables? public class IntOps { int a = 1234; int b = 99; int sum = a + b; int prod = a * b; int quot = a / b; int rem = a % b; 1333 122166 12 46 1234 = 12*99 + 46 15 16

Initializing Variables Double What happens if I forget to initialize the variable a or b? Java compiler does not allow this. Caveat: in other languages, variable initialized with "random" bits. Q. What is the default initialization value for Registrar's room assignment variables? A. 61 Nassau Street. The double data type. Represents floating point numbers. Internally stored 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 { double b = Double.parseDouble(args[0]); double c = Double.parseDouble(args[1]); b roots 2 b 4c 2 read coefficients from command line double discriminant = Math.sqrt(b*b - 4.0*c); double root1 = (-b + discriminant) / 2.0; double root2 = (-b - discriminant) / 2.0; calculate roots Nassau Presbyterian Church System.out.println(root1); System.out.println(root2); print them out 17 18 Command Line Arguments Booleans and Comparisons Command line arguments. Simple method for processing a small amount of user input. % java Quadratic 3.0 2.0 2.0 1.0 command line arguments x 2 3x + 2 The boolean data type. Has two values: or. Internally represented as one bit. 0 1 Useful to control logic and flow of a program. Logic Operators Comparison Operators % java Quadratic 1.0 1.0 1.618033988749895 golden ratio -0.6180339887498949 x 2 x -1 a b a && b a b op ==!= Description equal not equal 2 == 2 2!= 3 2 == 3 2!= 3 % java Quadratic 1.0 1.0 NaN not a number NaN x 2 + x + 1 < <= > less less or equal greater 2 < 3 2 <= 3 3 > 2 3 < 2 2 < 2 2 > 3 % java Quadratic 1.0 hello java.lang.numberformatexception: hello Logic Operators a!a >= greater or equal 3 >= 3 2 >= 3 % java Quadratic 1.0 java.lang.arrayindexoutofboundsexception 19 20

Booleans and Comparisons Type Conversion Is year y a leap year? Yes if divisible by 400, or divisible by 4 but not 100. public class LeapYear { int y = Integer.parseInt(args[0]); boolean isleapyear; 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 outputs a double between 0.0 and 1.0. // divisible by 4 but not 100 isleapyear = (y % 4 == 0) && (y % 100!= 0); // or divisible by 400 isleapyear = isleapyear (y % 400 == 0); public class RandomInteger { int N = Integer.parseInt(args[0]); double r = Math.random(); String to int (method) int n = (int) (r * N); System.out.println(isLeapYear); % java LeapYear 2004 % java LeapYear 1900 % java LeapYear 2000 double to int (cast) int to double (automatic) System.out.println("random integer is: " + n); int to String (automatic) 21 22 Summary A data type is a set of values and operations on those values. String: text processing. double, int: mathematical calculator. boolean: basis for decision making. 2.3 Flow Control Be aware. Declare type of values. Convert between types when necessary. 23

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. statement 1 statement 2 statement 3 statement 4 statement 1 boolean 1 boolean 2 statement 2 if (boolean expression) statement1 else statement2 if-else syntax can be a block of statements statement1 boolean expression statement2 statement 3 straight-line flow-of-control flow-of-control with conditionals and loops if-else flow chart 25 26 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 " Read in 3 integers and rearrange ascending order. public class Sort3 { System.out.println(year); if (isleapyear) { System.out.println(" is a "); else { System.out.println(" isn't a "); System.out.println("leap year"); int A = Integer.parseInt(args[0]); int B = Integer.parseInt(args[1]); int C = Integer.parseInt(args[2]); 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; read in 3 integers System.out.println(A + " " + B + " " + C); swap A and B % 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 27 28