AP Computer Science

¡Supera tus tareas y exámenes ahora con Quizwiz!

What are the escape sequences for a tab and for backspace?

"\t" and "\b"

Valid identifiers in java:

$down, drSiladi, If, _runner, my_var

The expression 1 / 4 is equal to which of the following? Circle one.

1 / (int) 4.0

Describe the benefits of an ArrayList over a Standard Array.

1. It's easy to increase the size of an ArrayList - just call add. 2. It's easy for a programmer to insert or remove an element to or from the interior of an ArrayList - just call add or remove and specify the element's index position.

How many bits does one character of Unicode occupy?

16

Why are there that many possible characters?

216 = 65,536

Consider the following code segment. for (int i = 1; i < 5; i++) for (int k = i; k > 2; k--) System.out.print(k + " ") What is printed as a result of executing the code segment:? Circle one:

3 4 3

How many characters are in the Unicode set?

65,536 characters.

A class encapsulates what two things and what are their "official" designations"?

A class encapsulates two "members" officially known as methods and instance variables.

What is a literal in Java? Give two examples of two types of numeric literals and describe their types.

A fixed value for any one of Java's primitive data types. Each data type has its own representation. 100 and -100 are int literals. 200.0F is a floating point literal.

Briefly describe the structure of the JVM and bytecode and their important role in the secure Java environment.

A java compiler produces bytecode, which is NOT compiled executable machine code, but is a highly optimized set of instructions designed to be executed only by a JVM (Java Virtual Machine). Each computer platform must have a run-time JVM created for it. Once this has been done, the JVM interprets the bytecode and executes it. While interpretive languages are often slow, the bytecode structure has been optimized and a just-in-time compiler, included in the JVM, speeds execution. NOTE: All browsers are JVMs!

Briefly, what is a switch and how does it work? What other type of "branching" structure can it sometimes replace with more "elegance" (succinctness)?

A switch provides for a multiway branch, similar to an if-else-if ladder. However, instead of logical boolean statements to determine the branching, it uses the value of a single expression that is successively tested against a list of constants. It can often replace an if-else-if ladder and is more compact code.

What is an infinite loop? What's the code for the simplest one.

An infinite loop never terminates. The following is the simplest code fragment for creating such. for (;;) { };

Give two examples, in the same program code, of different scopes for different variables. Include comments that indicate the start and end of the scopes.

Answers will vary but one variable would be declared, initialized and used in the main { } block, while another would be declared, initialized and used in a { } block inside main, such as in an if {} block or a for ( ; ; ) {} block.

Briefly describe autoboxing and "auto" unboxing, including why it is necessary. Give a minimal code snippet that show both occuring in code. Clearly indicate where each occurs.

Autoboxing occurs when an ArrayList is declared with a "wrapper" class for primitives types is filled with a primitive. The primitive is automatically "wrapped" in the appropriate class, and "unwrapped" if the primitive at a specific location is called. ArrayList<Double> stocks = new ArrayList<Double>(); double stock = 10.0; stocks.add(stock); // AUTOBOXING OCCURS HERE stock = stocks.get(i); // UNBOXING OCCURS HERE

Write a code snippet to show how two references would be created for two objects of a BankAccount class called yourAccount and myAccount (two separate references, two different objects).

BankAccount yourAccount = new BankAccount(); BankAccount myAccount = new BankAccount();

What numeric types can the % operator be applied to?

Both integer and floating data types.

BankAccount yourAccount = new BankAccount(); BankAccount myAccount = new BankAccount();

Both object references both refer to the same object in memory - they hold the same memory reference address in the object name memory slot. If the object reference that is reassigned was initialized, the object that it referred to is no longer available.

Compare the break statement to the go to used in other languages.

Break is similar to a goto in other languages. While both represent destructured code, which might be hard to follow and understand, breaking to a label still retains some structure, since you can only break to the end of a current block of code. A goto can jump to any other line of code in a program.

Describe where, when and how a break statement is used. Be sure to include "full" and "partial" implementation.

Break statements are commonly used in switch branches at the end of the code for each constant's statement sequence. It transfers control out of the entire switch statement to the next line of code. If a branch does not end a statement sequence associated with a case, then all the statements AT AND FOLLOWING the matching case WILL BE EXECUTED until a break or the end of the switch is encountered.

How can code be improved?

By using indentation!!!

Describe the differences between short, int, and long, including their usages.

