640 likes | 785 Views
Review Quick reference. Chapter 1: Basics. Methods usually go after the data. Data usually goes first in a class. Class. class Car { String Make; int MaxSpeed ; public brake() { System.out.println (“Stop!"); } } A class: data fields (properties) + methods (behavior).
E N D
Review • Quick reference
Methods usually go after the data Data usually goes first in a class Class class Car { String Make;intMaxSpeed; public brake() {System.out.println(“Stop!"); } } • A class: data fields (properties) + methods (behavior)
Class is a template for creating instances • How to create instances of a class? ClassNameinstanceName = newClassName(intialInputParam); Car c1= newCar(); c1.make = “Honda”; Car c2= newCar(); c2.make = “Ford”;
packagepackagename; packageRacingGamePackage; • Groups related classes in the same category • How to declare a class is part of a package? • Unique name • Hierarchal packagebook.chapter1;
Many packages in Java API • javax.swing • java.lang • java.util • … • How to use a package? import packagename; Only “Welcome” class is imported. import book.chapter1.Welcome; import book.chapter1.*; All classes in chapter1 imported.
3 types of comments in Java • Line comment // • Example • // This is a line comment! • Paragraph comment /* */ • Example • /* This is a paragraph comment. It includes multiple lines. */ • JavaDoc comments (automatic documentation) /** */
public class Test{ public static void main(String[] args) { System.out.println(“3.5 * 2 / 2 – 2.5 is "); • System.out.println(3.5 * 2 / 2 – 2.5); } } • What is the output? >3.5 * 2 / 2 – 2.5 is >1.0
Create a Scanner object Scanner input = new Scanner(System.in); • Use one of the methods below
A variable stores your data • int x = 10; • Identifier • Name of your variable • letters, digits, underscores (_), and dollar signs ($) • Cannot start with a digit • Cannot be a reserved word Identifier X Variable 23 Literal
Value is constant, doesn’t change • Use “final” keyword to declare a value as constant final datatype CONSTANTNAME = VALUE; Example: final double PI = 3.14159; final intSIZE = 3;
Operator Example Equivalent += i += 8 i = i + 8 -= f -= 8.0 f = f - 8.0 *= i *= 8 i = i * 8 /= i /= 8 i = i / 8 %= i %= 8 i = i % 8 • Shortcut operators for assignment
OperatorNameDescription ++varpre-increment The expression (++var) increments var by 1 and evaluates to the new value in varafter the increment. var++post-increment The expression (var++) evaluates to the original value in var and increments var by 1. --varpre-decrement The expression (--var) decrements var by 1 and evaluates to the new value in varafter the decrement. var--post-decrement The expression (var--) evaluates to the original value in var and decrements var by 1. • Increment, decrement operators
double d = 3; • Implicit casting (type widening) • A small number fits easily in a large variable • Explicit casting (type narrowing) • A large number (3.9, double) cannot be fit in a smaller variable (int), so fraction part is truncated. • You need to explicitly cast your number. inti = (int)3.9;
public class Test{ public static void main(String[] args) { char x = ‘a’; char y = ‘c’; System.out.println(++x); • System.out.println(y++); } } • Example >b >c
if (radius >= 0) { area = radius * radius * 3.14159; System.out.println("The area is: “ + area); } else { System.out.println("Negative input"); } • Example
if (score >= 90.0) • grade = 'A'; • else if (score >= 80.0) • grade = 'B'; • else if (score >= 70.0) • grade = 'C'; • else if (score >= 60.0) • grade = 'D'; • else • grade = 'F'; • if (score >= 90.0) • grade = 'A'; • else • if (score >= 80.0) • grade = 'B'; • else • if (score >= 70.0) • grade = 'C'; • else • if (score >= 60.0) • grade = 'D'; • else • grade = 'F'; • else if is used for checking multiple conditions
What if we need more complex conditions composed of “and/or/..”?
switch (status) { case 0: //compute taxes for single filers; break; case 1: //compute taxes for married file jointly; break; case 2: //compute taxes for married file separately; break; case3: //compute taxes for head of household; break; default: System.out.println("Errors: invalid status"); } • Tax Program
Conditional statement as (boolean-expression) ? expression1 : expression2 if (x > 0) y = 1 else y = -1; y = (x > 0) ?1 : -1;
%s s stands for a string • %f stands for floating point number • System.out.printf("%s, %s", "Hello", "World!"); • Output: “Hello, World!” • System.out.printf(“%.1f pounds” ,28.8968); • Output: “28.8 pounds”
Format specifiers in more detail Maximum number of digits after decimal point A flag (such as - to left justify) Tells the compiler to expect a specifier … Minimum number of characters to show Data type (e.g. %f)
Specifier Output Example %ba boolean valuetrue or false %ca character'a' %da decimal integer 200 %fa floating-point number45.460000 %ea number in scientific notation4.556000e+01 %sa string"Java is cool"
System.out.printf(“amount is %5.4f” ,32.32); • What is the output? > amount is 32.3200 >□□java > System.out.printf(“%6s \n” ,”java”);
while(condition) { statement; } • If the condition is true, the statement is executed; then the condition is evaluated again … • The statement is executed over and over until the condition becomes false. • When the loop finishes, control passes to the next instruction in the program, following the closing curly brace of the loop.
The body of awhileloop must eventually make the condition false • If not, it is an infinite loop, which will execute until the user interrupts the program! int count = 1; while (count > 0) { System.out.println("Welcome to Java!"); count++; }
Will be executed at least once do { // Loop body; Statement(s); } while (loop-condition);
int count = 0; while (count < 10) { System.out.println("Welcome to Java!"); count++; } for(int count =0; count < 10; count ++) { System.out.println("Welcome to Java!"); }
Some recommendations • Use the most intuitive loop • If number of repetitions known for • If number of repetitions unknown while • If should be executed at least once (before testing the condition) do-while
breakcauses the loop to be abandoned, and execution continues following the closing curly brace. while ( i > 0 ) { .... if ( j == .... ) break; // abandon the loop …. } // end of the loop body break will bring you here
continuecauses the rest of the current round of the loop to be skipped. • "while" or "do" loop moves directly to the next condition test of the loop. • "for" loop moves to the “action-after-each-iteration”expression, and then to the condition test.
int count = 0; while (count < 10) count++; intcount= 0; for (inti=0; i<= 10; i++) count++; • How many times count++ will be executed? 10 11 int count = 5; while (count < 10) count += 3; int count = 5; while (count < 10) count++; 2 5
Poll results • Look up your class section • Test credit card #
name output modifier input • A method publicstaticintsum(int x, int y) { int sum = 0; for (int i = x; i <= y; i++) sum += i; return sum; } Method body
First, a method should be defined • Then we can use the method • i.e. calling or invoking a method public static void main(String[] args) { int total1 = sum(1, 10); int total2= sum(20, 30); int total3 = sum(35, 45); int total4 = sum(35,1000); }
public class TestClass{ • public static void main(String[] args) { • int total1 = sum(1, 10); • } • //---------------------------------------------- • publicstaticint sum(int x, int y) • { • int sum = 0; • for (int i = x; i <= y; i++) • sum += i; • return sum; • } • } • When calling a method within the same class, we directly call the method calling directly
public class AnotherClass{ • publicstaticint sum(int x, int y) • { • int sum = 0; • for (int i = x; i <= y; i++) • sum += i; • return sum; • } • } • When calling a method from another class, use class name if a static method • public class TestClass{ • public static void main(String[] args) { • int total1 = AnotherClass.sum(1, 10); • } • } Class name
public class AnotherClass{ • publicintsum(int x, int y) • { • int sum = 0; • for (int i = x; i <= y; i++) • sum += i; • return sum; • } • } • When calling a method from another class, use class name if a static method • public class TestClass{ • public static void main(String[] args) { • AnotherClass a = new AnotherClass(); • int total1 = a.sum(1, 10); • } • } Instance name
How memory is managed? Space required for max method: Result: 5 x:5 y:2 Space required for max method: x:5 y:2 Space required for main method: k: i:5 j:2 Space required for main method: k: i:5 j:2 Space required for main method: k: i:5 j:2 Space required for main method: k: 5 i:5 j:2 Stack is empty
What about reference types? • E.g. Random r = new Random(); Space required for test method: x Actual Object … Space required for main method: r (reference) Heap Memory Stack Memory
Method overload is only based on input arguments • Method overload can not be based on different output values • Method overload cannot be based on different modifiers • Sometimes there may be two or more possible matches for an invocation of a method, but the compiler cannot determine the most specific match. • This is referred to as ambiguous invocation. Ambiguous invocation is a compilation error.
Scope: • Part of the program where the variable can be referenced. • A local variable: • A variable defined inside a method. • The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable.
Class level Scope: • Accessible to all methods of that class • public class Test{ • int x; //data field: accesible to all methods • publicint method1() • { //do something ...} • publicintmethod2() • { //do something ...} • }
Method level Scope: publicintsum(int x, int y) { int sum = 0; for (int i = x; i <= y; i++) sum += i; return sum; }
Block level Scope: publicintsum(int x, int y) { int sum = 0; for (int i = x; i <= y; i++) { int k = -1; sum = k + i; } return sum; }
publicintsum() { int sum = i; for(int i = 0; i <= 10; i++) { sum += j; for(intj = 0; j <= 10; j+=k) { intk = -1; sum = i+ j; } } returnsum; } • Which statements are incorrect?