Download presentation
Presentation is loading. Please wait.
Published byLiana Darmali Modified over 5 years ago
1
CS 200 More Primitives, Objects, Branches and Methods
Jim Williams, PhD
2
This Week pre-Exam1: Results - emailed In-class review
Exam 1: Alternatives - soon Programs: P4 due Thursday Lab: Branches, Eclipse & Styling Lecture: More Primitives, Objects, Branches & Methods
3
Are these equivalent? boolean tired = true; boolean tired = true;
Same result in all cases Different result sometimes Error boolean tired = true; if ( tired) { //take break tired = false; } if ( !tired) { //keep working boolean tired = true; if ( tired) { //take break tired = false; } else { //keep working }
4
Floating Down a River
5
Side Trip, maybe multiple side trips
boolean tired = true; if ( tired) { System.out.println(“take break”); }
6
One side of the Island or the other
boolean sunny = false; if ( sunny) { System.out.print(“sunny”); } else { System.out.print(“not sunny”); } System.out.println( “ and back together”);
7
Equivalent? Yes No char chr = //any valid char out = 'W';
if ( chr == 'A') { out = 'X'; } else if ( chr == 'B') { out = 'Y'; } else { out = 'Z'; } char chr = //any valid char out = 'W'; if ( chr == 'A') { out = 'X'; } if ( chr == 'B') { out = 'Y'; } if ( chr != 'A' || chr != 'B') { out = 'Z'; } Yes No
8
Switch: What is printed out?
char choice = 'a'; switch (choice) { case 'a': System.out.print("a"); case 'b': System.out.print("b"); break; default: System.out.print("other"); } a b ab other
9
What is the value of msg? boolean flag = false;
String msg = "before if"; if ( flag); { msg = "" + flag; } before if true false
10
Comparing: == vs equals()
Primitive data types use == for comparing primitive values No equals() method for primitive data types Reference data types use == and !=for comparing references use equals() for comparing instance/object contents The meaning of equals() depends on the class it is defined in.
11
What is printed out? true *compiler error false int i = 6; int j = 6;
System.out.println( i == j); System.out.println( i.equals( j)); Integer k = new Integer( 7); Integer m = new Integer( 7); System.out.println( k == m); System.out.println( k.equals( m)); true *compiler error false
12
Values of a1 and a2? char ch1 = 'H'; String str = "Hello";
a1: true a2: true a1: false a2: false char ch1 = 'H'; String str = "Hello"; char ch2 = str.charAt(0); boolean a1 = ch1 == ch2; boolean a2 = ch1.equals(ch2);
13
String: == vs equals() String str1 = "hello"; String str2 = "hello";
String str3 = new String("hello"); String str4 = "hello"; System.out.println( str1 == "hello" ); System.out.println( str1 == str2); System.out.println( str1.equals("hello")); System.out.println( str3 == str1); System.out.println( str3.equals( str2));
14
Scanner Scanner input = new Scanner("1 \ntwo \n 2\n\n");
int a = input.nextInt(); if ( input.hasNextInt()) { int b = input.nextInt(); } else { input.nextLine(); } String line = input.nextLine(); System.out.println("#" + line + "#");
15
Primitive Data Types byte short int long float double char
boolean 1 bit or more Bytes in Memory
16
Widening Primitive Conversion
Narrower to Wider Keeps magnitude may lose some precision byte -> short -> int -> long -> float -> double float f = 23; //implicit conversion double d = f; //implicit conversion int n = (int)43.2; //must explicitly cast
17
Widening Primitive Conversion
char -> int … Recall char is 2 bytes, non-negative: integers are negative to positive int num = 'C'; //implicit conversion char ch = (char)70; //must be explicitly cast
18
What will print? 65 static void mPrint( char ch) { A
compiler error other error static void mPrint( char ch) { System.out.print( ch); } public static void main(String []args) { mPrint( (char)65);
19
Integer Overflow int bigNum = Integer.MIN_VALUE; bigNum -= 1;
negative non-negative error int bigNum = Integer.MIN_VALUE; bigNum -= 1; String str; str = bigNum < 0 ? "negative" : "non-negative"; System.out.println( str); try it
20
Comparing Floats equal double num1 = 10.3; double num2 = 2.2;
not equal error double num1 = 10.3; double num2 = 2.2; double num3 = num1 - num2; if ( num3 == 8.1) { System.out.println( "equal"); } else { System.out.println( "not equal"); } try it
21
Comparing Floating Point values
double num1 = 10.3; double num2 = 2.2; double num3 = num1 - num2; double epsilon = 0.001; if ( Math.abs( num ) < epsilon ) { System.out.println( "equal"); } else { System.out.println( "not equal"); }
22
Short-Circuit && If the left side is false it doesn't matter what the right side is, so the right-side isn't evaluated. || If the left side is true it doesn't matter what the right side is, so the right-side isn't evaluated.
23
Short Circuit evaluation
boolean flag = true; if ( flag || (flag = false)) { System.out.print( "if: " + flag); } else { System.out.print( "else: " + flag); } if: true if: false else: true else: false try it
24
Notes Exam Alternatives have been Emailed
to those that filled out the form Exam Locations Review Questions Lecture: More on Previous 4 Chapters
25
Compound and unary operators
int i = 5; i += 2; // i = i + 2; if ((i += -3) < 2) { i = 3; }; i %= 2; System.out.print( i); 1 2 3 try it
26
What is the resulting value of nums?
String nums = "3"; nums += 4 + 5; //not equivalent due to operator precedence nums = nums ; 3 345 12 39 try it
27
Dangling Else - What is out?
int value = 0; String out = "abc"; if ( value >= 1 ) if ( value <= 10) out = "1 to 10"; else out = "else"; } out: abc out: 1 to 10 out: else out: abcelse try it Else goes with nearest if. Use braces!
28
null Reference String s = null; //null reference
null is no-reference or refers to nowhere Any Reference variable can be set to null. String s = null; //null reference String str = ""; //reference to 0-length string, not null if ( str != null) { //have valid reference }
29
null Reference Dereferencing null causes NullPointerException
Scanner in = new Scanner( System.in); String str = null; if ( in.hasNextInt()) { str = in.next(); } char ch = str.charAt(0); System.out.println( ch);
30
What will print?, How to fix?
true false compiler error runtime error public static void printIfA(String str) { if ( str.length()>0 && str != null) System.out.print( str.charAt(0) == 'A'); } Fix by changing condition to: str != null && str.length() > 0 which uses short-circuiting to avoid the right side of && when str is null. C - compiler error is the only incorrect one. If the argument to printIfA is "A", "a" then true or false will print If the argument to printIfA is "" then nothing will print If the argument to printIfA is null then runtime error
31
java.lang.String String strA = "This is a string"; //String literal
int lengthA = strA.length(); int lengthB = strA.substr(10).length(); //odd looking but works. int lengthB = "This is a string".substr(10).length();
32
packages: import vs. fully qualified
Fully qualified class name java.util.Scanner input = new java.util.Scanner( System.in); Not fully qualified so need import statement Scanner input = new Scanner( System.in);
33
char - Which will compile?
1, 2, 3 1, 3 1 2, 3 int intValue = 0; char aChar = 'B'; intValue = aChar; // 1 aChar = intValue + 1; // 2 aChar = '\u0041'; // 3 try it
34
Parameter Passing Java has Only Pass-by-Value
For both primitive and reference types only the value of a variable is passed as the argument. The argument may be either a primitive or a reference. The term Pass-by-Reference means the reference of the variable containing the value is passed as the argument. Java does NOT have Pass-by-Reference
35
What is print out? two one two main main two one two two two one main
one two two main static void one() { System.out.print( "one "); } static void two(int num) { System.out.print("two "); one(); public static void main( String []args) { two( 3); System.out.print("main "); try it.
36
What is print out? grape apple banana
public static void showFruit( String name) { name = new String("apple"); new String("banana"); } public static void main(String[] args) { String name = "grape"; showFruit( name); System.out.println( name); try it.
37
What prints out? print(double) static void print( double value) {
System.out.println( "print(double)"); } static int print( int value) { System.out.print( "print(int)"); return 1; public static void main( String [] args) { print( 10); print(double) print(int) error try it.
38
Method Overloading Overloaded methods have same name but differ in number or data types of parameters. Method signature in yellow public static int myMethod(int a, double b) { } Look at name and data types of arguments int result = myMethod( 10, 23.4);
39
What prints out? print(double)
static void print( double val1, double val2) { System.out.println( "print(double)"); } public static void main( String [] args) { double value = 10.0; print( value, 20); static void print( int val1, int val2) { System.out.println( "print(int)"); print(double) print(int) error try it.
40
What prints out? void print int print error
static void print( double val1, double val2) { System.out.println( "void print"); } static int print( double num1, double num2) { System.out.print( "int print"); return 1; public static void main( String [] args) { print( 10.0, 20.0); void print int print error try it.
41
What prints out? print(double)
static void print( double val1, double val2) { System.out.println( "print(double)"); } static int something( int val1, int val2) { System.out.print( "something(int)"); return 1; public static void main( String [] args) { print( 10, 20); print(double) something(int) error try it.
42
Memory Areas Stack Heap frame contains local variables and parameters
allocated on method call, freed on method return Heap allocated when needed, (e.g., using new) use references to access garbage collector frees memory no longer accessible review 1 passing primitive to method changing parameter in method 2 passing array to method changing contents of array in method 3 passing array to method changing parameter to another array in method 4 passing a string to method calling string method in method public class ClassNameHere { static void method1(int num) { num = 5; } static void method2(int []listA) { listA = new int[3]; listA[1] = 10; static void method3(StringBuffer name) { name //name.toUpperCase(); public static void main(String[] args) { String name = "Helen"; method3( name); System.out.println( name); // int [] listB = {4, 6, 8}; // method2( listB); // System.out.println( listB[1]); // int num = 4; // method1( num); // System.out.println("num=" + num);
43
Primitives and Wrapper classes
Draw a picture of memory and describe each. public static void main( String []args) { int k; Integer m; k = 2; //example of ? m = 3; //example of ? k = m; //example of ? }
44
Strings and memory class S { public static void main( String []args) {
String name; new String(“dog”); name = new String(“happy”); }
45
Where is memory allocated?
name: heap new String("spot"): heap name: stack new String("spot"): stack public static void main( String []args) { String name; name = new String("spot"); new String("fido"); } B is the best answer A, C and D are not true
46
Is result true or false? true Integer m = 5; Integer n = 5; false
boolean result = m == n; true false error A is correct. The fine print at the provided link says for Integer instances based on int literals between and 127 will have the same reference for the same int literal value. The intention of this example is to emphasize experimenting, discovering short illustrative examples and an introduction to the Java Language Specification. Part of relevant details: If the value p being boxed is an integer literal of type int between -128 and 127 inclusive (§3.10.1), or the boolean literal true or false (§3.10.3), or a character literal between '\u0000' and '\u007f' inclusive (§3.10.4), then let a and b be the results of any two boxing conversions of p. It is always the case that a == b. Ideally, boxing a primitive value would always yield an identical reference. In practice, this may not be feasible using existing implementation techniques. The rule above is a pragmatic compromise, requiring that certain common values always be boxed into indistinguishable objects. Java Language Specification
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.