cse 114 stony brook lecture 1

84
CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 Introduction to Computers, Programs, and Java

Upload: mondaynite28

Post on 16-Apr-2015

49 views

Category:

Documents


1 download

DESCRIPTION

CSE 114 Stony Brook lecture 1java intro

TRANSCRIPT

Page 1: CSE 114 Stony Brook lecture 1

CSE 114, Computer Science 1 Stony Brook University

http://www.cs.stonybrook.edu/~cse114

Introduction to Computers, Programs, and Java

Page 2: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

What do you need to get started? Blackboard account

http://blackboard.stonybrook.edu

SINC Sites: http://www.sinc.sunysb.edu/helpdesk/labs.shtml

Java 2 v. 1.7 (a.k.a. Java 7) http://java.sun.com/javase/downloads API: http://java.sun.com/javase/7/docs/api The Java Tutorial: http://java.sun.com/docs/books/tutorial

Eclipse IDE: http://www.eclipse.org/downloads Learn to use the debugger

Liang’s student Web site: http://www.cs.armstrong.edu/liang/intro9e

2

Page 3: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Tools for Writing Java Programs Integrated Development Environment (IDE) combines writing, compiling, running and debugging Java code

into a single application Eclipse, NetBeans, etc. makes coding efficient and organized

Alternative approach: the bare minimum editor edit Java source code in a text editor (ex: Notepad or Pico) compile source code into .class files from command line: javac can be tedious poor interactivity

3

Page 4: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

How does it work? Java Source Code you write this ProgramName.java files

Compiler Program Build - included in the Eclipse IDE OR Command: javac ProgramName.java results Java Executable Code ProgramName.class files - not humanly readable

Java Virtual Machine – runs Java programs Run - included in the Eclipse IDE OR command: java ProgramName 4

Page 5: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

What is a Computer?

5

A computer consists of a CPU, memory, hard disk, monitor, printer, and communication devices.

CPU

e.g., Disk, CD, and Tape

Input Devices

e.g., Keyboard, Mouse

e.g., Monitor, Printer

Communication Devices

e.g., Modem, and NIC

Storage Devices

Memory

Output Devices

Bus

Page 6: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

CPU

6

CPU

e.g., Disk, CD, and Tape

Input Devices

e.g., Keyboard, Mouse

e.g., Monitor, Printer

Communication Devices

e.g., Modem, and NIC

Storage Devices

Memory

Output Devices

Bus

• central processing unit (CPU)

•retrieves instructions from memory and executes them

•the CPU speed is measured in megahertz (MHz)

• 1 megahertz = 1 million pulses per second

Page 7: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Memory

7

CPU

e.g., Disk, CD, and Tape

Input Devices

e.g., Keyboard, Mouse

e.g., Monitor, Printer

Communication Devices

e.g., Modem, and NIC

Storage Devices

Memory

Output Devices

Bus

•stores data and program instructions for CPU to execute

•ordered sequence of bytes (8 bits – binary base unit)

Page 8: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

How Data is Stored?

8

What’s binary? a base-2 number system

What do humans use? base-10 Why?

Why do computers like binary? electronics easier to make hardware that stores

and processes binary numbers than decimal numbers

more efficient: space & cost

.

.

. 2000 2001 2002 2003 2004

.

.

. 01001010 01100001 01110110 01100001 00000011

Memory content

Memory address

Encoding for character ‘J’ Encoding for character ‘a’ Encoding for character ‘v’ Encoding for character ‘a’ Encoding for number 3

Page 9: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook) 9

Number Systems

0, 1 0, 1, 2, 3, 4, 5, 6, 7 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F

binary octal

decimal

hexdecimal

Page 10: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook) 10

• Computers use binary numbers internally because storage devices like memory and disk are made to store 0s and 1s.

• A number or a text inside a computer is stored as a sequence of 0s and 1s. • Each 0 and 1 is called a bit (short for binary digit)

