The Java Tutorials

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

API stands for

Application Programming Interface

What's wrong with the following program? public class SomethingIsWrong { public static void main(String[] args) { Rectangle myRect; myRect.width = 40; myRect.height = 50; System.out.println("myRect's area is " + myRect.area()); } }

Can never create a rectangle

Consider the Card, Deck, and DisplayDeck classes you wrote in the previous exercise. What Object methods should each of these classes override?

Card and Deck should override equals, hashCode, and toString.

What is the first thing you should check if you see the following error at runtime: Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorldApp.java.

Classpath

The program Problem.java doesn't compile. What do you need to do to make it compile? Why?

Delete static in front of the declaration of the Inner class, because it does not have access to the instance fields of the outer class.

When declaring the main method, which modifier must come first, public or static?

Either order, but the public static is proper.

True or false: an Enum type can be a subclass of java.lang.String.

False

What is the value of the following expression, and why? Integer.valueOf(1).equals(Long.valueOf(1))

False. The two objects (the Integer and the Long) have different types.

How do you write an infinite loop using the for statement?

For ( ; ; ) { }

What is wrong with the following interface? public interface SomethingIsWrong { void aMethod(int aValue) { System.out.println("Hi Mom"); } }

It has a method implementation in it. Only default and static methods have implementations.

What is wrong with the following interface? public interface House { @Deprecated void open(); void openFrontDoor(); void openBackDoor(); }

It should reflect why open is deprecated and what to use instead.

How long is the string returned by the following expression? What is the string? "Was it a car or a cat I saw?".substring(9, 12)

It's 3 characters in length: car. It does not include the space after car.

What is the initial capacity of the following string builder? StringBuilder sb = new StringBuilder("Able was I ere I saw Elba.");

It's the length of the initial string + 16: 26 + 16 = 42.

Given the following classes: class Shape { /* ... */ } class Circle extends Shape { /* ... */ } class Rectangle extends Shape { /* ... */ } class Node<T> { /* ... */ } Will the following code compile? If not, why? Node<Circle> nc = new Node<>(); Node<Shape> ns = nc;

No. Because Node<Circle> is not a subtype of Node<Shape>.

Will the following class compile? If not, why? public final class Algorithm { public static <T> T max(T x, T y) { return x > y ? x : y; } }

No. The greater than (>) operator applies only to primitive numeric types.

Bytecode

Platform independent code understood by a processor.

Explain the following code sample: result = someCondition ? value1 : value2;

The code should read as "If someCondition is true, assign the value of value1 to result. Otherwise, assign the value of value2 to result.

Will the following code compile without error? Why or why not? public @interface Meal { ... } @Meal("breakfast", mainDish="cereal") @Meal("lunch", mainDish="pizza") @Meal("dinner", mainDish="salad") public void evaluateDiet() { ... }

The code will fail to compile, because the program does not support repeatable annotations. In this code, the Meal annotation type was not defined to be repeatable.

To invert the value of a boolean, which operator would you use?

The logical component operator "!"

The following code creates one array and one string object. How many references to those objects exist after the code executes? Is either object eligible for garbage collection? ... String[] students = new String[10]; String studentName = "Peter Parker"; students[0] = studentName; studentName = null; ...

There is one reference to the students array, which contains one reference to Peter Smith. Neither object is eligible for garbage collection.

How do you write an infinite loop using the while statement?

While (true) { }

