CompSci Midterm Review

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

In Java, a comment on a line begins with which characters?

//

In Java, what symbol(s) indicate(s) a comment that starts at the symbol(s) and stops at the end of the line?

//

Assuming that the values stored in a byte are integers, what are the min value and the max value?

127 (2^7) ,-128 (-2^7)

What is the result of the following expression? 12 + 6 * 3 - 15

15

Which of the following statements about classes is correct?

A class declares the methods that you can apply to its objects.

Which of the following statements will create a reference, str, to the String "Hello, World"?

String str = new "Hello, World";

Which of the following is false about ASCII and Unicode?

A number in Unicode is stored inside the computer as the number itself. For example, the first character "1" in the string "123 Main Street" is internally stored as 0001-16 or 1-10

In all number systems, the lowest-value digit is 0; the highest-value digit varies depending on the system. What is the largest digit in the hexadecimal system?

F

Who created Java? Who owns it now?

Sun Microsystems, led by James Gosling. Oracle.

What is the difference between syntax and style?

Syntax is required by the compiler; style is necessary to promote readability & understanding by programmers.

If greeting refers to a String object, which of the following is a syntactically correct Java statement?

System.out.println(greeting.length());

Java source files end with the .class extension.

False

The contents of a variable cannot be changed while the program is running.

False

The public access specifier for a field indicates that the field may not be accessed by statements outside the class

False

The term "default constructor" is applied to the first constructor written by the author of the class.

False

When a local variable in an (instance) method has the same name as an (instance) field, the field hides the local variable.

False

Which of the following statements about test programs is true?

Test programs verify that methods have been implemented correctly.

You can find the Unicode Table by searching for "____".

Unicode

Given the following code is for a partial class: [1] public class ShoppingBag { [2] private int itemCount;... [3] public ShoppingBag(int count, ...) { [4] count = itemCount ;... } ... } Which line is the FIRST to contain an error, or "No error"?

Line 4

A value that is written/hard-coded in the code is called ____.

Literal

What is the difference between a literal constant and a symbolic constant?

Literal constant is the value (whether it is text or number); symbolic constant is a name representing an unchanged value (or constant)

There are 2 things that must be completely written in one line; i.e., without "return" key. What are they?