• Binary numbers are not intuitive, since we use decimal numbers in our daily life.

• When you write a number like 20 in a program, it is assumed to be a decimal number.

• Internally, computer software is used to convert decimal numbers into binary numbers, and vice versa.

Number Systems

Page 11: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook) 11

• The digits in the decimal number system are 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. • A decimal number is represented using a sequence of one or more of these digits. • The value that each digit in the sequence represents depends on its position. • A position in a sequence has a value that is an integral power of 10. • e.g., the digits 7, 4, 2, and 3 in decimal number 7423 represent 7000, 400, 20, and 3, respectively:

• We say that 10 is the base or radix of the decimal number system. • The base of the binary number system is 2 since the binary number system has two digits • The base of the hex number system is 16 since the hex number system has sixteen digits.

103

7 4 2 3

102 101 100

0123 103102104107 ×+×+×+×=

3204007000 +++= 7423=

Number Systems

Page 12: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook) 12

• Binary numbers tend to be very long and cumbersome: • For example: 101010101010

• Hexadecimal numbers are often used to abbreviate binary numbers: • For example: AAA

• The hexadecimal number system has 16 digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, and F.

• The letters A, B, C, D, E, and F correspond to the decimal numbers 10, 11, 12, 13, 14, and 15.

Number Systems

Page 13: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook) 13

Binary Numbers => Decimals

Given a binary number the equivalent decimal value is

10 in binary = 2 in decimal

1010 in binary = 10 in decimal

01221 ... bbbbbb nnn −−

01221 222...222 01221 ×+×+×++×+×+× −−−− bbbbbb nnn

nnn

021 1 +×

0212021 23 +×+×+×

10101011 in binary

= 171 in decimal

121202120212021 234567 +×+×+×+×+×+×+×

Page 14: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook) 14

Decimals => Binary • To convert a decimal number d to a binary number is to find the binary digits.. such that

• These numbers can be found by successively dividing d by 2 until the quotient is 0. The remainders are For example, the decimal number 123 is 1111011 in binary. The conversion is conducted as follows:

01221 ,,,...,,, bbbbbb nnn −−

01221 222...222 01221 ×+×+×++×+×+×= −−−− bbbbbbd nnn

nnn

01221 ,,,...,,, bbbbbb nnn −−

123 2

61

122 1

b0

61 2

30

60 1

b1

30 2

15

30 0

b2

15 2

7

14 1

b3

Remainder

Quotient

7 2

3

6 1

b4

3 2

1

2 1

b5

1 2

0

0 1

b6

Page 15: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook) 15

Windows Calculator The Windows Calculator is a useful tool for performing number conversions. To run it, choose Programs, Accessories, and Calculator from the Start button.

Page 16: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook) 16

Hexadecimals => Decimals

• The hexadecimal number system has sixteen digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, and F. • The letters A, B, C, D, E, and F correspond to the decimal numbers 10, 11, 12, 13, 14, and 15. • Given a hexadecimal number The equivalent decimal value is

01221 161616...161616 01221 ×+×+×++×+×+× −−−− hhhhhh nnn

nnn

7F in hex 15167 1 +× = 127 in decimal

FFFF in hex = 65535 in decimal 15161516151615 23 +×+×+×

01221 ... hhhhhh nnn −−

Page 17: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook) 17

To convert a decimal number d to a hexadecimal number is to find the hexadecimal digits such that

01221 161616...161616 01221 ×+×+×++×+×+×= −−−− hhhhhhd nnn

nnn

These numbers can be found by successively dividing d by 16 until the quotient is 0. The remainders are For example, the decimal number 123 is 7B in hexadecimal. The conversion is conducted as follows:

01221 ,,,...,,, hhhhhh nnn −−

nnn hhhhhh ,,,...,,, 12210 −−

123 16

7

112 11

h0

7 16

0

0 7

