110 likes | 255 Vues
This recitation covers essential concepts in computer programming with a focus on practical coding examples. Various Java snippets illustrate key programming aspects, including data types, casting, and logic. We explore outputs of different programs while emphasizing the importance of proper casting to avoid compilation errors. Through hands-on practice, students will learn how to interpret program output and understand coding errors. This session is designed to reinforce learning and build confidence in coding abilities.
E N D
Introduction to Computer Programming Recitation 2 Ihsan Ayyub Qazi
Agenda • Practice • Practice • Practice
What is the output of the program? public class Test { public static void main (String args []) { int x = 10, y = 3; double t = 3.0, z = 0.0; z = x/3; System.out.println(z); z = x/(double)3; System.out.println(z); z = (double)(x/3); System.out.println(z); z = x/t; System.out.println(z); } }
Output? public class Test { public static void main(String args []) { char letter = 'A'; int val = 0; double d = 0.0; byte b = 0; val = letter; System.out.println(val); d = letter; System.out.println(d); b = letter; System.out.println(b); } } Recall “narrowing conversion” To avoid a compilaton error explicit cast must be done !! Why? The compiler wants to make sure that the programmer knows what he/she is doing and didn’t make a mistake
Output? public class Test { public static void main(String args []) { char letter_1 = 65, letter_2 = 66; char temp; temp = letter_1; letter_1 = letter_2; letter_2 = temp; System.out.println(letter_1); System.out.println(letter_1); System.out.println((int) letter_1); System.out.println((int) letter_1); } }
Output? public class Test { public static void main(String args []) { int age = 0, height = 0, sum = 0; 15 = age; 20 = height; sum = age + height; System.out.println(sum); } } The operand to the left of the assignment “=“ operator always has to have a variable ! Why?
Output? public class Test { public static void main(String args []) { int x = 0, 34 = 0; 34 = 13; System.out.println(34); } } How about x=34?
Output? public class Test { public static void main(String args []) { int age = 21; short height = 78, sum = 0; sum = age + height; System.out.println(sum); } }
Output? public class Test { public static void main(String args []) { String str = "This is a class on computer programming"; String abc = "ABC"; char c, d; int val; System.out.println( str.toUpperCase() ); val = abc.charAt(0) + 1; c = (char) val; System.out.println(c); } }
Output? (Challenge Question) public class Test { public static void main(String args []) { int x = 10, y = 3; double t = 3.0, z = 0.0; z = (double)(x/3); System.out.println(z); z = (char)x/3; System.out.println(z); } }