Byte is a 8 bit numerical integer, Short is a 16 bit numerical integer, int is a 32 bit numerical integer and long is a 64 bit numerical integer. The ranges of each correspond to the possibilities in their bits. Generally this is the number 2 raised to the power of the number of bits. Thus, bytes range is 28, or 256 possibilities, while int is 2 for a total of approximately 4.9 billion possibilities. Bytes are very often used for combinations of 0s and 1s that control device setting. Short is passing into oblivion since many modern computers no longer support. int is recommended for efficient processing of numbers in the range -2.1 billion to +2.billion. If an application requires integers outside that range, long is recommended.

Java is directly descended from (circle one)

C++

What is a command-line argument? What part of a Java program receives the command-line arguments? Use a short code snippet example that show the simple use of these arguments.

Command-Line arguments are stored in array of String objects, and are passed at program invocation to the main method. public static void main (String args[]) { System.out.println( args[0] + " " + args[1] " " + args[3]); }

Name the three fundamental principles of OOP:

ENCAPSULATION, POLYMORPHISM, INHERITANCE

int x = 5, y = 9, z = 2, inside; boolean r = false, result; result = !( ( r || ( y < x ) ) && ( 5 >= x ) );

FALSE

int x = 5, y = 9, z = 2, inside; boolean r = false, result; result = ( x == ( (z++) + 2 ) );

FALSE

int x = 5, y = 9, z = 2, inside; boolean r = false, result; result = ( y < z );

FALSE

What are the two floating-point types? Describe their principle differences and usages.

Float is a is a 32 bit numerical value that can represent fractional components, or decimals. Double is a 64 bit numerical value that can also represent fractional decimals. They are called "floating point" types because the decimal in the numbers "floats"! While float may make more efficient usage of a computers resources, being smaller, double is the more commonly used. All Java's Math class values use and return doubles.

Promotion:

Happens automatically when operators in expressions convert their operands. If sum is a float and count is an int in the expression " sum / count ", the result is promoted to a float.

Write the output from this code and answer the "hidden" question. public class switchTest { public static void main (String args[]) { char ch1, ch2, ch3; ch1 = 'A'; ch2 = 'B'; ch3 = 'C'; switch(ch1) { case 'A': System.out.println(" Hi, I'm switch-ch1 Case A's switch"); ch2 = 'C'; switch(ch2) { case 'A': System.out.println(" Hi, I'm switch-ch2 Case A's switch"); break; case 'B': System.out.println(" Hi, I'm switch-ch2 Case B's switch"); break; default: { System.out.println(" Hi, I must be switch-ch2 default switch "); ch1 = 'B'; } } case 'B': System.out.println(" Hi, I'm switch-ch1 Case B's switch\n"); case 'C': System.out.println(" Did it get here? Why? __________ _______"); } } }

Hi, I'm switch-ch1 Case A's switch Hi, I must be switch-ch2 default switch Hi, I'm switch-ch1 Case B's switch Did it get here? Why? ____________________________ Because there was no break in switch ch1 condition statements!

A program has been written to process the scores of soccer games. Consider the following code segment, which is intended to assign an appropriate string to outcome based on the number of points scored by each of two teams. (The team with the greater number of points gains the victory!) if (team1points == team2points) outcome = "Tie game"; if (team1points > team2points) outcome = "Team 1 Rules!"; else outcome = "Team 2 Rules!"; The code does not work properly. For which of the following cases will the code assign the wrong string outcomes. The case where I. both teams score the same number of points II. Team 1 scores more points than Team 2 III. Team 2 scores more points than Team 1

I only

Given the following variable declarations: int a = 5; b = 4; double x = 5.0, y = 4.0; Which of the following expressions have the value of 1? I. (int) x / y II. a / b II. a % b

II and III only

In general, under what conditions should an if-else-if ladder rather than a switch-case series be used? Give a brief example, with code fragments, of a reason for choosing the if-else-if ladder.

In general, use an if-else-if ladder when the conditions controlling the selection process do not rely on a single value, as in the following: if (x < 10) // else if (y = 0) // else if (!done) This sequence could not be recoded into a switch because all 3 conditions involve different variables. Also, you need an if-else-if ladder when testing floating-point values of or other types not valid for a switch expression.

An object has its own copies of its class'

Instance variables.

Casting:

Is a conversion that is done explicitely by putting the desired conversion type in parenthesis in front of the value being converted. If sum and count are both ints, the following casts results in a float: " (float) sum / count"

C++ is not a secure portable language for the internet because (circle one)

It contains explicit memory pointers

Compare and contrast Java's finalize() method to destructors in C++.

Java does not have "destructors". Although the finalize() method approximates a destructor, it is not the same. In C++ the destructor is always called just before the object goes out of scope (pointers to it are severed), you can't know when finalize will be called. With Java's garbage collection, true destructors are not required.

