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

IntroductionToProgramming PDF

Nov 23, 2015

Download

Documents

Plinio Guzman

Introductory slide to object oriented programming. Java.
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • CSE 114, Computer Science 1Stony Brook University

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

    Introduction to Computers, Programs, and Java

  • (c) Pearson Education, Inc. & Paul 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:

    http://java.com/en/download/index.jsp Eclipse IDE:

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

    Liangs student Web site: http://www.cs.armstrong.edu/liang/intro9e

    2

  • (c) Pearson Education, Inc. & Paul 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 ProgramName3

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

    What is a Computer?

    4

    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

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

    CPU

    5

    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

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

    Memory

    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

    stores data and program instructions for CPU to execute

    ordered sequence of bytes (8 bits binary base unit)

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

    How Data is Stored?

    7

    Whats 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 contentMemory address

    Encoding for character J

    Encoding for character a Encoding for character v

    Encoding for character a Encoding for number 3

  • (c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)8

    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

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

    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

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

    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.

    1037 4 2 3

    102 101 100

    0123 103102104107 +++=

    3204007000 +++= 7423=

    Number Systems

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

    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

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

    Binary Numbers => Decimals

    Given a binary numberthe 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 +++++++

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

    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

    1232

    61

    122 1

    b0

    612

    30

    60 1

    b1

    302

    15

    30 0

    b2

    152

    7

    14 1

    b3

    Remainder

    Quotient

    72

    3

    6 1

    b4

    3 2

    1

    2 1

    b5

    1 2

    0

    0 1

    b6

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

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

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

    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 numberThe equivalent decimal value is

    01221 161616...161616 01221 ++++++ hhhhhh nnn nnn

    7F in hex 15167 1 + = 127 in decimal

    FFFF in hex = 65535 in decimal15161516151615 23 +++

    01221 ... hhhhhh nnn

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

    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

    12316

    7

    112 11

    h0

    7 16

    0

    0 7

    h1

    Remainder

    Quotient

    Decimals => Hexadecimals

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

    0000 0 00001 1 10010 2 20011 3 30100 4 40101 5 50110 6 60111 7 71000 8 8 1001 9 91010 A 101011 B 111100 C 121101 D 131110 E 141111 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

    D83

    Hexadecimals Binary

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

    Memory: What goes in each memory segment?

    18

    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)

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

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

    object/reference variable stores a memory address32 bit numbers (4 bytes)

    These addresses point to memory locations where the objects data is stored

    19

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

    So Hardware stores 0s & 1s

    20

    0101010101010101010101010101 Data is byte addressablewe can access or change any byte (group of 8 bits)

    independently as neededHow do we store text?Numerically (using its code)Each character is stored in memory as a numberStandard character sets: ASCII & UnicodeASCII uses 1 byte per character A is 65

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

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

    Programming Languages

    22

    Machine Language Assembly Language High-Level Language

    A program called assembler is used to convert assembly language programs into machine codeFor 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

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

    Programming Languages

    23

    Machine Language Assembly Language High-Level Language

    assembly: Far easier to use than binaryBUT: 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

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

    Popular High-Level Languages

    24

    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

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

    Compiling Source Code

    25

    Whats a compiler? A software program Input: High Level Language source codeOutput: 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

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

    Operating Systems

    26

    The operating system (OS) is a program that manages and controls a computers activities

    Windows XP, Vista, 7 and 8

    Mac OsXAndroidLinux

    User

    Application Programs

    Operating System

    Hardware

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

    Why Java?

    27

    Java is somewhat differentJava 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 bytecodebytecode is executed by the

    Java Virtual Machine (JVM)

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

    Java, JVM, Web, and Beyond

    28

    Java Virtual MachineA 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

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

    JDK Versions

    29

    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 JDK 1.8 (2014) a. k. a. JDK 8 or Java 8

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

    JDK Editions

    30

    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.

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

    A Simple Java Program

    31

    //This program prints Welcome to Java! public class Welcome {

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

    }}

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

    Creating, Compiling, and Running Programs

    32

    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 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)

  • (c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)33

    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

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

    Compiling and Running Java from the Command Window

    34

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

    Set classpath to include the current directory set classpath=.

    Compile javacWelcome.java

    Run java Welcome

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

    Running Programs in Eclipse

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

    Supplements on the Companion Website

    36

    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/intro10e

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

    Trace a Program Execution

    37

    //This program prints Welcome to Java! public class Welcome {

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

    }}

    Enter main method

  • (c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)38

    //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

  • (c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)39

    //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

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

    Anatomy of a Java Program

    40

    CommentsReserved wordsModifiers Statements BlocksClassesMethodsThe main method

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

    Comments

    41

    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.

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

    Reserved Words

    42

    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

  • (c) Pearson Education, Inc. & Paul 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://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html43

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

    Modifiers

    44

    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, protectedA public datum, method, or class can be accessed by other programsA private datum or method cannot be accessed by other programs

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

    Statements

    45

    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 (;)

  • (c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)46

    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

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

    Variable, class, and method names Whats 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 Oracle/Sun (or someone elses) API

    Your Identifiers (Names) Why name them? they are your data and commands youll need to reference them elsewhere in your programint myVariable = 5; // Declaration... // Using the variablemyVariable = myVariable + 1;

    47

  • (c) Pearson Education, Inc. & Paul 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, my4Var Illegal: 4myVariable, my class, my!Var, @#$myClass

    48

  • (c) Pearson Education, Inc. & Paul 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, compareToarea = PI * radius * radius;49

  • (c) Pearson Education, Inc. & Paul 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 variables type determines:what kind of value the variable can holdhow much memory to reserve for that variable

    50

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

    Javas Primitive Types Integers (whole numbers)

    byte1 byte (-128 to 127) short 2 bytes (-32768 to 32767) int4 bytes (-2147483648 to 2147483647) long8 bytes (-9223372036854775808 to

    9223372036854775807) Real Numbers

    float4 bytes double8 bytes

    char2 bytes stores a single character (Unicode 2)

    booleanstores true or false (uses 1-bit or byte)51

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

    Variables Must be declared before being assigned valuespublic 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);

    }52

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

    Variables Must be initialized before being referencedpublic void methodWithGoodReference(){double salary;salary = 20000.0;double raise = salary * 0.05; // 5% raiseSystem.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);

    }53

  • (c) Pearson Education, Inc. & Paul 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

    54

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

    Variables Should only be declared oncepublic 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 declarationSystem.out.println("Salary is " + salary);

    }55

  • (c) Pearson Education, Inc. & Paul 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;

    56

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

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

    scope that they themselves are declaredpublic 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

    }57

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

    Variables The Assignment Statementvariable = expression;

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

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

    58

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

    Variables The Assignment Statementvariable = expression;

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

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

    59

  • (c) Pearson Education, Inc. & Paul 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

    60

  • (c) Pearson Education, Inc. & Paul 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

  • (c) Pearson Education, Inc. & Paul 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;

    62

  • (c) Pearson Education, Inc. & Paul 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); ?

    63

  • (c) Pearson Education, Inc. & Paul 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

    64

  • (c) Pearson Education, Inc. & Paul 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 precedenceint r2d2c3po = 3 * 4 + 5 / 6; // ?int r2d2c3po2 = (3 * (4 + 5))/ 6; // ?

    65

  • (c) Pearson Education, Inc. & Paul 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 precedenceint r2d2c3po = 3 * 4 + 5 / 6; //12int r2d2c3po2 = (3 * (4 + 5))/ 6; //4

    66

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

    Division Integer division:

    8/3 = 2 Double division:

    8.0/3.0 = 2.666666666666667 8.0/3 = 2.666666666666667 8/3.0 = 2.666666666666667

    67

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

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

    68

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

    Arithmetic Operators The modulo/remainder % operator

    Produces division remainders

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

    69

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

    Arithmetic Operators The modulo/remainder % operator

    Produces division remainders

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

    70

  • (c) Pearson Education, Inc. & Paul 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 amountint x = 5, y = 15, z = 25;x = x + 1;y++;

    z += 1;System.out.println(x); ?System.out.println(y); ?System.out.println(z); ?71

  • (c) Pearson Education, Inc. & Paul 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 amountint x = 5, y = 15, z = 25;x = x + 1;y++;

    z += 1;System.out.println(x); 6System.out.println(y); ?System.out.println(z); ?72

  • (c) Pearson Education, Inc. & Paul 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 amountint x = 5, y = 15, z = 25;x = x + 1;y++;

    z += 1;System.out.println(x); 6System.out.println(y); 16System.out.println(z); ?73

  • (c) Pearson Education, Inc. & Paul 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 amountint x = 5, y = 15, z = 25;x = x + 1;y++;

    z += 1;System.out.println(x); 6System.out.println(y); 16System.out.println(z); 2674

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

    Increment andDecrement Operators, cont.

    75

    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

  • (c) Pearson Education, Inc. & Paul 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

    Examples1.23456e+2 = 1.23456e2 = 123.4561.23456e-2 = 0.0123456

    76

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

    Classes

    77

    A class is a template or blueprint for objectsA program is defined by using one or more classespublic class ClassName {

    public static void main(String[] args) {// ClassName PROGRAMS POINT OF ENTRY// THIS PROGRAMS INSTRUCTIONS// START HERE

    }}

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

    Methods

    78

    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!");

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

    main Method

    79

    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) {

    ...

    }}

  • (c) Pearson Education, Inc. & Paul 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!"

    }}

    80

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

    Homework 1

    Homework 1 won't be not gradedLearn submission of homework

    through Blackboard as an assignment

    81

  • (c) Pearson Education, Inc. & Paul 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

    82

  • (c) Pearson Education, Inc. & Paul 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

    83