CS 170 Midterm
Q 11 What is the output of the code below: if (6 > 8) { System.out.println(" ** "); System.out.println("****"); } else if (9 == 4) System.out.println("***"); else System.out.println("*"); A. **** B. * C. *** D. **
B. * Neither statements are true so we skip those blocks of code & use else block of code
Based on the code below: int x = [???], y; if (x > 5) y = 1; else if (x < 5) { if (x < 3) y = 2; else y = 3; } else y = 4; What is the value of y if x = 6? A. 4 B. 1 C. 2 D. 3
B. 1 the first code is correct & will be used encoding y = 1 we skip the next two areas of code.
Q7 Consider the following statements. double x; String y = "$ 1,234 "; y = y.replace("$", ""); y = y.replace(",", ""); y = y.trim(); x = Integer.parseInt(y); What is the value of x? A. 1234 B. 1234.0 C. Crashes D. 1234.0
B. 1234.0 x is a double and when x = y then it turns int(y) which is 1234 into a number with decimals so x=1234.0
If you try to use an instance variable that has not been initialized, your program will throw a: A. DivideByZeroException B. NullPointerException C. NotInitializedException D. ArithmeticException
B. NullPointerException Your code will not compile if you have an uninitialized local variable. But an uninitialized object instance variable will throw a NullPointerException, even though Java is supposed to have no pointers.
Q8 When you define the procedure, create a _________________ for each value you want to pass into the procedure. A. instance variable B. formal parameter C. actual parameter D. local variable
B. formal parameter The variables you create to hold data passed to a procedure are called the procedure's formal parameters.
Q8 Using the informal, general terms, a ________ refers to a method that returns a value to the caller, and that can be used to initialize variables or as part of an expression, like the methods in the Math class. A. procedure B. function C. program D. class
B. function A procedure is a method that carries out an action, while a function calculates and returns a value.
Q3 Instance variables will almost always use the modifier _________________ when you define them. A. static B. private C. public D. final
B. private. Instance variables are the ones defined outside of the individual methods but within a class. private is our access specifier and if you recall this portion of a variable definition determines if its going to be localized to the class or accessible by others(public).
Q1 When a Java string does not have surrounding double quotes, what type of error occurs? A. Logic error B. Run-time error C. Compile-time error D. Linker error
C. Compile-time error
Q5 Font style parameters should be specified using a class constant. Which of these is invalid? A. Font.PLAIN B. Font.ITALIC C. Font.BOLD_ITALIC D. Font.BOLD
C. Font.BOLD_ITALIC there are different ways to explain style Font.BOLD, Font.ITALIC, Font.PLAIN & Font.BOLD + Font.ITALIC
Q3 Which one of the following is a correct method of declaring and initializing an integer variable with name value? A. Int value = 30; B. integer value = 30; C. int value = 30; D. Int value = 30;
C. int value = 30;
Q4 In Java, Scanner is a class in which package? A. java.lang B. java.io C. java.util D. java.text
C. java.util
Q 10 What is the output of the following code snippet, if the input is 25? public static void main(String[] args) { Scanner cin = new Scanner(System.in); System.out.print("Please enter a number: "); int i = cin.nextInt(); if (i > 25) { i++; } else { i--; } System.out.println(i); } A. 27 B. 25 C. 26 D. 24
D. 24
Q6 Suppose x = 2 and y = 3. If the statement x *= y; is executed once, what is the value of x? A. 2 B. 3 C. 5 D. 6
D. 6
Q2 Here is a portion of the source code for a computer program: 69 6D 70 6F 72 74 20 6A-61 76 61 2E 61 77 74 2E 2A 3B 0D 0A 69 6D 70 6F-72 74 20 6A 61 76 61 2E 61 77 74 2E 65 76 65 6E-74 2E 2A 3B 0D 0A 69 6D This program is an example of _____________________________. A. high-level language B. hard-coded language C. assembly language D. machine language
D. machine language Machine language is the numerical code that your CPU is programmed to respond to. Assembly language is more english type of code used for people to understand.
Q2 Which of these words that can appear in a Java program are identifiers? A. static B. public C. void D. out
D. out Only out is an identifier. void, public and static are all keywords that you've used in your programs.
Q5 The OOP technique used to write programs so that different objects respond differently to the same commands is known as _____________________________. A. encapsulation B. decomposition C. inheritance D. polymorphism
D. polymorphism
prompt
For Scanner input, you must tell the person what to type in (you are prompting the person on what you expect the input is to be).
null string
If you don't initialize a String variable if you initalize a string w/no value then it is an empty string
font size
In general, use 12 for the smallest fonts, and 18-24 for medium headings.
Java is a _____ language
Object-oriented Object-oriented languages are languages that support the bundling of data and instructions into a single entity—called an object—and then sending messages to that object asking it to perform certain operations. Programs are communities of cooperating objects Objects are software components that interact with and provide services to each other
mutators
Objects, (like Font and Color) contains methods that change their internal state
RAM
Random Access Memory temporary holding place for data & instructions RAM = read/write memory RAM = volatile only keeps info when comp is on
Register
a tempoary high speed storage area on CPU it stores instructions data and results from ALU
A phantom semicolon
, placed after the loop condition, can lead to either an endless loop or a body that is executed exactly once, regardless of the condition
A test-at-the-top loop
,or entry-condition loop, checks its condition before carrying out the actions in its body.
To define a procedure you specify the:
1) access modifier, 2) optional static modifier, 3) return type, 4) method name, 5) the parameter list 6) the body enclosed in brace
Typographical errors
1. missing semicolons 2. using assignment (=) instead of equality ( ==)
Q6 Here is the expression to evaluate: 10.0 / 2 / 4
1.25
Q 10Based on the code below: String str1 = "car"; String str2 = "cars"; String str3 = "cat"; String str4 = "can"; str2.compareTo(str1); //statement 1 str1.compareTo(str3); //statement 2 str3.compareTo(str4); //statement 3 the value of statement 1 is ____. A. a positive integer B. a boolean value C. a negative integer D. 0
A. a positive integer
Q 11The AND operator is written as two ___. A. ampersands B. plus signs C. asterisks D. equal signs
A. ampersands (&&) aterisks (**) not an operator
Q8 To retrieve a single character from a String, use the __________ function, along with the position of the character you wish to retrieve. A. charAt() B. char() C. substring() D. nextChar()
A. charAt() While you can retrieve a single character (returned as a String) with the substring() method, you'd need to supply two parameters. Only charAt() allows you to retrieve the character by supplying only its position.
Q3 To join two String objects together, use the __________ operator. A. concatenation B. join C. continuation D. addition
A. concatenation
Q7 int x; String y = " 1234 "; y = y.trim(); x = Integer.parseInt(y); What is the value of x? A. 1234 B. 1234.0 C. Crashes D. 0
A.1234 inetger = real number trim = taking down the excess spaces
Q6 The expression (int)9.9 evaluates to ____. A. 9 B. 9.0 C. 9.9 D. 10
A.9
String literals
formed using regular characters, enclosed in double quotes, like the parameters passed to the println() method in your console program
To retrieve a character
from a String, use the charAt() function, along with the position of the character you wish to retrieve. The position of the first character is 0, and the position of the last is str.length() - 1.
byte
group of eight bits
nybble
half a byte or four bits
instance variables
instance variables are declared inside the class, but outside of any method. Instance variables normally use the modifier private.
Encapsulation
is the OOP design principle and technique that enforces data hiding. In a properly encapsulated class, all data elements are private and the only access to those elements are through the object's methods.
Polymorphism
is the OOP design principle that allows you to write programs in terms of an "ideal" or "generic" class, but substitute or plug-in related objects that act in different ways when your program runs. Polymorphism allows you to write code that is significantly simpler and more flexible.
The Association for Computing Machinery (ACM)
is the leading international academic, scientific and professional organization for computing professionals and computing education. * use run instead of main method * use extends inheritance * omit reciever
Parsing
just means converting text or String values to their numeric equivalent * scrub then parse * no characters should be left * use Double.parseDouble() or Int.parseInt()
A debugger
lets you pause your program when it is running, examine the values in your variables and then continue running your program one line at a time.
impossible condtion
logical operands: when you use AND instead of OR
unavoidable condition
logical operands: when you use OR instead of AND
Syntax errors
mistakes that arrive from compiling
expired counter
occurs when you fail to initialize your counter to its starting position immediately before your loop begins.
An endless loop
occurs when you fail to update your loop counter at the bottom of the loop body.
using color object
pass it to the Graphics setColor() method inside your paint() method
% in formating acts as a:
placeholder
builder methods
replace() or replaceAll() creates new strings
logical operators
|| = or && = and ! = (doesnt equal) == (equals) work with boolean operands & produce boolean results.
OOP
—Object-Oriented Programs—are organized as "communities", where each object has its own attributes and behavior, and the program "runs" as the objects interact with one another.
If you repeatedly calculate a value, you should write a ______________. A. user-defined procedure B. user-defined function C. user-defined class D. Math class function
B. user-defined function You cannot add more functions to the Math class. A procedure carries out an action, while a class represents a new type. Only a function calculates a value.
If the Java compiler complains that you have "unreachable code", it most likely means that you have written statements in your function that appear after: A. your function's closing brace B. your function return C. your function's parameter list D. a comment character
B. your function return If you place any code after the final return statement in your function, the code can never be executed because the return statement ends the function, as well as returning a value.
Q1 What is the computer component that stores program instructions during a program execution? A. Hard disk B. Memory C. DVD drive D. Input
B.Memory
Q7 double x; String y; y = String.format(".2f", x); If x = 43.579, what is the value of y? A. "43" B. "43.57" C. "43.58" D. None of these
C. "43.58" Since 9 is above 5 we round the value up
Q 12 What is the output of the following Java code? int j; for (j = 10; j <= 10; j++) System.out.print(j + " "); System.out.println(j); A. 10 B. 10 10 C. 10 11 D. 11 11
C. 10 11
Q6 Suppose that alpha is a double variable. What is the value of alpha after the following statement executes: alpha = 11.5 + (double)(15) / 2;. A. 18.0 B. 18.5 C. 19.0 D. None of these
C. 19.0
Q 10 What is the value of the price variable after the following code snippet is executed? int price = 42; if (price < 40) { price = price + 10; } if (price > 30) { price = price * 2; } if (price < 100) { price = price - 20; } A. 84 B. 42 C. 64 D. 52
C. 64
Q 11 Based on the code below: int x = [???]; int y = !(12 < 5 || 3 <= 5 && 3 > x) ? 7 : 9; What is the value of y if x = 2? A. 2 B. 3 C. 9 D. 7
C. 9
Q 10 What are the two required parts of an if statement? A. A check and an increment B. An increment and a decrement C. A condition and a body D. An increment and a body
C. A condition and a body
Q3 Which one of the following types of statements is an instruction to replace the existing value of a variable with another value? A. Update B. Initialization C. Assignment D. Declaration
C. Assignment
Q1 Text, like everything else in your computer, is stored as raw binary numbers. To treat those numbers as characters, they must be encoded. The encoding scheme used in Java is called: A. EBCDIC B. RSA C. Unicode D. SHA-256
C. Unicode EBCDIC is a character encoding scheme, but not the one used in Java, which is Unicode.
loops
Programming statements that perform iteration are called loops. Unlike an if statement, a loop returns to the test condition after performing its actions; thus a loop repeats its actions until its test condition becomes false.
procedure
The "generic" informal term for user-defined methods that carry out an action
Q8 A procedure _____________ always has a return type before the name. A. definition B. call C. body D. stub
A. definition public void myMethod(int arg) { } is a procedure definition. myMethod(); is a procedure call. void = return type
Q 11 The ____ statement is useful when you need to test a single variable against a series of exact integer or character values. A. switch B. if C. break D. else
A. switch if statements are used only for true indepenedent statements else is used to prove a false statement The switch statement is different than the if-else statement because the switch is based upon an integer evaluation, rather than upon a boolean test. A break statement to end each case.
Q7 When drawing an arc, the end parameter represents: A. the number of degrees of arc to draw, with a positive number drawing a counter-clockwise direction and a negative number drawing in a clockwise direction. B. the number of degrees of arc to draw in a clockwise direction C. the ending angle of the arc, using polar coordinates D. the number of degrees of arc to draw in a counter-clockwise direction E. the number of degrees of arc to draw, with a positive number drawing a clockwise direction and a negative number drawing in a counter-clockwise direction.
A. the number of degrees of arc to draw, with a positive number drawing a counter-clockwise direction and a negative number drawing in a clockwise direction. starting point is 3 o clock (0) going clockwise = negative & counter clockwise is positive
Q5 If you have a Color object named background. You can change the screen color of your applet by writing: A. this.setBackground(background); B. this.setColor(background); C. pen.setColor(background); D. pen.setBackground(background);
A. this.setBackground(background); This does not need a reciever. If you want to use a color do pen.setColor() or pen.setFont()
Q3 In a variable definition, the kind of value stored inside is called its: A. type B. name C. initial value D. modifier
A. type. Variables are named storage area that holds a value. Syntax of variable= modifier type name = intial value; int x =2; x = type where value is stored
The Java Platform
An object-oriented programming language A common set of class libraries A cross-platform execution environment: Java Virtual Machine
pre increment & post increment
a++ changes the value of the variable before calculations (preincrement) ++ a post increment stores value
The for loop header consists of three expressions:
the initialization expression where the loop counter is initialized INITALIZATION ( int i = 0; the test expression where the counter is compared against an ending value CONDITION ; int < len ; and the update expression where the counter is modified prior to the next iteration. INCREMENT ++i
The syntax of the while loop consists of:
the keyword while followed by a Boolean condition in parentheses followed by the statement to execute. If you wish to execute multiple statements, follow the condition with a block.
The precision of a floating-point number
the number of significant digits included in its display. A float has 7-8 significant digits, while a double has 15-16.
associativity of operands
the tie breaker of operands.
comparison methods
to compare object and String types compareTo();
ASCII
to encode system to save characters in java AKA unicode
increment
unary operator only applied to variables adding one from variable & storing result back into same variable ++ a a = a + 1
decrement
unary operator only applies to variables substracting one from variable & storung result into same variable -- a a = a -1
To locate the position of a character or a substring
use the searching functions indexOf() and lastIndexOf(). Both functions return the starting position of the character or substring, or -1 if it is not contained inside the String you are searching.
real syntax errors
using grammar elements such as keywords
accesors
value-producing methods that report on the object's internal state To use an accessor method, store the returned value in a variable, or use it as part of a calculation or method call.
side effect
whenever an expression changes the value of its operands. ex: casts
widening conversion & narrowing conversion
widening conversion = Java implicitly converts lower types to higher type narrowing conversion = casting
Type error
you store little values (less precise) into a big bucket ( more precise) int ---> double cant double ---> int
libraries
creating high level languages of codes that performed common tasks
Attributes
in class body —the data fields used to store object state
relational operators
inequality operators <, <=, >, >=, equality operators == , !=
To write a loop that counts down:
initialize the loop counter to the upper bounds test that the counter is greater than or equal to the lower bounds and make sure the update expression decrements the counter, instead of incrementing it. * the update is a decrement
Iteration
is a CS term that means repeating a group of actions.
A class
is a definition or "blueprint" specifying the data attributes and methods for a group of similar objects.
An operand
is a symbol that represents a value, while an operator is a symbol that represents an operation
An indefinite loop
monitors some condition other than the state of a counter as its loop bounds.
Common escape sequences
newline, the tab, the double quote and the backslash itself. \n newline \t tab \"" double quotes \\ blackslash
method
piece of code that performs an action or calculates a value Like classes they consist of a header and a body.
Two ways to represent data
primitive types like numbers and characters, and object types like fonts, buttons, Strings and Scanners.
Server-side Java programs
process data on a remote server and use your computer's Web browser for input and output
Micro-Java
programs run on mobile phones and PDAs.
Color in parameter list is listed as
red, green, blue
Assembly language
second generation of programming language consists oflibraries, interpreters, virtual assembly languages and compilers. the assembler changed assembly language into machine language , but had to be re written every time for a new computer
using background object
setBackground() method inside
Defining a method
specifies a set of actions to carry out inside the method body, and attaches a name to those actions in the method header. public static void main( String[] args) { }
Naming conventions for method and field names
startLowThenCaps
Your computer has two kinds of software:
systems software (aka the operating system), which is loaded when your computer starts up, and applications which are programs you use to accompish a particular task.
the while loop
the # of loops is not known & condition is true
Your CPU consists of two parts:
the Control Unit and the Arithmetic Logic Unit (ALU)— that work together to perform the steps of the machine cycle: fetch, decode, execute, and store.
A test-at-the-bottom loop
, or exit-condition loop, performs its actions first, and then checks its condition to see if it should "do it again".
Q4 Evaluate the result from evaluating the following integer expression. Make sure that your answer is the correct type. For instance, if the answer is 2 and the type is int, then you should enter 2. 8 * 2 - 7 / 4
15
Q4 13 + Math.abs(-7) - Math.pow(2.0, 3) + 5
17.0
Q6 12 / 7 * 4.4 * 2 / 4
2.2
Q4 6 / 2 + 7 / 3
5
Q4 6 % 10 % 4 * 3
6
Q4 (12 + 3) / 4 * 2
6
Q6 Here is the expression to evaluate: 813 % 100 / 3 + 2.4
6.4
the machine cycle( for danny everything simple)
: fetch, decode, execute, and store.
Uniary & binary
A unary operator (like - for the negative sign), works on a single piece of data. A binary operator (like - for subtraction), needs two pieces of data. (The same symbol (-) can represent two different operators).
Q8 Look at the following use of the substring() method: String word = "Hello World!"; String subs = word.substring(1, 2); The String subs will contain: A. "e" B. "H" C. "el" D. "He"
A. "e" Since this is the two-argument version of substring(), it returns a new String beginning at position 1 (that is, the second character in the original String, since Strings begin at 0), and going up to, but not including the character at index position 2. the 2 is the limit and should not include the l
Q8 If you use the String searching functions to search for a particular character or substring, and the value you're searching for is not found, the methods will return: A. -1 B. "" C. 0 D. false
A. -1 The indexOf() and lastIndexOf() functions search through a String. If the character or substring you are searching for, both functions return -1.
Consider this method comment. Which of the following options is recommended? /** Computes the area of a rectangle. @param width the width of the rectangle @return the area of the rectangle */ public static double area(double width, double height) { double area = width * height; return area; } A. Both parameters should be described. B. The parameter "width" need not be described. C. The @return clause of the comment should be omitted because it is obvious. D. The first line of the comment should be omitted because it is obvious.
A. Both parameters should be described.
Q1 In the DrJava IDE, you can evaluate and try out fragments of Java code without writing an entire program in the: A. Interactions Pane B. Interpreter Pane C. Snippets Pane D. Definitions Pane
A. Interactions Pane. Definitions Pane is where you write your code.
Q 12 Which statement about this code snippet is accurate? int years = 50; double balance = 10000; double targetBalance = 20000; double rate = 3; for (int i = 1; i <= years; i++) { if (balance >= targetBalance) { i = years + 1; } else { double interest = balance * rate / 100; balance = balance + interest; } } A. The loop will run at most 50 times, but may stop earlier when balance exceeds or equals targetBalance. B. The loop will never stop. C. The loop will run 50 times. D. There is a compilation error.
A. The loop will run at most 50 times, but may stop earlier when balance exceeds or equals targetBalance.
What is the syntax error in the following method definition? public static int area(double r) { double a; a = 3.14 * r * r; return r * r; } A. The value that is returned does not match the specified return type. B. The method does not return the value a. C. The method does not specify a return type. D. The variable a is set but never used.
A. The value that is returned does not match the specified return type.
Q2 Which of these is a legal (that is, syntactically correct) Java identifier? A. U2 B. bo-Tox C. 2LiveCrew D. moo tunes
A. U2 While letters, digits and underscores are legal in identifiers, you cannot start with a digit. You also cannot have spaces or hyphens in an identifier. That leaves only U2. identifiers can start with S signs or _ as well.
Q1 The devices that feed data and programs into computers are called ____. A. input devices B. output devices C. monitors D. printers
A. input devices Devices like keyboards, mice and scanners, which your program uses to receive information, are called input devices.
Q2 Method definitions should be placed: A. inside the body of your class B. after the class it is used in C. inside the Java class library D. before the class it is used in
A. inside the body of your class method definition = (String[] args)
Q2A(n) ___________________ is a program that converts assembly language or high-level language statements into machine code at the time the program runs. A. interpreter B. assembler C. linker D. compiler
A. interpreter A compiler converts an entire program to machine language. An interpreter converts your program on a line-by-line basis while program runs. This resolved portability & translation issues. An assembler is used to convert assembly to machine language for CPU to understand, it needed to be written everytime for a new computer.
Q 12 Which of the following is NOT a reserved word in Java? A. loop B. while C. do D. for
A. loop
Q5 To create a Font object, use a constructor, passing A. name, style, size B. name, size, style C. name, size D. name, style
A. name, style, size
Q8 Structured programming encourages programmers to organize their programs as a hierarchy of: A. procedures or functions B. classes C. objects D. subclasses
A. procedures or functions Structured programming is based around the idea of procedures or functions, while OO programming is based on the ideas of classes, subclasses and objects.
Q 12 Suppose j, sum, and num are int variables, and the input is 26 34 61 4 -1 What is the output of the following code? (Assume that cin is a Scanner object initialized to the standard input device.) sum = 0; num = cin.nextInt(); for (j = 1; j <= 4; j++) { sum = sum + num; num = cin.nextInt(); } System.out.println(sum); A. 124 B. 125 C. 126 D. None of these
B. 125
Q 10 Which of the following is a relational operator? A. && B. == C. ! D. =
B. ==
Q 10 What is the output of the following code snippet? public static void main(String[] args) { double income = 45000; double cutoff = 55000; double min_income = 30000; if (min_income > income) { System.out.println("Minimum income requirement is not met."); } if (cutoff < income) { System.out.println("Maximum income limit is exceeded."); } else { System.out.println("Income requirement is met."); } } A. Minimum income requirement is not met. B. Income requirement is met. C. Maximum income limit is exceeded. D. There is no output.
B. Income requirement is met.
Q3 The statement System.out.print("No" + 2 + 3 + "way"); produces the output: A. No5way B. No23way C. None. Illegal statement. D. No 2 3 way
B. No23way The concatenation "pastes" the 2 onto the end of "No" before the 3 could be added. The the 3 is concatenated onto the result.
Q4 The statement System.out.print("No" + ( 2 + 3 ) + "way"); produces the output: A. No23way B. No5way C. None. Illegal statement. D. No 2 3 way
B. No5way The parentheses ensure that the numbers 2 and 3 are added before concatenation "pastes" the result together.
Q7 Which of the following outputs 56734.987 to three decimal places? A. System.out.printf("3f%", 56734.9875); B. System.out.printf(".3f%", 56734.9875); C. System.out.printf(".03f%", 56734.9875); D. None of these
B. System.out.printf(".3f%", 56734.9875); 03 means leading zeros but there are no leading zeros in # 3f% means the # is 3 wide .3% means 3 decimal points
Q2 Which of these identifiers follows the Java conventions (not just the syntax rules) for a constant name? A. TotalCost B. TOTAL_COST C. totalCost D. total_cost
B. TOTAL_COST By convention, constants are all CAPS_WITH_UNDERSCORES separating the words.
Suppose x is 5 and y is 7. What is the value of the following expression? (x != 7) && (x <= y) A. false B. true C. This is an invalid expression in Java. D. None of these
B. true both sides of the && are true the whole expression is true
Q 10 What is the output of the following Java code? int x = 0; if (x < 0) System.out.print("One "); System.out.print("Two "); System.out.print("Three"); A. Two B. Two Three C. One Two Three D. None of these
B. Two Three
When you try to convert String data to numeric values, using the Integer.parseInt() or Double.parseDouble() functions on a String that is improperly formatted (containing spaces, commas, or other illegal characters) you will get: A. an InputMismatchException B. a NumberFormatException C. an incorrectly converted number D. an ArithmeticException
B. a NumberFormatException The NumberFormatException is the Integer and Double class message that tells you your String contains invalid characters.
Q7 To draw a "pie-slice" shape, use the Graphics method: A. drawArc() B. fillArc() C. drawSlice() D. none of these; you cannot draw pie slices.
B. fillArc()
Q5 Assume that font is an initialized Font variable. Which of these lines contains a logical error? A. String name = getFontName(); B. font.getFontName(); C. String style = font.getStyle(); D. int size = font.getSize();
B. font.getFontName();
Q 12 Which of the following is the logical or test expression in the for loop shown here? for (i = 1; i < 20; i++) System.out.println("Hello World"); System.out.println("!"); A. i = 1; B. i < 20; C. System.out.println("Hello World"); D. i++
B. i < 20;
Q 12 In a for loop, which of the following is executed first? A. logical or test expression B. initialization expression C. for loop statement D. update expression
B. initialization expression
Q8 Consider the following method definition: public static void printTopHalf() { } The word static: A. surrounds the parameter list B. is needed if the method is called from main() C. is known as the access specifier D. is called the method name E. surrounds the method body F. is called the return type
B. is needed if the method is called from main() The keyword public is called the access specifier and determines who has access to the method. The modifier static is normally only used when the method needs to be called from the main() method. The word void represents the return type of the method. The word void indicates that the method doesn't calculate a value, but carries out an action instead. The word printTopHalf is the method name, which is used to call it. The parentheses following the name are called the parameter list. Since there are no parameters, the list is empty. The body of the method is surrounded with braces on the subsequent lines.
Q7 A shape's bounds include all except A. it origin (x, y of the upper-left corner) B. its extent (x, y of the lower-right corner) C. its size (width and height) D. all of these are needed to specify the bounds of a shape
B. its extent (x, y of the lower-right corner) A shape's bound includes x, y from upper left corner its size width & height = size
Q1 Which of the following is NOT part of the central processing unit? A. instruction register B. main memory C. program counter D. control unit
B. main memory
Q2 In a main method definition, the symbols appearing inside the () are called the: A. modifier B. parameter list C. access specifier D. method return type
B. parameter list
Q5 According to the text, the ________ of an object includes all the information about the object; that is, its attributes or characteristics. A. methods B. state C. value D. constructors
B. state
Q6 The Syntax Errors section lists several categories of compile-time errors. Forgetting a double-quote at the end of a String literal would be classified as a: A. "real" syntax error B. structural error C. typographical error D. type error
B. structural error Structural errors occur when the compiler cannot tokenize your program because of mismatched delimiters.
Q 12 Which of the following is not a repetition structure in Java? A. for B. switch C. while D. None of these
B. switch
Q6 Mistakes in Java's built-in grammer are called: A. logic errors B. syntax errors C. intent errors D. runtime errors
B. syntax errors Syntax errors are caught by the compiler.
Which of the following is true about methods? A. Methods can have one parameter and can return multiple return values. B. Methods can have multiple parameters and can return multiple return values. C. Method can have multiple parameters and can return at most one return value. D. Methods can have only one parameter and can return only one return value.
C. Method can have multiple parameters and can return at most one return value.
Q3 The "factory" that uses a class definition to initialze an object is called ____________________. A. an init() method B. an object factory C. a constructor D. an initializer
C. a constructor. A concstructor = a method that allocates & intializes instance variables for new operators. person p = new person(); An initializer is a line of code (or a block of code) placed outside any method, constructor, or other block of code. Initializers are executed whenever an instance of a class is created, regardless of which constructor is used to create the instance. int x =2;
Q1 Each memory cell has a unique location in main memory, called the ____. A. unique identifier B. ID C. address D. cell location
C. address
Q6 Suppose that alpha and beta are int variables. The statement alpha = beta++; is equivalent to the statement(s) ____. A. alpha = 1 + beta; B. alpha = alpha + beta; C. alpha = beta; beta = beta + 1; D. None of these
C. alpha = beta; beta = beta + 1; beta++ means beta +1 You need to intialize that beta = alpha
Q2 The elements inside the class body are surrounded with, or delimited by: A. single-quotes B. brackets [ ] C. braces { } D. double-quotes
C. braces {}
Q3 A local numeric variable: A. is automatically initialized with the value 0 when defined. B. can be used without first giving it a value. C. cannot be used unless you explicitly initialize or assign a value. D. is initialized with a random value when defined.
C. cannot be used unless you explicitly initialize or assign a value.
Q7 To draw a rectangle with round corners use: A. drawRect() with five parameters and the style set to Rectangle.ROUNDED B. drawRoundRect() with eight parameters C. drawRoundRect() with six parameters D. drawRoundRect() with four parameters
C. drawRoundRect() with six parameters drawRoundRect(x, y, width, height, start angle, end angle)
Q5 The statement new Color(.5f, .5f, .5f) creates a ___________ Color object. A. red B. green C. gray D. white E. blue F. black
C. gray
Q 12 Which of the following is the initializer expression in the for loop shown here? for (i = 1; i < 20; i++) System.out.println("Hello World"); System.out.println("!"); A. i < 20; B. System.out.println("Hello World"); C. i = 1; D. i++
C. i = 1;
Q 12 Which of the following is the update expression in the for loop shown here? for (i = 1; i < 20; i++) System.out.println("Hello World"); System.out.println("!"); A. System.out.println("Hello World"); B. i = 1; C. i++; D. i < 20;
C. i++;
Q 11 Consider the following code snippet: Scanner cin = new Scanner(System.in); System.out.print("Enter number: "); int number = cin.nextInt(); if (number > 30) { //.......... } else if (number > 20) { //.......... } else if (number > 10) { //.......... } else { //.......... } Assuming that the user input is 40, which of the following block of statements is executed? A. else if (number > 10) { . . . } B. else if (number > 20) { . . . } C. if (number > 30) { . . . } D. else { . . . }
C. if (number > 30) { . . . }
Q 10 Which of the following will cause a syntax error, if you are trying to compare x to 5? A. if (x <= 5) B. if (x == 5) C. if (x = 5) D. if (x >= 5)
C. if (x = 5)
Q2 Which of these must appear outside the body of a class? A. variable definitions B. comments C. import statements D. output statements
C. import statements
Q4 Which of the following code fragments will cause an error? A. String greeting = "Hello, Dave!"; B. String greeting = "Hello, World!"; int n = greeting.length(); C. int luckyNumber; System.out.println(luckyNumber); D. System.out.println("Hi " + 5);
C. int luckyNumber; System.out.println(luckyNumber);
When defining a function, (unlike a procedure), you must specify a ______________ other than void. A. access specifier B. return statement C. return type D. parameter list
C. return type A void return type means that you have a procedure. Functions should not contain a void.
Q1 If your Java source code program compiles, but displays an error message when you run it, then it must have a: A. spelling error B. syntax error C. runtime error D. logic error
C. runtime error
Naming conventions for constants
CAPS_WITH_UNDERSCORES
Naming conventions for class
CapitalizeEveryWord
java.awt imports which class?
Color class
Constants
Constants are defined by using the modifier final when declaring the variable. Often constants are defined outside of a method
Coordinates
Coordinates start in upper-left position (0,0) called origin x increases to right y increases down Coordinates are baseline
Q1. Software or programs, are generally stored on your hard or fixed disk, but are run by loading them: A. into your network adapter B. into secondary storage C. onto the CPU D. into main memory
D. into main memory
In an accounting application, you discover several places where the total profit, a double value, is calculated. Which of the following should be done to improve the program design? A. Provide the same comment every time you repeat the total profit calculation. B. All of the listed items. C. The next time the total profit is calculated, use copy and paste to avoid making coding errors. D. Consider writing a method that returns the total profit as a double value.
D. Consider writing a method that returns the total profit as a double value.
Q2 The early high-level programming language designed as a general-purpose numeric and scientific programming language, and one which had a significant influence on the procedural languages that we use today was named ___________________ A. Algol B. LISP C. COBOL D. FORTRAN
D. FORTRAN fortran = scientists & engineers cobol = buisness LISP = math algol - arithmetic for general purpouse
Q3 According to the CS 170 style rules, every method and each class must have a ______________________. A. Single-line comment B. header C. body D. Javadoc comment
D. Javadoc comment According to the Java syntax rules, every method and class must have both a header and body. According to the style rules, methods and classes must both have Javadoc comments.
Q12 Is the code snippet written below legal? String s = "12345"; for (int i = 0; i <= 5; i++) { System.out.print(s.substring(i, i + 1)); } A. No; line 4 should have no semicolon at the end. B. Yes. C. No; there should be a semicolon at the end of line 2. D. No; for i = 5, s.substring(i, i + 1) will result in an StringIndexOutOfBounds error.
D. No; for i = 5, s.substring(i, i + 1) will result in an StringIndexOutOfBounds error.
Q7 int x; String y = "1234.45"; x = Double.parseDouble(y); What is the value of x? A. 1234 B. 1234.0 C. 1234.45 D. None of these
D. None of these x is an int, but Double.parseDouble returns a double.
Q 10 What is the output of the following code snippet? public static void main(String[] args) { int num = 100; if (num != 100) { System.out.println("100"); } else { System.out.println("Not 100"); } } A. 100 B. There is no output due to compilation errors. C. 100 Not 100 D. Not 100
D. Not 100
Q4 Which of the following statements correctly creates a Scanner object for keyboard input? A. Scanner keyboard(System.in); B. Keyboard scanner = new Keyboard(System.in); C. Scanner kbd = new Scanner(System.keyboard); D. Scanner keyboard = new Scanner(System.in);
D. Scanner keyboard = new Scanner(System.in);
Q6 Based on the code below: String sentence; String str1, str2, str3; int length1, length2; sentence = "Today is Wednesday."; str1 = sentence.substring(9, 18); str2 = str1.substring(0, 3); str3 = sentence.replace('d', '*'); length1 = sentence.length(); length2 = str1.length(); What is the value of str3? A. Today * Wednesday B. Today is Wednesday. C. **d** ** **d***d** D. To*ay is We*nes*ay.
D. To*ay is We*nes*ay.
Q8 To use a local variable in a different method, you pass the variable as _______________________. A. an int B. a String C. a formal parameter D. an actual parameter
D. an actual parameter The type of the variable doesn't matter. The values (and variables) that you pass to another method are known as arguments or actual parameters.
Q1 Programs that are designed to "work for you", carring out a task you specify, are known as: A. system programs B. operating systems C. utility software D. application programs
D. application programs
Q4 What is the result of the following code snippet? public static void main(String[] args) { double bottles; double bottle_volume = bottles * 2; System.out.println(bottle_volume); } A. 0 B. 1 C. 2 D. compile-time error
D. compile-time error missing double quotes
Q 11 When you place a block within an if statement, it is crucial to place the ____ correctly. A. periods B. commas C. angle brackets D. curly braces
D. curly braces
Q8 Procedures and functions allow us to place commonly used actions or calculations in a named block of code and then to simply use that new name instead of repeating the same block of code over and over again. This is called: A. stepwise refinement B. top-down design C. procedural decomposition D. eliminating redundancy
D. eliminating redundancy you use stepwise refinement through procedures to eliminate redundancy.
Q3 An ________________________ must appear inside a method. A. initializing or executable assignment statement B. variable definition C. initializing assignment statement D. executable assignment statement
D. executable assignment statement
Q5 To create a new class by adding features or data elements to an existing class, you use the OOP technique of ___________________. A. encapsulation B. abstraction C. polymorphism D. inheritance
D. inheritance. Inheritance can be defined as the process where one object acquires the properties of another. ex: public class newFont extends Scanner {}
Q 11 Based on the code below: switch (lastInitial) { case 'A': System.out.println("section 1"); break; case 'B': System.out.println("section 2"); break; case 'C': System.out.println("section 3"); break; case 'D': System.out.println("section 4"); break; default: System.out.println("section 5"); } What is the output if lastInitial = 'A'? A. section 5 B. section 3 C. section 2 D. section 1
D. section 1
Q5 The three properties of every object are its identity, ___________, and behavior. A. methods B. constructors C. value D. state
D. state
When writing your own String functions, always start by writing a skeleton, so that your function will compile and can be tested. The skeleton includes all of these except: A. a body B. the return statement C. each of the parameters D. the calculations E. the return type
D. the calculations public String(return type) nameFunct(String str)(parameters) (body){ String result = ""; return result; (return statement) } The goal of the skeleton is to get a syntactically correct method written, without worrying about the correct calculations.
Q5 Local variables in your program are stored in an area called: A. persistent storage B. the heap or freestore C. the static storage area D. the stack-based storage area
D. the stack-based storage area. Stack-based storage area is when variables are next to each other and stores local variables. The static storage area stores constant data like String literals. The heap shares info between methods and stores reference types.
Q7 When drawing a rectangle, the third parameter is: A. the height B. the vertical coordinate of the top of the rectangle C. the horizontal coordinate of the left edge of the rectangle D. the width E. the vertical coordinate of the bottom of the rectangle F. the horizontal coordinate of the right edge of the rectangle
D. the width drawRect(x, y, width, height)
Q 11 Based on the code shown here: boolean val = 5 < 3 || 6 > 7 || 4 > 1 && 5 > 3 || 2 < x; What is the value of the expression above? A. It cannot be determined. B. x C. false D. true
D. true start from left in || statements one value must be true in && statements both sides must be true in order for the whole statement to be true false || true || true && true || true or false overall it will be true
3 parts of an object
Identity: who the object is State: the characteristics of the object Behavior: what the object can do
JavaScript
JavaScript programs are embedded (as source) in Web pages and then interpreted by your Web browser
Dangling else
Nested if-else statements cause problems if every if statement doesn't have a corresponding else
assignment statement
The assignment statement copies the value on its right, and stores the copy in the named memory location (the variable) on its left. int x = 72; this
for loop
The for loop is designed for writing counter-controlled loops. counter-controlled loops that compare an index or loop counter to determine how many repetitions to perform. used to repeat a task a certain # of times
The reciver & request
The who that takes in the input ex: System.out What you want the program to execute ex:System.out.println("");
IPO programs
These programs are interactive. INPUT,PROCESSING,OUTPUT. read external input and then store and process their input
local variables
Variable that are defined inside a method. ex: defined inside the main() method need to be initalized with an int or double Local variables also don't use modifiers like static, public, or private.
Variables
Variables are named regions of memory that store a value. Before you can use a variable, it must be declared by specifying its name and the kind of value it will store.
numeric input
When you want to read a numeric input use: the Scanner class, use cin.nextInt() or cin.nextDouble(
Identifiers
are programmer-defined names used to specify classes, methods, variables and attributes. Syntactically, identifiers must begin with a letter, dollar-sign, or underscore, and may contain any number of letters, digits, dollar-signs or underscores. no spaces or hyphines Ex: U2
Calling a method
activates or executes a specific set of actions, using the method's name. invoke method it plays an action ex: System.out.println()
array
an object the contains elements of similar data type. It is a data structure where we store similar elements. ex: String[] can limit size
Logical errors
are a category of runtime error where the program's output is not correct or not as expected. To discover logical errors requires testing and to fix them requires debugging.
There are four different integer types: be sleek in life
byte, short, int and long. These differ only in the amount of memory that they use (8, 16, 32 and 64 bytes, respectively).
There are two different floating point or real number types:
float and double, using 32 and 64 bits of memory respectively.
nesting
embedding one if statement into another tests different levels of decision making
Machine language
every CPU understands machine language which is a numeric language memory inside computer can only store numeric data works w/ binary #'s first generation of programming language ex: E1 S4 G6 X9 etc
A sentinel loop
examines each value in input looking for a value which indicates the end of the loop. The sentinel may be a single value or a range of values.