Literal string in double quotes, and end-of-line comment (with //)

Every Java application program must have ____.

a method named main

A computer program is ____.

a set of instructions that allow the computer to solve a problem or perform a task

What terminology describes a method that returns information about an object and does not change the object's internal data?

accessor

Variables of the boolean data type are useful for

evaluating conditions that are either true or false

How does one finds out which libraries come with the JDK, and how to use/call data or methods in them?

We search on the Internet for "java api", which will show the javadoc-style documentation detailing all libraries in Java.

The header of a value-returning method must specify __________.

the data type of the return value

The scope of a public instance field is ____

the instance methods outside the class

To indicate the data type of a variable in a UML diagram, you enter __________.

the variable name followed by a colon and the data type

which type of method performs a task and sends a value back to the code that called it?

value-returning

What is a named storage location in the computer's memory called?

variable

In Java, ___ must be declared before they can be used.

variables

What is the declared return type for a method that does not have a return value?

void

Which of the following statements will correctly convert the data type, if x is a float and y is a double?

x = (float)y;

if x has been declared an int, which of the following statements is invalid

x=1,000;

The only purpose of ____ is to initialize the fields of the class.

constructors

Assuming that the values stored in a byte are non-negative, what are the min value and the max value?

0,255(2^8 -1)

What is the result of the following expression? 11 - 7 * 2 + 25 / 5

2

What will be the value stored in the variable a after the execution of the following code segment? int x = 9; int y = 36; int z = 4; int a = y / x /* z */;

4

What is the result of the following expression? 17%3*2-12+15

7

What is the result of the following expression? 25 / 4 + 4 * 10 % 3

7

Which of the following is false?

Constructors & methods of one class can call all constructors & methods (i.e., both private & public) of another class

The line public class HelloPrinter indicates which declaration below?

Declaration of the class HelloPrinter.

Which of the following is not a primitive data type? I. int II. double III. char IV. String

IV only

What is the result of the following code? int count = 2000 * 3000 * 4000;

Integer overflow

Which of the following does not describe a valid comment in Java?

Multi-line comments, start with */ and end with /*

Where must program instructions and data reside in order for the CPU to directly read and execute them?

RAM, or memory

Which of the following signature(s) is/are a no-args constructor(s)?

Rectangle()

What is the name of the type that denotes a string of characters?

String

What are the 3 kinds of variables? Describe the characteristics of each kind: how/where are they declared & initialized, their scope, etc.

The 3 kinds of variables are: Fields Local variables Parameters, or formal parameters See the Supplemental Slide about the differences & similarities of these variables

What are the 4 main parts (including the tester) inside the body of a class? Cite them in the order used by most programmers.

The 4 parts inside the body of a class are, in the following order: fields constructors methods main program / tester

A class in not an object. It is a description of an object.

True

In Java, what must be declared before they can be used?

Variables

What is the name of the = operator in Java?

assignment

What tool translates high-level instructions into low level machine code?

compiler

A value that is written/hard-coded in the code is called __.

literal

____ represent behaviors of a class.

methods.

The methods of which class (same vs. different) can access private fields of that class?

of the same class

Software refers to

programs

public class Pyramid { private Triangle base; private double height; public Pyramid() { base = new Triangle(1); height = 1; } public Pyramid(double side, double h) { base = new Triangle(side); height = h; } public double getBaseArea() { return base.getArea(); } public double getVolume() { double baseArea = getBaseArea(); return baseArea * height / 3; } } Given class Pyramid above, identify the line number(s) for the class header.

1

What are the two important things about developing good source code?

1. A programmer's product is not an executable program. It is the source code, which is updated periodically, can live for years; thus, to be of any use, it must be readable to others. 2. Bad or unconventional style is uncool, as if developed by an amateur lacking aesthetic pride.

In the base-10 system, adding 1 to the max digit 9 results in 10. What is the result of adding 1 to 1 in the binary system (written as a binary number)? What is the result of adding 1 to F in the hexadecimal system (written as a hex number)?

10_2, 10_16

public class Pyramid { private Triangle base; private double height; public Pyramid() { base = new Triangle(1); height = 1; } public Pyramid(double side, double h) { base = new Triangle(side); height = h; } public double getBaseArea() { return base.getArea(); } public double getVolume() { double baseArea = getBaseArea(); return baseArea * height / 3; } } Given class Pyramid above, identify the line number(s) for the method(s).

12-18

How many possible colors are there if 24 bits are used?

16777215 (2^24 -1)

How many the possible values that can be stored in a bit?

2 (0 and 1)

When we say the size of a photo is "2 meg", we mean that it contains approximately __.

2 million bytes

There are ten digits in the decimal number system. How many digits are there in a binary system? In a hexadecimal system?

2,16

public class Pyramid { private Triangle base; private double height; public Pyramid() { base = new Triangle(1); height = 1; } public Pyramid(double side, double h) { base = new Triangle(side); height = h; } public double getBaseArea() { return base.getArea(); } public double getVolume() { double baseArea = getBaseArea(); return baseArea * height / 3; } } Given class Pyramid above, identify the line number(s) for the field(s).

2-3

The color of a pixel can be represented using the RGB (Red, Green, Blue) color model, which stores values for red, green, and blue. Each of these components ranges from 0 to 255. How many bits would be needed to represent a color in the RGB model?

24

The data type for a color in Java is composed of three parts (i.e., Red, Green, and Blue), each of which is 8 bits. The lowest Red value is 0, i.e., no red. What is the highest Red value? Note: This value is the same for Green or Blue also.

255

How many the possible values that can be stored in a byte?

256 (2^8)

In Appendix B, how many common errors were cited?

28 errors

In Java, a variable of type int is represented internally as a 32-bit signed integer. Suppose that one bit stores the sign, and the other 31 bits store the magnitude of the number in base 2. In this scheme, what is the largest value that can be stored as type int?

2^31 - 1

Given that the Circle class has a field containing the radius, and the setRadius method updates it. What is the output of the following code: Circle c1 = new Circle(3); Circle c2 = new Circle(3); c1.setRadius(4); System.out.println(c2.getRadius());

3

public class Pyramid { private Triangle base; private double height; public Pyramid() { base = new Triangle(1); height = 1; } public Pyramid(double side, double h) { base = new Triangle(side); height = h; } public double getBaseArea() { return base.getArea(); } public double getVolume() { double baseArea = getBaseArea(); return baseArea * height / 3; } } Given class Pyramid above, identify the line number(s) for the constructor(s).

4-11

What is the result of the following expression? 10 + 5 * 3 - 20

5

What is the value of z after the following code is executed? int x = 5, y = 28; float z; z = (float) (y / x);

5.0

Recall that ASCII or Unicode character for upper case "A" and lower case "z" are 6510 and 12210, respectively. What is the value of character "J"?

74-10

How many bits are there in a byte?

8

What is the result of the following expression? 11 + 7 * 2 - 17

8

a) How many bits does a 2-digit hex number occupy? b) And if the smallest value is 0, what is the largest base-10 value?

8, 225

Suppose there are 2 int values numOne and numTwo in a tester program with the following code fragment: : // Suppose numOne has value 3, and numTwo has value 5 at this time numOne = numOne + numTwo; System.out.print(numOne); System.out.print(", "); System.out.print(numTwo); :

8, 5

What is the value of z after the following statements have been executed? int x = 4, y = 33; double z; z = (double) (y / x);

8.0

What is the (decimal) value of the largest digit in a base-10 system?

9 (0-9)

When writing documentation comments for a method, you can provide a description of each parameter by using a __________.

@param tag

What is the difference between class and object?

A class (the source code written by programmers) may be thought of as a blueprint describing what the objects are and how they behave. An object (which becomes live, created by the new operator and initialized by the constructor, during run-time) is a specific entity of the "class" type, with its own set of (unique) attributes. E.g., Dog may be a class; Spot an object.

What is the difference between a console application and a GUI application?

A console application communicates with the user through simple text and the keyboard a GUI application uces windows, different kinds of graphics, keyboard, mouse and more.

What is the return type of a constructor?

A constructor does not have a return type.

What is "Scanner"?

A library class in the java.util package that helps to read user input from the keyboard

What is the purpose of a library? Give one example of a class in library that you have used.

A library is often something basic or common, which is created once and used many times by (other) programmers. Example: Scanner, or Math.

What is FALSE about Java naming convention?

A method name starts with an upper-case letter.

Which of the following is false about ASCII and Unicode?

A number in Unicode is stored inside the computer as the number itself. For example, the first character "9" in the string "9870 Broadmoor Drive" is internally stored as 0009-16 or 9-10

What is a run-time/logic error?

A program that is syntactically correct but does not do what it is supposed to do.

In OOP paradigm, is a subclass more general or more specific than its superclass? Give an example.

A subclass is more specific than its superclass; e.g., a Student object is more specific than a Person.

What is the difference in RAM storage between a variable of primitive data type vs. of a class?

A variable of primitive data type has designated number of bytes on RAM (e.g., 4 bytes for an int), where the value is stored as the result of an assignment statement. An object (i.e., variable of class type), also called instance of a class, has 2 RAM "slots". The first slot is for the address (as the result of the declaration, e.g., Rectangle box). The second slot has the contents of the object (as the result of new and constructor call). The address is also called reference.

What is a compile-time/syntax error?

A violation of the rules of the computer language.

What are the major components of a typical computer? A) All of these B) Secondary Storage Devices C) Input/Output Devices D) The CPU E) Main memory

A) All of these

Given the following statements: (i) "User friendly" software is one of the current priorities in software development. (ii) Debugging (i.e., finding and correcting the errors in the code) is one of the responsibilities of a programmer. (iii) The term "software engineering" refers to the profession of developing computer software. A) I, II, III B) I, II C) II, III D) I, III

A) I, II, III

Given the following statements: (I) Java reusable software components are usually distributed in packages. (II) To use a software component created by another programmer, you must have access to its source code. (III) A reusable software module should come with documentation that describes the conditions under which it works properly. (IV) You need a special compiler to create reusable software components. A) I, III B) I, II C) II, III, IV D) I, II, III

A) I, III

A block of Java code, such as the body of a class or the body of the main program or method, is enclosed in: I. A pair of (square) brackets II. A pair of braces (i.e. curly brackets) III. A pair of parentheses A) II only B) All C) I and II D) II and III E) III only

A) II only

Which of the following is not a rule that must be followed when naming identifiers (i.e., variables, methods, classes, etc.)? I. The first character must be one of the letters a-z, A-Z, and underscore or a dollar sign. II. Identifiers can contain spaces. III. Uppercase and lowercase characters are distinct IV. After the first character, you may use the letters a-z, A-Z, the underscore, a dollar sign, or digits 0-9. A) II B) II and IV C) III D) I E) IV

A) II only

About char data type in Java (which is used for Unicode character), a) How many bytes are there? b) How many possible values (i.e., the size of the Unicode Table)? How? c) What is the lowest value? d) What is the highest value? NOTE: You don't need to memorize this value.

A) There are 2 bytes. B) There are 65,536 possible values. C) The lowest value is 0. D)The highest value is 65,535.

Recall that an int in Java occupies 4 bytes. Explain each case. a) How many different integer values are in an int? b) What are the minimum and maximum values? c) Which of the following can be stored in an int? Why or why not? 10-digit telephone number: Date in the form MMDDYYYY; e.g., July 4, 1776 is represented as 07041776

A) There are 4 bytes, or 32 bits, in an int. Thus, there are 2^32 = 4,294,967,296 B) -2^31= -2,147,483,648 and 2^31 -1 = 2,147,483,647 c) You can't put Telephone numbers because the numbers can not be higher than 2,147,483,64. But you can put the date because that's only 8 numbers.

About int data type in Java, a) How many bytes are there? b) How many possible values? How? c) What is the lowest value? How? What is it called in the Java language? d) What is the highest value? How? What is it called in the Java language? e) Is this int data type large enough to store a 9-digit social security number? A full 10-digit telephone number?

A) There are 4 bytes. B) 4,294,967,296 C) Integer.MIN_VALUE -2,147,483,648 D) Integer.MAX_VALUE 2,147,483,647 E) An int is large enough to store a 9-digit social security number. But it can't store a telephone number because the numbers can not be higher than 2,147,483,64.

About double data type in Java, a) How many bytes are there? c) What is the lowest value? NOTE: You don't need to memorize this value but should know how to look up.. d) What is the highest value? NOTE: You don't need to memorize this value but should know how to look up. e) Give some examples of real-life data that can be represented by a double.

A) There are 8 bytes. B) -1.8 X 10^308 C) 1.8 X 10^308 D) Distance, Time, Money

About ASCII and Unicode characters: a) What does ASCII stand for? And how is it pronounced? b) How many bytes are used for an ASCII character? c) Are the ASCII characters part of the Unicode Table? d) What are the values for characters from 'A' to 'Z'? Answer in hex and decimal values. e) What are the values for characters from 'a' to 'z'? Answer in hex and decimal values. f) What are the values for characters from '0' to '9'? Answer in hex and decimal values. g) What are the values for characters of your initials, in upper case? Answer in hex only. i) Which character of your initial is larger? By how much, compared to the other initial. Answer in hex only.

A)American Standard Code for Information Interchange B) 1C) YesD) 65 - 90, with 65 for A, 66 for B and so on 41 - 5A, with 41 for A, 42 for B and so onE) 97 - 122; , with 97 for a, 98 for b and so on 61 - 7A, with 61 for A, 62 for B and so on F) 48 - 57, with 48 for 0, 49 for 1 30 - 39, with 30 for 0, 31 for 1 and so on G) SR S-53 R-52 I) S is bigger by 1

Which of the following is true? An object in OOP can a) model real-world objects (e.g., Spot, Clifford, etc.) b) represent GUI (Graphical User Interface) components (e.g., window, menu bar, etc.) c) represent software entities (events, files, images, etc.) d) represent abstract concepts (for example, rules of a game, a location on a grid, etc.)

All true

What is the order of operations?

All unary operators have higher rank than all binary operators. Among the binary operators, the ranking is as follows, from highest to lowest: o Arithmetic operators (*, /, +, -), like PEMDAS order o Relational operators (<, >=, etc.) o Logical operators (and &&, or ||): && has higher rank than || Use parentheses when unsure of order of operation.

What is an object?

An entity in your program that is manipulated by calling methods.

What is the result of executing the following code? final int x = 22, y = 4; y += x; System.out.println("x = " + x + ", y = " + y);

An error occurs

Which of the following best describes a console application?

An interactive program that uses only text input and output, and no GUI

What does an interpreter do?

An interpreter takes the source code, compiles it, links it, and runs it all at the same time.

In Object-Oriented Programming (OOP) model, a program is a world of objects. What are the 2 things that an object have? And what are their purposes/functions?

An object has fields and methods. Fields represent the object's attributes (e.g., color or dimension). Methods represent the object's behaviors: do a task (e.g., move, turn, stop), calculate something and/or modify its fields, create a new object, communicate with another object (e.g., get that object's location), etc.

In Object-Oriented Programming (OOP) model, a program is world of objects. What are the 2 things that a class have? And what are their functions?

An object has fields and methods. Fields represent the object's attributes (e.g., color or dimension). Methods represent the object's behaviors: do a task (e.g., move, turn, stop), calculate something and/or modify its fields, create a new object, communicate with another object (e.g., get that object's location), etc.

Which one of the following is a function of a CPU? A) Performing arithmetic operations B) Fetching and storing data from storage and devices C) All of these D) Processing data and controlling programs

C) All of these

One of the advantages of Java's hybrid compiler + interpreter approach is that it (I) lets us deliver platform-independent applets over the Internet without their source code. (II) speeds up the interpretation of applets received from the Internet. (III) provides an additional step at which applets can be screened for malicious code. A) I, II B) II, III C) I, II, III D) I, III

C) I, II, III

Which of the following is JDK's program editor? A) javac.exe B) javadoc.exe C) JDK does not include an editor D) java.exe

C) JDK does not include an editor

Try the code in your Verifier to verify your answers. Consider the following code segment: int sum = 0; for (int k=1; k < 2; k++) sum += k; System.out.println("k and sum = " + k + " " + sum); What will be displayed if the following code segment is run? Explain why.

Campiles

Which statement declares a variable that references a Circle of radius 3, assuming the construction parameter is the radius value?

Circle c = new Circle(3);

Which of the following is not a primitive data type? I. int II. double III. char IV. String A) II only B) I only C) III only D) IV only E) III and IV only

D) IV only

Cite 4 development tools.

Editor, compiler, linker, debugger

Show the path as well as the tools and input/output necessary in creating a Java program.

Editor: Programmer -> source Compiler: Source -> Bytecode Interpreter Bytecode -> user

In a method's header, which of the following indicates that the method does not take any parameters/inputs?

Empty parentheses after the method's name

What is the result of executing the following code? public class Tester { public static void main(String[] args) { int num = 5; System.out.println(num); int num = 16; System.out.println(num); int num = 22; System.out.println(num); } }

Errors

What is a program called when the user is in control by initiating tasks (such as resizing the window, or dragging something) at any time - instead of the program being in control where it asks/forces the user to choose/do certain tasks at certain time/condition.

Event-driven program

Which of the following statements about objects is correct?

Every object belongs to a class.

Give an example of a symbolic constant used in the Color class.

Example of a symbolic constant used in the Color class is: static Color BLACK;

Select all that apply. Local variables __________. a)cannot be changed once they are given a value in the method where they exist b)may have the same name as local variables in other methods c)lose the values stored in them between calls to the method in which the variable is declared d)are hidden from other methods

May have the same name as local variables in other methods Lose the values stored in them between calls to the method in which the variable is declared Are hidden from other methods

Use the Student class for the next questions. Suppose class Student has three constructors: public Student() { /* code not shown */ } public Student(String name) { /* code not shown */ } public Student(String name, int age) { /* code not shown */} Based on these constructors of Student, for each of the statements in the next questions, decide whether the statement is compiled successfully, and answer "yes" or "no". Student s3 = new Student(16);