h1

Remainder

Quotient

Decimals => Hexadecimals

Page 18: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook) 18

0000 0 0 0001 1 1 0010 2 2 0011 3 3 0100 4 4 0101 5 5 0110 6 6 0111 7 7 1000 8 8 1001 9 9 1010 A 10 1011 B 11 1100 C 12 1101 D 13 1110 E 14 1111 F 15

Binary Hex Decimal To convert a hexadecimal number to a binary number, simply convert each digit in the hexadecimal number into a four-digit binary number.

To convert a binary number to a hexadecimal, convert every four binary digits from right to left in the binary number into a hexadecimal number. For example,

1 1 1 0 0 0 1 1 0 1

D 8 3

Hexadecimals <=> Binary

Page 19: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Memory: What goes in each memory segment?

19

Stack Segment temporary variables declared inside methods removed from memory when a method returns

Heap Segment for dynamic data (whenever you use new) data for constructed objects persistent as long as an existing object variable

references this region of memory

Global Segment data that can be reserved at compile time global data (like static data)

Page 20: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

How objects are stored? You must understand that in Java, every object variable stores

a memory addresses 32 bit numbers (4 bytes)

These addresses point to memory locations where the

objects’ data is stored

20

Page 21: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

So Hardware stores 0s & 1s

21

0101010101010101010101010101 … Data is byte addressable we can access or change any byte (group of 8 bits) independently as

needed

How do we store text? Numerically (using its code) Each character is stored in memory as a number Standard character sets: ASCII & Unicode ASCII uses 1 byte per character

‘A’ is 65

Page 22: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Page 23: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Programming Languages

23

Machine Language Assembly Language High-Level Language

A program called assembler is used to convert assembly language programs into machine code For example, to add two numbers, you might write an instruction in assembly code like this: ADDF3 R1, R2, R3

… ADDF3 R1, R2, R3 …

Assembly Source File

Assembler

… 1101101010011010 …

Machine Code File

Page 24: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Programming Languages

24

Machine Language Assembly Language High-Level Language

assembly: Far easier to use than binary BUT: not very user friendly, very low-level operations, programming is time consuming High Level programming Languages (HLL): – more user friendly, easy to use – more flexible – platform independent

Page 25: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Popular High-Level Languages

25

COBOL (COmmon Business Oriented Language)

FORTRAN (FORmula TRANslation)

BASIC (Beginner All-purpose Symbolic Instructional Code)

Pascal (named for Blaise Pascal)

Ada (named for Ada Lovelace)

C (whose developer designed B first) Visual Basic (Basic-like visual language developed by Microsoft)

Delphi (Pascal-like visual language developed by Borland)

C++ (an object-oriented language, based on C)

C# (a Java-like language developed by Microsoft)

Java

Page 26: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Compiling Source Code

26

What’s a compiler? A software program Input: High Level Language source code Output: Assembly Code

It is typically integrated with an assembly together they can make an executable or binary program

Compiler Source File Machine-language File Linker Executable File

Library Code

Page 27: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Operating Systems

27

The operating system (OS) is a program that manages and controls a computer’s activities Windows XP, Vista or 7 MacOS Android

User

Application Programs

Operating System

Hardware

Page 28: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Why Java?

28

Java is somewhat different Java has a principle, “write once, run anywhere”

What does that mean? Platform independence for compiled Java code

How? The Java Virtual Machine

Java programs are compiled into Java bytecode bytecode is executed by the Java Virtual Machine

Page 29: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Java, JVM, Web, and Beyond

29

Java Virtual Machine A program that runs Java programs and manages

memory for Java programs Why? Each platform is different (Mac/PC/Linux/etc.)

Java can be used to develop Web applications. Java Applets Java Web Applications Java can also be used to develop applications for hand-

held devices such as Palm and cell phones

Page 30: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Examples of Java use: PDA and Cell Phone

30

Page 31: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

