Docsity

Introduction to Programming in Java - Test 1 Study Guide | CS 1054, Study notes of Java Programming

Toggle sidebar
bg1
JAVA Test 1 Notes
Ch1
Algorithms
In an informal sense, you can think of an algorithm as simply a procedure for solving a problem.
To meet its more formal definition, an algorithm must be:
Clearly and unambiguously defined.
Effective, in the sense that its steps are executable.
Finite, in the sense that it terminates after a bounded number of steps.
Chapter 2
1. Examples, examples, examples - Big picture.
a. Hello World example
public class HelloProgram extends GraphicsProgram {
public void run() {
add( new GLabel("hello, world", 100, 75) );
i. Comments help regular people understand the code
ii. HelloProgram is the class, which the extends keyword identifies as a
GraphicsProgram
oImport indicates what library packages the program uses
oPublic void run () --here run is the method
oStatements- the statement is add which adds an object to display
oArgument- ex.GLabel --this is the object that add is is indicated in an
argument to the add method
o(new GLabel (“hello, world”, 100, 75)); here new is acting as the
constructor****** (know difference between constructing and
declaring)
oThe argument supply info that the constructor needs to make an object
such as the string to display coordinates
oString- A string is a variable that holds a word, or a few words, or a
mixture of characters, that do not mean anything besides for a quote
In this case its (“hello world”, 100, 75)
b. A program to Add two numbers
i. Holistic perspective—understanding program as a whole
ii. ConsoleProgram- a console program reads input from the keyboard
and displays characters on the screen. No Graphics
iii. Integer (ex. int n1 = readInt (“Enter n1: “)
1. And integer is a WHOLE number
2. The input values (n1 and n2) are stored in memory cells
called variables that serve as placeholders for those values
iv. int total = n1 + n2;
1. This is a statement
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15

Partial preview of the text

Download Introduction to Programming in Java - Test 1 Study Guide | CS 1054 and more Study notes Java Programming in PDF only on Docsity!

JAVA Test 1 Notes Ch Algorithms In an informal sense, you can think of an algorithm as simply a procedure for solving a problem. To meet its more formal definition, an algorithm must be:  Clearly and unambiguously defined.Effective, in the sense that its steps are executable.  Finite, in the sense that it terminates after a bounded number of steps. Chapter 2

  1. Examples, examples, examples - Big picture. a. Hello World example public class HelloProgram extends GraphicsProgram { public void run() { add( new GLabel("hello, world", 100, 75) ); i. Comments help regular people understand the code ii. HelloProgram is the class , which the extends keyword identifies as a GraphicsProgram o Import indicates what library packages the program uses o Public void run () --here run is the method o Statements- the statement is add which adds an object to display o Argument- ex.GLabel --this is the object that add is is indicated in an argument to the add method o (new GLabel (“hello, world”, 100, 75)); here new is acting as the **constructor******** (know difference between constructing and declaring) o The argument supply info that the constructor needs to make an object such as the string to display coordinates o String- A string is a variable that holds a word, or a few words, or a mixture of characters, that do not mean anything besides for a quote  In this case its (“hello world”, 100, 75) b. A program to Add two numbers i. Holistic perspective— understanding program as a whole ii. ConsoleProgram- a console program reads input from the keyboard and displays characters on the screen. No Graphics iii. Integer (ex. int n1 = readInt (“Enter n1: “) 1. And integer is a WHOLE number 2. The input values (n1 and n2) are stored in memory cells called variables that serve as placeholders for those values iv. int total = n1 + n2; 1. This is a statement

2. variables n1, n

    • is an operator that represents addition v. println(“The total is “ + total + “.”)
  1. in this instance the + operator signifies concatenation which consists of combining the operands together as strings c.
  2. Idioms and Patterns a. Experienced programmers also often take a holistic approach to programming. Effective programmers can recognize a variety of common operations and have learned a standard solution strategy for each one. The code that implements such a solution strategy is called a programming idiom or programming pattern. Learning to use these patterns saves you from having to think about the nitty gritty details b. Think of this Ex. int n1 = readInt(“Enter n1: “); i. Think of it not in terms of what each part of the statement means but rather as a holistic pattern to read an integer from the user
  3. int variable = readInt (“prompt);
  4. Classes and Objects a. Java programs are written as collections of classes , which serve as templates for individual objects. Each object is an instance of a particular class, which can serve as a pattern for many different objects b. Classes in Java form hierarchies. Except for the class named Object that stands at the top of the hierarchy, every class in Java is a subclass of some other class, which is called its superclass. A class can have many subclasses but each class has only one superclass i. when you define a new class in Java, that class automatically inherits the behavior of its superclass c. highest to lowest AppletJAppletProgram i. Program types
  5. ConsoleProgram
  6. DialogProgram
  7. GraphicsProgram d. The DialogProgram class i. In Java class specifies behavior of objects of that class ii. The DialogProgram class has exactly the same operations as the ConsoleProgram class; the only difference is that the input and output operation use popup dialogs instead of a console
  8. Console program---has popup Message
  1. The GObject Hierarchy a. The clases that represent graphical objects form a hierarchy i. GObject 1. GLabel 2. GRect 3. GOval 4. GLine b. The GOject class represents the collection of all graphical objects c. Operations on the GObject class i. object.setColor(color) 1. Sets the color of the object to the specified color constant 2. Standard colors in java.awt package a. Color.BLACK, Color.DARK_GRAY, Color.GRAY, LIGHT_GRAY, WHITE, RED, YELLOW, GREEN, CYAN, BLUE, MAGENTA, ORANGE, PINK ii. object.setLocation (x,y)
  2. changes the location of the object to the point (x,y) iii. object.move(dx, dy)
  3. moves the object on the screen by adding dx and dy to its current coordinates d. Operations on the GLabel Class i. Constructor 1. new GLabel (text, x, y) a. Creates a label containing the specified text that begins at the point (x,y) ii. method specific to GLabel class
  4. label.setFont(font) a. sets the font used to display the label as specified by the font string i. font string format
  5. “family-style-size” a. family is name of font family b. style is either PLAIN, BOLD, ITALIC, or BOLDITALIC c. size is an integer indicating point size

e. Drawing Geometrical Objects i. Constructors

  1. new GRect (x, y, width, height) a. creates a rectangle whose upper left corner is at (x,y) of the specified size
  2. new GOval (x, y, width, height) a. creates an oval that fits inside the rectangle with the same dimensions
  3. new GLine (x 0 , y0, x 1 , y 1 ) a. creates a line extending from (x 0 , y 0 ) to (x 1 , y 1 ) ii. methods shared by the GRect and GOval classes
  4. object.setFilled(fill) a. if fill is true, fills in the interior of the object; if false, shows only the outline
  5. object.setFillColor(color) a. sets the color used to fill the interior which can be different from the border
  6. Some definitions a. run method—Every main class containts a method called run. when the program is executed, the statements in the body of run are executed in order b. Class- template for creating objects that represents individual instances of the class i. ex. public void run(){ add(new GLabel(“hello, world”, 100,75)); } ii. method -a sequence of program steps that have been collected together and given a name—in this ex it is “run” iii. statements -the steps that the method perform are listed between the curly braces iv. run method plays a special role in programs that use the acm.program package. Whenever you run a Java program the computer executes the statements enclosed in the body of the run method for the main class c. concatenation- applying the + operator to string data reinterprets that operator to mean adding the strings together end to end to combine their charactors i. ex println( “ The total is “ + total + “.”); ii. +total+ is a variable implanted in a string of words d. declaration- when you introduce a new variable in Java you must declare that variable i. ex int n1 = (value); e. floating-point numbers- numbers that include a decimal fraction i. ex. double most common type of floating point number f. double vs int -- an int is a whole number only

iii. indentifiers should make their purpose obvious to the reader iv. identifiers should adhere to standard conventions. Variable names, for example, should begin with a lowercase letter f. You must declare a variable before you can use it i. type name = value;

  1. type if the name of a java primitive type or class
  2. name is identifier
  3. value is expression specifying initial value ii. local variables —declared in the body of a method and are accessible only inside that method iii. instance variables - declared as part of a class
  4. Operators and Operands a. The most common type of operators in Java are the ones that specify arithmetic computation i. + Addition ii. - substraction iii. * multiplication iv. / division v. % remainder b. operators in Java usually appear between two subexpressions which are called its operands. operators that take two operands are called binary operators c. the – operator can also appear as a unary operator, as in the expression –x , which denotes the negative x
  5. Division and type a. Whenever you apply a binary operator to numeric values in Java the result will be of type int if both operands are of type int, but will be a double if either operand is a double b. this rule has important consequences i. 14/5 = 2.8 but if both operands are of type in Java computes an integer by throwing away the fractional part. The result will be 2 c. if you want to get correct result need to convert at least one operand to a double as in i. (double) 14/ ii. the conversion is accomplished by means of a type cast, which consists of a type name in parentheses iii. ex. double c = 100; double f = 9 / 5 * c + 32;
  6. since 9 and 5 are both type int the result is also an int iv. you can fix this by doing this double = 100 double f = (double) 9 / 5 * c + 32;
  1. The Remainder Operator a. The only arithmetic operator that has no direct mathematical counterpart is % (mod), which applies only to integer operands and computes the remainder when the first divided by the second i. ex 14 % 5 returns 4 14 % 7 returns 0 7 % 14 returns 7
  2. Precedence a. if an expression contains more than one operator java uses order of operations i. unary- (type cast) ii. * / % iii. + - b. only applies when two operands compete for the same operator. If the operators are independent, Java evaluates left to right c. fix is to use parentheses
  3. Assignment Statements a. you can change the value of a variable in your program by using an assignment statement, which has the general form i. variable = expression; b. the effect of an assignment statement is to compute the value of the expression on the right side of the equal sign and assign that value to the variable that appears on the left thus the assignment statement i. total = total + value adds together the current values of the variables total and value and then stores the sum back in the variable total ii. when you assign a new value to a variable the old value of that variable is lost c. Short hand assignments i. total = total + value; are so common that java allows the following shorthand 1. total +=value; ii. general shorthand form
  4. variable op= expression;
  5. where op is any of Javas binary operators. The effect of this statement is the same as variable = variable op (expression);
  6. ex salary *=2 same as salary = salary * 2
  1. Short Circuit Evaluation a. Java evaluates the && and || operators using a strategy called Short-circuit mode in which it evaluates the right operant only if it needs to do so b. for example if n is 0, the right operant of && in n != 0 && x % n == 0 is not evaluated at all because n != 0 is false because the expression false && anything is always false, the rest of the expression no longer matters c. one of the advantages of short-circuit evaluation is that you cand use && and || to prevent execution errors. If n were 0 in the earlier example, evaluating x % n would cause a “division by zero” error http://docs.oracle.com/javase/tutorial/java/nutsandbolts/index.html Chapter 4
  2. Statement Types in Java a. Programs in Java consist of a set of classes. Those classes contain methods, and each of those methods consists of a sequence of statements. b. Statements in Java fall into 3 basic types: i. simple statements ii. compound statements (aka blocks)

iii. control statements

  1. conditional statements that specify some kind of test
  2. iterative statements that specify repetition c. simple statements are formed by adding a semicolon to the end of a Java expression d. compound statements (also called blocks) consist of a sequence of statements enclosed in curly braces e. control statements fall into two categories
  3. conditional statements that specify some kind of test
  4. iterative statements that specify repetition
  5. Control statements and Problem solving a. Add2Integers ex b. these slides illustrate three different strategies(look at next page) i. adding new code to process each input value ii. repeating the input cycle a predetermined number of times iii. repeating the input cycle until the user enters a special sentinel value
  6. The Repeat-N-Times Idiom (Walk through code on slide 9 of ch4 powerpoint) a. one strategy for generalizing the addition program is to use the Repeat-N- times idio which executes a set of statements a specified number of times the general form of the idiom is for (int i = 0; i < repetitions ; i++) { statements to be repeated } i. as is true for all idiomatic patterns in this book the italicized words indicate the parts of the pattern you need to change for each application. to use this pattern you need to replace repetitions with an expression giving the number of repetitions and include the statements to be repeated inside curly braces for (int i = 0; i < repetitions ; i++) b. The information about the number of repetitions is specified by the first line in the pattern which is called the header line statements to be repeated c. the statement to be repeated are called the body of the for statement and are indented with respect to the header line d. a control statement that repeats a section of code is called a loop e. each execution of the body of a loop is called a cycle
  7. Repeat-Until-Sentinel Idiom (read through AddIntegerList Program

d. Cascading if statement if ( condition 1 ) { statements 1 } else if ( condition 2 ) { statements 2

... more else / if conditions... } else { statements else }

  1. The ?: Operator a. in addition to the if statement java provides a more compact way to express conditional execution that can be extremely useful in certain situations. This is called the ?: operator (pronounces question-mark-colon) and is part of the expression structure. The ?: operator has the following form condition? expression 1 : expression 2 b. when Java evaluates the ?: operator it first determines the value of the condition which must be a Boolean. If condition is true, Java evaluates expression1 and uses that as the value; if condition is false, Java evaluates expression2 instead c. you could use the ?: operator to assign the larger of x and y to the variable max like this: max = (x > y)? x : y;
  2. The Switch statement a. the switch statement provides a convenient syntax for choosing among a set of possible paths b. when Java executes a switch statement it begins by evaluating expression which must produce an integer like value c. Java then loks for a case clause that matches the expression. If expression was equal to v 2 Java would choose the second clause

d. Java evaluates the statements in a case clause until it reaches the break statement which should appear at end of each clause e. if none of the values in the case clauses match the expression Java evaluates the statements in the default clause switch ( expression ) { case v 1 : statements to be executed if expression = v 1 break; case v 2 : statements to be executed if expression = v 2 break;

... more case clauses if needed... default: statements to be executed if no values match break; }

  1. The while statement (Digit sum problem) a. the while statement is the simplest of Java iterative control statements and has the following form while ( condition ) { statements to be repeated } b. When Java encounters a while statement, it begins by evaluating the condition in parentheses, which must have a boolean value. c. If the value of condition is true , Java executes the statements in the body of the loop. d. At the end of each cycle, Java reevaluates condition to see whether its value has changed. If condition evaluates to false , Java exits from the loop and continues with the statement following the closing brace at the end of the while body. e. Look at DigitSum Program**************************** f. Loop-and-a-half pattern*****use this when using easier for most students to use  The while statement in Java always tests the condition at the beginning of each cycle of the loop. Sometimes, however, you need

c. the advantage of the for statement is that everything you need to know to understand how many times the loop will run is explicitly included in the header line d. for statement ex i. for (int i = 1; i <= 10; i++)

  1. This statement executes the loop body ten times, with the control variable i taking on each successive value between 1 and 10 ii. for (int i = 0; i < N; i++)
  2. This statement executes the loop body N times, with i counting from 0 to N - 1. This version is the standard Repeat-N-Times idiom iii. for (int n = 99; n >= 1; n -= 2)
  3. This statement counts backward from 99 to 1 by twos iv. *for (int x = 1; x <= 1024; x = 2)
  4. This statement executes the loop body with the variable x taking on successive powers of two from 1 up to 1024. e. The Countdown program check it
  5. Nested for statements a. The body of a control statement can contain other statements. Such statements are said to be nested. b. Many applications require nested for statements. The next slide, for example, shows a program to display a standard checkerboard in which the number of rows and number of columns are given by the constants N_ROWS and N_COLUMNS. c. The for loops in the Checkerboard program look like this: for (int i = 0; i < N_ROWS; i++) { for (int j = 0; j < N_COLUMNS; j++) { Display the square at row i and column j. } } d. Because the entire inner loop runs for each cycle of the outer loop, the program displays N_ROWS x^ N_COLUMNS squares.
  6. Triangle number table a. As you think about the design of the TriangleTable program, it will help to keep the following thoughts in mind: b. The program involves two nested loops. The outer loop runs through each of the values of N from 1 to the maximum; the inner loop prints a series of values on each output line.

c. The individual elements of each output line are easier to display if you call print instead of println. The print method is similar to println but doesn’t return the cursor position to the beginning of the next line in the way that println does. Using print therefore makes it possible to string several output values together on the same line. d. The n th^ output line contains n values before the equal sign but only n – 1 plus signs. Your program therefore cannot print a plus sign on each cycle of the inner loop but must instead skip one cycle. public class TriangleTable extends ConsoleProgram { public void run() { for (int n = 1; n <= MAX_VALUE; n++) { int total = 0; for (int i = 1; i <= n; i++) { if (i > 1) print(" + "); print(i); total += i; } println(" = " + total); } } / Private constants / private static final int MAX_VALUE = 10; }

14. Simple Graphical Animation a. The while and for statements make it possible to implement simple graphical animation. The basic strategy is to create a set of graphical objects and then execute the following loop: for (int i = 0; i < N_STEPS; i++) { update the graphical objects by a small amount pause(PAUSE_TIME); }

println("This program adds four numbers."); int n1 = readInt("Enter n1: "); int n2 = readInt("Enter n2: "); int n3 = readInt("Enter n3: "); int n4 = readInt("Enter n4: "); int total = n1 + n2 + n3 + n4; println("The total is " + total + "."); } } can be written as public class AddNIntegers extends ConsoleProgram { public void run() { println("This program adds " + N + " numbers."); int total = 0; for (int i = 0; i < N; i++) { int value = readInt("? "); total += value; } println("The total is " + total + "."); } private static final int N = 100; }

Test 1: Wednesday, February 27

This is a multiple-choice exam scheduled during regular lecture time. It consists of approximately 30 questions that need to be answered in 50 minutes. This is a closed notes and books exam. Calculators and other electronic devices are not allowed during exam. Bring a pencil and paper!

Topics

This exam covers the text chapters AND everything I have said in class thus far including: o Chapters 1 o Algorithm and problem solving o Chapter 2 o Examples, examples, examples - Big picture. o Understanding idioms and patterns so that you can learn the material. o basic acm graphic shapes and how to use them (declare/create a shape, call methods on it to make it display, change color, etc.) o recangle, oval, line label o readInt(), readDouble(), readLine(), print(), println() etc. o extends GraphicsProgram, DialogProgram, COnsoleProgram o run() method o Chapter 3 o Expressions o primative data types o declaring constants and variables o operators and precedence... Evaluating expressions o int division, floating-point division, mixed division (and other operations) o type conversions, "upgrading" o assignment statement (especially conpared to == equality!) o increment and decrement o Boolean expressions o relational operators o logical operators o Chapter 4 o Statements o Simple, compound (blocks) i.e. { }, and control statements o Iterative vs Conditional o repeat-N-times pattern (for loop) o while loop o (please do NOT use an if statement to break out of a while loop!) o infinite loop o sumation o nested loops o for loops o nested for loops o if statement o series of statements with if statements o imbedded if statements o if-else statements o cascading and embedded if-else o NEVER use the ?: operator in this class. It is too confusing. o switch statement o cases are independant o expression must eval to int or char o cases must be int/char constants