Download presentation
Presentation is loading. Please wait.
1
CS 200 Primitives and Expressions
Jim Williams, PhD
2
CS Student Organization Fair
Friday, September 13th 1-4PM CS Building Lobby | 1210 W. Dayton St Open to all students and majors Make connections with CS related organizations A great way to meet new people and get new experiences Questions?
3
This Week Chap 1 Programs - 3 parts: Due Thursday
Piazza: Don't Post Code Unless posted to "Instructors" which makes private. Team Lab tomorrow Feedback: Talk with TAs during office hours Lecture: Programming Process (continued) Primitive Data Types and Expressions
4
Pair Programming 2 people working together on 1 computer.
One person types, the other provides direction and reviews. Many report more confidence in solution and more enjoyment programming. Important to switch roles (who has the keyboard). Provide respectful, honest and friendly feedback.
5
Team Labs First meeting this week. 1350 and 1370 Computer Sciences
1st floor, around corner from elevators Meet Assistants Assigned small groups and pairs Overview of Team Lab Content TA Discussion
6
A Java Program public class Hello {
public static void main(String[] args) { System.out.println("Welcome"); System.out.print(" to "); System.out.print("CS 200!"); } Java is a text language for controlling the computer. Programs are called "code" for a reason. Decode (read) "convert (a coded message) into intelligible language." [Google Dictionary]
7
Tracing Code How does the current line affect:
input? memory? output? What is the next line to be executed?
8
Java Visualizer Demo
9
Edit-Compile-Run Cycle
In Java Visualizer: Typing code in webpage (Editor) Clicking Visualize Execution (Compiler) Clicking Forward (Virtual Machine) Edit Code (Return to Editor)
10
Edit-Compile-Run Cycle
From the command-line: notepad (Editor) javac (Compiler) java (Virtual Machine)
11
Demo Command Prompt/Terminal
Cat.java is created using an Editor such as Notepad. Cat.class is the result of successfully compiling Cat.java with the javac compiler. The command: java Cat executes/runs the Cat.class file in the Java Virtual Machine (JVM)
12
Edit-Compile-Run Cycle
Users Editor (Virtual) Machine Compiler Hello.java Hello.class (byte code) Computer Files Programmer writes code in an Editor. Programmer uses a compiler to check the program syntax and translate to byte code byte code is a form of machine code that can be run on a Java Virtual Machine (JVM or VM) A programmer or user runs/executes the program using the virtual machine the virtual machine runs on the actual computer hardware. Programmer
13
Various Errors Naming/Saving Syntax/Compile time Runtime & Logic Files
Editor (Virtual) Machine Compiler Hello.java Hello.class Computer Files Programmer
14
TopHat What is the command-line command to compile a Java program named Cat.java? Answer: javac Cat.java The virtual machine (on command-line named java) runs/executes Cat.class with the following command: java Cat
15
TopHat After compiling Cat.java what is the name of the file created?
Compiling Cat.java results in Cat.class, which contain bytecodes. Cat.class can then be run/executed by the virtual machine on the command-line with java Cat
16
Programming Process What are inputs, outputs and their relationship?
Solve a small example by hand. Design an algorithm in pseudocode e.g., structured English Convert to Java. Edit-Compile-Run Cycle Tips for Solving Programming Problems
17
Problem Estimate the cost to carpet a floor.
What are inputs, outputs and their relationship? Solve a small example by hand. Design an algorithm in pseudocode (e.g. structured English). Convert to Java.
18
TopHat Order the steps in the Programming Process
19
Expensive Software Bug
On June 4, 1996 an unmanned Ariane 5 rocket exploded just forty seconds after its first lift-off. The destroyed rocket and its cargo were valued at $500 million. It turned out that the cause of the failure was a software error. A 64 bit floating point number was converted to a 16 bit signed integer. The number was larger than 32,767, the largest integer storeable in a 16 bit signed integer, and therefore the conversion was not accurate. double num = ; short num2 = (short)num; System.out.println(Short.MAX_VALUE);
20
Infinite Numbers Numbers are infinitely large, small, and precise.
How can a computer with finite memory do calculations? 2 systems: integer math (exact) floating point math (approximate)
21
Memory Terms 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 bit nibble (4 bits)
byte (8 bits) 2 bytes (16)
22
Possible Permutations
Number of bits 1 2 3 n Possible Permutations 00 01 10 11 Number of Possible Permutations or 21 2*2 or 22 2*2*2 or 23 2n
23
Integer Data Types Examples: -192, 0, 42, 2000000000 byte short int
long Number of Bytes
24
TopHat Order primitive integer data types by size in bytes.
25
Floating Point Data Types
Examples: , 2.0, -5.2, float double Number of Bytes
26
All 8 Primitive Data Types
char single character (2 bytes) boolean true or false value (>= 1 bit) Integer byte, short, int, long Floating Point float, double
27
Literals Data literally typed into a program. 2 2.3 12l 12L 2.4F true
double long float boolean char String
28
Variable Declaration & Assignment
int j; j = 5; int k = 4; j 5 k 4 a variable is a name for an area of memory = is "assignment" operator, Not equals (==) value on right copied into variable on left "initialization" is assigning the first value
29
What are the values in a, b & c?
int a = 2; int b = 1; int c = a + b; b = c; a = b; a: 2 b: 1 c: 3 a: 3 c: 2 try it in Java Visualizer
30
Swap int a = 5; int b = 3; Order the following to swap values in a & b. a = c; c = b; b = a; Google "swapping values without third variable" for many creative ways.
31
Widening Conversion byte short int long float double char
implicit cast Compiler converts automatically In some cases, may lose some precision (e.g., int to float). Example: float f = ; print out the value in f and see if it is the same as the integer assigned to it.
32
Widening Primitive Conversion
implicit cast (compiler does automatically) float f = 23; double d = f; char ch = 'a'; short s = ch; //Both are 2 bytes will this work? char ch = 'a'; short s = ch; //won't compile, even though both are 2 bytes since char values hold from 0 to about and short holds values from about -32,000 to 32,000
33
Narrowing Primitive Conversion
Programmer must explicitly cast. May do truncation and lose significant info. int n = (int)65.2; char c = (char)n; //Similar example to $500 Million Error short s = (short) ; The Ariane software was written in Ada, not Java. More:
34
TopHat Assuming a Java expression, what is the value and data type of this result? double result = 9 / 2 * ( );
35
What should the results be?
double result1 = 4 / 8 * 2.0; double result2 = 2.0 * 4 / 8; double result3 = 2.0 * (4 / 8); Tutorial: Precedence, Associativity & Order of Evaluation
36
Integer vs Floating Point Division
Meaning depends on data type of operands. integer divide floating point divide 1 / vs / 2.0 integer remainder (modulus operator) 5 % 2 Different data type operands are implicitly converted to "wider" by compiler.
37
Operator Precedence & Associativity
38
What are the values of a, b & c?
int a = 1; int b = 2; int c = a = b = 3; Check your answer with Java Visualizer Assignment operators are evaluated right-to-left resulting in c being the last variable assigned the value 3.
39
TH: What are the values of d & e?
int d = 4; int e = d / (d = 2); The value of d is retrieved before doing (d=2). int e = d / (d = 2) 4 / (d = 2) 4 / 2 2
40
TH: What should the result be?
"3" Try it: String result = "3" ; plus (+) is left associative meaning is addition resulting in 3 then 3 + "3" is concatenation since having a string on either side of + means concatenation. then "33" + 4 means concatenation again "334" + 5 "3345"
41
Application: Temperature Conversion
(Degrees Fahrenheit – 32) x 5 / 9 = Degrees Celsius What symbols have different meanings in Java? What changes must be made to implement this equation in Java? //(Degrees Fahrenheit – 32) x 5 / 9 = Degrees Celsius double degreesCelsius; degreesCelsius = (degreesFahrenheit ) * (5.0 / 9); //a complete class with temperature conversion method and testing method public class TemperatureConversion { public static void main(String[] args) { //testFahrenheitToCelsius(); //comment out when tests are all passing //method call; the result is a double value double result = fahrenheitToCelsius( 212.0); //212.0 is the argument } //test method with a set of test cases. Run to test initially or //after changing the method to verify the method is still working //correctly. If a bug is found in the method being tested, then //create a different test case to demostrate the bug. Fix your code //then run all the tests to make sure all work correctly. public static void testFahrenheitToCelsius() { System.out.println( fahrenheitToCelsius( 212.0) + " expect 100.0"); System.out.println( fahrenheitToCelsius( 0.0) + " expect "); System.out.println( fahrenheitToCelsius( 98.6) + " expect 37"); System.out.println( fahrenheitToCelsius( -20) + " expect "); //method definition //for most of this course, methods you create will be public static //return type method name (parameter list) public static double fahrenheitToCelsius(double degreesFahrenheit) { //the parameter degreesFahrenheit (a variable) is initialized to //the argument passed when the method is called. //the equation we are converting to Java return degreesCelsius; //the value return as a result of the method
42
My List X vs * equals (==) vs assignment (=)
value is stored on the left hand side of assignment (=) operator Variables: name areas of computer memory, declare before use, declare type of data, initialize Variable names: start with letter, include letters numbers and _, but no spaces Conventions: camelCasing, spell out names Semicolon at the end of statements
43
Magic Numbers (bad practice)
Numbers with unexplained meaning: public class H { public static void main(String []args) { double s = 71 / ; }
44
Name Variables and Constants
Constants (final variables) can help with readability. public class Height { public static void main(String []args) { final double INCHES_IN_METER = ; double heightInInches = 71; double heightInMeters = heightInInches / INCHES_IN_METER; }
45
Methods A named section of code that can be "called" from other code.
Lots of existing methods that you can use rather than writing yourself.
46
API Application Programmer Interface Example: Search for "Java 8 Math"
Call class/static methods with the class name
47
Calling Class/static Methods
Call class/static methods with the class name. double numInts = Math.pow( 2, 32); double root = Math.sqrt( 16); int num1 = 16; int num2 = 3; double result = num2 + Math.sqrt( num1);
48
API vs Code API:What Code: How
49
TopHat: Method Name Select the method name.
public static int add3(int a) { return a + 3; } The method name is: add3
50
TopHat: Method Parameter
Select the method parameter. public static int add3(int a) { return a + 3; } (int a) is the parameter list, containing the parameter named a of data type int.
51
TopHat: Return Data Type
Select the return data type. public static int add3(int a) { return a + 3; } The "int" before the method name indicates the data type (type of data) being returned from the method.
52
TopHat: Method Definition
Select the add3 method definition. public class Example { public static int add3(int a) { return a + 3; } public static void main(String[] args) { int num = 1; int num2 = Example.add3( num); The add3 method defintion: public static int add3(int a) { return a + 3; } The method call: int num2 = Example.add3( num); Note that the definition of the main method is: public static void main(String[] args) { int num = 1; //Note: Including Example. is optional since in the same class
53
TopHat: Method Call Select the add3 method call.
public class Example { public static int add3(int a) { return a + 3; } public static void main(String[] args) { int num = 1; int num2 = Example.add3( num); The add3 method defintion: public static int add3(int a) { return a + 3; } The method call: int num2 = Example.add3( num); Note that the definition of the main method is: public static void main(String[] args) { int num = 1; //Note: Including Example. is optional since in the same class
54
TopHat: Method Argument
What is the add3 argument? public class Example { public static int add3(int a) { return a + 3; } public static void main(String[] args) { int num = 1; int num2 = Example.add3( num); The argument is the value passed into the method when the method is called. The method call is: Example.add3( num ) The value within num is 1, so the method argument is 1. Example.add3( num);
55
TopHat: Method Value What is the value of the method?
public class Example { public static int add3(int a) { return a + 3; } public static void main(String[] args) { int num = 1; int num2 = Example.add3( num); The value of the method is the value returned when called. In this case 4 will be returned.
56
TopHat: What prints out?
3 5 35 error static void calc(int num) { num = 3; } public static void main(String []args) { int n = 5; calc( n); System.out.println( n); try it. Changing the value in a primitive parameter doesn't change the value outside the method. The calc method doesn't return the new value in num. Also the value in n within main isn't changed. So the value 5 will be printed out.
57
Which is called first: calc or println?
error static int calc(int num) { num -= 33; return num; } public static void main(String []args) { int n = 55; System.out.println( calc( n)); In Java Visualizer put a print statement within the calc method to see if it is called before the println method. In the statement: System.out.println( calc( n)); calc is called first, in order to get the value that is then passed as the argument into the println method. This will result in 22 being printed out.
58
Testing Methods Methods written to run test cases to help validate and debug your code. //(Degrees Fahrenheit – 32) x 5 / 9 = Degrees Celsius double degreesCelsius; degreesCelsius = (degreesFahrenheit ) * (5.0 / 9); //a complete class with temperature conversion method and testing method public class TemperatureConversion { public static void main(String[] args) { //testFahrenheitToCelsius(); //comment out when tests are all passing //method call; the result is a double value double result = fahrenheitToCelsius( 212.0); //212.0 is the argument } //test method with a set of test cases. Run to test initially or //after changing the method to verify the method is still working //correctly. If a bug is found in the method being tested, then //create a different test case to demostrate the bug. Fix your code //then run all the tests to make sure all work correctly. public static void testFahrenheitToCelsius() { System.out.println( fahrenheitToCelsius( 212.0) + " expect 100.0"); System.out.println( fahrenheitToCelsius( 0.0) + " expect "); System.out.println( fahrenheitToCelsius( 98.6) + " expect 37"); System.out.println( fahrenheitToCelsius( -20) + " expect "); //method definition //for most of this course, methods you create will be public static //return type method name (parameter list) public static double fahrenheitToCelsius(double degreesFahrenheit) { //the parameter degreesFahrenheit (a variable) is initialized to //the argument passed when the method is called. //the equation we are converting to Java return degreesCelsius; //the value return as a result of the method
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.