No

Use the Student class for the next questions. Suppose class Student has three constructors: public Student() { /* code not shown */ } public Student(String name) { /* code not shown */ } public Student(String name, int age) { /* code not shown */} Based on these constructors of Student, for each of the statements in the next questions, decide whether the statement is compiled successfully, and answer "yes" or "no". Student s4 = new Student(16, "Amy");

No

Which of the following statements correctly creates a Scanner object for keyboard input?

Scanner keyboard = new Scanner(System.in);

Write a statement to construct Scanner object to get input from the user through the keyboard.

Scanner keyboard = new Scanner(System.in);

Which one of the following memory types provides storage that persists without electricity

Secondary Storage

Which one of the following memory types provides storage that persists without electricity?

Secondary Storage

Cite the 17 "rules" in Appendix A.

See the document

With the same variables as the previous question, what does the following statement do? int b = b;

The statement takes the value of b and assign it to b, which causes no changes ... so don't ever write a statement like that

What is wrong with the following code segment? int sum; sum = u85;

The sum variable is assigned a non-numeric value.

public class Book { : : public Book(int pages) { int pages = numPages; int currentPage = 1; }

The two fields were already declared in the field section of the class. The two variables, numPages and currentPage, declared as int here, are local variables, not the fields. Remember: every time you declare, you get new/different RAM space. It is these local variables that are assigned here. And they "go away" at the end of the constructor call (scope). The fields were never assigned to appropriate values.

What is the result of executing the following code? int n = 203; System.out.print("There are " + n + 2 + "\n" + "hens in the hen house.");

There are 2032 hens in the hen house.

What is the result of executing the following code? int n = 203; System.out.print("There are " + n + 2 + "\n" + "hens in the hen house.");

There are 2032 hens in the hen house.

How many kinds of errors are there? What are they?

There are 3 kinds of errors: • Syntax or compiler errors occur at incorrect syntax, flagged by the compiler; e.g., incorrect spelling of a reserved word, or passing the wrong number of parameters or data types to a method call. • Logic errors occur at code with unintended consequence although correct syntax; such as "Hello, Word" instead of "Hello, World". • Runtime errors occur during runtime (which normally results in a program crash), caused by lack of checking of all scenarios in the code; e.g., division by zero

There may be more than one constructor in a class. Why/how? And what is this situation called?

There are several constructors to accommodate different parameters/inputs. This is called overloading the constructors.

Chapter 2 files from "StudentsFiles": Open the "Ch02" folder in the "StudentsFiles" Questions: What are in the "Ch02" folder? What are the files in each folder? Cite full names, i.e., including the file extensions.

There are: The "Exercises" folder: o The "Solutions" folder: The "HelloApplet2.java" file The "PrintFace.java" file The "TestApplet2.html" file o The "RedCross.java" file The "Hello" folder: o The "Greetings.java" file o The "Greetings2.java" file o The "HelloWorld.java" file The "HelloGui" folder: o The "Banner.java" file o The "HelloApplet.java" file o The "HelloGraphics.java" file o The "HelloGui.java" file o The "TestApplet.html" file o The "TestBanner.html" file

What is the result of the following code when executed?System.out.println("Hello!);

There is a compile-time/syntax error.

What is the result of running the following code? final double x = 99.0; x = 54.3; System.out.println("x = " + x );

There is an error

What is false about comments written for the purpose of javadoc documentation?

They are written inside /* ... */

What is the purpose of verifying the results of a program?

To determine whether the program solves the original problem

What does TCP/IP stand for?

Transmission Control Protocol / Internet Protocol

A constructor is a "method" that is called when an object is created.

True

Methods are commonly used to break a problem into small manageable pieces.

True

True or false? A class description (as in the API) usually (but not always) has 3 parts: * fields, to represent the attributes or characteristics of the object * constructors, to initilize the fields when an object is created * methods, to carry out behaviors

True

When an object's internal data is hidden from outside code and access to that data is retricted to the object's methods, the data is protected from accidental corruption.

True

Compare/contrast the functionality of a compiler vs. interpreter.

Using a compiler gives faster run time because the source code has already been translated to executable code. Using an interpreter requires only one kind of files: the source code.

Recall that, in Java, an int represents negative and non-negative integers, where 1 bit is set aside for the sign (i.e., + or -), called the sign bit. Which of the following is false?

When the sign bit contains 1, the integer is positive

When MUST a method have a return statement?

When, in the signature, there is a data type for e a return value, i.e., when it is not void.

Use the Student class for the next questions. Suppose class Student has three constructors: public Student() { /* code not shown */ } public Student(String name) { /* code not shown */ } public Student(String name, int age) { /* code not shown */} Based on these constructors of Student, for each of the statements in the next questions, decide whether the statement is compiled successfully, and answer "yes" or "no". Student s1 = new Student();

Yes

Use the Student class for the next questions. Suppose class Student has three constructors: public Student() { /* code not shown */ } public Student(String name) { /* code not shown */ } public Student(String name, int age) { /* code not shown */} Based on these constructors of Student, for each of the statements in the next questions, decide whether the statement is compiled successfully, and answer "yes" or "no". Student s2 = new Student("Amy");

Yes

Use the Student class for the next questions. Suppose class Student has three constructors: public Student() { /* code not shown */ } public Student(String name) { /* code not shown */ } public Student(String name, int age) { /* code not shown */} Based on these constructors of Student, for each of the statements in the next questions, decide whether the statement is compiled successfully, and answer "yes" or "no". Student s4 = new Student("Amy", 16);

Yes

Consider the following code fragment: : [1] int itemCount = 5; [2] int unitPrice = 2; // in whole dollars only [3] int totalCost = unitPrice * itemCount; : [4] int itemCount = 7; [5] int totalCost = unitPrice * itemCount; : Which is the FIRST incorrect statement?

[4]

The following face is the result of four of System.out.println statements: Fill the text for the string in line 4, which has 5 characters altogether: 1 backslash, 3 underscores, 1 forward slash: System.out.println(" ");

\\___/

To understand the min & max integers (Integer.MIN_VALUE & Integer.MAX_VALUE), do the following, and write the 4 values on your paper & tell your observation: a) Print the min integer b) Print the min integer minus 1 c) Print the max integer d) Print the max integer plus 1

a) -2,147,483,648, as expected b) 2,147,483,647, now positive: error! c) 2,147,483,647, d) -2,147,483,648, now negative: error!

About documentation comments: a) What are these comments enclosed in? b) Where/what should there be such comments c) What are the @ tags, and what do they mean?

a) /** ... */ b) Before a class, before each constructor, and before each method. c) There are 4 tags: @author: for the author's name @version: for the version number/date @param: for each parameter (with name and description @return: for a return value, describing it

Explore BlueJ: a) What are the menus in the project window? b) What indicates that a "class" tile is selected? c) What are the menu items in the terminal window or console window? Note: it is a good idea, in the Option menu, to always check "Clear screen at method call" and "Unlimited buffering". d) What happens when a class tile in the project window is double-clicked?