What are Java's simple, or primitive, types? Why are they called "simple"? Name them all.

Java's basic data types are called simple because they are not objects, but rather, normal binary values. The eight primitive data types are boolean, byte, char, double, float, int, long and short

What is Java's character type, and how does it differ from the character type used by many other programming languages?

Java's character type is Unicode. Prior character types, in particular ASCII, used only 8 bits and had 128 characters. Unicode uses 16 bits and was designed to represent all the world's languages, not just English, French, German or Spanish as does ASCII.

Is the final else of an if-else if sequence required? What does it do if it's used?

No, it is not required. It is used as a default if none of the other conditions are true.

Does a short-circuit operator always evaluate both of its operands? Explain what happens for both the short-circuit AND and short-circuit OR. You must use brief examples.

No. If the first operand is sufficient to definitevly determine true/false, the second is not evaluated. For the AND short-circuit operator, if the first operand is false, then the boolean AND expression must be false and evaluation stops. For the OR short-circuit operator, if the first operand is true, then the boolean OR expression must be true and evaluation stops.

Can a byte be assigned to a char without a cast?

No. This type of narrowing must be done explicitely with a cast.

Which, if any, of the three segments of the for( initialization; condition; iteration) loop are syntactically required by Java?

None of them! See the infinite loop above.

Assignment:

Occurs when a value of one type is assigned to a variable of another, such as an int to a decimal. For example, double myNum = 100 + 5. Only this type of "widening" assignments can occur in Java.

Write the lines of code required to read multiple typed character from the keyboard?

Scanner in = new Scanner(System.in); String Hello = in.nextLine();

The central driving force behind the creation of Java was the need for (circle one)

Secure, cross-platform, portable code

E. "hello"

String

What type of variable would you use to store your name?

String

Given this output: (it is meant to be tabbed) I (tabbed once)Love (tabbed twice) Java! Using a single string, show the print( your code here); statement that produced it. Notice the tabbing!

System.out.print( "I \n \t Love \n\t\t Java")

Write a one line code snippet that calls the length() method in a println() statement on the String literal: "I love Java deeply." NO variables.

System.out.println("I love Java deeply.".length());

int x = 5, y = 9, z = 2, inside; boolean r = false, result; result = ( !r && ( (--y) > (z + x) ) );

TRUE

int x = 5, y = 9, z = 2, inside; boolean r = false, result; result = ( ( x + y ) >= ( 16 - z ) );

TRUE

int x = 5, y = 9, z = 2, inside; boolean r = false, result; result = ( 5 >= x);

TRUE

int x = 5, y = 9, z = 2, inside; boolean r = false, result; result = ( x == ( (++z) + 2 ) );

TRUE

int x = 5, y = 9, z = 2, inside; boolean r = false, result; result = (y == 9) && ( (x >= 2) || r );

TRUE

Describe where, when and how a break statement is used. Be sure to include its general use in any switch, loop or block of code with a label.

The break statement can be used to terminate the execution of any block of code, including if, switch and loop blocks. When a break is encountered, control is transferred to the end of the block. It is commonly used in switch statements at the end of each branch, because if it is not encountered, all statements after a match is found will execute. The general form of a labeled break statement is: break label:, where the label is a statement that names a block of code. When this form of break is encountered, control is transferred to the end of the labelled block. The labelled block of code must enclose the break statement, but it need not be the immediately enclosing block, but could be another that itself encloses the block with the break.

What part of a class does an object NOT have a copy of, something that all of the class' objects "share"?

The classes "code", methods.

Examine the following code: 01 class Chapter2Test 02 { 03 public static void main (String args[]) 04 { 05 int x; 06 for (x = 1; x < 2; x++) 07 { 08 int y = 1; 09 y -= x; 10 System.out.println ( y + " + " + x + " = " + y + x); 11 } 12 System.out.println ("The for loop ran " + y + " times"); 13 } 14 } What will be the last line output from this code? Circle ALL that are true

The code will not compile due to an error on line 12

What is the main difference between the do-while and while loops? Include situations when you would want to use each one.

The do-while loop tests the conditional expression at the end of the loop, while a while loop tests the conditional at the beginning of the loop. The biggest difference is that a do-while loop must execute at least once, while a while loop might not execute at all - the conditional test fails the first time. Do-while is very useful for testing valid user input: the loop is not exited until the desired input passes the final test. The while loop is best used when the loop will repeat an unknown number of times.

What are Java's simple data types? Name them all. Why are they called "simple"?

The eight primitive data types are boolean, byte, char, double, float, int, long and short Java's basic data types are called simple because they are not objects, but rather, normal binary values.

Which of the following is the best description of when the finalize()method is used? Circle ONE.