Which of the following is not a valid comment: a. /** comment */ b. /* comment */ c. /* comment d. // comment

/* comment

Is the following interface valid? public interface Marker { }

Yes, methods are not required

Consider this implementation of the House interface, shown in Question 1. public class MyHouse implements House { public void open() {} public void openFrontDoor() {} public void openBackDoor() {} } If you compile this program, the compiler produces a warning because open was deprecated (in the interface). What can you do to get rid of that warning?

You can deprecate the implementation of open or suppress the warning.

If the compiler erases all type parameters at compile time, why should you use generics?

You should use generics because: The Java compiler enforces tighter type checks on generic code at compile time. Generics support programming types as parameters. Generics enable you to implement generic algorithms.

a container object that holds a fixed number of values of a single type.

array

Statements may be grouped into

blocks

A block is a group of zero or more statements between balanced ___ and can be used anywhere a single statement is allowed.

braces

What are the eight primitive data types supported by the Java programming language?

byte, short, int, long, float, double, Boolean, char

What methods would a class that implements the java.lang.CharSequence interface have to implement?

charAt, length, subSequence, and toString.

blueprint for a software

class

The following code snippet is an example of a ___ expression. 1 * 2 * 3

compound

hiding internal data from the outside world...

data encapsulation

The ___ statement is similar to the while statement, but evaluates its expression at the ___ of the loop.

do-while, bottom

Operators may be used in building ___, which compute values.

expressions

a software objects state is stored in...

fields

The most basic control flow statement supported by the Java programming language is the ___ statement.

if-then

Write a generic method to find the maximal element in the range [begin, end) of a list.

import java.util.*; public final class Algorithm { public static <T extends Object & Comparable<? super T>> T max(List<? extends T> list, int begin, int end) { T maxElem = list.get(begin); for (++begin; begin < end; ++begin) if (maxElem.compareTo(list.get(begin)) < 0) maxElem = list.get(begin); return maxElem; } }

Statements are roughly equivalent to sentences in natural languages, but instead of ending with a period, a statement ends with a ___.

semicolon

real world objects contain...

state & behavior

Expressions are the core components of ___.

statements

The term "class variable" is another name for

static field

6. Common behavior can be defined in a ___ and inherited into a ___ using the ___ keyword.

superclass, subclass, extends

The ___ statement allows for any number of possible execution paths.

switch

Consider this class: class Node<T> implements Comparable<T> { public int compareTo(T obj) { /* ... */ } // ... } Will the following code compile? If not, why? Node<String> node = new Node<>(); Comparable<String> comp = node;

yes

Will the following method compile? If not, why? public static void print(List<? extends Number> list) { for (Number n : list) System.out.print(n + " "); System.out.println(); }

yes

Assume you have written some classes. Belatedly, you decide they should be split into three packages, as listed in the following table. Furthermore, assume the classes are currently in the default package (they have no package statements). Destination Packages Package Name Class Name mygame.server Server mygame.shared Utilities mygame.client Client 1. Which line of code will you need to add to each source file to put each class in the right package? 2. To adhere to the directory structure, you will need to create some subdirectories in the development directory and put source files in the correct subdirectories. What subdirectories must you create? Which subdirectory does each source file go in? 3. Do you think you'll need to make any other changes to the source files to make them compile correctly? If so, what?

1. The first line of each file must specify the package: In Client.java add: package mygame.client; In Server.java add: package mygame.server;: In Utilities.java add: package mygame.shared; 2. Within the mygame directory, you need to create three subdirectories: client, server, and shared. In mygame/client/ place: Client.java In mygame/server/ place: Server.java In mygame/shared/ place: Utilities.java 3. Yes, you need to add import statements. Client.java and Server.java need to import the Utilities class, which they can do in one of two ways: import mygame.shared.*; --or-- import mygame.shared.Utilities; Also, Server.java needs to import the Client class: import mygame.client.Client;

In the following program, called ComputeResult, what is the value of result after each numbered line executes? public class ComputeResult { public static void main(String[] args) { String original = "software"; StringBuilder result = new StringBuilder("hi"); int index = original.indexOf('a'); /*1*/ result.setCharAt(0, original.charAt(0)); /*2*/ result.setCharAt(1, original.charAt(original.length()-1)); /*3*/ result.insert(1, original.charAt(4)); /*4*/ result.append(original.substring(1,4)); /*5*/ result.insert(3, (original.substring(index, index+2) + " ")); System.out.println(result); } }

1.si 2.se 3.swe 4.sweoft 5.swear oft

Which operator is used to compare two values, = or == ?

==

Consider the following code snippet. arrayOfInts[j] > arrayOfInts[j+1] Which operators does the code contain?

>, +

How does a program destroy an object that it creates?

A program doesn't destroy objet, but can set their references to null so it may become eligible for garbage collection.

What parameters does the main method define?

A single parameter (args)

