Final Exam: Fundamentals of Computer Science

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

How do you use the dot operator to access an element within a class?

<class name>.<element>

When you try to print the name of an array, what is the value returned? (Hint: it is not the values in the array)? What method allows you to print the contents of the array?

<class name>@<object's hash code> The method Arrays.toString

What is the general syntax for creating an array? Give an example of an array holding 10 first names?

<element type>[] <name> = new <element type>[<length>]; String[] names = new String[10];

Why is assigning a double to an int a problem? How can we avoid this issue?

A variable can only store a value of its own type. We can avoid this issue by finding ways around it,, like type in 11.0/2.0 and getting 5.5 rather than just typing in 11/2 and getting 5

Describe what an abstract method is. What is an abstract class?

Abstract method - a method that is declared (as in an interface) but not implemented. Abstract methods represent the behavior that a class promises to implement when it implements an interface. Abstract class - a Java class that cannot be instantiated, but that instead serves as a superclass to hold common code and declare abstract behavior.

What is an Array actually made of in Java? Why can't you use the == operator to compare array contents?

An array is formed by arranging a set of objects into rows and columns. In order to compare String values, you must make a call on the equals method rather than using a simple == comparison. Only takes the reference, not the values. Arrays.equals

Describe the difference between an int and an Integer.

An int is a primitive type, not an object. An Integer is an object with only one field: an int value.

Describe the instance of a keyword and how it helps with passed objects.

An operator called instanceof tests whether a variable refers to an object of a given type. An instanceof test is a binary expression that takes the following form (<expression> instanceof <type>) and produces a Boolean result. The instanceof keyword can help with passed objects by: by changing our equals method's parameter to type Object, we have allowed objects that are not from that class to be passed. The method still does not behave properly when clients pass these objects, but with the instanceof keyword, it tests whether a variable refers to an object of a given type, so it will not produce an exception (if the code is written correctly).

Why is testing arrays for equality more challenging? What method simplifies this task?

Arrays are objects. Arrays.equals method

Describe what boxing and unboxing are. How do they relate to a wrapper class?

Boxing - an automatic conversion from primitive data to a wrapped object of the appropriate type (an int boxed to form an Integer). Unboxing - an automatic conversion from a wrapped object to its corresponding primitive data (an Integer unboxed to yield an int). Because Java has boxing and unboxing, the only place you generally need to use the wrapper class is when you describe a type like ArrayList<Integer>. Primitive Type: int - Wrapper Class : Integer Primitive Type: double - Wrapper Class: Double Primitive Type: char - Wrapper Class: Character Primitive Type: boolean - Wrapper Class: Boolean

Give an example of boxing and unboxing.

Boxing Example - an int boxed to form an Integer Unboxing Example - an Integer unboxed to yield an int

Give 3 reasons why 'C' is different from "C"?

Char is primitive while string is an object. Char uses up 2 bytes of memory while a string uses up memory depending on length. Char has exactly 1 letter while a string can have 0 to many.

What are two of the advantages of encapsulation?

Class invariants and making internal design changes to a class without impacting its clients.

What object is required to read from / write to a file? How do you create one to read from a file?

File object File f = new File("file name");