The finalize() is called by the JVM when your object is about to be collected by the garbage collector

void myMeth() { int i; for(i=0; i<10;i++) { if (i == 5) return; System.out.println(); }} Which of the following statements are True regarding the code above? (Circle more than one - Choose all correct answers)

The for loop will run from i equal 0 to 5

What is a cast? In general, when are they needed?

The genaral description is answered above, in Question 8. In addition, casts can either be widening, when a primitive type is cast as a wider primitive, as in (double) 7/14, or narrowing as in (int) (7.0 / 14.0). Narrowing casts can only be done with a cast and can result in lost data, as when an int is cast into a byte. Casts are also required to convert incompatible data types, such as a char and a byte.

A constructor is called automatically when an object is created, is usually declared public, has the same name as the class, and has no specified return type.

True

In general, when does an object become a candidate for garbage collection? What happens when an object is "eaten" by the garbage collector?

When no object reference points to an objects location in memory, as occurs when you reassign its reference to another object, it becomes a candidate for garbage collection. When the garbage collector finds such a memory location, it tells the operating system that that memory is now unused and available.

Write a code snippet to that shows yourAccount becoming a reference to the same object as myAccount in Question 6. What are these two references called?

When no object reference points to an objects location in memory, as occurs when you reassign its reference to another object, it becomes a candidate for garbage collection. When the garbage collector finds such a memory location, it tells the operating system that that memory is now unused and available.

Describe dynamic initialization? Give an example.

While variables are commonly initialized using constants (e.g. int myInt = 6), Java allows variables to be initialized dynamically, using any valid expression. An expression is any combination of variables, literals and operators. double radius = 4, height = 5; double volume = 3.1416 * radius * height;

Can a short be assigned to an int without a cast?

Yes. It can be done with a widening assignment.

Describe Polymorphism:

a programming concept expressed in the phrase, "one interface, multiple methods". Thus, a number of types of animal classes could all have a general type of method called "move". When each similarly named method is executed, the response is different (an amoeba ciliates, a snake crawls and a bird flies).

Describe Encapsulation:

a programming mechanism that binds together code and the data it manipulates into an object structure. Encapsulation keeps the code and data safe from outside interference by making specific members (variables & methods) private within the object. Public members can also be created but are generally used to provide controlled interfaces to the private members. An example is a bike class where private gear data can only be set by a "setGear" code method that checks the setting is valid.

Name the 3 general ways that data conversions can occur in Java.

assignment, promotion, casting

The expression controlling a switch statement can be of which types?

byte, short, int, char or String

Write a line of code that reads one character from the keyboard?

ch = (char) System.in.read();

A. 'x'

char

Write a program that fills a two-dimensional array with dimensions of 5 and 5 with the numbers 1 - 25 using a for loop. Don't worry about printing anything.

class arrayFill {public static void main(String args[]) { int table[][] = new int[5][5]; int intFill = 0; for (int row = 0; row < table.length; row++) { for (int col = 0; col < table[row].length; col++) { intFill ++; table[row][col] = intFill; } } } }

Write a java program that converts and prints earth weights from 1 to 200 pounds to corresponding moon weights. Print a blank line every 10 lines. Print a special line when the code reaches YOUR EARTH WEIGHT that says "I weigh ___ pounds on earth and ____ on the moon.", with YOUR weights filling in the blanks. The moon weights are about 17 percent of that on earth. Complete and correct syntax and punctuation are required. Use appropriate indentation.