JDK Versions

31

JDK 1.02 (1995) JDK 1.1 (1996) JDK 1.2 (1998) JDK 1.3 (2000) JDK 1.4 (2002) JDK 1.5 (2004) a. k. a. JDK 5 or Java 5 JDK 1.6 (2006) a. k. a. JDK 6 or Java 6 JDK 1.7 (2011) a. k. a. JDK 7 or Java 7

Page 32: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

JDK Editions

32

Java Standard Edition (J2SE) J2SE can be used to develop client-side standalone

applications or applets.

Java Enterprise Edition (J2EE) J2EE can be used to develop server-side

applications such as Java servlets and Java ServerPages.

Java Micro Edition (J2ME). J2ME can be used to develop applications for mobile

devices such as cell phones.

Our textbook uses J2SE to introduce Java programming.

Page 33: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

A Simple Java Program

33

//This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Java!"); } }

Listing 1.1

Page 34: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Creating, Compiling, and Running Programs

34

Source Code

Create/Modify Source Code

Compile Source Code i.e., javac Welcome.java

Bytecode

Run Byteode i.e., java Welcome

Result

If compilation errors

If runtime errors or incorrect result

public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Java!"); } }

… Method Welcome() 0 aload_0 … Method void main(java.lang.String[]) 0 getstatic #2 … 3 ldc #3 <String "Welcome to Java!"> 5 invokevirtual #4 … 8 return

Saved on the disk

stored on the disk

Source code (developed by the programmer)

Byte code (generated by the compiler for JVM to read and interpret, not for you to understand)

Page 35: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook) 35

pfodor@sparky ~$ pico Welcome.java //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Java!"); } } pfodor@sparky ~$ javac Welcome.java pfodor@sparky ~$ java Welcome Welcome to Java!

Running Programs from command line

Page 36: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Compiling and Running Java from the Command Window

36

Set path to JDK bin directory set path=c:\Program Files\java\jdk1.6.0\bin check Java path

Set classpath to include the current directory set classpath=.

Compile javac Welcome.java

Run java Welcome

Page 37: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook) 37

Running Programs in Eclipse

Page 38: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Supplements on the Companion Website

38

See Supplement I.B for installing and configuring JDK

See Supplement I.C for compiling and running Java from the command window for details

See Supplement II.D for installing and using Eclipse IDE

http://www.cs.armstrong.edu/liang/intro9e

Page 39: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Trace a Program Execution

39

//This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Java!"); } }

Enter main method

Page 40: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook) 40

//This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Java!"); } }

Execute statement

Trace a Program Execution

Page 41: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook) 41

//This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Java!"); } }

print a message to the console

Trace a Program Execution

Page 42: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Anatomy of a Java Program

42

Comments Reserved words Modifiers Statements Blocks Classes Methods The main method

Page 43: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Comments

43

Line comment: A line comment is preceded by two slashes (//) in a line. Paragraph comment: A paragraph comment is enclosed between /* and */ in one or multiple lines.

javadoc comment: javadoc comments begin with /** and end with */. They are used for documenting classes, data, and methods. They can be extracted into an HTML file using JDK's javadoc command.

Three types of comments in Java.

Page 44: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Reserved Words

44

Reserved words or keywords are words that have a specific meaning to the compiler Cannot be used for other purposes in the program Example: class the word after class is the name for the class

Page 45: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Java Vocabulary Words (Keywords) abstract,assert,boolean,break,byte, case,catch,char,class,const,continue,default,do,double,else,enum,extends,false,final,finally,float,for,goto,if,implements,import,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

http://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html 45

Page 46: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Modifiers

46

Java uses certain reserved words called modifiers that specify the properties of the data, methods, and classes and how they can be used Examples: public, static, private, final, abstract, protected A public datum, method, or class can be accessed by other programs A private datum or method cannot be accessed by other programs

Page 47: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Statements

47

A statement represents an action or a sequence of actions

System.out.println("Welcome to Java!"); is a statement to display the greeting "Welcome to Java!"

Every statement in Java ends with a semicolon (;)

Page 48: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook) 48