a) 5 menu items: Project, Edit, Tools, View, Help b) 2 slant lines at the lower right corner of a tile indicates that it is selected. c) 1 menu item: Options d) When the tile is double-clicked, the source file is opened, ready to be edited. We will refer to this window as the class window.

About a method: a) How is a method named? b) How is a method declared, i.e., what is the signature of a method, and how many parts? Give an example. c) What is the purpose of a method? d) How many outputs can a method have? e) How is a method invoked/called? Give an example.

a) A method name, like a field name, starts with a lower-case letter, and each subsequent word starts with an upper-case letter (camel case). The method name, decided by the programmer, is usually a verb and should be descriptive of what the method does. b) There are at least 4 parts in a constructor declaration, one more than a constructor: reserved word public or private, return/output data type or void, method name, and optional parameters (i.e., inputs) inside a pair of parentheses. E.g.: public void deposit(double amt) c) The purpose of a method is to do a task, or calculate some value, or both, and optionally return an output. d) There is either no output (if declared with void), or 1 output (if declared with a return data type). There cannot be more than 1 output. e) If the method is called by a method in another class/file (like a tester), then the object must have been already created; and the call is made like the following: nemosAcct.deposit(200);. If the method is called by another method in the same class/file, then the method call does not include the object: deposit(5);

Public vs. private: a) What is the restriction of a public vs. private constructor or method? I.e., how does a programmer decide a constructor or method public or private? b) What about a public vs. private field?

a) A public constructor or method can be used by another constructor or method of another class. A private constructor or method can be used only by another constructor or method of the same class. Thus, a public constructor or method is to serve others; a private one is for internal use only. b) Similar restriction is on a field. Due to the advantages of information hiding, most fields are declared private; and these fields may be accessed by public methods.

What is a software engineer able to do?

a) Absorb and use emerging technical information b) Create sound software system architectures c) Understand and devise effective algorithms d) Be proficient with the syntax and style of programming languages e) Diagnose and correct programming errors f) Use software development tools and documentation g) Find and utilize reusable software components h) Design and implement friendly user interfaces i) Uphold the highest standards of professional ethics

a) What does an escape sequence look like? b) How many characters does one escape sequence represent? c) What is the purpose of an escape sequence?

a) An escape sequence is a 2-character sequence, starting with a backslash b) One escape sequence (i.e. 2 character) represent 1 (special) character c) To represent a special character, like tab or newline, or quotes

In Java, how does a programmer indicate a) Inheritance? b) Ownership?

a) By using reserved word extends in a class header; e.g., public class Bug extends Actor b) By having the owned item as a field in the class; e.g., class Cylinder has a field called Circle base.

a) What does CPU stand for? b) What is a CPU?

a) Central Processing Unit b) It is composed of a large number of transistors on silicon chips that control the signals/spikes of electricity - where the presence of the electricity spike is represented by 1, and absence by 0. It is the CPU that interprets and performs tasks as instructed in a program.

Run a program in a BlueJ project, in Proj02: In BlueJ, right-click on the brown tile & choose "void main(String[] args)" Question: a) What happened? b) There is a name for this kind of programs, where the input & output between the computer & user is text- based (i.e., no fancy pictures or images or GUI). What is this kind of programs called?

a) The program launched, and displayed "Hello, World!" in a separate window called "terminal window". b) It is called console programs.

Delete a class from a BlueJ project, in Proj02: In the project window, click on the HelloWorld tile and choose "Edit > Remove" Questions: a) In BlueJ, what is or is not in the project window? b) In the Proj02 folder on disk, what is there? c) In the StudentsFiles folder, is the HelloWorld.java file still there? Now "add class from file ..." the HelloWorld class from the StudentsFiles folder, so as to continue with the next steps

a) The tile was deleted from the project window. b) All the files related to this HelloWorld class were deleted from the Proj02 folder on disk. c) Yes, it is still there; the StudentsFiles folder is not affected (same as when a class was added to the Java project).

a) How many primitive data types does Java have? b) What are the 4 primitive data types that we will be working with? Their sizes in bytes for each? c) Are the names of primitive data types reserved words?

a) There are 8 primitive data types b) What are the 4 primitive data types that we will be working with: int (4 bytes), double (8 bytes), char (2 bytes), boolean (1 byte) c) Yes, the names of primitive data types are reserved words (& all in lower-case letters)

What is each of the following? What does each do? a) Browser b) Search engine c) Portal d) Host e) Server f) URL

a) provides convenient way to download and display information from the Internet b) indexes and helps find the Internet documents that contain specified keywords and phrases c) a large popular/main web site as an "entrance" to an organization or function d) a computer connected to a network e) a computer on a network that provides a specific service (i.e., email) f) Uniform Resource Locator, an address of or link to a document or a resource on the Internet

The word "bit" is from ____.

binary digit

If greeting is a String object, which method call is incorrect?

greeting.println()

Suppose there are 2 int variables called height and width, where height is 3 and width is 4. What values do these variables have after the following Java statement? height = width;

height is 4; width is 4

A Java source file usually has one class, which can use other classes. Which of the following statements tells the compiler where to find these other classes (from the Java Library)?

import

Write a statement to include java.util.Scanner (to enable getting input from the user through the keyboard) in a program.

import java.util.Scanner;

Parameters may be viewed as ___ to a constructor or method.

inputs

When an object is created, the attributes associated with the object are called __________.

instance fields

Select all that apply. Which of the following types of values can be passed to a method that has an int parameter variable? a)long b)double c)int d)float

int

What are the data types for 0 and "0"?

int and String

To simulate the roll of a 6-sided die, we can use the Random class to get a number. Suppose the import statement has been specified, and object randGen of class Random has been created. Complete the following statement to get a number which simulates a die roll: int dieVal = randGen.nextInt__________;

int dieVal = randGen.nextInt(6) + 1;

public class Date { //FIELDS private int month; private int day; private int year; //CONSTRUCTORS public Date() { ... } public Date(int mo, int da, int yr) { ... } // METHODS public int getMonth() { ... } // returns month public int getDay() { ... } // returns day public int getYear() { ... } // returns year // Returns a date representation of Date "m/d/y"; // e.g., 6/6/1944 public String toString() {...}} A client program declared Date d, and correctly created that object (for 9/2/1945). Which of the following code will cause an error?

int y = d.year;

A constructor always has the same name as ___.

its class

When an argument is passed to a method ___

its value is copied into the methods parameter variable

What are some common Java packages that you have worked with?

java.util - miscellaneous utility classes java.awt (Abstract Window Toolkit) - windowing & graphics toolkit javax.swing — GUI development package (look & feel - checkbox, button, label)

What does JDK stand for? Cite the 5 tools in the JDK, and their functions.

javac (compiler) java (interpreter) appletviewer (viewer of applets) javadoc (documentation generator) jar (packaging)

You should always document a method by writing comments that appear ___.

just before the method's definition.

Validating the results of a program is important to ____.

make sure the program solves the original problem

A __________ contains sequences of programming instructions that describe how to perform a particular task.

method

What is the decimal value of the largest digit in a base-n system?

n-1

Which operator constructs objects

new

Which operator constructs objects?

new

What is the name of the method in the Scanner class that reads a String?

nextLine()

Google Drive provides 15GB of storage space. If you decide to set aside 10GB for pictures, where the average size is 2MB, how many pictures can you store on 10GB of Google Drive?

numberOfPictures =TotalStorage/AveragePicturesSize =10GB/2MB =10,000MB/2MB =5,000MB So5,000 pictures may be stored in 10GB of Google Drive.

A method name is ____________________ if a class has more than one method with that name (but different parameter types).

overloaded

Methods that have the same name but differ in number of parameters, or differ in data types of parameters are called ____.

overloaded methods

A(n) _____________ is a collection of classes with a related purpose.

package

What is the name of the method in the following method call?System.out.println("Welcome");

println

The access specifier in the declaration of fields (aka instance variables) should be ___.

private

Write the code to declare a private field called sideLength, of class Square.

private int sideLength;

Who or what is responsible for inspecting and testing the program to guard against logic error?

programmer

What term is used to refer to an informal description of a sequence of steps or to an algorithm for solving a problem?

pseudocode

Write the signature for a no-args constructor of class Player

public Player()

Write the signature of a no-args constructor of class Player.

public Player()

Write the header/signature of a constructor of class Player with parameter called name of type String.

public Player(String playerName)

If r has been declared a double, which of the following statements is invalid? A) r = 374; B) r = -339.31; C) r = 4.2823e18; D) r = 2.2752e19; E) r = 2.3723X108;

r = 2.3723X108;

Byte code instructions are

read and interpreted by the JVM

The value calculated by a method is called its ___ value

return

What statement is used in a method to give a value to its calling method?

return

A method with void as return data type does not need to contain a/an ___.

return statement

An output from a method is called a(n) ____.

return value

What indicates the end of a Java statement?

semi-colon (;)

Character literals are enclosed in __; string literals are enclosed in __.

single quotes; double quotes