What is the difference between a binary and a text file? (They are both stored in binary, so wouldn't they be the same?)

Files can be classified into text files and binary filed depending on the format that is used. Text files can be edited using simple text editors. Binary files are stored using an internal format that requires special software to process.

Give an example of a use for a wrapper class.

For example, consider simple integers, which are of type int, a primitive type. Primitive types are not objects, so we can't use values of type int in an object context. To allow such use, we must wrap up each int into an object of type Integer. Integer objects are very simple because they have just one field: an int value. When we construct an Integer, we pass an int value to be wrapped; when we want to get the int back, we call a method called intValue that returns the int.

Give an example of a superclass and a subclass. What keyword allows a superclass to become a subclass?

In real life, a parent could be an example of a superclass and a child could be an example of a subclass since the child (subclass) inherits various attributes from the parent (superclass).

Give an example of the usage of a min or max loop.

Initialize max for (all numbers to examine) { obtain "next"; if (next > max) { max = next; } }

What is the input cursor? Explain the concept of consuming input.

Input Cursor - a pointer to the current position in an input file. Consuming Input - moving the input cursor forward past some input. This process doesn't actually change the file, it just changes the corresponding Scanner object so that it is positioned at a different point in the file.

What is a robust program? How can the Scanner Lookahead help with robustness?

It is a program that can deal with user errors. (Robust is the ability of a program to execute even when presented with illegal data). It allows you to look before you leap

What must be true about the type of elements in the list in order to sort it?

It must implement Comparable (for example, you can use Collections.sort to sort an ArrayList<String> but not to sort an ArrayList<Point> because the Point class doesn't implement Comparable.

What is the point class? What package is required to use it?

It represents a location in a two-dimensional (x,y) coordinate space. The java.awt package is required to use it.

How does a scanner treat an input file? How do you use Java to tell when you are at the end of the file?

It treats an input file the same way it treats user input. Scanner.hasNextLine();

Why can a program read the wrong token?

It's easy to write code that accidentally reads the wrong kind of data. Suppose the input file has some extraneous text in it. The first line of the file would contain 3 numbers that the program will read properly, but when it attempts to read a fourth number, the computer finds that the next token in the file is text "hello". This token cannot be interpreted as a double, so the program generates an exception.

Are constructors inherited? Why or Why Not?

No because constructors are special and have the same name as the class name. So if constructors were inherited in the child class, then the child class would contain a parent class constructor which is against the constraint that a constructor should have the same name as a class name. If we define a parent class constructor inside of a child class, it will give a compile time error for return type and consider it a method. A constructor can't be called as a method because it is called when the object of the class is created. A parent class constructor is not inherited in a child class which is why super() is added automatically in a child class constructor if there is no explicit call to "super" or "this".

What are De Morgan's laws?

Original Expression: P || Q Negated Expression: !(P || Q) Simplified Expression: !P && !Q Original Expression: P && Q Negated Expression: !(P && Q) Simplified Expression: !P && !Q

Define precondition. Define postcondition.

Precondition - a condition that must be true before a method executes in order to guarantee that the method can perform its task. Postcondition - a condition that the method guarantees will be true after it finishes executing, as long as the preconditions were true before the method was called.

What is PrintStream used for? Give an example.

PrintStream is used for: it lets you print output to a destination such as a file. Example: PrintStream output = new PrintStream(new File("out.txt")); output.println("Hello, file!"); output.println("This is a second line of output.");

What is a private field? What is a public method? Why do we use public methods to access private variables, when a public field would be less complicated?

Private field - only accessible inside the class they are declared or inside inner classes; it encapsulates the fields of an object. Public method - a method which can be called by any object. Using encapsulation, we'll put a casing around our Point objects so that clients will only need to use the objects' method and will not access the fields directly.

Why did Java choose to use reference semantics for objects?

Reference semantics allows you to have many references to a single object, which allows different parts of your program to share a certain object.

What is Sequential Access? What is Random Access? Which is required for streams and files? Which is possible with arrays?

Sequential Access - manipulating values in a sequential manner from first to last Random Access - manipulating values in any order whatsoever to allow quick access to each value Sequential Access is required for files and streams Which is possible with arrays: random access

Java can have multiple constructors, how does Java tell which one you are calling? What term describes this reuse of constructor names to do different operations?

Signature Parameter counts and types overloading

What would happen if you put a statement after the return in a function in a method?

Statement is never executed

What is the common error with string and array indexing? Why does the error occur?

String Index Out of Bounds. This error occurs when the user forgets that the last index of a String of length n is actually n - 1.

Using your example from the 10 name string, provide the code to store "Jim" in the last index and store "Kelli" in the first index.

String[] fNames = new String[10]; fNames[0] = "Kelli"; fNames[9] = "Jim";

Describe what the diamond operator is. Why is it useful?

The "diamond operator" is a new shorter syntax for declaring collections whereby the element type may be omitted on the right side of the statement and replaced by <>, such as: ArrayList<String> list = new ArrayList<>(); The diamond operator syntax is shorter and more convenient, and its behavior is identical to that of the longer code.

When using the compareTo methods, what do the values 15, 0, and -15 represent?

The -15 and 15 represent the distance between the positions of the characters. The second character appears 15 positions later than the first character. A negative number to indicate a less than relationship 0 to indicate equality A positive number to indicate a greater-than relationship

Why does the == not work for string objects? What should you use for equality of strings?

The == operator only compares object references. Every Java object has a method called equals that takes another object as an argument. You can use this method to ask an object whether it equals another object

Describe the equals method and how it differs from ==?

The == operator tests whether two objects have the same identity and whether two variables refer to the same object, not whether two distinct objects have the same state. We use the equals method to find out whether the objects have the same state. Every Java object contains an equals method that it uses to compare itself to other objects

What is the Java Array Class, and what package does it belong to?

The Java Array Class provides many methods that make it easier to work with arrays The Arrays class is part of the java.util package, so you would have to import it.

What is the difference between the file YourProgram.java and the file YourProgram.class?

The Java programs that you create must use the extension .java. When you compile a Java program, the resulting Java bytecodes are stored in a file with the same name and the extension .class.

If you NOT a logical operator, what is the resulting logical operator? (Ex. !(x<4 && x>2))? Explain.

The NOT operator (!) reverses the truth value to its operand. If an expression evaluates to true, its negation evaluates to false and vice versa.

Describe the controversy with boxing and unboxing.

The ability to manipulate an ArrayList<Integer> almost as if it were an ArrayList<int> can simplify code, and everyone agrees that simplification is good. The disagreement comes from the fact that it is almost like an ArrayList<int>. Some argue that "almost" isn't good enough. Because it comes close, programmers are likely to use it and eventually come to count on it. That can prove troublesome when "almost" isn't "always".

What happens when your code reads beyond the End of File?

The computer will try to read a word when there is no word to read. Java throws an exception when this occurs.

What is the advantage of a "do while" loop versus a standard while loop?

The do/while loop always executes its controlled statements at least once. The do/while loop is most useful in situations in which you know you have to execute the loop at least once. With a do/while loop, we can eliminate the priming. They are useful in interactive programs where you know you want to do something at least once.

What is the difference between a for-each loop and a for loop you used previously? Why is this an advantage?

The for-each loop is known as the enhanced for loop. You can use it whenever you want to examine each value in an array. The basic syntax of the for-each loop is: for(<type> <name> : <array>) { <statement>; <statement>; ... <statement>; } The for-each loop is most useful when you simply want to examine each value in sequence. For-each loops: efficient in all cases because it use Iterator specific for the collection, works not only with every Collection but with every Iterable since Iterable#iterator() is used, and it is more robust (less code, fewer special characters).

Describe how to arrange an ArrayList into sorted order.

The method Collections.sort can be used to sort an ArrayList, which sorts it in ascending order by default.

When working with files, why can you not assume the file can be read? How do you check on the file in Java?

The programs we have studied so far assume that the user will provide a legal file name. If the user does not input a legal file name, you can keep prompting until the user

What are the elements required when creating a class?

The state stored in each object, the behavior each object can perform, and how to construct objects of that type.

What method makes it easier to change values between two array indexes?

The swap method

What is the purpose of the throws clause?

The throws clause is a declaration that a method will not attempt to handle a particular type of exception

When drawing an image, what do the x,y coordinates represent?

The x and y coordinates passed when drawing the image represent its top/left corner pixel position

When creating an array of point objects, what would the auto-initializer set the values to? What is this value's meaning?

The zero-equivalent for the type. The zero-equivalent for all reference types is the special value null, which indicates "no object".

Why does redeclaring variables in a constructor not produce a compilation error?

They are in a different scope in the constructor method

Describe how to interpret inherited polymorphic code.

To determine the output of a polymorphic program, you must determine what happens when each element is printed and when its method1 method2 methods are called. You can draw a diagram of the classes and their methods to see the hierarchy ordering and see which methods exist in each class. Draw each class as a box listing its methods, and connect subclasses to their superclasses with arrows. A good second step is to write a table that lists each class and its methods' output. Write the output not just for the methods defined in each class, but for the ones that the class inherits, as well. Since the A class is at the top of the hierarchy, that is where we will begin in our example explanation. When someone calls method1 on an A object, the resulting output is "A 1". When someone calls method2 on an A object, the resulting output is "A 2". When someone prints an A object with toString, the resulting output is "A". The next layer in the hierarchy is the B class, which inherits all the behavior from A, except that it overrides the method2 output to be "B 2". That means that the output will be identical to the A output, except that you replace "A" with "B". The C class also inherits all the behavior from A, but it overrides the method1 output to be "C 1" and it overrides the toString method to be "C" and the method2 output to be "C 2". Once you have created a table with all of the values (leftmost column is toString, method1, and method2; and the rightmost column is first marked A, B, or C, and then "A" for toString, "A 1" for method1, "A 2" for method2, along with all of the variations concerning B and C), you can find the output of the client code. The array contains an A object, a B object, and a C object. For each of these it prints the toString output, then calls method1, then calls method2, then prints a blank line. When a method gets called on an object, you can look up the output of that method for that type in the table.

What does it mean to be a unary operator? What does it mean to be a binary operator?

Unary Operator - an operator that takes a single operand/argument (a single input) and performs an operation Binary Operator - an operator that operates on 2 operands and manipulates them to return a result

Explain how to access inherited fields. Why the complexity?

Use accessor or mutator methods associated with our fields to access or change their values. The reason Java is built this way is to prevent a subclass from violating the encapsulation of the superclass. If a superclass object held sensitive data and subclasses were allowed to access that data directly, they could change it in malicious ways the superclass did not intend.

What does factoring do for you if/else statements? How is it similar to mathematics factoring?

Using this simple technique (factoring), you factor out common pieces of code from the different branches of the if/else construct. Factoring in mathematics is like splitting an expression into a multiplication of simpler expressions

Describe the values semantics of an array? Describe the reference semantics of an array? Why do they cause confusion?

Values Semantics - a system in which values are stored directly and copying is achieved by creating independent copies of values. Types that use value semantics are called value types. Reference Semantics - a system in which references to values are stored and copying is achieved by copying these references. Types that use reference semantics are called reference types. They cause confusion because it can be hard to remember is that when you are working with objects, you are always working with references to data rather than the data itself.

Define variable. Define declaration. Define initialization.

Variable - a memory location with a name and a type that stores a value Declaration - a request to set aside a new variable with a given name and type Initialization - specifying a specific initial value to assign it

How is Graphics2D an example of inheritance? What methods were added in the subclass?

When Java's designers wanted additional graphical functionality, they extended the Graphics class into a more powerful class called Graphics2D. This is a good example of one of the more common uses of inheritance: to extend and reuse functionality from a powerful existing object. rotate(angle) - rotates subsequently drawn items by the given angle in radians with respect to the origin scale(sx, sy) - adjusts the size of any subsequently drawn items by the given factors (1.0 means equal size) shear(shx, shy) - gives a slant to any subsequently drawn items translate(dx, dy) - shifts the origin by (dx, dy) in the current coordinate system

What is required when you negate a Boolean expression? What is the result of NOT((A>B) && (C <= D))?

When negating a Boolean expression, you must put ! before the expression and put the expression in parenthesis. A <= B || C > D

What is the purpose of casting a variable? Give an example of casting.

When you want Java to convert a double into an int, you ask Java for this conversion with a cast. You request a cast by putting the name of the type you want to cast to in parentheses in front of the value you want to cast. (int) 4.75 will produce the int value 4

In what cases should you use an ArrayList rather than an array?

You should use an ArrayList instead of an array when you do not know the exact length of the list, since arrays are of fixed length and you cannot change them once they are created. You should use an ArrayList instead of an array when elements need to be inserted at or deleted from a particular position. You should use an ArrayList instead of an array when you need to use the ArrayList methods to manipulate the stored objects.

What does "this" in Java allow you to do? Give an example.

a Java keyword that allows you tp refer to the implicit parameter inside a class. With "this", you can access a certain reference in your code. The compiler converts an expression such as x to this.x. this.<field name> this.<method name>(<expression>, <expression>, ... , <expression>); You can use "this" to deal with shadowed variables

Define primitive data type. Give an example of a primitive data type.

a basic building block provided by a programming language Boolean

Describe what a Generic Class is. How would you use a Generic Class like ArrayList?

a class such as ArrayList<E> that takes a type parameter to indicate what kind of values it will use. Generic classes are similar to parameterized methods. You can use a parameter to define a family of related tasks that differ just by a particular characteristic like height or width. In this case, the parameter is a type and it is used to declare another type. The type ArrayList<E> represents a family of types that differ just by the type of element they store. You would use ArrayList<String> to store a list of String, ArrayList<Point> to store a list of Points, ArrayList<Color> to store a list of Colors, and so on.

Describe what a wrapper class is. Why is it useful?

a class that "wraps" (stores) primitive data as an object. It is useful because it makes handling primitive data more convenient and when we want to interact with the primitive data, we access the class.

Describe what an ArrayList is. What package does ArrayList belong to?

a class that enables us to specify certain operations to be performed (add, remove) without having to worry about the details of how those operations are performed (shifting, constructing new arrays). ArrayList belongs to the java.util package

Describe what Has-A Relationship is. Give an example.

a connection between two objects where one has a field that refers to the other. The contained object acts as part of the containing object's state. Example: Consider the task of writing a Circle class, in which each Circle object is specified by a center point and a radius. A point does make up a fundamental part of the state of each Circle object. You can have each Circle object hold a Point object in a field to represent its center.

What is a file path? Give an example on your computer.

a description of a file's location on a computer, starting with a drive and including the path from the root directory to the directory where the file is stored. C:\Users\mmhav\Downloads\W7ChapterAssignment.docx

Define formal verification.

a field of computer science that involves reasoning about the formal properties of programs to prove the correctness of a program

Describe what an "is-a" relationship is. Give an example.

a hierarchical connection between two categories in which one type is a specialized version of the other Example: a legal secretary can also fill the roles of a secretary and an employee

What is an instance method? Give an example.

a method inside an object that operates on that object. An example is a String object has a length method and a Scanner object has a nextInt method

Define class constant. What keyword defines a class constant in Java?

a named value that cannot be changed and can be accessed anywhere in the class final

Define object. Give an example.

a programming entity that contains state (data) and behavior (methods). An example of an object is a radio.

Describe inheritance in OO Programming.

a programming technique that allows a derived class to extend the functionality of a base class, inheriting all of its state and behavior

Define behavior. Give an example.

a set of actions an object can perform, often reporting or modifying its internal state. The behavior of a radio is that it produces sound when it is turned on and the volume is turned up. There are actions that you can perform on a radio that manipulate its internal state. We can turn a radio on or off, and we can change the station or volume, and can also check what station the radio is set to at any given moment. We call the collection of these operations the behavior of an object

Describe what an inheritance hierarchy is? Give an example.

a set of hierarchical relationships between classes of objects Example: each group of employees in our example is analogous to a class in programming. The different employee groups represent a set of related classes connected by is-a relationships. We call such a set of classes an inheritance hierarchy.

Define state. Give an example.

a set of values (internal data) stored in an object. A radio can be in different states. It can be turned on or turned off. It can be tuned to one of many different stations, and it can be set to one of many different volumes.

Describe what an interface is. What are the benefits of interfaces?

a type that consists of a set of method declarations; when classes promise to implement an interface, you can treat those classes similarly in your code. We can use interfaces to achieve polymorphism. We can create an array of Shapes, pass a Shape as a parameter to a method, return a Shape from a method, and so on. It would be fairly easy to modify our client program if another shape class, such as Hexagon or Ellipse, were added to the hierarchy. This is another example of the desired property of "additive, not invasive" change. Interfaces help us cope with the limitations of single inheritance. Many classes in the Java class libraries both extend a superclass and implement one or more interfaces. The ActionListener interface in the java.awt package is used to assign behavior to events when a user clicks on a button or other graphical control. The Serializable interface in the java.io package denotes classes whose objects may be saved to files and transferred over a network. The Formattable interface lets objects describe different ways that they can be printed by the System.out.printf command. The Runnable interface is used for multithreading, which allows a program to execute two pieces of code at the same time. Interfaces such as List, Set, Map, and Iterator in the java.util package describe data structures that you can use to store collections of objects.

Define field. Give an example.

a variable inside an object that makes up part of its internal state. In a class representing an employee, the Employee might contain the field <name>.

Describe what a comparison function is.

a well-defined procedure for deciding, given a pair of values, the relative order of the two values (less than, equal to, or greater than).

What is a class invariant? Why would you want to use one?

an assertion about an object's state that is true for the lifetime of that object Invariants bring to light the importance of proper encapsulation. If a certain class weren't encapsulated, we wouldn't be able to properly enforce our invariant. A buggy or malicious client would be able to make a certain object's state invalid by setting its fields' values directly. When the class is encapsulated, it has much better control over how clients can use its objects, making it impossible for a misguided client program to violate the class invariant

What is a checked exception? How does it differ from previous exceptions?

an exception that must be caught or specifically declared in the header of the method that might generate it. A checked exception is different than previous exceptions because you can't just ignore it. Java provides a construct known as the try/catch statement for handling such errors, but it allows you to avoid handling this error as long as you clearly indicate the fact that you aren't handling it. All you have to do is include a throws clause in the header for the main method to clearly state the fact that your main method might generate this exception.

Define array. Why must they hold data of the same type?

an indexed structure that holds multiple values of the same type. Arrays must hold data of the same type because the sizes must remain consistent.

What is a mutator? Give an example.

an instance method that modifies the object's internal state. An example is that, going back to the radio example we used earlier, the mutators would be the switches and knobs that turn the radio on and off or change the station or volume.

What is an accessor? Give an example.

an instance method that provides information about the state of an object without modifying it. Using our radio analogy, an accessor might return the current station or volume.

Define index. What is the starting index of arrays in Java? What is the last index?

an integer indicating the position of a particular value in a data structure The starting index of arrays in Java is 0 The last index is (list.length - 1)

Describe what a comparable interface is. Which one is used for sorting an ArrayList?

an interface mainly used to sort the arrays (or lists) of custom objects. Lists and arrays of objects that implement Comparable interface can be sorted automatically by Collections.sort and Arrays.sort. Java has a convention for indicating the natural ordering of a type. Any type that has such an ordering should implement the Comparable interface: public interface Comparable<Type> { public int compareTo(other Type); } The interface has only one method within it: compareTo To sort an ArrayList, we call the Collections.sort(arraylist) method.

What is an immutable object? Are strings immutable?

an object whose value cannot be changed yes

Describe what refactoring is. How is it related to Object-Oriented Design?

changing a program's internal structure without modifying its external behavior to improve simplicity, readability, maintainability, extensibility, performance, etc. The process of Object-Oriented Design involves knowing what classes of objects to write, what behavior the client wants each of the objects to have, what data the objects need to store in order to implement the behavior, and whether the classes are related (if so, know the nature of the relationships), which relates to refactoring because refactoring focuses on a program's internal structure, similar to OOD, while not modifying the external behavior. OOD is modeling a program as a collection of cooperating objects, implemented as a set of classes, while refactoring changes the program's internal structure. The practice of redesigning code to meet new requirements is sometimes called refactoring.

Describe what a client code is. Give an example.

code that interacts with a class or objects of that class. An example is code calling the object methods from the main driver

Explain what boilerplate code is? How is it useful? Give an example.

code that tends to be the same from one program to another. It is useful because it is the code for opening a file, it is fairly standard and could be used without modification in many programs. The getInput method is a good example of the kind of boilerplate code that you might use in may different file-processing programs.

Define abstraction. Give an example.

focusing on essential properties rather than inner details. A radio has a case or chassis that houses all of the electronics so that we don't see them from the outside. Dials, buttons, and displays on the case allow us to manipulate the radio without having to deal with all of the circuitry that makes it work.

Define encapsulation. Give an example.

hiding the implementation details of an object from the clients of the object. Recall the analogy of radios as objects. Almost everyone knows how to use a radio, but few people know how to build a radio or understand how the circuitry inside a radio works.

Explain the concept of priming the loop.

initializing variables before a loop to "prime the pump" and guarantee that the loop is entered

Give an example of a use of an Integer and an int.

int x = 38; Integer y = new Integer(38);

What package is required for file operations?

java.io.*;

What package does the random class belong to?

java.util package

What is the method required for running Java programs? What happens when the program doesn't terminate?

main a runtime error

What are pseudorandom numbers? Why can they not truly be random?

numbers that, although they are derived from predictable and well-defined algorithms, mimic the properties of numbers chosen at random. They are pseudorandom because they are produced algorithmically.

What is the off-by-one bug?

occurs when a loop performs an extra iteration and tries to make a reference to an array element that doesn't exist

What is a buffer overrun? Why is it a security problem?

occurs when a program writes data beyond the bounds of the buffer that is set aside for that data. It is a security problem because already written code can be overwritten.

How do you use the magenta color constant in Java?

panel.setBackground(Color.MAGENTA)

Define array traversal. Do you always have to start at index 0?

processing each array element sequentially from the first to the last Yes, you always have to start at index 0

Define token-based processing. What token is at the end of a string?

processing input token by token (one word at a time or one number at a time). Null token

Define Object-Oriented Programming.

reasoning about a program as a set of objects rather than as a set of actions

What is the Object Class (Not the object of a class)? What method of this class do you find most interesting and why?

serves as the ultimate superclass for all other Java classes, even those that do not declare explicit superclasses in their headers. I think that the most useful method of this class is the equals(obj) method because it indicates whether the other object is equal to the one which is specified.

What keyword allows you to call the method in the superclass that has been overridden?

super

What is polymorphism? Give an example.

the ability for the same code to be used with several different types of objects and for the code to behave differently depending on the actual type of object used Example: With the employee class hierarchy described earlier, it is possible for client code to create an array or other data structure that contains both lawyers and legal secretaries, and then perform operations on each element of that array.

Describe what Substitutability is. Why is it important?

the ability of an object of a subclass to be used successfully anywhere an object of the superclass is expected. Substitutability is important because it is the principle which does not allow, for example, Point3D to extend Point because any code that asks for a Point object should be able to work correctly with a Point3D object, as well.

What is an instance of a class?

the created objects of the class because one class can be used to construct many objects.

Define auto-initialization. What value in Java is used for an integer? What value in Java is used for a char?

the initialization of variables to a default value, such as on an array's elements when it is constructed 0 is the value used in Java for an integer '\0' is the value used in Java for a char

Define implicit parameter. Give an example.

the object that is referenced during an instance method call. In the code: Point p1 = new Point(); p1.x = 7; p1.y = 2; Point p2 = new Point(); p2.x = 4; p2.y = 3; The implicit parameter is p1's object.

Define natural ordering. How do you define a natural ordering for a class you've written?

the order imposed on a type by its comparison function (the ArrayList type does not have a natural ordering) Any type that has a natural ordering should implement the Comparable interface because it is used to provide natural order of sorting to objects (numeric order is a natural order for numbers, alphabetic order is a natural order for String, and chronological order is a natural order for dates). When you define your own objects, sorting it on name sounds natural.

What is line-based processing? How is it the same as token-based processing? What makes it different?

the practice of processing input line by line (reading in entire lines of input at a time). Similar: they both take things one at a time (one line at a time for line-based processing and one token at a time for token-based processing) Different: when you read a file token by token, you lose the spacing within the line because the Scanner skips any leading whitespace when it reads a token. Spacing (such as a specific indentation) would be lost if a fie containing it was read as a series of tokens. (different tokens .. CRLF is end of line token)

Describe what code reuse is? What are its advantages? What could be a disadvantage?

the practice of writing program code once and using it in many contexts. Advantages: a coder could be more confident in their code if they know that it can successfully run due to prior knowledge, it can be faster than doing research or asking peers for assistance Disadvantages: it is easy to write disorganized and redundant code (maintenance of such code was likely to take a long time and to introduce new bugs into the system); user interfaces in graphical systems were much more sophisticated than the text interfaces that preceded them and the original graphical programs were prone to redundancy because they had to describe in detail how to implement buttons, text boxes, and other onscreen components; the graphical components themselves contained a lot of common states and behavior, such as particular sizes, shapes, colors, positions, or scrollbars.

Describe what an override is. How is it different than overloading?

to implement a new version of a method to replace code that would otherwise have been inherited from a superclass Overloading occurs when one class contains multiple methods that have the same name but different parameter signatures. Overriding occurs when a subclass substitutes its own version of an otherwise inherited method that uses exactly the same name and the same parameters.

Evaluate the example expression. Give the intermediate values from each operator and explain the result.

(2 * 2) + (3 * 3) + 1 (4) + (9) + 1 (13) + 1 14 I did (2 * 2) first because it was in parentheses and the first from left to right, I got 4. Second, I did (3 * 3) because it was in parenthesis and it was the second from left to right, I got 9. Then I did 4 + 9 + 1 and got 13 + 1, which is 14.

What is an escape sequence, and why is it necessary? Give an example of an escape sequence.

2 character sequences used to represent special characters which would not work otherwise \t for tab character

Define assertion. Define provable assertion.

Assertion - a declarative sentence that is either true or false Provable Assertion - an assertion that can be proven to be true at a particular point in program execution

Define class. Define method. Define statement. How are classes, method, and statements related?

Class - a unit of code that is the basic building block of Java programs Method - a program unit that represents a particular action or computation Statement - an executable snippet of code that represents a complete command A Java program is stored in a class. Within a class, there are methods. Within a method, there is a series of statements.

Define digital. Define discrete.

Digital - based on numbers that increase in discrete increments, such as the integers 0,1,2,3,etc. Discrete - individually separate and distinct

What is the difference between draw and fill? Why is it misunderstood?

Draw only outlines, while Fill actually gives the shape its specified color and overall look. Some new programmers think that a shape (such as with drawRect) before it can be filled (such as with fillRect). This is not the case.

Give an example of a file. In your example, what is the file extension, and what application uses that extension to read the file?

For example, if you were to download the text of Hamlet from the Gutenberg site, you might store it on your computer in a file called hamlet.txt. In this example, the file extension if .txt (a text file) Notepad or Avast Secure Browser is an application you use for the extension.

Define formal parameter. Define actual parameter. How are they related?

Formal Parameter - a variable that appears inside parentheses in the header of a method that is used to generalize the method's behavior Actual Parameter - a specific value or expression that appears inside parentheses in a method call Computer scientists use the word "parameter" broadly to mean both what appears in the method header (formal parameter) and what appears in the method call (actual parameter)

Why would you want a static method for error handling?

If the user types something other than an integer, the Scanner will throw an exception.

What are the 2 ways to provide comments in your code? Explain the difference.

In the first way, open the comment with a slash followed by an asterisk and close it with an asterisk followed by a slash. In the second way, use two consecutive slashes to indicate that everything to the right of the slashes is a comment

What is the difference between an indefinite loop and a definite loop?

Indefinite Loop - is executed until some condition is satisfied and the number of times it is going to execute is not known in advance Definite Loop - a loop in which the number of times it is going to execute is known in advance before entering the loop

What would or would not happen if you ignore the return value from a method?

It is legal (but unwise) to simply call the method and ignore the value being returned from it. It does not print or have any noticeable effect.

What is a Boolean flag? When are they typically used?

It is used as a signal in programming to let the program know that a certain condition has been met. Typically we use flags within loops to record error conditions or to signal completion.

What is the difference between print and println?

Java has a variation of the println command called print that allows you to produce output on the current line without going to a new line of output. The println command does 2 different things: sends output to the current line and then moves to the beginning of a new line. The print command only sends output to the current line. Thus, a series of print commands will generate output all on the same line. Only a println command will complete the current line and start a new line.

What is the purpose of the AWT? What package must you import to utilize the AWT?

Java's original graphical tools were collectively known as the Abstract Window Toolkit (AWT). They are used to create graphical user interface (GUI) objects, such as buttons, scroll bars, and windows. import java.awt;

How do you use the dot operator to call a method within a class?

The dot operator, also known as separator or period used to separate a variable or method from a reference variable. Only static variables or methods can be accessed using class name. Code that is outside of the class of the object require the use of an object reference or expression, which is then followed by a simple field name. <class name>.<element>

Char data types are stored as integers in the computer, so what is the integer (Unicode) value of 'A'? How can you find out the integer value of a char using Java?

The integer value of 'A' is 65. You can find out the integer value using Java by having Java automatically convert a value of type char into an int whenever it is expecting an int. Int letter = 'a' + 2; // stores 99

What are the purposes of the increment and decrement operators? Give an example of an increment operator and a decrement operator using the variable count.

The operators are necessary because they are useful for a particular family of programming, incrementing (increasing the value of a variable by a particular amount) and decrementing (decreasing the value of a variable by a particular amount) count++; count--;

What is the concatenation operator in Java? Give an example using the operator with string1 and string2.

The string concatenation operator in Java is +. System.out.println(string1 + string2 + " are both examples of strings.");

How does Java handle mixed-type operations? Give an example of a mixed operation.

You can declare multiple variable all of the same type, and you can initialize them at the same time. Java even allows you to mix initializing and not initializing. When a mixed type operation occurs, Java will convert the less complex variable into the more complex one, such as from an int to a double. 3 * 4.6, in which 3 would be converted to 3.0, and for which the result would be 13.8

Give an example of the usage of a cumulative if.

You start by initializing the counter to 0: int negatives = 0; if (next < 0) { negatives++; }

Define class. How is a class related to an object?

a category or type of object a class is like a blueprint of what the object looks like

Define file.

a collection of information that is stored on a computer and assigned a particular name

Define package. What is used to request access to a Java package?

a collection of related Java classes an import declaration

Define method call. How would you call the example static method?

a command to execute another method, which causes all the statements inside that method to be executed public class DrawBoxes2 { public static void main(String[] args) { drawBox(); System.out.println(); drawBox(); } public static void drawBox() { System.out.println("+------+"); System.out.println("| |"); System.out.println("| |"); System.out.println("+------+"); } }

Define program. Give an example of a program you use in life.

a list of instructions to be executed by a computer a video game

Define sentinel loop. Give an example of the sentinel used to stop a car traveling on a road.

a loop that continues to process data until it reaches a special value that signals the end The sentinel would be a stop sign.

Define infinite loop. What is a common cause of an infinite loop?

a loop that never terminates A common cause of an infinite loop is that the exit condition may never become true.

Define data type. How is Java considered a type-safe language?

a name for a category of data values that are all related it requires you to be explicit about what kind of information you intend to manipulate and it guarantees that you manipulate

Define identifier. Give an example of an identifier.

a name given to an entity in a program, like a class or method numStudents

Define static method. Give an example of a static method.

a named group of Java statements public static void drawBox() { System.out.println("+------+"); System.out.println("| |"); System.out.println("| |"); System.out.println("+------+"); }

Define binary. Why do we use it for coding?

a number composed of just 0s and 1s When making computers, using it was easier and caused less confusion

Define round-off error. Why does it cause problems with comparisons and equalities?

a numerical error that occurs because floating-point numbers are stored as approximations rather than as exact value Roundoff errors are generally small and can occur in either direction (slightly high or slightly low). Each time through the loop, the error is compounded, which is why the roundoff error gets worse each time. Don't expect to be able to compare variables of type double for equality. The test would evaluate to false because the values are very close, but not close enough for Java to consider them equal. We rarely use a test for exact equality when we work with doubles.

Define fence post algorithm. Give an example of a fence post algorithm using an 'if' for the game duck duck goose

a particular kind of loop involved with a common programming problem known as the "loop and a half" problem-where we want to execute one half of this loop one additional time. Public static void birdGame(String duck, String goose, int times) { System.out.print("["); For (int I = 1; I <= times; i++) { System.out.print(duck); If (I < times) { System.out.print(", "); } System.out.println(goose); } System.out.println("]"); }

Define the char data type. Give an example of a char usage.

a primitive data type that represents a single character of text. An example: char ch = 'A';

Define compiler. What does the Java compiler do?

a program that translates a computer program written in one language into an equivalent program in another language (usually translating from a high-level language into machine language) The Java compiler transforms code into bytecode

Define object. Give an example of an object containing a method and a data item.

a programming entity that contains state (data) and behavior (methods) in real life, a car is an object. It has attributes (data items), such as weight and color, and methods, such as drive and brake

Define exception. What happens when an exception is not handled?

a runtime error that prevents a program from continuing its normal execution When an exception is thrown, Java looks to see if you have written code to handle it. If not, program execution is halted and you will see what is known as a stack trace or back trace.

Define String literal. What must it be enclosed in?

a sequence of characters which must be enclosed in quotation marks

Define expression. Give an example of an expression.

a simple value or a set of operations that produces a value (2 * 2) + (3 * 3) + 1

Define token. What is used to separate tokens?

a single element of input (one word, one number) whitespace

Define pixel.

a single small dot on a computer screen

Define constructor. Give an example of a call of a constructor for the Scanner object.

a special syntax used to create and initialize an object to construct a specific Scanner object, you have to pass information about the source of input; in particular, you have to provide an input stream

Define control structure. What is the purpose of a control structure? Give an example of a control structure.

a syntactic structure that controls other statements to control other statements the for loop

What is the Java Virtual Machine? How does the JVM relate to the Java Runtime Environment (JRE)?

a theoretical computer whose machine language is the set of Java bytecodes JRE actually executes compiled Java bytecodes

Define parameter. How does a parameter relate to a method? What in Java is differentiated by using the parameter list?

a value passed to a method by its caller, any of a set of characteristics that distinguish different members of a family of tasks a parameter is a value passes to a method by its called method

What is a return value from a method? What keyword is used to return the value from the method?

a value sent out as the result of a method that can be used in an expression in your program void

Define local variable. Is a local variable in scope or out of scope? Why?

a variable inside a method that is accessible only in that method In scope because they are local to the functions or blocks they are defined in. Localizing variables means declaring variables in the innermost (most local) scope possible

What is a string object?

an individual instance of the Java language

Define index. What does it mean to be 0 indexed?

an integer used to specify a location in a sequence of values Zero-based numbering is a way of numbering in which the initial element of a sequence is assigned the index 0

Define cumulative algorithm. What are 2 ways you can calculate a cumulative sum?

an operation in which an overall value is computed incrementally, often using a loop The first way is to keep a running tally of the result and process one number at a time. Sum = sum + next; The second way is using the shorthand assignment operator. Sum += next;

Define font. How do you construct a font?

an overall design for a set of text characters, including the style, size, weight, and appearance of each character by passing 3 parameters: the font's name as a String, its style (such as bold or italic), and its size as an integer.

Define string concatenation. Give an example using your first and middle names.

combining several strings into a single string, or combining a string with other data into a new, longer string "Megan" + "Marie"

What is throwing an exception? Why is it useful?

creating an exception object and handing it to the runtime system. Throwing an exception is useful because it can return complex error information as an object and the code flow for the common case is clearer.

Define procedural decomposition. Give an example with one of your daily tasks.

dividing a complex task into a set of subtasks making a cake: [making the batter (mixing dry ingredients, cream butter sugar, beat in eggs, stir in dry ingredients), bake, make frosting, and frost cake]

Define text processing. Give an example of its use.

editing and formatting text strings. An example of its use: email filters

Define syntax error. Give an example.

occurs when you misuse Java; the programming equivalent of bad grammar and is caught by Java's compiler misplacing a single semicolon in a program

Define logic error. Give an example of a logic error.

occurs when you write code that doesn't perform its intended task assigning a value to the wrong variable

Define keyword. Give an example of a keyword.

predefined identifier Abstract

Define console input. How does a scanner class relate to console input?

responses typed by the user when an interactive program pauses for input Scanner objects in the class read console input

List the Java traits.

simple, object-oriented, network-savvy, interpreted, robust, secure, architecture-neutral, portable, high-performance, multithreaded, and dynamic language

Define algorithm. Give an example of an algorithm you use in life.

step-by-step description of how to accomplish a task. A chocolate chip cookie recipe

Define method overloading. Give an example of a method signature. Give an example of an overloaded method.

the ability to define 2 or more different methods with the same name but different method signatures public void setMapReference(int xCoordinate, int yCoordinate) { //code } public static MethodLoan() { //code } public static MethodLoan(String first) { //code } The println method is actually a series of overloaded methods. We can call println passing it a String, an int, a double, and so on.

Define program execution. How do you execute a program?

the act of carrying out the instructions contained in a program First, identify the problem and subproblems; second, develop the algorithms; third, develop the program; fourth, compile or translate the program into machine language; fifth, run the program.

Define operator precedence. Why is operator precedence important to understand?

the binding power of an operator it determines how to group parts of an expression which is vital to computer programming

Define flow control. How does flow control relate to a method call?

the order in which the statements of a Java program are executed. each time the program encounters a static method call, the execution of the program "jumps" to that static method, executes each statement in that method in order (the order is flow control), and then "jumps" back to the point where the call began and resumes executing

Define scope. How do the curly braces relate to scope?

the part of a program in which a particular declaration is valid The scope of a variable declaration extends from the point of declaration to the right curly brace that encloses it. The scope of the variable is from the point of declaration to the closing curly brace

Define iterative enhancement. Why is it important to a programmer?

the process of producing a program in stages, adding new functionality at each stage a programmer can test it to make sure the newly added piece works before moving on, saving a lot of time

What is short-circuit evaluation? What are the conditions that would make this equation short-circuit ((A || B) && (C || D))?

the property of the logical operators && and || that prevents the second operand from being evaluated if the overall result is obvious from the value of the first operand. The first operand has to be false.

What is the mod operator? How does the mod operator relate to the division operator?

the remainder operator (%) lets you know how much was left unaccounted for by the truncating division operator the mod operator tells you how much was left unaccounted for by the truncating division operator

What is a Boolean value? How many possibilities are there and what are they?

used to describe logical true/false relationships. Only two, true and false.


Set pelajaran terkait

Night (chapters 1 - 4 review questions)

View Set

Ch. 17 Activity-Based Costing and Analysis

View Set

EAQ 56 Increased Intracranial Pressure

View Set

Ricci Chapter 26 - Test Bank - 4th Edition

View Set

IFT 372 Wireless Communication - Helm - Quiz 1-7 + Midterm + Lecture Activities

View Set

Literary Terms #2, Irony and Tone

View Set