A pair of braces in a program forms a block that groups components of a program.

public class Test { public static void main(String[] args) { System.out.println("Welcome to Java!"); } }

Class block

Method block

Blocks

Page 49: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Variable, class, and method names What’s an API? Application Programming Interface a library of code to use

Names (variables, classes, and methods) From 2 sources:

your own classes, variables, and methods the Sun (or someone else’s) API

Your Identifiers (Names) – Why name them? they are your data and commands you’ll need to reference them elsewhere in your program int myVariable = 5; // Declaration ... // Using the variable myVariable = myVariable + 1;

49

Page 50: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Rules for Identifiers Should contain only letters, numbers, & ‘_’ Cannot begin with a digit Uppercase and lowercase letters are considered to be

different characters $ is allowed, but only for special use. Examples: Legal: myVariable, my_class, my4Variable Illegal: 4myVariable, my class, my!Variable, @#$myClass

50

Page 51: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Common Java Naming Conventions Variables & Methods start with lower case letters: x, toString

Classes start with upper case letters: Person Variables and Class identifiers should generally be nouns Method identifiers should be verbs

Use Camel notation: myVariable, MyClass Although it is legal, do not begin with ‘_’ (underscore).

Use descriptive names: LinkedList, compareTo area = PI * radius * radius;

51

Page 52: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Variables In a program, they store data

Primitives store single pieces of data (ex: char) char letter = 'A';

Objects store multiple pieces of data (ex: String) String text = "ABCDEFG"; All Java variables must have a declared type A variable’s type determines: what kind of value the variable can hold how much memory to reserve for that variable

52

Page 53: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Java’s Primitive Types Integers (whole numbers) byte–1 byte (-128 to 127)

short –2 bytes (-32768 to 32767)

int–4 bytes (-2147483648 to 2147483647)

long–8 bytes (-9223372036854775808 to 9223372036854775807)

Real Numbers float–4 bytes

double–8 bytes

char–2 bytes stores a single character (Unicode 2)

boolean–stores true or false (uses 1-bit or byte) 53

Page 54: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Variables Must be declared before being assigned values public void methodWithGoodDeclaration()

{

double salary;

salary = 20000.0;

System.out.println("Salary is " + salary);

}

public void methodWithBadDeclaration()

{

salary = 20000.0;

double salary;

System.out.println("Salary is " + salary);

} 54

Page 55: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Variables Must be initialized before being referenced public void methodWithGoodReference()

{

double salary;

salary = 20000.0;

double raise = salary * 0.05; // 5% raise

System.out.println("Raise is " + raise);

}

public void methodWithBadReference()

{

double salary; // Salary has no value.

double raise = salary * 0.05;

System.out.println("Raise is " + raise);

} 55

Page 56: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Variables A variable gets a value in an assignment statement (discussed

later).

Variable = some_value or

an expression Undefined Variables Compiler error If a variable does not occur on the left in an assignment

statement before its use in an expression, then it is probably undefined

56

Page 57: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Variables Should only be declared once public void methodWithGoodDeclaration()

{

double salary = 20000.0;

System.out.println("Salary is " + salary);

salary = 60000.0;

System.out.println("Salary is " + salary);

}

public void methodWithBadDeclaration()

{

double salary = 50000.0;

System.out.println("Salary is " + salary);

double salary = 60000.0; // Second declaration

System.out.println("Salary is " + salary);

} 57

Page 58: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Variables Variables can be declared and initialized at once

char yesChar = 'y'; String word = "Hello!"; double avg = 0.0, stdDev = 0.0; char initial3 = 'T'; boolean completed = false;

58

Page 59: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Variables Variables can only be used inside the block { …} or