class moonweight { public static void main(String args[]) { double earth, moon, myWeight; int counter; myWeight = 180; counter = 0; for(earth = 1; earth <= 200; earth++) { moon = earth * 0.17; System.out.println("Earth weight of " + earth + " pounds is " + moon + " pounds on the moon"); if (earth==myWeight) { System.out.println("I weigh " + earth + " pounds on earth and " + moon + " on the moon.");} counter++; // every 10th line, print a blank line if(counter == 10) { System.out.println(); counter = 0; // reset the line counter } } } } Answers

C. 10.2

double

What type of variable would you sue to store the square root of 2?

double

Write a code snippet to show how a method call myMath() is declared if it has a return type of double and has two int parameters called a and b. Include something "mathmagicall" that it performs with a and b.

double myMath(int a, int b) { double result = (double) a / (double) b; return result;}

In the following code segments, circle and label the argument and circle and label the parameter. class DblValue { double multByTwo( double x ) { return x * 2; } class GetDouble { public static void main(String Args)[]) { double twiceNumber; DblValue twice = new DblValue(); twiceNumber = twice.multByTwo(3.3);

double x is the Parameter 3.3 is the argument

Show a Java loop that checks for specific input from a user and won't end until that input is entered.

do{ System.out.print(" Guess the letter! Enter a letter followed by Enter: "); ch = (char) System.in.read(); } while (ch != 'q');

Why will The code will not compile due to an error on line 12?

f is correct because the reference to variable y is out of scope.

Show the for statement for a loop that counts from 1000 to 0 by -2.

for (i = 0; i <= 1000; i -= 2)

Consider the following while loop int k = 8; while (k > 0) { k = k - 2; System.out.println(k); } Which of the following for loops produces the same output as the while loop? Circle one.

for (int k = 6; k >= 0; k = k - 2) { System.out.println(k); }

Write a "for" loop that copies all the elements in: char[] arr1 = { 'x', 'y', 'z'); to the last 3 elements of char[] arr2 = new char[26]

for (int position = 0; position < arr1.length; position ++) arr2[position+24] = arr1[position];

Write a "code snippet" for a for loop that executes 10 times and does something "simple" inside the loop.

for(count = 0; count < 10; count = count+1) System.out.println("This is count: " + count);

Give a code example of if-else if code syntax (only 2 else ifs and a default "ending" required).

if(luck>10) luck=10; else if(strength>10) strength=10; else if(health>10) health=10; else System.out.println("luck strength and health are all <=10";

B. 10

int

Write a code snippet for the ternary branching operator and explain how it works. You do not have to write code that elaborates on the consequences.

int larger; larger = ((num1 > num2) ? num1 : num2); If num1 is greater than num2, then num1 is assigned to larger; otherwise, num2 is assigned to larger The conditional operator is ternary because it requires three operands: a condition and two alternative values

Write a code snippet to show how a short-circuit operator AND can be used to prevent a divide-by-zero error.

int n, d; if ( d != 0 && (n % d) == 0) // If d IS 0, the second operand will not // execute preventing a crash!

Write a code snippet that initializes an irregular two-dimensional array. Choose any dimensions that you want.

int table[][] = new int[3][]; table[0] = new int[5]; table[1] = new int[4]; table[0] = new int[3];

Show two ways to declare a one-dimensional array of 13 integers.

int x[] = new int [13]; int[] x = new int [13];

D. 100L

long

What will be printed by the following code segment boolean flag = true; int x = -1; if (flag && (x > 0) System.out.println("yes"); else if (x == 0) System.out.println("maybe"); else if (!flag) System.out.println("sometimes"); else System.out.println("no way, Jose");

no way, Jose

Describe Inheritance:

the process by which one object can acquire the properties, methods and data, of another object. Thus, we could define a general bike class with the common properties of all bikes (e.g. 2 wheels). Other bike objects could inherit this information and then add to it, for example 2 seats instead of one.

What is this referring to in the following code and why is it necessary? Include the concept of "hiding". class Pwr { double b; int e; double val; Pwr(double b, int e) { this.b = b; this.e = e; val = 1; if (e==0) return; for( ; e>0; e--) val *= b; } double get_pwr() { return val; } }

this in the method Pwr indicates that the variables b and e are the ones declared at the top of the class, and NOT the b and e used as parameters in the Pwr method. It is required because the local variables / parameters b and e "hide" the class' own b and e.

Write the "detailed" output from these lines of code (assume that they are in a complete program): int var; double x; var = 20; x = 10; var = var / 3; x = x / 4; System.out.println("var after division by 3 is: " + var); System.out.println("x after division by 4 is: " + x);

var after division by 3 is: 6 x after division by 4 is: 2.5

Show how each of the statements below can be rewritten using a shorthand assignment operator.

x = x - 2; x -= 2 x x = x + 2; x += 2 x = x * 2; x *= 2 x = x % 2 x %= 2

Show how this sequence can be rewritten using the? operator. if(x < 0) y = 10; else y = 20;

y = x < 0 ? 10 : 20;


Conjuntos de estudio relacionados

Megaquest, Ultraquest, Hyperquest, Black Hole Quest, Fortnite, D&D, and more internet games ban. [Part 2 - Chameleon Master Roller Jonathan Gets Sent To Hell - Scenes 41-76]

View Set

Final Exam for Clinical Chemistry (Quiz 6,7 and 8)

View Set

Community Nursing Ch. 15: Emerging Infectious Diseases

View Set

Chapter 5 - Receivables and Sales, Ch 4: Cash and Internal Controls, CHAPTER 6: Cost of Goods Sold, ACC 210 E2

View Set

***HURST Review Elevate Q-Cards***

View Set

6 - Java OCA 8 - Array, ArrayList, String, StringBuilder, Lambda, and Date

View Set