Introduction to Computers, Programs, and Java
CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114
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 Liangs student Web site: http://www.cs.armstrong.edu/liang/intro9e
2
(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
(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
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
What is a Computer?
A computer consists of a CPU, memory, hard disk, monitor, printer, and communication devices.
Bus
Storage Devices e.g., Disk, CD, and Tape
Memory
CPU
Communication Devices e.g., Modem, and NIC
Input Devices e.g., Keyboard, Mouse
Output Devices e.g., Monitor, Printer
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
CPU
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
Bus
Storage Devices e.g., Disk, CD, and Tape
Memory
CPU
Communication Devices e.g., Modem, and NIC
Input Devices e.g., Keyboard, Mouse
Output Devices e.g., Monitor, Printer
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
Memory
stores data and program instructions for CPU to execute ordered sequence of bytes (8 bits binary base unit)
Bus
Storage Devices e.g., Disk, CD, and Tape
Memory
CPU
Communication Devices e.g., Modem, and NIC
Input Devices e.g., Keyboard, Mouse
Output Devices e.g., Monitor, Printer
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
How Data is Stored?
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
. . . 2000 2001 2002 2003 2004 . . . 01001010 01100001 01110110 01100001 00000011 Encoding for character J Encoding for character a Encoding for character v Encoding for character a Encoding for number 3 Memory address Memory content
and processes binary numbers than decimal numbers more efficient: space & cost
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
Number Systems
binary octal decimal hexdecimal 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
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
Number Systems
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.
10
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
Number Systems
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: = 7 10 3 + 4 10 2 + 2 101 + 3 100
7 4 2 3 103 102 101 100
= 7000 + 400 + 20 + 3 = 7423
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.
11
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
Number Systems
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.
12
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
Binary Numbers => Decimals
Given a binary number bnbn 1bn 2...b 2b1b 0 the equivalent decimal value is
bn 2 n + bn 1 2 n1 + bn 2 2 n2 + ... + b 2 2 2 + b1 21 + b 0 2 0
10 in binary 1010 in binary 10101011 in binary
13
1 21 + 0
= 2 in decimal = 10 in decimal = 171 in decimal
1 2 3 + 0 2 2 + 1 2 + 0
1 2 7 + 0 2 6 + 1 25 + 0 2 4 + 1 23 + 0 2 2 + 1 2 + 1
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
Decimals => Binary
To convert a decimal number d to a binary number is to find the binary digits.. bn, bn 1, bn 2,..., b 2, b1, b 0 such that
d = bn 2 n + bn 1 2 n1 + bn 2 2 n2 + ... + b 2 2 2 + b1 21 + b 0 2 0
These numbers can be found by successively dividing d by 2 until the quotient is 0. The remainders are bn, bn 1, bn 2,..., b 2, b1, b 0 For example, the decimal number 123 is 1111011 in binary. The conversion is conducted as follows:
0 2 1 0 1 b6 2 1 3 2 1 b5 2 3 7 6 1 b4 2 7 15 14 1 b3 2 15 30 30 0 b2 2 30 61 60 1 b1 2 61 123 122 1 b0 Remainder Quotient
14
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
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.
15
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
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 hnhn 1hn 2...h 2 h1h 0 The equivalent decimal value is
hn 16 n + hn 1 16 n 1 + hn 2 16 n 2 + ... + h 2 16 2 + h1 161 + h 0 160
7F in hex
7 161 + 15
= 127 in decimal
FFFF in hex 15 163 + 15 162 + 15 16 + 15 = 65535 in decimal
16
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
Decimals => Hexadecimals
To convert a decimal number d to a hexadecimal number is to find the hexadecimal digits hn, hn 1, hn 2,..., h 2, h1, h 0 such that
d = hn 16n + hn 1 16n 1 + hn 2 16n 2 + ... + h 2 162 + h1 161 + h 0 160
These numbers can be found by successively dividing d by 16 until the quotient is 0. The remainders are h 0, h1, h 2,..., hn 2, hn 1, hn For example, the decimal number 123 is 7B in hexadecimal. The conversion is conducted as follows:
17
0 16 7 0 7 h1 16
7 123 112 11 h0
Quotient
Remainder
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
Hexadecimals <=> Binary
Binary Hex Decimal 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111
18
0 1 2 3 4 5 6 7 8 9 A B C D E F
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
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,
1110001101
3
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
Memory: What goes in each memory segment?
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)
19
(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
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
So Hardware stores 0s & 1s
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
21
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
Programming Languages
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
Assembly Source File ADDF3 R1, R2, R3 Machine Code File 1101101010011010
Assembler
23
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
Programming Languages
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
24
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
Popular High-Level Languages
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
25
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
Compiling Source Code
Whats 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
Source File
Compiler
Machine-language File
Linker
Executable File
Library Code
26
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
Operating Systems
The operating system (OS) is a program that manages and controls a computers activities Windows XP, Vista or 7 MacOS Android
User
Application Programs
Operating System
Hardware
27
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
Why Java?
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
28
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
Java, JVM, Web, and Beyond
Java Virtual Machine
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 handheld devices such as Palm and cell phones 29
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
A program that runs Java programs and manages
Examples of Java use: PDA and Cell Phone
30
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
JDK Versions
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
31
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
JDK Editions
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. 32
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
A Simple Java Program Listing 1.1
//This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Java!"); } }
33
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
Creating, Compiling, and Running Programs
Create/Modify Source Code
Source code (developed by the programmer)
Saved on the disk
public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Java!"); } }
Source Code
Byte code (generated by the compiler for JVM to read and interpret, not for you to understand)
Compile Source Code i.e., javac Welcome.java
If compilation errors stored on the disk
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
Bytecode
Run Byteode i.e., java Welcome
Result
34
(c) Pearson Education, Inc. & P.Fodor (CS Stonyruntime errors or incorrect result If Brook)
Running Programs from command line
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!
35
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
Compiling and Running Java from the Command Window
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
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
36
Running Programs in Eclipse
37
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
Supplements on the Companion Website
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
38
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
See Supplement I.B for installing and configuring
Trace a Program Execution
Enter main method
//This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Java!"); } }
39
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
Trace a Program Execution
Execute statement
//This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Java!"); } }
40
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
Trace a Program Execution
//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
41
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
Anatomy of a Java Program
Comments Reserved words Modifiers Statements Blocks Classes Methods The main method
42
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
Comments
Three types of comments in Java.
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.
43
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
Reserved Words
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
44
(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/tutoria l/java/nutsandbolts/_keywords.html
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
45
Modifiers
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
46
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
Statements
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 (;)
47
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
Blocks
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
48
(c) Pearson Education, Inc. & P.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 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 program int myVariable = 5; // Declaration ... // Using the variable myVariable = myVariable + 1;
49
(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
(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
(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 variables type determines:
what kind of value the variable can hold how much memory to reserve for that variable
52
(c) Pearson Education, Inc. & P.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)
53
booleanstores true or false (uses 1-bit or byte)
(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
(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); } (c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
55
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
(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
(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
(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
double x = 5.0; if (x > 0.0) System.out.println("x is " + x);
public void methodWithGoodScope() {
} // 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 }
(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: Whats the output?
int x = 5; x = x + x + x + 10; System.out.print(x);
60
(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: Whats the output?
int x = 5; x = x + x + x + 10; System.out.print(x);
25
61
(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
(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
(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
(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
(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);
66
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
30
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);
My Advice: avoid rules of precedence
Whenever in doubt, go with explicit use of parentheses.
int r2d2c3po = 3 * 4 + 5 / 6; int r2d2c3po2 = (3 * (4 + 5))/ 6;
//12 //4
67
(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);
My Advice: avoid rules of precedence
25
Whenever in doubt, go with explicit use of parentheses.
int r2d2c3po = 3 * 4 + 5 / 6; int r2d2c3po2 = (3 * (4 + 5))/ 6;
//12 //4
68
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
Arithmetic Operators
Division Operator - evaluate full expression first
69
double average = 100.0/8.0; average = 100.0/8; average = 100/8; int sumGrades = 100/8; sumGrades = 100.0/8.0; sumGrades = (int)100.0/8.0; sumGrades = (int)(100.0/8.0); int fifty_percent = 50/100; double fiftyPercent = 50/100; fiftyPercent = 50.0/100.0;
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
//12.5 //12.5 //12.0 //12 //ERROR //ERROR //12 //0 //0.0 //0.5
Arithmetic Operators
The modulo/remainder % operator
Produces division remainders
int remainder = 100 % 8; System.out.println(remainder);
70
(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);
71
(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
72
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);
(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
73
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);
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
6 ? ?
Arithmetic Operators
++ -+= -= *= /= Increment by one Decrement by one Increment by specified amount Decrement by specified amount Multiply by specified amount Divide by specified amount
74
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);
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
6 16 ?
Arithmetic Operators
++ -+= -= *= /= Increment by one Decrement by one Increment by specified amount Decrement by specified amount Multiply by specified amount Divide by specified amount
75
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);
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
6 16 26
Increment and Decrement Operators, cont.
int i = 10; int newNum = 10 * i++;
Same effect as
int newNum = 10 * i; i = i + 1;
int i = 10; int newNum = 10 * (++i);
Same effect as
i = i + 1; int newNum = 10 * i;
76
(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
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
Classes
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 PROGRAMS POINT OF ENTRY // THIS PROGRAMS INSTRUCTIONS // START HERE } }
78
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
Methods
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!");
79
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
main Method
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) {...} }
80
(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
(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
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
Homework: Implement&Test Welcome.java
> 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!
83
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)
import java.util.Scanner; public class ChangeMaker {
Homework: Implement public static void main(String[] args) { ChangeMaker int change, rem, qs, ds, ns, ps; System.out.print("Input change amount (1-99): "); Eclipse
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");
}
84 }
(c) Pearson Education, Inc. & P.Fodor (CS Stony Brook)