scope that they themselves are declared public void methodWithGoodScope()

{

double x = 5.0;

if (x > 0.0)

System.out.println("x is " + x);

} // x is in scope here.

public void methodWithBadScope()

{

double y = 100.0;

if (y > 0.0)

{

double x = 5.0;

}

System.out.println("x " + x); // x is not in scope

} 59

Page 60: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Variables The Assignment Statement variable = expression;

What does it do? Solves/evaluates expression first Assigns resulting value to the variable

Exercise: What’s the output? int x = 5; x = x + x + x + 10; System.out.print(x); ?

60

Page 61: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Variables The Assignment Statement variable = expression;

What does it do? Solves/evaluates expression first Assigns resulting value to the variable

Exercise: What’s the output? int x = 5; x = x + x + x + 10; System.out.print(x); 25

61

Page 62: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Variables Assignment Compatibility: The variable and expression should be the same type if not, you may get a compiler error.

Examples: int sumGrades, gradeX, gradeY; gradeX = 1; sumGrades = 1473; sumGrades = 1472 + 1; sumGrades = 1472 + gradeX; sumGrades = true; // ILLEGAL

62

Page 63: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Variables What about mixing numeric types?

Are these assignment statements ok?

int x = 5;

long y = x;

double z = y; What about these?

double a = 6.5;

long b = a;

int c = b;

byte <short <int <long <float <double

No assigning big types to little types OR real types to integer types

63

Page 64: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Variables Type Casting as a type override temporarily change a data type to another type (type_name), example: (int) no type casting to/from boolean Examples: double myReal = 10.0; int badInt = myReal; int goodInt = (int)myReal;

64

Page 65: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Arithmetic Operators + Addition - Subtraction * Multiplication / Division % Modulo/Remainder (integer operands only) int x = 5; int y = 10; int z = 2; int num1 = (x + y) * z; System.out.println(num1); ?

65

Page 66: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Arithmetic Operators + Addition - Subtraction * Multiplication / Division % Modulo/Remainder (integer operands only) int x = 5; int y = 10; int z = 2; int num1 = (x + y) * z; System.out.println(num1); 30

66

Page 67: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Arithmetic Operators Multiplication (*) has higher precedence over addition (+). int x = 5; int y = 10; int z = 2; int num1 = x + y * z; System.out.println(num1); ?

Whenever in doubt, go with explicit use of parentheses. My Advice: avoid rules of precedence int r2d2c3po = 3 * 4 + 5 / 6; //12 int r2d2c3po2 = (3 * (4 + 5))/ 6; //4

67

Page 68: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Arithmetic Operators Multiplication (*) has higher precedence over addition (+). int x = 5; int y = 10; int z = 2; int num1 = x + y * z; System.out.println(num1); 25

Whenever in doubt, go with explicit use of parentheses. My Advice: avoid rules of precedence int r2d2c3po = 3 * 4 + 5 / 6; //12 int r2d2c3po2 = (3 * (4 + 5))/ 6; //4

68

Page 69: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Arithmetic Operators Division Operator - evaluate full expression first double average = 100.0/8.0; //12.5 average = 100.0/8; //12.5 average = 100/8; //12.0 int sumGrades = 100/8; //12 sumGrades = 100.0/8.0; //ERROR sumGrades = (int)100.0/8.0; //ERROR sumGrades = (int)(100.0/8.0); //12 int fifty_percent = 50/100; //0 double fiftyPercent = 50/100; //0.0 fiftyPercent = 50.0/100.0; //0.5

69

Page 70: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Arithmetic Operators The modulo/remainder % operator Produces division remainders

int remainder = 100 % 8; System.out.println(remainder); ?

70

Page 71: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Arithmetic Operators The modulo/remainder % operator Produces division remainders

int remainder = 100 % 8; System.out.println(remainder); 4

71