What term is used to refer to an individual instruction inside a method?

statement

Fill in the blank to complete the header of the main method: public _______(String[] args)

static void main

When one or both operands of the + operator is/are string(s), the operator is called __.

string concatenation operator

Variables are

symbolic names made up by the programmer that represent memory locations

A running program is a sequence of instructions stored in

the computer's memory

The central processing unit (CPU) consists of two parts which are

the control unit and the arithmetic and logic unit (ALU)

Application software refers to

the programs that make the computer useful to the user

In Java, a(n) _________ specifies the kind of values that can be stored in a variable.

type

By convention among Java programmers, class names begin with a(n) _____________.

uppercase letter

The camel case naming convention uses _________ at intervals in the middle of the variable name.

uppercase letters

In the API of the Rectangle class, among the method signatures are: double getWidth() void grow(int h, int v) Suppose object rect of class Rectangle has been created.Which of the following 4 statements uses the API with incorrect syntax, or "All have correct syntax"?

void g = rect.grow(20, 30);

What would be displayed as a result of executing the following code? int x = 15, y = 20, z = 32; x += 12; y /= 6; z -= 14; System.out.println("x = " + x + ", y = " + y + ", z = " + z);

x = 27, y = 3, z = 18

What output will be displayed as a result of executing the following code? int x = 5, y = 20; x += 32; y /= 4; System.out.println("x = " + x + ", y = " + y);

x = 37, y = 5

What will be displayed as a result of executing the following code? int x = 5, y = 20; x += 32; y /= 4; System.out.println("x = " + x + ", y = " + y);

x = 37, y =5

Based on good convention, which of the following is identified as a field, and which is a local variable? (I) private double curBalance; (II) double curBalance; Which of the following is TRUE?

(I) is a field; (II) is a local variable

Input to a method, enclosed in parentheses after the method name, is known as ______________.

arguments/parameters

In computer science (i.e., not math), what is a number such as 39.636363636364 called?

floating-point

A value-returning method must specify __________ as its return type in the method header.

Any valid data type

When an applet is called (by a browser), where, in the source code, does it start?

At public void init( )

When a Java program is run (by a user), where, in the source code, does it start?

At the main program: public static void main (String[] args)

Program errors can be caused by (I) bad syntax (II) code that compiles fine but is interpreted differently from what the programmer intended (III) code that compiles fine and behaves just as the programmer intended A) II, III B) I, II C) I D) I, II, III

B) I, II

How does BlueJ help you with understanding the scopes of variables in most situations?

BlueJ helps identify the scopes of variables by coloring the "blocks".

Which of the following is true about RAM (while a program is running)?

Both program and data are stored in RAM

What conventions should one follow when drawing a hierarchy diagram? What relationship does an arrow in the diagram represent?

Each class name is inside a tile More general classes (superclasses) closer to the top An arrow goes from a subclass to a superclass The arrow represents an IS-A relationship; e.g., a Student is a Person.

What is the simplest way to convert number (for example, of int type) to a String type?

The simplest way to convert number (for example, of int type) to a String type is to concatenate it with an empty literal string

public class Date { //FIELDS private int month; private int day; private int year; //CONSTRUCTORS public Date() { ... } public Date(int mo, int da, int yr) { ... } // METHODS public int getMonth() { ... } // returns month public int getDay() { ... } // returns day public int getYear() { ... } // returns year // Returns a date representation of Date "m/d/y"; // e.g., 6/6/1944 public String toString() {...}} Which of the following correctly creates a Date object in a client class?

Date d = new Date (7, 4, 1776);

In Java, it is standard practice to capitalize the first letter of: I) Variable Names II) Class Names III) Method Names A) III only B) I and III only C) I only D) I and II only E) II only

E) II only

What is the result of the following statement:System.out.print("\\* This calculates\n the total cost *\\"); A) \\* This calculates the total cost*\\ B) * This calculates the total cost * C) \* This calculates the total cost *\ D) * This calculates the total cost * E) \* This calculates the total cost *\

E) \* This calculates the total cost *\

Approximately how many bytes are there in the following? a) 1 Kilobyte (KB) b) 1 Megabyte (MB) c) 1 Gigabyte (GB) d) 1 Terabyte (TB)

Each "jump" is worth 2 10 or 1,024, i.e., approximately 103 or 1,000 bytes: a) Kilobyte (KB): approx. 1,000 (1 thousand) bytes b) Megabyte (MB): approx. 1,000,000 (1 million) bytes c) Gigabyte (GB): approx. 1,000,000,000 (1 billion) bytes d) Terabyte (TB): approx. 1,000, 000,000,000 (1 trillion) bytes

Cite 3 advantages of using OOP.

Facilitates team development Easier to reuse software components and write reusable software Easier GUI (Graphical User Interface) and multimedia programming

Critique the following source code: public class Book { : : // fields int numPages; int currentPage; : : }

Fields must be declared with reserved word public or private.

Which of the following cannot be done by a debugger?

Fix bugs in the program.

__________ refers to the physical components that a computer is made of.

Hardware

What is the name of the file that contains the Java source code for the public class HelloPrinter?

HelloPrinter.java

Which of the following is true about constructors? I. Providing a constructor for a class is optional. II. You can only provide one constructor for a class. III. The body of the constructor must initialize all instance variables, or the constructor will not successfully compile. IV. A constructor has a void return type.

I only

Which of the following is true about the constructors? I. Providing a constructor for a class is optional. II. You can only provide one constructor for a class. III. The body of the constructor must initialize all instance variables, or the constructor will not successfully compile IV. A constructor has a void return type.

I only

Given a class called Square, as partially shown: public class Square { private double side; ... public Square(...) { ..} ... public double getSide() {...} ... }

II only

In Java, it is standard practice to capitalize the first letter of I. Variable names II. Class names III. Method names

II only

The following are some method signatures of the Rectangle class: void setLocation(int x, int y) Moves this Rectangle to the specified location. double getY() Returns the Y coordinate of the bounding Rectangle in double precision. Which of the following is not syntactically correct, or "All correct", in using rect (which is a Rectangle object)? I. rect.setLocation(30, 50); II. void n = rect.setLocation(30, 50); III. rect.getY(); IV. double y = getY();

II only

Which of the following is not a rule that must be followed when naming identifiers (i.e., variables, methods, classes, etc.)? I. The first character must be one of the letters a-z, A-Z, and underscore or a dollar sign. II. Identifiers can contain spaces. III. Uppercase and lowercase characters are distinct. IV. After the first character, you may use the letters a-z, A-Z, the underscore, a dollar sign, or digits 0-9.

II only

Which of the following is not a rule that must be followed when naming identifiers?

Identifiers can contain spaces.

Cite all of the naming conventions in Java, in general, and also specifically for classes, variables & fields, constructor, and methods, constants, reserved words.

In general: Programmers choose the names in the code they write A name in Java must not contain blanks; thus, all words are next to each other. Words are "separated" by a starting uppercase letter (or are "separated" with an underscore); e.g., unitPrice. Names are case-sensitive; thus, unitPrice and unitprice are 2 different variables (i.e., in 2 separate RAM chunks) A name may contain (1) letters, (2) digits, (3) underscore character, and must start with a letter; e.g., 6pack is CANNOT be a name Names are chosen by programmers for the things that they code, and should be meaningful: unitPrice is meaningful; stuff is not. Name for a class: • should start with an upper-case letter; e.g., Rectangle • should be a noun (because it represents a category) • NOTE: constructor name must be exactly the same as that of the class name; the name of the source file is also the same (with extension .java) Name for a variable or field: • should start with a lower-case letter; e.g., unitPrice • should be a noun (because it represents a value, etc.) Name for a constructor: • See "Name for a class" Name for a method: • should start with an lower-case letter; e.g., getHeight • should be a verb (because it represents an action) Name for a constant: • should be all upper case; e.g., RED in Color.RED A reserved word: is in all lower case; e.g., public must be typed as-is, and cannot be used as a name for anything else

What does IDE stand for?

Integrated Development Environment

What is a console application?

It is a program where the interface is simple text, not GUI

What is RAM (random-access memory) used for?

It is a volatile type of memory, used only for temporary storage (while running a program)

When is it required to cast a numerical value? Give an example.

It is required to cast a numerical value from a higher-ranked type to a lower-ranked type. This is because this kind of assignment would result in losing some info; and the compiler wants programmers to confirm such loss. E.g., we must cast when assigning a double to an int: double x = ...; int n = (int) x;

What is the difference between the equal sign (=) in Java and in math?

It means the action of storing a value into a variable in Java; it means the assertion that 2 values are equal to each other

What does a semi-colon signify?

It signifies the end of a statement

How many digits are there in a base-n system? 16 In all number systems, the lowest-value digit is 0; the highest-value digit varies depending on the system. What is the largest digit in the hexadecimal system?

It's the base.

What are some of the peripheral devices (to provide input and output and secondary storage)?

Keyboard, external hard disk, flash drive, DVD drive, wireless network adapter, web camera, touch pad, microphone, speakers.

What are some of the input/output (I/O) devices?

Keyboard, mouse, printer, speakers.

Cite at least 5 kinds of software applications.

Large Business systems Databases Internet, e-mail, etc. Military Embedded systems Scientific Research AI Word processing and other small business and personal productivity tools Graphics/arts/digital photography Games

Try the code in your Verifier to verify your answers. Is the following statements correct? If yes, rewrite it as 2 separate simpler statements, and explain. int i = 1, k = 5;

No, it is not correct

Is it necessary to have a semi-colon after a closing brace?

No, it is not necessary. However, having a semi-colon after a closing brace causes no harm because it means that there is an empty statement after the block

What would be printed out as a result of the following code? Syestem.outprintln("The quick brown fox + "jumped over the \n" "slow moving hen.");

Nothing there is an error

What will be displayed as a result of executing the following code? public class test { public static void main(String[] args) { int value1 = 9; System.out.println(value1); int value2 = 45; System.out.println(value2); System.out.println(value3); value = 16; } }

Nothing. This is an error

what would be displayed as a result of executing the following code? final int x = 22, y = 4; y+=x; Syestem.out .println("x = "+x+", y= " + y)

Nothing. there is an error in the code

Because Java byte code is the same on all computers, on what kinds of computers can compiled Java programs run?

On computers with Java Virtual Machine (JMV)

What is the difference between one equal sign (=) and two equal signs (==).

One equal sign means assignment; two equal signs evaluate whether the 2 operands are equal or not, and give then answer as true or false

Declare 2 variables (unitPrice and quantity), and assign a reasonable value to each, say, for pens

One example is: double unitPrice = 4.50; int quantity = 3;

In the following Java statement, what value is stored in the variable name? String name = "Donald Duck";

The memory address where "Donald Duck" is located

In the API of the Rectangle class,among the fields is: int width and among the method signatures is:double getWidth() Suppose object rect of class Rectangle has been created. Write a statement to update the width of rectangle rect to, say, 400.

Only rect.width = 400;

What is the name (including the extension) of the file that is the result of compiling Pet.java?

Pet.class

Cite at least 5 advantages of using bytecode.

Platform-independent (i.e., not dependent on the Operating System (OS)) Loads from the Internet faster than source code Interpreter is faster and smaller than it would be for Java source Source code is not revealed to end users Interpreter performs additional security checks, screens out malicious code

Select all that apply. Which of the following are benefits of using methods in programming? a)Problems are solved more easily. b)Programs are simplified. c)The program will compile faster. d)Code can be reused.