What is the following method converted to after type erasure? public static <T extends Comparable<T>> int findFirstGreaterThan(T[] at, T elem) { // ... }

public static int findFirstGreaterThan(Comparable[] at, Comparable elem) { // ... }

What is the correct signature of the main method?

public static void main(String[] args)

Consider the following string: a. String hannah = "Did Hannah see bees? Hannah did."; What is the value displayed by the expression hannah.length()? b. What is the value returned by the method call hannah.charAt(12)? c. Write an expression that refers to the letter b in the string referred to by hannah.

a. 32 b. e c. hannah.charAt(15)

2. Use the Java API documentation for the Box class (in the javax.swingpackage) to help you answer the following questions. a. What static nested class does Box define? b. What inner class does Box define? c. What is the superclass of Box's inner class d. Which of Box's nested classes can you use from any class? e. How do you create an instance of Box's Filler class?

a. box filler b. box accessiblebox c. [java.awt.]Container.AccessibleAWTContainer d. box filler e. New Box.Filler(minDimension, prefDimension, maxDimension)

2. Consider the following code snippet. int i = 10; int n = i++%5; a. What are the values of i and n after the code is executed? b. What are the final values of i and n if instead of using the postfix increment operator (i++), you use the prefix version (++i))?

a. i=11 N=0 b. i=11 N=1

Consider the following two classes: public class ClassA { public void methodOne(int i) { } public void methodTwo(int i) { } public static void methodThree(int i) { } public static void methodFour(int i) { } } public class ClassB extends ClassA { public static void methodOne(int i) { } public void methodTwo(int i) { } public void methodThree(int i) { } public static void methodFour(int i) { } } a. Which method overrides a method in the superclass? b. Which method hides a method in the superclass? c. What do the other methods do?

a. methodtwo b.methodfour c. they cause compile-time errors

Use the API documentation to find the answers to the following questions: a. What Integer method can you use to convert an int into a string that expresses the number in hexadecimal? For example, what method converts the integer 65 into the string "41"? b. What Integer method would you use to convert a string expressed in base 5 into the equivalent int? For example, how would you convert the string "230" into the integer value 65? Show the code you would use to accomplish this task. c. What Double method can you use to detect whether a floating-point number has the special value Not a Number (NaN)?

a. toHexString b. valueOf. Here's how: String base5String = "230"; int result = Integer.valueOf(base5String, 5); c. isNan

Consider the following class: public class IdentifyMyParts { public static int x = 7; public int y = 3; } a. What are the class variables? b. What are the instance variables?

a. x b. y

c. What is the output from the following code: IdentifyMyParts a = new IdentifyMyParts(); IdentifyMyParts b = new IdentifyMyParts(); a.y = 5; b.y = 6; a.x = 1; b.x = 2; System.out.println("a.y = " + a.y); System.out.println("b.y = " + b.y); System.out.println("a.x = " + a.x); System.out.println("b.x = " + b.x); System.out.println("IdentifyMyParts.x = " + IdentifyMyParts.x);

a. y=5 b.y=6 a.x=2 b.x=2 IdentifyMyParts.x=2

a collection of methods with no implementation is called...

interface

Character strings are represented by the class

java.lang.string

A local variable stores temporary state; it is declared inside a

method

a software objects behavior is exposed through...

methods

Will the following class compile? If not, why? public class Singleton<T> { public static T getInstance() { if (instance == null) instance = new Singleton<T>(); return instance; } private static T instance = null; }

no you cannot create a static field of the type parameter

The term "instance variable" is another name for

non static field

A namespace that organizes classes and interfaces by functionality is called...

package

A variable declared within the opening and closing parenthesis of a method signature is called a

parameter

What is the following class converted to after type erasure? public class Pair<K, V> { public Pair(K key, V value) { this.key = key; this.value = value; } public K getKey(); { return key; } public V getValue(); { return value; } public void setKey(K key) { this.key = key; } public void setValue(V value) { this.value = value; } private K key; private V value; }

public class Pair { public Pair(Object key, Object value) { this.key = key; this.value = value; } public Object getKey() { return key; } public Object getValue() { return value; } public void setKey(Object key) { this.key = key; } public void setValue(Object value) { this.value = value; } private Object key; private Object value; }

Write a generic method to count the number of elements in a collection that have a specific property (for example, odd integers, prime numbers, palindromes)

public final class Algorithm { public static <T> int countIf(Collection<T> c, UnaryPredicate<T> p) { int count = 0; for (T elem : c) if (p.test(elem)) ++count; return count; } }

Write a generic method to exchange the positions of two different elements in an array.

public final class Algorithm { public static <T> void swap(T[] a, int i, int j) { T temp = a[i]; a[i] = a[j]; a[j] = temp; } }

Fix the interface public interface SomethingIsWrong { void aMethod(int aValue) { System.out.println("Hi Mom"); } }

public interface SomethingIsWrong { void aMethod(int aValue); }


संबंधित स्टडी सेट्स

Term 2 comprehensive test questions

View Set

North Carolina Drivers Ed Mid Term

View Set

Responding to Theme and Character in a Narrative

View Set

ch 5 sexually transmitted infections OB

View Set

Maternity & Pediatric Nursing - Ricci - Ch's 32-38 40-44

View Set