Page 72: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Arithmetic Operators ++ Increment by one -- Decrement by one += Increment by specified amount -= Decrement by specified amount *= Multiply by specified amount /= Divide by specified amount int x = 5, y = 15, z = 25;

x = x + 1;

y++;

z += 1;

System.out.println(x); ?

System.out.println(y); ?

System.out.println(z); ? 72

Page 73: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Arithmetic Operators ++ Increment by one -- Decrement by one += Increment by specified amount -= Decrement by specified amount *= Multiply by specified amount /= Divide by specified amount int x = 5, y = 15, z = 25;

x = x + 1;

y++;

z += 1;

System.out.println(x); 6

System.out.println(y); ?

System.out.println(z); ? 73

Page 74: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Arithmetic Operators ++ Increment by one -- Decrement by one += Increment by specified amount -= Decrement by specified amount *= Multiply by specified amount /= Divide by specified amount int x = 5, y = 15, z = 25;

x = x + 1;

y++;

z += 1;

System.out.println(x); 6

System.out.println(y); 16

System.out.println(z); ? 74

Page 75: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Arithmetic Operators ++ Increment by one -- Decrement by one += Increment by specified amount -= Decrement by specified amount *= Multiply by specified amount /= Divide by specified amount int x = 5, y = 15, z = 25;

x = x + 1;

y++;

z += 1;

System.out.println(x); 6

System.out.println(y); 16

System.out.println(z); 26 75

Page 76: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Increment and Decrement Operators, cont.

76

int i = 10; int newNum = 10 * i++;

int newNum = 10 * i; i = i + 1;

Same effect as

int i = 10; int newNum = 10 * (++i);

i = i + 1; int newNum = 10 * i;

Same effect as

Page 77: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Scientific Notation Floating-point literals can also be specified in scientific

notation: E (or e) represents an exponent and it can be either in

lowercase or uppercase

Examples 1.23456e+2 = 1.23456e2 = 123.456 1.23456e-2 = 0.0123456

77

Page 78: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Classes

78

A class is a template or blueprint for objects A program is defined by using one or more classes public class ClassName

{

public static void main(String[] args)

{

// ClassName PROGRAM’S POINT OF ENTRY

// THIS PROGRAM’S INSTRUCTIONS

// START HERE

}

}

Page 79: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Methods

79

A method is a collection of statements that performs a sequence of operations It is used by invoking a statement with arguments System.out.println("Welcome to Java!");

Page 80: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

main Method

80

The main method provides the control of program flow.

ClassName is executable because it has a main method we can compile and then run it

Not all classes require main methods only those classes that initiate program execution require a main method

public class ClassName { public static void main(String[] args) {...} }

Page 81: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Our first program: HelloWorldApp.java /**

* HelloWorldApp is a Java application

* that simply displays "Hello World!“ in the

* Java console.

*/

public class HelloWorldApp

{

public static void main(String[] args)

{

System.out.println("Hello World!");

// Statement above displays "Hello World!"

}

}

81

Page 82: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

Homework 1

Homework 1 won't be not graded Learn submission of homework

through Blackboard as an assignment

82

Page 83: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

> notepad Welcome.java //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Java!"); } } > javac Welcome.java > java Welcome Welcome to Java!

Homework: Implement&TestWelcome.java

83

Page 84: CSE 114 Stony Brook lecture 1

(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)

import java.util.Scanner;

public class ChangeMaker

{

public static void main(String[] args)

{

int change, rem, qs, ds, ns, ps;

System.out.print("Input change amount (1-99): ");

Scanner input = new Scanner(System.in);

change = input.nextInt();

qs = change / 25;

rem = change % 25;

ds = rem / 10;

rem = rem % 10;

ns = rem / 5;

rem = rem % 5;

ps = rem;

System.out.print(qs + " quarters," + ds + " dimes,");

System.out.println(ns + " nickels and" + ps + " pennies");

}

}

Homework: Implement ChangeMaker Eclipse

84