Problems are solved more easily The program will compile faster. Code can be reused.

Cite at least 5 priorities of today's software

Programmer's productivity Team development Reusability of code Easier Maintenance Portability Better documented User-Friendly

For a method to return a value, which of the following must be true?

The method's header must have a data type before the name; and the body must have a return statement

What is the simplest way to convert a numeric value to a String? Note: One of the reasons to convert a numeric value to a String because a method you want to call requires a String parameter.

Simply concatenate the numeric value and an empty String, which is expressed by a pair of empty double quotes ("").

What is another term for "programs"?

Software

What are some of the reasons for using a symbolic constant instead of a literal constant?

Some of the reasons for using a symbolic constant instead of a literal constant: self-documenting/meaningful, easy for programmers to update

Write a statement to assign the name Mickey Mouse to a variable.

String name = "Mickey Mouse";

What are the "rules" (based on syntax and style) in naming a class, field or variable, constructors, and methods?

Syntax: A name can include: o upper- and lowercase letters o digits o underscore characters Syntax: A name cannot begin with a digit Style: Names should be descriptive to improve readability; names of fields are nouns, of methods are verbs Style: Names are in camel case; class names start with a upper-case letter, others with lower-case letter

What are the common units of measure for processing speed of a CPU (i.e., how fast a computer is)?

The CPU speed is measured in GHz (gigahertz, billions of clock cycles per second) or, in older computers, in MHz (megahertz, millions of cycles). A CPU instruction takes one or several clock cycles.

Given the following code fragment: String someState = "New York"; someState.toUpperCase(); System.out.println("The state is " + someState); What will this code fragment display?

The state is New York

How does parameter passing work (note: same for a constructor or method)?

The calling method must pass the same number of, same order of, and same data types for the inputs, as expected in the parameter list in the constructor signature, in the API.

What is the result when the following code is executed? System.out.println("The quick brown fox" + "jumped over the \n" "slow moving hen.");

The code contains an error.

public class Book { : : public Book(int pages) { pages = numPages; currentPage = 1; } : : }

The pages = numPages; statement takes the field numPages and saves it in the parameter/input pages. As the result, field numPages is still 0 (i.e., the default initial value by Java); although parameter/input pages was modified, its life ends when control goes back to the caller. Remember: the assignment is from right to left.

Which of the following statements about methods is correct?

The return value of a method can be used as an argument to another method.

Which statement best describes the portability characteristic of Java?

The same already-compiled Java programs will run on Windows, UNIX, Linux, or Macintosh operating systems without any change.

What is the scope of each of the following? a) private field in a class b) local variable

The scope of a) private field in a class is the entire class, so any method in the class can access or reassign it b) local variable is from the declaration statement to the end of that block

What is the scope? And how does one know the scope of each of the 3 types of variables?

The scope of a variable is the context during run-time when the variable is "visible" The scope of: a local variable is from the time it is declared until the innermost closing brace a field is the entire class a parameter is the entire called method

What is the difference between these 2 following statements? import javax.swing.JButton; import javax.swing.*;

The first statement makes use of the JButton class only; the second, all classes in swing

Describe the assignment statements for all cases. What is on the left side of the assignment symbol, and on the right side?

The left side (i.e., destination) MUST be a variable name (for local variable or field). The right side (i.e., source) may be one of the following: literal, another variable, mathematical expression, method call with return value.

In the following Java statement what value is stored in the variable name? String name = "Donald Duck";

The memory address where "Donald Duck" is located

Print special characters (escape sequence and characters from Unicode Table), and various characters in one statement: Escape sequence are special characters: o "\n" for new line o "\t" for tab o "\"" for double quote In the BlueJ, bring up HelloWorld to edit Questions: a) Edit the print statement to show: Hello <your classmate's name> from <your name> ☺ b) Change println to print, and add a print statement passing to it 3+4. What is the difference between println & print? System.out.print(3+4); Add a println statement passing to it the following 3*4 to multiply 2 numbers c) Replace all the print and println statements with one println statement, using the concatenation operator, to show the same message NOTE: If both operands are numeric, the plus sign adds the 2 numbers If at least 1 operand is a string, the plus sign concatenates the strings (after converting the numeric, if any, to string)

a) Compile, run & show to your classmate, who should verify the result. What is displayed? b) Compile, run & show to your classmate, who should verify the result. What is displayed? c) Compile, run & show to your classmate, who should verify the result. What is displayed?

Determine whether each of the following has correct or incorrect syntax: a int width = 20; b int perimeter = 4 * width; c String greeting = "Hi!"; d height = 30; e int width = "20"; f double mile/hour; g int period 1; h String double; i double 101dalmations; j double side = 6.0; double side * side = area;

a) Correct b) Correct c) Correct d) Incorrect - need declaration before assigning e) Incorrect - must assign the value of the same data type; in this case, "20" is a String type, which cannot be assigned to an int type f) Incorrect - names can contain letters, digits, and underscore only g) Incorrect - names cannot contain blanks h) Incorrect - cannot use reserved word double as a name i) Incorrect - names cannot start with a digit j) Incorrect - the left side of the assignment symbol must be a name; and the right side is an expression

About a constructor: a) How is a constructor named? b) How is a constructor declared, i.e., what is the signature of a constructor? Give an example. c) What is a constructor called if it does not accept parameters/inputs? d) Does a constructor always/sometimes have a return value? If not, is the reserved word void used? e) What is the purpose of a constructor? f) How is a constructor called? Give an example.

a) Exactly like the class name. Thus, the file, the class, and the constructors have the same name. b) There are 4 parts in a constructor declaration: reserved word public or private, constructor name, a pair of parentheses, and optional parameters (i.e., inputs) inside the parentheses. The parameters are separated by commas; each parameter is declared with a data type and variable name. Example: public Book(int initPgNum) c) Without the parameters, the constructor is called a no-args constructor. d) No, a constructor never has a return value, or void. e) The purpose of a constructor (which is invoked/called by the new operator to create a new object) is to initialize the fields. f) With new in front of the constructor call - for example Book aBook = new Book();

Create a class in a BlueJ project, in Proj02: Do Edit > Add a Class from File... Choose HelloWorld from "StudentsFiles > Ch02 > Hello" folder. Questions: a) In YourFolder, what was just added? Cite full names (i.e. including the extensions) for files. What kind of file is it? b) Do you see the stripes over the item in (a)? c) In the Proj02 folder in your disk, what was just added? Use full names (i.e. including the extensions) for files. What kind of file (i.e., of Java code) is it? d) In "StudentsFiles > Ch02 > Hello", is the "HelloWorld.java" file still there?

