Escolar Documentos
Profissional Documentos
Cultura Documentos
Answer: A comment that is sent to the client in the viewable page source.The JSP
engine handles an output comment as uninterpreted HTML text, returning the comm
ent in the HTML output sent to the client.You can see the comment by viewing the
page source from your Web browser.
JSP Syntax:
!-- comment [ %= expression % ] --
# What is a Hidden Comment?
Answer: A comments that documents the JSP page but is not sent to the client.The
JSP engine ignores a hidden comment, and does not process any code within hidde
n comment tags.A hidden comment is not sent to the client, either in the display
ed JSP page or the HTML page source.
The hidden comment is useful when you want to hide or "comment out" part of your
JSP page.You can use any characters in the body of the comment except the closi
ng --% combination.If you need to use --% in your comment, you can escape it by ty
ping --%\
JSP Syntax:
%-- comment --%
Examples:
%@ page language="java" %
html
head
title A Hidden Comment /title
/head
body
%-- This comment will not be visible to the colent in the page source --%
/body
/html
# What is a Expression?
Answer: An expression tag contains a scripting language expression that is evalu
ated, converted to a String, and inserted where the expression appears in the JS
P file.Because the value of an expression is converted to a String, you can use
an expression within text in a JSP file.Like
%= someexpression % %= (new java.util.Date()).toLocaleString() %
You cannot use a semicolon to end an expression
# What is a Declaration?
Answer: A declaration declares one or more variables or methods for use later in
the JSP source file.A declaration must contain at least one complete declarativ
e statement.You can declare any number of variables or methods within one declar
ation tag, as long as they are separated by semicolons.The declaration must be v
alid in the scripting language used in the JSP file.
%! somedeclarations %
%! int i = 0; %
%! int a, b, c; %
# What is a Scriptlet?
Answer: A scriptlet can contain any number of language statements, variable or m
ethod declarations, or expressions that are valid in the page scripting language
.Within scriptlet tags, you can:
* Declare variables or methods to use later in the file.
* Write expressions valid in the page scripting language.
* Use any of the JSP implicit objects or any object declared with a jsp:useBe
an tag.You must write plain text, HTML-encoded text, or other JSP tags outside th
e scriptlet.Scriptlets are executed at request time, when the JSP engine process
es the client request.If the scriptlet produces output, the output is stored in
the out object, from which you can display it.
# What are implicit objects? List them?
Answer: Certain objects that are available for the use in JSP documents without
being declared first.These objects are parsed by the JSP engine and inserted int
o the generated servlet.
The implicit objects are listed below:
* Request
* Response
* PageContext
* Session
* Application
* Out
* Config
* Page
* Exception
# Difference between forward and sendRedirect?
Answer: When you invoke a forward request, the request is sent to another resour
ce on the server, without the client being informed that a different resource is
going to process the request.This process occurs completly with in the web cont
ainer.When a sendRedirtect method is invoked, it causes the web container to ret
urn to the browser indicating that a new URL should be requested.Because the bro
wser issues a completly new request any object that are stored as request attrib
utes before the redirect occurs will be lost.This extra round trip a redirect is
slower than forward.
# What are the different scope valiues for the jsp:useBean ?
Answer: The different scope values for jsp:useBean are:
* Page
* Request
* Session
* Application
# Explain the life-cycle mehtods in JSP?
Answer: The generated servlet class for a JSP page implements the HttpJspPage in
terface of the javax.servlet.jsp package.Hte HttpJspPage interface extends the J
spPage interface which inturn extends the Servlet interface of the javax.servlet
package.the generated servlet class thus implements all the methods of the thes
e three interfaces.
The JspPage interface declares only two mehtods:
* jspInit()
* jspDestroy()
However the JSP specification has provided the HttpJspPage interfaec specificall
y for the JSp pages serving HTTP requests.This interface declares one method _js
pService().The jspInit()- The container calls the jspInit() to initialize te ser
vlet instance.It is called before any other method, and is called only once for
a servlet instance.The _jspservice()- The container calls the _jspservice() for
each request, passing it the request and the response objects.The jspDestroy()-
The container calls this when it decides take the instance out of service.It is
the last method called n the servlet instance.
# How do I prevent the output of my JSP or Servlet pages from being cached by th
e browser?
Answer: You will need to set the appropriate HTTP header attributes to prevent t
he dynamic content output by the JSP page from being cached by the browser.Just
execute the following scriptlet at the beginning of your JSP pages to prevent th
em from being cached at the browser.
You need both the statements to take care of some of the older browser versions.
%response.setHeader("Cache-Control","no-store"); //HTTP 1.1response.setHeader("Pr
agma\","no-cache"); //HTTP 1.0response.setDateHeader ("Expires", 0); //prevents
caching at the proxy server%
# One of the components of a computer is its CPU.What is a CPU and what role doe
s it play in a computer?
Answer: The CPU, or Central Processing Unit, is the active part of the computer.
Its function is to execute programs that are coded in machine language and store
d in the main memory (RAM) of the computer.It does this by repeating the fetchan
dexecute cycle over and over; that is, it repeatedly fetches a machine language
instruction from memory and executes it.
# Explain what is meant by an "asynchronous event." Give some examples.
Answer: An asynchronous event is one that occurs at an unpredictable time outsid
e the control of the program that the CPU is running.It is not "synchronized" wi
th the program.An example would be when the user presses a key on the keyboard o
r clicks the mouse button.(These events generate "interrupts" that cause the CPU
to interrupt what it is doing and to take some action to handle the asynchronou
s event.After handling the event, the CPU returns to what it was doing before it
was interrupted.)
# What is the difference between a "compiler" and an "interpreter"?
Answer: Compilers and interpreters have similar functions: They take a program w
ritten in some programming language and translate it into machine language.A com
piler does the translation all at once.It produces a complete machine languagepr
ogram that can then be executed.An interpreter, on the other hand, just translat
es one instruction at a time, and then executes that instruction immediately.(Ja
va uses a compiler to translate java programs into Java Bytecode, which is a mac
hine language for the imaginary Java Virtual Machine.Java Bytecode programs are
then executed by an interpreter.)
# Explain the difference between highlevel languages and machine language.
Answer: Programs written in the machine language of a given type of computer can
be directly executed by the CPU of that type of computer.Highlevel languageprog
rams must be translated into machine language before they can be executed.(Machi
ne language instructions are encoded as binary numbers that are meant to be used
by a machine, not read or written by people.Highlevel languages use a syntax th
at is closer to human language.)
# If you have the source code for a Java program, and you want to run that progr
am, you will need both a compiler and an interpreter.What does the Java compiler
do, and what does the Java interpreter do?
Answer: The Java compiler translates Java programs into a language called Java b
ytecode.Although bytecode is similar to machine language, it is not the machine
language of any actual computer.A Java interpreter is used to run the compiled J
ava bytecode program.(Each type of computer needs its own Java bytecode interpre
ter, but all these interpreters interpret the same bytecode language.)
# What is a subroutine?
Answer: A subroutine is a set of instructions for performing some task that have
been grouped together and given a name.Later, when that task needs to be perfor
med, it is only necessary to call the subroutine by giving its name, rather than
repeating the whole sequence of instructions.
# Java is an objectoriented programming language.What is an object?
Answer: An object consists of some data together with a set of subroutines that
manipulate that data.(An object is a kind of "module," or selfcontained entity t
hat communicates with the rest of the world through a welldefined interface.An o
bject should represent some coherent concept or realworld object.)
# What is a variable?
Answer: A variable is a memory location that has been given a name so that it ca
n easily be referred to in a program.The variable holds a value, which must be o
f some specified type.The value can be changed during the course of the executio
n of theprogram.
# Java is a "platformindependent language." What does this mean?
Answer: A Java program can be compiled once into a Java Bytecode program.The com
piled program can then be run on any computer that has an interpreter for the Ja
va virtual machine.Other languages have to be recompiled for each platform on wh
ich they are going to run.The point about Java is that it can be executed on man
y different types of computers without being recompiled.
# What is the "Internet"? Give some examples of how it is used.
Answer: The Internet is a network connecting millions of computers around the wo
rld.Computers connected to the Internet can communicate with each other.The Inte
rnet can be used for:
* Telnet:which lets a user of one computer log onto another computer remotel
y.
* FTP:which is used to copy files between computers.
* World Wide Web:which lets a user view "pages" of information published on
computers around the world.
# What is garbage collection? What is the process that is responsible for doing
that in java?
Answer: Reclaiming the unused memory by the invalid objects.Garbage collector is
responsible for this process
# What kind of thread is the Garbage collector thread?
Answer: It is a daemon thread.
# What is a daemon thread?
Answer: These are the threads which can run without user intervention.The JVM ca
n exit when there are daemon thread by killing them abruptly.
# How will you invoke any external process in Java?
Answer: Runtime.getRuntime().exec(.)
# What is the finalize method do?
Answer: Before the invalid objects get garbage collected, the JVM give the user
a chance to clean up some resources before it got garbage collected.
# What is mutable object and immutable object?
Answer: If a object value is changeable then we can call it as Mutable object.(E
x., StringBuffer, ) If you are not allowed to change the value of an object, it
is immutable object.(Ex., String, Integer, Float,)
# What is the basic difference between string and stringbuffer object?
Answer: String is an immutable object.StringBuffer is a mutable object.
# What is the purpose of Void class?
Answer: The Void class is an uninstantiable placeholder class to hold a referenc
e to the Class object representing the primitive Java type void.
# What is reflection?
Answer: Reflection allows programmatic access to information about the fields, m
ethods and constructors of loaded classes, and the use reflected fields, methods
, and constructors to operate on their underlying counterparts on objects, withi
n security restrictions.
# What is Class.forName() does and how it is useful?
Answer: It loads the class into the ClassLoader.It returns the Class.Using that
you can get the instance ( class-instance.newInstance() ).
# When you think about optimization, what is the best way to findout the time/me
mory consuming process?
Answer: Using profiler
# What is the purpose of assert keyword used in JDK1.4.x?
Answer: In order to validate certain expressions.It effectively replaces the if
block and automatically throws the AssertionError on failure.This keyword should
be used for the critical arguments.Meaning, without that the method does nothin
g.
# How will you get the platform dependent values like line separator, path separ
ator, etc., ?
Answer: Using Sytem.getProperty() (line.separator, path.separator, )
# What is skeleton and stub? what is the purpose of those?
Answer: Stub is a client side representation of the server, which takes care of
communicating with the remote server.Skeleton is the server side representation.
But that is no more in use it is deprecated long before in JDK.
# What is the final keyword denotes?
Answer: final keyword denotes that it is the final implementation for that metho
d or variable or class.You cant override that method/variable/class any more.
# What is the significance of ListIterator?
Answer: You can iterate back and forth.
# What is the major difference between LinkedList and ArrayList?
Answer: LinkedList are meant for sequential accessing.ArrayList are meant for ra
ndom accessing.
# What is nested class?
Answer: If all the methods of a inner class is static then it is a nested class.
# What is inner class?
Answer: If the methods of the inner class can only be accessed via the instance
of the inner class, then it is called inner class.
# What is composition?
Answer: Holding the reference of the other class within some other class is know
n as composition.
# What is aggregation?
Answer: It is a special type of composition.If you expose all the methods of a c
omposite class and route the method call to the composite method through its ref
erence, then it is called aggregation.
# Can you instantiate the Math class?
Answer: You cant instantiate the math class.All the methods in this class are st
atic.And the constructor is not public.
# What is singleton?
Answer: It is one of the design pattern.This falls in the creational pattern of
the design pattern.There will be only one instance for that entire JVM.You can a
chieve this by having the private constructor in the class.For eg., public class
Singleton { private static final Singleton s = new Singleton(); private Singlet
on() { } public static Singleton getInstance() { return s; } // all non static m
ethods }
# What is DriverManager?
Answer: The basic service to manage set of JDBC drivers.
# Suppose that temperature measurements were made on each day of 1999 in each of
100 cities.The measurements have been stored in an array
int[][]temps=newint[100][365];
where temps[c][d] holds the measurement for city number c on the dth day of the
year.Write a code segment that will print out the average temperature, over the
course of the whole year, for each city.The average temperature for a city can b
e obtained by adding up all 365 measurements for that city and dividing the answ
er by 365.0.
Answer: A pseudocode outline of the answer is
For each city {
Add up all the temperatures for that city
Divide the total by 365 and print the answer
}
Adding up all the temperatures for a given city itself requires a for loop, so t
he code segment looks like this:
for (int city = 0; city < 100; city++) {
int total = 0;
for (int day = 0; day < 365; day++)
total = total + temps[city][day];
double avg = total / 365.0;
System.out.println("Average temp for city number " + city + " is " + avg);
}
# Suppose that a class, Employee, is defined as follows: class Employee {
String lastName;
String firstName;
double hourlyWage;
int yearsWithCompany;
}
Suppose that data about 100 employees is already stored in an array:
Employee[] employeeData = new
Employee[100];
Write a code segment that will output the first name, last name, and hourly wage
of each employee who has been with the company for 20 years or more.
Answer: The code segment is as follows:
for (int i=0; i < 100; i++) {
if ( employeeData[i].yearsWithCompany >= 20 )
System.out.println(employeeData[i].firstName + " " + employeeData[i].lastName +
": " + employeeData[i].hourlyWage);
}
# Suppose that A has been declared and initialized with the statement
double[] A = new double[20];
And suppose that A has already been filled with 20 values.Write a program segmen
t that will find the average of all the non-zero numbers in the array.(The avera
ge is the sum of the numbers, divided by the number of numbers.Note that you wil
l have to count the number of non-zero entries in the array.) Declare any variab
les that you use.
Answer: int nonzeroCt = 0;
double total = 0;
double average;
for (int i = 0; i < 20; i++) {
if (A[i] != 0) {
total += A[i];
nonzeroCt++;
}
}
if (nonzeroCt > 0)
average = total / nonzeroCt;
else
average = 0;
# What does it mean to say that a program is robust?
Answer: A robust program is one that can handle errors and other unexpected cond
itions in some reasonable way.This means that the program must anticipate possib
le errors and respond to them if they occur.
# Why do programming languages require that variables be declared before they ar
e used? What does this have to do with correctness and robustness?
Answer: It's a little inconvenient to have to declare every variable before it i
s used, but its much safer.If the compiler would accept undeclared variables, th
en it would also accept misspelled names and treat them as valid variables.This
can easily lead to incorrect programs.When variables must be declared, the unint
entional creation of a variable is simply impossible, and a whole class of possi
ble bugs is avoided.
# What is "Double.NaN"?
Answer: Double.NaN is a special value of type double.(It is defined as a public
static member variable of the standard class, Double.) It is used to represent t
he result of an undefined operation on real numbers.For example, if you divide a
number of type double by zero, the result will be Double.NaN.
# What does it mean to use a null layout manager, and why would you want to do s
o?
Answer: If the layout manager for a container is set to null, then the programme
r takes full responsibility for setting the sizes and positions of all of the co
mponents in thatcontainer.This gives the programmer more control over the layout
, but the programmer has to do more work.For simple layouts in a container that
does not change size, the setBounds() method of each component can be called whe
n it is added to the container.If the container can change size, then the sizes
and positions should be recomputed when a size change occurs.This is done automa
tically by a layout manager, and this is one good reason to use a layout manager
for acontainer that can change size.
# What is a JCheckBox and how is it used?
Answer: A JCheckBox is a component that has two possible states, "checked" and "
unchecked".The user can change the state by clicking on the JCheckBox.If box is
a variable of type JCheckBox, then a program can check the box by calling box.se
tSelected(true) and can uncheck the box by calling box.setSelected(false).The cu
rrent state can be determined by calling box.isSelected(), which is a boolean-va
lued function.A JCheckBox generates an event of type ActionEvent when it changes
state.A program can listen for these events if it wants to take some action at
the time the state changes.Often, however, it's enough for a program simply to l
ook at the state of the JCheckBox when it needs it.
# What is a thread ?
Answer: A thread, like a program, executes a sequence of instructions from begin
ning to end.Several threads can execute "in parallel" at the same time.In Java,
a thread is represented by an object of type Thread.A Thread object has a run()
method to execute (usually the run() method of a Runnable object that is provide
d when the Thread is constructed).The thread begins executing the run() routine
when its start() method is called.At the same time, the rest of the program cont
inues to execute in parallel with the thread.
# Explain how Timers are used to do animation?
Answer: Displaying an animation requires showing a sequence of frames.The frames
are shown one after the other, with a short delay between each frame and the ne
xt.A Timer can generate a sequence of ActionEvents.When a timer is used to do an
imation, each event triggers the display of another frame.The ActionListener tha
t processes events from the timer just needs to be programmed to display a frame
when its actionPerformed() method is called.
# Menus can contain sub-menus.What does this mean, and how are sub-menus handled
in Java?
Answer: Menus can be "hierarchical." A menu can contain other menus, which are c
alled sub-menus.A sub-menu is represented as a single item in the menu that cont
ains it.When the user selects this item, the full sub-menu appears, and the user
can select an item from the sub-menu.In Java, a sub-menu is no different from a
ny other menu.A menu can be added to a menu bar, or it can be added to another m
enu.In the latter case, it becomes a sub-menu.
# What is the purpose of the JFrame class?
Answer: An object belonging to the class JFrame is an independent window on the
screen.You don't need a Web browser to create a JFrame like you do for an JApple
t.A JFrame can be used as a user interface for a stand-alone program.It is also
possible for an applet to open a JFrame.
# What does the computer do when it executes the following statement? Try to giv
e as complete an answer as possible.
Color[]pallette=newColor[12];
Answer: This is a declaration statement, that declares and initializes a variabl
e named pallette of type Color[].The initial value of this variable is a newly c
reated array that has space for 12 items.To be specific about what the computer
does: It creates a new 12-element array object on the heap, and it fills each sp
ace in that array with null.It allocates a memory space for the variable, pallet
te.And it stores a pointer to the new array object in that memory space.
# What is meant by the basetype of an array?
Answer: The base type of an array refers to the type of the items that can be st
ored in that array.For example, the base type of the array in the previous probl
em is Color.
# What does it mean to sort an array?
Answer: To sort an array means to rearrange the items in the array so that they
are in increasing or decreasing order.
# What is meant by a dynamic array? What is the advantage of a dynamic array ove
r a regular array?
Answer: A dynamic array is like an array in that it is a data structure that sto
res a sequence of items, all of the same type, in numbered locations.It is diffe
rent from an array in that there is no preset upper limit on the number of items
that it can contain.This is an advantage in situations where a reasonable value
for the size of the array is not known at the time it is created.
# Briefly explain what is meant by the syntax and the semantics of a programming
language.Give an example to illustrate the difference between a syntax error an
d a semantics error?
Answer: The syntax of a language is its grammar, and the semantics is its meanin
g.A program with a syntax error cannot be compiled.A program with a semantic err
or can be compiled and run, but gives an incorrect result.A missing semicolon in
a program is an example of a syntax error, because the compiler will find the e
rror and report it.If N is an integer variable, then the statement "frac = 1/N;"
is probably an error of semantics.The value of 1/N will be 0 for any N greater
than 1.It's likely that the programmer meant to say 1.0/N.
# What does the computer do when it executes a variable declaration statement.Gi
ve an example.
Answer: A variable is a "box", or location, in the computer's memory that has a
name.The box holds a value of some specified type.A variable declaration stateme
nt is a statement such as
int x;
which creates the variable x.When the computer executes a variable declaration,
it creates the box in memory and associates a name (in this case, x) with that b
ox.Later in the program, that variable can be referred to by name.
# What is a type, as this term relates to programming?
Answer: A "type" represents a set of possible values.When you specify that a var
iable has a certain type, you are saying what values it can hold.When you say th
at an expression is of a certain type, you are saying what values the expression
can have.For example, to say that a variable is of type int says that integer v
alues in a certain range can be stored in that variable.
# One of the primitive types in Java is boolean.What is the boolean type? Where
are boolean values used? What are its possible values?
Answer: The only values of type boolean are true and false.Expressions of type b
oolean are used in places where true/false values are expected, such as the cond
itions in while loops and if statements.
# Give the meaning of each of the following Java operators - ++, &&, !=
Answer: The Operators are Explained as follows:
* ++:The operator ++ is used to add 1 to the value of a variable.For example
, "count++" has the same effect as "count = count + 1".
* &&:The operator && represents the word and.It can be used to combine two b
oolean values, as in "(x > 0 && y > 0)", which means, "x is greater than 0 and y
is greater than 0."
* !=:The operation != means "is not equal to", as in "if (x != 0)", meaning
"if x is not equal to zero.".
# Explain what is meant by an assignment statement, and give an example.What are
assignment statements used for?
Answer: An assignment statement computes a value and stores that value in a vari
able.
Examples include:
x = 17;
newRow = row;
ans = 17*x + 42;
An assignment statement is used to change the value of a variable as the program
is running.Since the value assigned to the variable can be another variable or
an expression, assignments statements can be used to copy data from one place to
another in the computer, and to do complex computations.
# What is meant by precedence of operators?
Answer: If two or more operators are used in an expression, and if there are no
parentheses to indicate the order in which the operators are to be evaluated, th
en the computer needs some way of deciding which operator to evaluate first.The
order is determined by the precedence of the operators.For example, * has higher
precedence than +, so the expression 3+5*7 is evaluated as if it were written 3
+(5*7).
# What is a literal?
Answer: A literal is a sequence of characters used in a program to represent a c
onstant value.For example, 'A' is a literal that represents the value A, of type
char, and 17L is a literal that represents the number 17 as a value of type lon
g.A literal is a way of writing a value, and should not be confused with the val
ue itself.
# In Java, classes have two fundamentally different purposes.What are they?
Answer: A class can be used to group together variables and subroutines that are
contained in the class.These are called the static members of the class.For exa
mple, the subroutine Math.sqrt is a static member of the class called Math.Also,
the main routine in any program is a static member of a class.The second possib
le purpose of a class is to describe and create objects.The class specifies what
variables and subroutines are contained in those objects.In this role, classes
are used in object-oriented programming (which we haven't studied yet in any det
ail.)
# What is the difference between the statement "x = TextIO.getDouble();" and the
statement "x = TextIO.getlnDouble();"
Answer: Either statements will read a real number input by the user, and store t
hat number in the variable, x.They would both read and return exactly the same v
alue.The difference is that in the second statement, using getlnDouble, after re
ading the value, the computer will continue reading characters from input up to
and including the next carriage return.These extra characters are discarded.
# Explain briefly what is meant by "pseudocode" and how is it useful in the deve
lopment of algorithms.
Answer: Pseudocode refers to informal descriptions of algorithms, written in a l
anguage that imitates the structure of a programming language, but without the s
trict syntax.Pseudocode can be used in the process of developing an algorithm wi
th stepwise refinement.You can start with a brief pseudocode description of the
algorithm and then add detail to the description through a series of refinements
until you have something that can be translated easily into a program written i
n an actual programming language.
# What is a block statement? How are block statements used in Java programs?
Answer: A block statement is just a sequence of Java statements enclosed between
braces, { and }.The body of a subroutine is a block statement.Block statements
are often used in control structures.A block statement is generally used to grou
p together several statements so that they can be used in a situation that only
calls for a single statement.For example, the syntax of a while loop calls for a
single statement: "while (condition) do statement".However, the statement can b
e a block statement, giving the structure: "while (condition) { statement; state
ment;...}".
# What is the main difference between a while loop and a do..while loop?
Answer: Both types of loop repeat a block of statements until some condition bec
omes false.The main difference is that in a while loop, the condition is tested
at the beginning of the loop, and in a do..while loop, the condition is tested a
t the end of the loop.It is possible that the body of a while loop might not be
executed at all.However, the body of a do..while loop is executed at least once
since the condition for ending the loop is not tested until the body of the loop
has been executed.
# What does it mean to prime a loop?
Answer: The condition at the beginning of a while loop has to make sense even th
e first time it is tested, before the body of the loop is executed.To prime the
loop is to set things up before the loop starts so that the test makes sense (th
at is, the variables that it contains have reasonable values).For example, if th
e test in the loop is "while the user's response is yes," then you will have to
prime the loop by getting a response from the user (or making one up) before the
loop.
# Explain what is meant by an animation and how a computer displays an animation
?
Answer: An animation consists of a series of "frames." Each frame is a still ima
ge, but there are slight differences from one frame to the next.When the images
are displayed rapidly one frame after another, the eye perceives motion.A comput
er displays an animation by showing one image on the screen, then replacing it w
ith the next image, then the next, and so on.
# Write a for loop that will print out all the multiples of 3 from 3 to 36, that
is: 3 6 9 12 15 18 21 24 27 30 33 36.
Answer: Here are two possible answers.Assume that N has been declared to be a va
riable of type int:
for ( N = 3;N <= 36;N = N + 3 )
{
System.out.println( N );
}
or
for ( N = 3;N <= 36;N++ )
{
if ( N % 3 == 0 )
System.out.println( N );
}
# Fill in the following main() routine so that it will ask the user to enter an
integer, read the user's response, and tell the user whether the number entered
is even or odd.(You can use TextIO.getInt() to read the integer.Recall that an i
nteger n is even if n % 2 == 0.)
public static void main(String[] args) {
}
Answer: The problem already gives an outline of the program.The last step, telli
ng the user whether the number is even or odd, requires an if statement to decid
e between the two possibilities.
public static void main (String[] args)
{
int n;
TextIO.put("Type an integer: ");
n = TextIO.getInt();
if (n % 2 == 0)
System.out.println("That's an even number.");
Else
System.out.println("That's an odd number.");
}
# Show the exact output that would be produced by the following main() routine:
public static void main(String[] args) {
int N;
N = 1;
while (N <= 32)
{
N = 2 * N;
System.out.println(N);
}
}
Answer: The exact output printed by this program is:
2
4
8
16
32
64
# What output is produced by the following program segment? Why?
String name;
int i;
boolean startWord;
name = "Richard M.Nixon";
startWord = true;
for (i = 0; i < name.length(); i++) {
if (startWord)
System.out.println(name.charAt(i));
if (name.charAt(i) == ' ')
startWord = true;
else
startWord = false;
}
Answer: This is a tough one! The output from this program consists of the three
lines:
R
M
N
As the for loop in this code segment is executed, name.charAt(i) represents each
of the characters in the string "Richard M.Nixon" in succession.The statement S
ystem.out.println(name.charAt(i)) outputs the single character name.charAt(i) on
a line by itself.However, this output statement occurs inside an if statement,
so only some of the characters are output.The character is output if startWord i
s true.This variable is initialized to true, so when i is 0, startWord is true,
and the first character in the string, 'R', is output.Then, since 'R' does not e
qual ' ', startWorld becomes false, so no more characters are output until start
Word becomes true again.This happens when name.charAt(i) is a space, that is, ju
st before the 'M' is processed and again just before the 'N' is processed.In fac
t whatever the value of name, this for statement would print the first character
in name and every character in name that follows a space
# A "black box" has an interface and an implementation.Explain what is meant by
the terms interface and implementation.
Answer: The interface of a black box is its connection with the rest of the worl
d, such as the name and parameters of a subroutine or the dial for setting the t
emperature on a thermostat.The implementation refers to internal workings of the
black box.To use the black box, you need to understand its interface, but you d
on't need to know anything about the implementation.
221. Explain carefully what null means in Java, and why this special value is n
ecessary.
Answer: When a variable is of object type (that is, declared with a class
as its type rather than one of Java's primitive types), the value stored in the
variable is not an object.Objects exist in a part of memory called the heap, and
the variable holds a pointer or reference to the object.Null is a special value
that can be stored in a variable to indicate that it does not actually point to
any object.
222. What is a constructor? What is the purpose of a constructor in a class?
Answer: A constructor is a special kind of subroutine in a class.It has th
e same name as the name of the class, and it has no return type, not even void.A
constructor is called with the new operator in order to create a new object.Its
main purpose is to initialize the newly created object, but in fact, it can do
anything that the programmer wants it to do.
223. Suppose that Kumquat is the name of a class and that fruit is a variable o
f type Kumquat.What is the meaning of the statement "fruit = new Kumquat();"? Th
at is, what does the computer do when it executes this statement? (Try to give a
complete answer.The computer does several things.)
Answer: This statement creates a new object belonging to the class Kumquat
, and it stores a reference to that object in the variable fruit.More specifical
ly, when the computer executes this statement, it allocates memory to hold a new
object of type Kumquat.It calls a constructor, which can initialize the instanc
e variables of the object as well as perform other tasks.A reference to the new
object is returned as the value of the expression "new Kumquat()".Finally, the a
ssignment statement stores the reference in the variable, fruit.So, fruit can no
w be used to access the new object.
224. What is meant by the terms instance variable and instance method?
Answer: Instance variables and instance methods are non-static variables a
nd methods in a class.This means that they do not belong to the class itself.Ins
tead, they specify what variables and methods are in an object that belongs to t
hat class.That is, the class contains the source code that defines instance vari
ables and instance methods, but actual instance variables and instance methods a
re contained in object.
225. Explain what is meant by the terms subclass and superclass.
Answer: In object oriented programming, one class can inherit all the prop
erties and behaviors from another class.It can then add to and modify what it in
herits.The class that inherits is called a subclass, and the class that it inher
its from is said to be its superclass.InJava, the fact that ClassA is a subclass
of ClassB is indicated in the definition of ClassA as follows:
class ClassA extends ClassB {...}
226. Explain the term polymorphism.
Answer: Polymorphism refers to the fact that different objects can respond
to the same method in different ways, depending on the actual type of the objec
t.This can occur because a method can be overridden in a subclass.In that case,
objects belonging to the subclass will respond to the method differently from ob
jects belonging to the superclass.
227. Java uses "garbage collection" for memory management.Explain what is meant
here by garbage collection.What is the alternative to garbage collection?
Answer: The purpose of garbage collection is to identify objects that can
no longer be used, and to dispose of such objects and reclaim the memory space t
hat they occupy.If garbage collection is not used, then the programmer must be r
esponsible for keeping track of which objects are still in use and disposing of
objects when they are no longer needed.If the programmer makes a mistake, then t
here is a "memory leak," which might gradually fill up memory with useless objec
ts until the program crashes for lack of memory.
228. For this problem, you should write a very simple but complete class.The cl
ass represents a counter that counts 0, 1, 2, 3, 4,....The name of the class sho
uld be Counter.It has one private instance variable representing the value of th
e counter.It has two instance methods: increment() adds one to the counter value
, and getValue() returns the current counter value.Write a complete definition f
or the class, Counter.
Answer: Here is a possible answer.
public class Counter {
private int value = 0;
public void increment() {
value++;
}
public int getValue() {
return value;
}
}
229. This problem uses the Counter class from Question 9.The following program
segment is meant to simulate tossing a coin 100 times.It should use two Counter
objects, headCount and tailCount, to count the number of heads and the number of
tails.Fill in the blanks so that it will do so.
Counter headCount, tailCount;
tailCount = new Counter();
headCount = new Counter();
for ( int flip = 0;flip < 100;flip++ ) {
if (Math.random() < 0.5)
______________________;
else
______________________;
}
System.out.println("There were " + ___________________ + " heads.");
System.out.println("There were " + ___________________ + " tails.");
Answer: The variable headCount is a variable of type Counter, so the only
thing that you can do with it is call the instance methods headCount.increment()
and headCount.getValue().Call headCount.increment() to add one to the counter.C
all headCount.getValue() to discover the current value of the counter.Note that
you can't get at the value of the counter directly, since the variable that hold
s the value is a private instance variables in the Counter object.Similarly for
tailCount.Here is the program with calls to these instance methods filled in:
Counter headCount, tailCount;
tailCount = new Counter();
headCount = new Counter();
for ( int flip = 0;flip < 100;flip++ ) {
if (Math.random() < 0.5)
headCount.increment();
else
tailCount.increment();
}
System.out.println(("There were " + headCount.getValue() + " heads.");
System.out.println(("There were " + tailCount.getValue() + " tails.");
230. Programs written for a graphical user interface have to deal with "events.
" Explain what is meant by the term event.Give at least two different examples o
f events, and discuss how a program might respond to those events.
Answer: An event is anything that can occur asynchronously, not under the
control of the program, to which the program might want to respond.GUI programs
are said to be "event-driven" because for the most part, such programs simply wa
it for events and respond to them when they occur.In many (but not all) cases, a
n event is the result of a user action, such as when the user clicks the mouse b
utton, types a character, or clicks a button.The program might respond to a mous
e-click on a canvas by drawing a shape, to a typed character by adding the chara
cter to an input box, or to a click on a button by clearing a drawing.More gener
ally, a programmer can set up any desired response to an event by writing an eve
nt-handling routine for that event.
# What is the purpose of the following subroutine? What is the meaning of the va
lue that it returns, in terms of the value of its parameter?
static String concat( String[] str ) {
if (str == null)
return "";
String ans = "";
for (int i = 0; i < str.length; i++) {
ans = ans + str[i];
return ans;
}
Answer: The purpose of the subroutine is to chain all the strings in an array of
strings into one long string.If the array parameter is null, then there are no
strings, and the empty string is returned.Otherwise, the value returned is the s
tring made up of all the strings from the array.For example, if stringList is an
array declared as String[] stringList = { "Put 'em ", "all", " together" };
then the value of concat(stringList) is "Put 'em all together".
# Show the exact output produced by the following code segment.
char[][] pic = new char[6][6];
for (int i = 0; i < 6; i++)
for (int j = 0; j < 6; j++) {
if ( i == j || i == 0 || i == 5 )
pic[i][j] = '*';
else
pic[i][j] = '.';
}
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 6; j++)
System.out.print(pic[i][j]);
System.out.println();
}
Answer: The output consists of six lines, with each line containing six characte
rs.In the first line, i is 0, so all the characters are *'s.In the last line, i
is 5, so all the characters are *'s.In each of the four lines in the middle, one
of the characters is a * and the rest are periods.The output is
******
.*....
..*...
...*..
....*.
******
It might help to look at the array items that are printed on each line.Note that
pic[row][col] is '*' if row is 0 or if row is 5 or if row and col are equal.
pic[0][0] pic[0][1] pic[0][2] pic[0][3] pic[0][4] pic[0][5]
pic[1][0] pic[1][1] pic[1][2] pic[1][3] pic[1][4] pic[1][5]
pic[2][0] pic[2][1] pic[2][2] pic[2][3] pic[2][4] pic[2][5]
pic[3][0] pic[3][1] pic[3][2] pic[3][3] pic[3][4] pic[3][5]
pic[4][0] pic[4][1] pic[4][2] pic[4][3] pic[4][4] pic[4][5]
pic[5][0] pic[5][1] pic[5][2] pic[5][3] pic[5][4] pic[5][5]
# Write a complete subroutine that finds the largest value in an array of ints.T
he subroutine should have one parameter, which is an array of type int[].The lar
gest number in the array should be returned as the value of the subroutine.
Answer: public static int getMax(int[] list) {
int max = list[0];
for (int i = 1; i < list.length; i++) {
if (list[i] > max)
max = list[i];
}
return max;
}
# What is a precondition? Give an example.
Answer: A precondition is a condition that has to hold at given point in the exe
cution of a program, if the execution of the program is to continue correctly.Fo
r example, the statement "x = A[i];" has two preconditions: that A is not null a
nd that 0 <= i < A.length.If either of these preconditions is violated, then the
execution of the statement will generate an error.
Also, a precondition of a subroutine is a condition that has to be true when the
subroutine is called in order for the subroutine to work correctly.
# Is "abc" a primitive value?
Answer: The String literal "abc" is not a primitive value. It is a String object
.
# What restrictions are placed on the values of each case of a switch statement?
Answer: During compilation, the values of each case of a switch statement must e
valuate to a value that can be promoted to an int value.
# What modifiers may be used with an interface declaration?
Answer: An interface may be declared as public or abstract.
# Is a class a subclass of itself?
Answer: A class is a subclass of itself.
# What is the difference between a while statement and a do statement?
Answer: A while statement checks at the beginning of a loop to see whether the n
ext loop iteration should occur. A do statement checks at the end of a loop to s
ee whether the next iteration of a loop should occur. The do statement will alwa
ys execute the body of a loop at least once.
# What modifiers can be used with a local inner class?
Answer: A local inner class may be final or abstract.