a) In BlueJ, a brown tile named "HelloWorld" was added b) Yes c) In YourFolder, there is a file named "HelloWorld.java". It is a source file. d) Yes, the "HelloWorld.java" file is still in "StudentsFiles > Ch02 > Hello". This means that "Add a Class from File..." makes a copy of the original file for the Java project.

Create a BlueJ project: Decide/name the folder in your disk that you are going to keep all your work - we will refer to it as YourFolder here Start BlueJ Do Project > New Project Type the project name: Proj02 and keep in YourFolder Questions: a) In BlueJ, what does the image in the project window look like? What is its name? (Hint: If you hover the mouse over it or right-click, you will see the name.) b) What is the purpose of the file in question (a)? c) In your disk, what are in the Proj02 folder? Write full file names (i.e. including the extensions). d) Quit BlueJ, then click on each file in the Proj02 folder in your disk. What happens when you click on each file? Hint: To find a file extension, right-click on the icon in your disk then choose "Properties".

a) In BlueJ, the image looks like a sheet of binder paper. Its name is "README". b) The purpose of the "README" file is for the programmer to write a summary about this Java project. c) In the disk, there is a folder called "Proj02" (i.e., with same name as your Java project), which contains 2 items: The BlueJ icon, with the name "package.bluej", representing the project The spiral notebook paper icon, with the name "README.TXT", which is the same as in (a) d) Clicking name "package.bluej" will launch BlueJ & open the project. Clicking "README.TXT" shows the text contents (in one of the applications that can open a text file, such as WordPad, MS Word, NotePad etc.)

a) In a byte, is the least significant bit at the beginning/left or the end/right of the byte? Which bit number is it? b) Same questions for the most significant bit.

a) The least significant bit is at the end or right of the byte (just like in a base-10 number). The location is bit 0. b) The most significant bit is at the beginning or left of the byte. The location is bit 7.

Compile a class in a BlueJ project, in Proj02, by doing one of the following: Right-click on the brown tile HelloWorld & choose Compile OR Click on the brown tile & do Tools > Compile OR Click on the brown tile & click button Compile in the left panel OR Double-click on the brown tile (& see source code), and click on Compile button in the top bar NOTE: the "javac.exe" application does the compiling here. Questions: a) In BlueJ, how did the brown tile for HelloWorld change? What do you think caused the change? b) In YourFolder, what was just added? Cite full names (i.e. including the extensions) for files.

a) In BlueJ, the stripes over brown tile disappeared. The successful compile took the stripes away. b) In YourFolder, there are 2 additional files "HelloWorld.class" and "HelloWorld.ctxt". The "class" file is the bytecode, the output of the compiler. We are not going to pay attention to the "ctxt" file, which is used by BlueJ only.

More on inheritance: a) What kind of relation is inheritance? b) Draw an inheritance diagram. c) What are the advantages of class inheritance - the basis for OOP? d) How is inheritance declared in Java? Give an example.

a) Inheritance is a IS-A relation. E.g., Bug is an Actor. b) no pic c) Inheritance allows a subclass to "reuse" all the superclasses. All the fields and methods in Actor are also "in" Bug. A subclass can override its superclass's methods, and can add additional methods. d) A class's inheritance is declared with the reserved word extends; e.g.: public class Bug extends Actor

About a field: a) What else is a field called? b) How is a field named? Who decides the name? c) How is a field declared, i.e., with which reserved words at the minimum? Give an example. d) Where/when is a field initialized?

a) Instance variable. b) A field name starts with a lower-case letter, and each subsequent word starts with an upper-case letter (camel case). The field name, decided by the programmer, is usually a noun and should be descriptive of what the field represents. c) There are at least 3 parts in a field declaration: reserved word public or private, data type, and field name; e.g., private int itemCount; d) In a constructor

Run & study Greetings: In project Proj02, add Greetings from "StudentsFiles > Ch02 > Hello" Run the program by right-clicking on the tile, and typing inside the braces your first name and last name in quotes separated by a comma; e.g., "John", "Doe". Observe the source code. Question: a) What did the program do? b) Observe the source code. After you typed your name and clicked "OK" to run the program, args[0] contains your first name, and args[1] contains your last name. Thus, the code saves your names in appropriate variables (i.e., firstName and lastName). What does the plus sign (+) in the println statement do?

a) It displayed the following for John Doe: Hello, John Doe Congratulations on your second program! b) plus sign (+) concatenates all the texts (represented as String in Java)

a) What is toString? b) What is the purpose of toString in the context of displaying in the Terminal Window? c) What will print or println display if a class does not provide a toString method? d) What is the "shorthand" of calling the toString method of an object?

a) It is a method of the Object class, of which every java class is a subclass, whether directly (if declared without extends) or indirectly (if declared with extends). b) The toString method is called by System.out.print or System.out.println to get the object's typical info the class chooses to "describe". For example, a Fraction object (with numerator 2 and denominator 3) may describe its typical info as 2/3, as written in the toString method of the Fraction class: Fraction aFractn = new Fraction(2, 3); System.out.println(aFractn); c) The class name and object's address in hex will be displayed; e.g., Cylinder@382b9a. d) The following is the shorthand: System.out.println(aFractn); e) The following is the longhand: System.out.println(aFractn.toString);

About a class: a) How is a class named? b) How many main parts are there in a class? What are they? Cite them in the order they should appear in a source file.

a) It is named in camel case, where the starting letter is in upper case. b) Three main parts: fields, constructors, methods

a) Is it necessary to construct a String object with the new operator (as in the case of Bug or WiltingFlower, or any other class)? b) What is the text inside a pair of double quotes called?

a) No, it is not necessary to construct a String object with the new operator. b) The text inside a pair of double quotes is called literal string

What do the following stand for? a) OS b) GUI c) OOP

a) OS Operating System b) GUI Graphical User Interface c) OOP Object-Oriented Programming

a) What does RAM stand for? b) Based on its name, what is the main characteristic of RAM? c) What is the main purpose of RAM?

a) Random Access Memory b) It can be accessed by "jumping" around (like going to certain track on a CD); i.e., it does not have to be accessed sequentially (like a cassette tape) c) RAM is the place where a program and its data reside when the program is running. After a program terminates, that RAM space is released for others to use.

a) What does ROM stand for? b) Based on its name, what is the main characteristic of ROM? c) What is one main purpose of ROM?

a) Read Only Memory b) It cannot be erased c) ROM contains, among other things, the computer code that boots up the operating system

You are in the leadership class and are in charge of keeping track of some info (in java) about the students in your school. Which data types would you choose for the following? Explain your choices. a) Student ID: ______________ b) Graduation year: ______________ c) Gender (i.e., Male or Female): ______________ d) Is an ASB member or not: ______________

a) Student ID: int b/c it is a 6-digit integer, which can fit in java 4-byte int b) Graduation year: int b/c it is a 4-digit integer, which can fit in java 4-byte int c) Gender: char, which can be represented by a character "M" (i.e., male) or "F" (i.e., female), etc. d) Is an ASB member or not: boolean, which can be represented by true or false

Which of the following is syntax? Which style? a) One statement per line b) Indented block of code within a pair of braces c) Blank line between methods d) Extraneous semi-colon e) Brackets, parentheses, braces in pairs f) Spaces around operators, such as = or +, etc.

a) Style b) Style c) Style d) Syntax e) Syntax f) Style

a) How many primitive data types are there? b) What are they? And how many bytes for each type?

a) The are 8 primitive data types b) They are int (4 bytes), long (8 bytes), short (2 bytes), float (4 bytes), double (8 bytes), boolean (1 byte), char (2 bytes, Unicode), byte (1 byte)

Download "StudentsFiles" (if not yet): Go to publisher's website http://www.skylit.com/disks.html Save on CHS server or your Google Drive or your flash drive, in a folder called "Student Files" (so we can all refer to it the same way) - REMEMBER WHERE YOU SAVE THIS FOLDER SO YOU CAN GET THE PROGRAMMING EXERCISES TO WORK ON Questions: a) What are in the StudentsFiles? b) What is the content of the "---PackingList---"? c) What is the content of the "SolutionsToExercises"?

a) There are: chapter folders, from chapter 2 to chapter 27 one folder called "EasyClasses" one text file called "---PackingList---" one pdf file called "SolutionsToExercises" b) The "---PackingList---" file shows the "table of contents" for the "StudentsFiles" folder c) The "SolutionsToExercises" has the answers to the book's exercises marked with the check marks.

About a class: a) Is there a separate source file for each class, or all classes for one program are in one source file? b) How is a source file named? And with what extension? c) How is a class named? Who decides the class name?

a) There is a separate file for each class. b) The file name starts with an upper-case letter, and each subsequent word starts with an upper-case letter (camel case. The extension is "java". c) A class name is exactly the same as the file name (without the extension). The file name or class name, decided by the programmer who writes the class, should be descriptive.

a) What are reserved words? b) About how many are there in Java? c) Which case are they written in: lower case, upper case, camel case?

a) They are the words that must be written as specified, and have specific meanings b) There are about 50 reserved words in Java c) Lower case only

Syntax, expected by the compiler - Do the following with HelloWorld, and answer the questions: a) What happens if you remove one or both double quotes around Hello, World? b) Change the lower/upper cases of any text other than the class name or the text inside the double quotes; for example public or class or System. Does the program still compile & run correctly? Why or why not? c) Delete any of the semi-colon at the end of any statement. Does the program still compile & run correctly? Why or why not? NOTE: The reserved words are those that must appear as-is. They are part of the Java syntax.

a) This causes a compile-time error; text must be inside double quotes b) No, the program no longer compiles. That is because they are reserved words, as expected by the compiler, and are case-sensitive. For example, you must use public, not Public; System, not system, etc. c) No, the program no longer compiles. The Java compiler expects a semi-colon at the end of each statement; thus, when it is not there, a compile error occurs.

a) What is the purpose of writing comments? b) What are the 2 non-javadoc ways to write comment in a Java source file?

a) To document what the code does, or to temporary "disable" some code in order to try something else b) Two ways: Inside /* ... */, for block comments After //, for single-line comments

True or false? a) ___ A local variable must be declared before being used. b) ___ A local variable (within a scope) must be declared only once but may be (re)assigned many times. c) ___ A field, when not explicitly initialized by the programmer, is initialized automatically with default values: zero for int or double; null for object d) ___ A local variable, when not explicitly initialized by the programmer, is initialized automatically with default values: zero for int or double; null for object

a) True b) True c) True d) False

a) Is a class a data type? b) Is String a data type? c) Is String a primitive data type?

a) Yes, a class is a data type b) Yes, String is a data type c) No, String is a class

Convention, followed by programmers - Do the following & answer the questions: a) In the HelloWorld class window, change the name HelloWorld to helloWorld. Does the program still compile without errors? Does it still run as before? What is the name of the tile? What are the names of the files in the Proj02 folder? Note: it is good convention (i.e., not syntax) to name a class similar to HelloWorld: use an upper-case letter at the start of each word in the name, including the very first letter of the name). b) Observe the color blocks. Which color block contains which color block? c) In the HelloWorld class window again, delete the lines bounded by /* ... */. Does the program still compile & run correctly? Why or why not? d) Do the following: Copy the entire HelloWorld class Click the "New class" button in the left panel, or choose "Edit > New class" Delete the whole contents of this new class Paste HelloWorld Change the class name from HelloWorld to Temp as the in the window Delete all "new lines" and tabs/indentations, to make the whole class as a block of very-hard-to-read text. Compile & run Does the program run successfully with good result? Why or why not? e) Observe the color "blocks" again. Are they similar to (b)? f) Remove Temp from this project. Did the Temp tile disappear?

a) Yes, the program still compiles and runs correctly, but not respected by other fellow programmers. The name of the tile in BlueJ and the names of the files in the disk change to "HelloWorld", i.e., lower case. NOTE: By convention, Java programmers use camel- case to name classes. Java compiler does not insist on certain case; and it keeps the name consistent all throughout. b) Green block is for the whole file/class, which contains the yellow block for the class body, which contains the white block for the body of the main method. c) Yes, the program still compiles and runs correctly. The text bounded by /* ... */ is documentation, for programmers; the compiler ignores all such text. d) Yes, the program runs successfully because all the new lines and indentations are for humans only; the compiler looks for things like braces & semi-colons. e) Yes f) Yes

Logic, expected by you/programmer - Do the following with HelloWorld, and answer the questions: a) Delete the letter "l" from the word "World". Does the program still run? What is the result? b) What is the result if you put 3+4 in double quotes? Why is the result not the same as previously?

a) Yes. Similar to previous result, but with the misspelled "World". b) It is 3+4. When in quotes, it is treated as a String of text.

Which statement stores an integer value in a variable? a) count = 5; b) count = 5.0; c) count == 5; d) count != 5;

a) count = 5;

a) What are javadoc comments? b) How are they written? c) Give an example of javadoc comments

a) javadoc comments are called documentation comments, which are written in a special way so that the javadoc program can extract them and put them in a document describing the public fields, constructors, and methods so that other programmers know how to use/call the methods, etc. b) These comments are written inside /** ... */; each line inside the block starts with *; each block is written before a class, a constructor, or a method; the description of certain items (such as author, parameter, etc.) starts with @ c) Documentation for nFactorial: /** * Returns the value of n! * @param n integer for factorial * @return n factorial */

What is the result of "NOT" for each of the following? a) not true b) not false

a) not true false b) not false true

Two-way communication with the user: Download the Conversation.java file & keep in your StudentsFiles Do Edit > Add a Class from File..., to add that class to your project Compile & run; study the code Questions: a) What is the class header? b) What is the main program header? c) How many variables are there? d) What are their names & data types? e) Choose a name, say, kboard, and do Ctrl-f to search for kboard. What do you see?

a) public class Conversation b) public static void main(String[] args) - same as always c) 6 d) kboard of type Scanner, name of type String, age & numOfYrs & futureAge of type int, dist of type double e) All of the occurrences of kboard are highlighted, which is useful to know where the variable is used

Study class HelloWorld: study the source code in the class window for HelloWorld: a) What is the header of the HelloWorld class? b) What is the body of the HelloWorld class contained in? c) How many items are there in the body of the HelloWorld class? d) What is the header of the main method? Why is the main method important? e) What is the body of the main method contained in? f) What is the statement that displays text in the terminal window? g) What are the pieces called in the (only) statement? System.out.println(" ......"); NOTE: All of these questions relate to Java syntax; and you must memorize the correct syntax.

a) public class HelloWorld b) The body of the class is contained in a pair of braces: {} c) There is only one: the main program d) The header is public static void main (String[] args). The main method is important because (1) each Java application must have a main method, and (2) when a Java application is launched, the starting point is the first line of the main method. e) The body of the main method is contained in a pair of braces: {} f) It is the "print line" statement: System.out.println(" ......"); g) System.out.println is the method call; the content of the parentheses is the parameter (or input) to the call. The parameter in this case is a String, which must appear in double quotes. The statement must end with a semi-colon.

What is the result of "AND" for each of the following? a) true and true b) true and false c) false and true d) false and false

a) true and true true b) true and false false c) false and true false d) false and false false

What is the result of "OR" for each of the following? a) true or true b) true or false c) false or true d) false or false

a) true or true true b) true or false true c) false or true true d) false or false false

Try the code in your Verifier to verify your answers. a) What is the largest (positive) integer that can be stored in an int in Java? How do you code this number in your source file? b) If you are to write a program that keeps people's social security numbers, is it safe to use an int for a social security number? c) How about telephone numbers, including area codes?

a)2147483647 b)Yes c)No

Input to a method, enclosed in parentheses after the method name, is known as ___

arguments/parameters

a) What does IDE stand for? b) What is the name of the IDE you are using? c) Who created it? (Hint: In BlueJ, look at Help > About BlueJ.)

a. Integrated Development Environment. b. BlueJ. c. Neil Brown, Michael Kolling, Davin McCall, Ian Utting - See Help > About BlueJ in BlueJ.

In the edit-compiler-linker-run paradigm, a) What is the input of a compiler? Output? b) What is the input of a linker? Output?

a. Source code, object code b.Object code, Executable program

Cite the pieces of info in a declaration of a method.

an access specifier, a return type, a method name, and a list of the parameters (if any)

Cite the pieces of info in a declaration of a field (aka instance variable).

an access specifier, the type of the instance variable, and the name of the instance variable

local variables can be initialized with

any of these (constants, parameter values, the result of an arithmetic operation)

If m has been declared an int, which of the following statements is invalid? A) m = 0; B) m = -53391; C) m = 3,291; D) m = 393; E) m = 9_191;

c) m = 3,291;

a) Search for "java api" on the Internet b) Look for the "Math" class in the Javadoc document c) Identify all the methods that you have seen or used in a calculator (scientific & graphing) d) There are a number of methods that are overloaded; for example, min. What is your observation about the method headers/signatures of each group of overloaded methods?

c) sin, cos, etc. - See Slide Supplement d) They have different number of parameters or data types

Which part of a class contains the code to initialize an object's fields (or instance variables)?

constructor(s)

The type of an object is given by its ______ ?

class

In a @return tag statement the description ___

describe the return value

Which of the following statements is invalid? double r = 9.4632e15; double r = 9.4632E15 double r = 2.9X106 double r = 326.75;

double r = 2.9X106

Give an example for the variable name of the volume of a box, and declare it

double volume;

Which term means hiding objects' data and providing methods for data access?

encapsulation

_____ represent attributes of a class.

fields or instance variables

What are the 3 common main parts inside the body of a class (i.e., inside a pair of braces after the class header)?

fields, constructors, methods

A class specifies the __________ and __________ that a particular type of object has.

fields, methods


Kaugnay na mga set ng pag-aaral

week 13 carmen quiz: t distribution

View Set

Chapter 40: Nursing Care of the Child with an Alteration in Gas Exchange/ Respiratory Disorder

View Set

CFA Level 1 Part 2 (Alternative Investments)

View Set

Anatomical Techniques FALL - COMBINED

View Set

Chapter 17 & 18: Great Depression and New Deal

View Set