Lesson 2: Data Types and Program Control Flashcards

1
Q

hat are the two general categories of built-in data types?

A

Java contains two general categories of built-in data types: object-oriented and non-object-oriented. Java’s object-oriented types are defined by classes،

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are the eight primitive types of data، do we use primitive types?

A

at the core of Java are eight primitive (also called elemental or simple) types of data، which are shown in Table 2-1. The term primitive is used here to indicate that these types are not objects in an object-oriented sense، but rather، normal binary values. These primitive types are not objects because of efficiency concerns. boolean: Represents ture/false values byte: 8-bit integer char: Character double: Double-precision floating point float: Single-precision floating point int: Integer long: Long integer short: Short integer

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are the 4 integer data types in Java? What range of numbers do they support?

A

Java defines four integer types: byte، short، int، and long. Type : Width in Bits : Range byte : 8 : ±128 short : 16 : ±32،768 int : 32 : 2،147،483،648(2billion147million) long : 64 : ±9،223،372،036،854،775،808(9quintillion223quadrillion)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are unsigned integers and does Java support them?

A

Java does not support unsigned (positive-only) integers.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Where are byte variables especially useful?

A

Variables of type byte are especially useful when working with raw binary data that may not be directly compatible with Java’s other built-in types.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

If char is formally specified as an integral type، why isn’t it used for number values?

A

The formal specification for Java defines a type category called integral types، which includes byte، short، int، long، and char. They are called integral types because they all hold whole-number، binary values. However، the purpose of the first four is to represent numeric integer quantities. The purpose of char is to represent characters. Therefore، the principal uses of char and the principal uses of the other integral types are fundamentally different.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How many bits wide are float and double types? Which type does the sqrt() method use?

A

Type float is 32 bits wide and type double is 64 bits wide. Of the two، double is the most commonly used، and many of the math functions in Java’s class library use double values. For example، the sqrt( ) method (which is defined by the standard Math class) returns a double value that is the square root of its double argument.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

If characters in other code languages have 8 bits، how many bits is Java’s Unicode.

A

Java uses Unicode. Unicode defines a character set that can represent all of the characters found in all human languages. In Java، char is an unsigned 16-bit type having a range of 0 to 65،535.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How do you assign a character variable?

A

A character variable can be assigned a value by enclosing the character in single quotes. char ch; ch = ‘x’;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Why does java use unicode instead of just using English letters?

A

Java was designed for worldwide use. Thus، it needs to use a character set that can represent all the world’s languages. Unicode is the standard character set designed expressly for this purpose. Of course، the use of Unicode is inefficient for languages such as English، German، Spanish، or French، whose characters can be contained within 8 bits.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is returned when a relational operator comes up as true and when it comes up as false?

A

the outcome of a relational operator، such as <، is a boolean value. This is why the expression 10 > 9 displays the value “true.”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What are literals in Java?

A

In Java، literals refer to fixed values that are represented in their human-readable form. For example، the number 100 is a literal. Literals are also commonly called constants.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What types of data can literals be?

A

Java literals can be of any of the primitive data types. The way each literal is represented depends upon its type. Integer literals are specified as numbers without fractional components. For example، 10 and –100 are integer literals. Floating-point literals require the use of the decimal point followed by the number’s fractional component. For example، 11.123 is a floating-point literal.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How do you specify a long literal and a float literal.

A

By default، integer literals are of type int. If you want to specify a long literal، append an l or an L. For example، 12 is an int، but 12L is a long. By default، floating-point literals are of type double. To specify a float literal، append an F or f to the constant. For example، 10.19F is of type float.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How can you separate digits (numerical literals) in Java to make larger numbers more readable?

A

You can embed one or more underscores into an integer or floating-point literal. Doing so can make it easier to read values consisting of many digits. When the literal is compiled، the underscores are simply discarded.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is the octal number system?

A

The number system based on 8 is called octal، and it uses the digits 0 through 7. In octal the number 10 is the same as 8 in decimal.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is the hexadecimal number system?

A

The base 16 number system is called hexadecimal and uses the digits 0 through 9 plus the letters A through F، which stand for 10، 11، 12، 13، 14، and 15. For example، the hexadecimal number 10 is 16 in decimal.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

In Java، what do you have to put in front of an octal and hexadecimal numbering system?

A

A hexadecimal literal must begin with 0x or 0X (a zero followed by an x or X). An octal literal begins with a zero. hex = 0xFF; // 255 in decimal oct = 011: // 9 in decimal

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

How do you indicate a binary literal in Java?

A

It is possible to specify an integer literal by use of binary. To do so، precede the binary number with a 0b or 0B.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What are the escape sequence characters? Which ones do what?

A

Java provides special escape sequences، sometimes referred to as backslash character constants: Escape Sequence : Description ' : Single quote " : Double quote \ : Backslash \r : Carriage return \n : New line \f : Form feed \t : Horizontal tab \b : Backspace \ddd : Octal constant (where ddd is an octal constant) \uxxxx : Hexideciam constant (Where xxxx is a hex constant)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is a string in Java?

A

A string is a set of characters enclosed by double quotes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

How are strings different than a character literals?

A

You must not confuse strings with characters. A character literal represents a single letter of type char. A string containing only one letter is still a string. Although strings consist of characters، they are not the same type.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

How do you change the type of data a variable can hold?

A

You cant. Declare a variable of any valid type، including the simple types just described، and every variable will have a type. Thus، the capabilities of a variable are determined by its type. For example، a variable of type boolean cannot be used to store floating-point values. Furthermore، the type of a variable cannot change during its lifetime.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

When must you give a variable a value?

A

In general، you must give a variable a value prior to using it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

How do you assign value to variables using one declaration? BTW، this is called initializations.

A

When declaring two or more variables of the same type using a comma-separated list، you can give one or more of those variables an initial value. For example: int a، b = 8، c = 19، d; // b and c have initializations

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

When are scopes created and what do they determine?

A

A block defines a scope. Thus، each time you start a new block، you are creating a new scope. A scope determines what objects are visible to other parts of your program. It also determines the lifetime of those objects.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

What is included in a method’s scope? What is a method body? How do scopes provide encapsulation?

A

The scope defined by a method begins with its opening curly brace. However، if that method has parameters، they too are included within the method’s scope. A method’s scope ends with its closing curly brace. This block of code is called the method body. As a general rule، variables declared inside a scope are not visible (that is، accessible) to code that is defined outside that scope. Thus، when you declare a variable within a scope، you are localizing that variable and protecting it from unauthorized access and/or modification. Indeed، the scope rules provide the foundation for encapsulation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

What is a local variable?

A

A variable declared within a block is called a local variable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

Why is it a bad idea to initialize a variable at the end of a block?

A

Within a block، variables can be declared at any point، but are valid only after they are declared. Thus، if you define a variable at the start of a method، it is available to all of the code within that method. Conversely، if you declare a variable at the end of a block، it is effectively useless، because no code will have access to it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

What happens to a variable that is initialized in a loop block?

A

If a variable declaration includes an initializer، that variable will be reinitialized each time the block in which it is declared is entered.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

What are operators and what are the four general classes of operators?

A

Java provides a rich operator environment. An operator is a symbol that tells the compiler to perform a specific mathematical or logical manipulation. Java has four general classes of operators: arithmetic، bitwise، relational، and logical. Java also defines some additional operators that handle certain special situations. Operator : Meaning + : Addition - : Subtraction * : Multiplication / : Division % : Modulus ++ : Increment – : Decrement

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

When the division of an integer would result in 3.999، what would happen to the decimal numbers?

A

The new interger value would be 3. When division is applied to an integer، any remainder will be truncated. For example 3/2 would be 1.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

What does the % operator do?

A

10 % 3 is 1. In Java، the % (Modulus) can be applied to both integer and floating-point types. Thus، 10.0 % 3.0 is also 1. It yields the remainder of an integer division.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

What side of a variable do the in/decrement operators need to be on?

A

”++x” or “x++”. Both the increment and decrement operators can either precede (prefix) or follow (postfix) the operand. When an increment or decrement operator precedes its operand، Java will perform the corresponding operation prior to obtaining the operand’s value for use by the rest of the expression. If the operator follows its operand، Java will obtain the operand’s value before incrementing or decrementing it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

How are the terms relational operators different from logical operators? What are the operators associated with both?

A

In the terms relational operator and logical operator، relational refers to the relationships that values can have with one another، and logical refers to the ways in which true and false values can be connected together. Since the relational operators produce true or false results، they often work with the logical operators.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

How is an exclusive or statement different from a regular or statement?

A

the outcome of an exclusive OR operation is true when exactly one and only one operand is true. “true and false” or “false and true”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

What’s the difference between a normal and short-circuit operands?

A

The only difference between the normal and short-circuit versions is that the normal operands will always evaluate each operand، but short-circuit versions will evaluate the second operand only when necessary.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

When is a short-circuit and operator useful?

A

To prevent a divide-by-zero، the if statement first checks to see if d is equal to zero. If it is، the short-circuit AND stops at that point and does not perform the modulus division.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

What is the formal name for short-circuit operators?

A

The formal specification for Java refers to the short-circuit operators as the conditional-or and the conditional-and operators، but the term “short-circuit” is commonly used.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

How can you assign multiple variables to one value in a single line of code?

A

The assignment operator does have one interesting attribute that you may not be familiar with: it allows you to create a chain of assignments. For example، consider this fragment: int x، y، z; x = y = z = 100; // set x، y، and z to 100

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

When is it more beneficial to use the non-short-circuit version of an operands?

A

if your code expects the right-hand operand of an AND or OR operation to be evaluated، you must use Java’s non-short-circuit forms of these operations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

What are the shorthand logical and arithmetic expressions you can use in Java?

A

55This shorthand will work for all the binary operators in Java (that is، those that require two operands). The general form of the shorthand is var op = expression; Thus، the arithmetic and logical shorthand assignment operators are the following: += and -= are some examples.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

What is the formal name of the shorthand operation like x += 10; and x -= 10;

A

Because these operators combine an operation with an assignment، they are formally referred to as compound assignment operators.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

When will an automatic type conversion occur?

A

When one type of data is assigned to another type of variable، an automatic type conversion will take place if ● The two types are compatible. ● The destination type is larger than the source type.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

What are widening conversions?

A

For example، the int type is always large enough to hold all valid byte values، and both int and byte are integer types، so an automatic conversion from byte to int can be applied. For widening conversions، the numeric types، including integer and floating-point types، are compatible with each other.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

When do widening conversions fail?

A

Although there is an automatic conversion from long to double، there is no automatic conversion from double to long، since this is not a widening conversion.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

What are cast conversions، when are they useful، and what I their general form?

A

Although the automatic type conversions are helpful، they will not fulfill all programming needs because they apply only to widening conversions between compatible types. For all other cases you must employ a cast. A cast is an instruction to the compiler to convert one type into another. Thus، it requests an explicit type conversion. A cast has this general form: (target-type) expression Here، target-type specifies the desired type to convert the specified expression to. Example: double x، y; // … (int) (x / y): The parentheses surrounding x / y are necessary. Otherwise، the cast to int would apply only to the x and not to the outcome of the division.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q

What happens to the value in a narrowing conversion?

A

When a cast involves a narrowing conversion، information might be lost. For example، when casting a long into a short، information will be lost if the long’s value is greater than the range of a short because its high-order bits are removed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
49
Q

What is the input method complementary to the System.out method? What type of value is returned?

A

System.in is the complement to System.out. It is the input object attached to the keyboard. The read( ) method Page 67waits until the user presses a key and then returns the result. The character is returned as an integer، so it must be cast into a char to assign it to a char variable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
50
Q

What does it mean to have input as line buffered?

A

console input is line buffered. Here، the term buffer refers to a small portion of memory that is used to hold the characters before they are read by your program. In this case، the buffer holds a complete line of text. As a result، you must press ENTER before any character that you type will be sent to your program.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
51
Q

What clause must be stated in the main() when using System.in.read?

A

Because System.in.read( ) is being used، the program must specify the throws java.io.IOException clause. This line is necessary to handle input errors. It is part of Java’s exception handling mechanism

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
52
Q

What is the complete form an if statement?

A

The complete form of the if statement is if(condition) statement; else statement; where the targets of the if and else are single statements. The else clause is optional.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
53
Q

In a complete if statement، when will “else” be executed?

A

if(condition) { statement sequence } else { statement sequence } If the conditional expression is true، the target of the if will be executed; otherwise، if it exists، the target of the else will be executed.

54
Q

An if statement need to provide what type of value?

A

The conditional expression controlling the if must produce a boolean result.

55
Q

What are nested if statements?

A

A nested if is an if statement that is the target of another if or else.

56
Q

What is an if-else-if ladder and why is it more efficient than using several if statements?

A

based upon the nested if is the if-else-if ladder. It looks like this: if(condition) statement; else if(condition) statement; else if(condition) statement; . . . else statement; The conditional expressions are evaluated from the top downward. As soon as a true condition is found، the statement associated with it is executed، and the rest of the ladder is bypassed.

57
Q

What are switch statements and how are they structured?

A

Although a series of nested if statements can perform multiway tests، for many situations the switch is a more efficient approach. It works like this: the value of an expression is successively tested against a list of constants. When a match is found، the statement sequence associated with that match is executed. The general form of the switch statement is switch(expression) { case constant1: statement sequence break; case constant2: statement sequence break; case constant3: statement sequence break; . . . default: statement sequence }

58
Q

What is another way to If-Else statements that are more stream-line and involve “?” and “:” as operators?

A

There’s also a special operator provided to simplify writing code when the two alternative actions in an if-else statement are to assign different values to the same variable: if (condition) var = expression1; else var = expression2; This can be written as: var = condition ? expression1 : expression2 ; For example، the following line computes the absolute value of a number: absval = num < 0 ? -num : num;

59
Q

What does the default statement sequence do in a switch statement?

A

The default statement sequence is executed if no case constant matches the expression. The default is optional; if it is not present، no action takes place if all matches fail.

60
Q

How would you write a code that uses a switch statement to out put the number value of “i” up until 5 where the output states “i is five or more”?

A

The following program demonstrates the switch: package switchdemo; /* * Code for school * Demonstrate the switch */ class SwitchDemo { public static void main(String args[]) { int i; for(i=0; i<10; i++) switch(i) { case 0: System.out.println(“i is zero”); break; case 1: System.out.println(“i is one”); break; case 2: System.out.println(“i is two”); break; case 3: System.out.println(“i is three”); break; case 4: System.out.println(“i is four”); break; default: System.out.println(“i is five or more”); } } }

61
Q

While technically not needed، what happens when you don’t include a break statement in your switch statements?

A

When encountered within the statement sequence of a case، the break statement causes program flow to exit from the entire switch statement and resume at the next statement outside the switch. However، if a break statement does not end the statement sequence associated with a case، then all the statements at and following the matching case will be executed until a break (or the end of the switch) is encountered.

62
Q

What is the general form for a for loop?

A

The general form of the for loop for repeating a single statement is for(initialization; condition; iteration) statement; For repeating a block، the general form is for(initialization; condition; iteration) { statement sequence } The initialization is usually an assignment statement that sets the initial value of the loop control variable، which acts as the counter that controls the loop. The condition is a Boolean expression that determines whether or not the loop will repeat. The iteration expression defines the amount by which the loop control variable will change each time the loop is repeated.

63
Q

When would you use an if-else-if ladder over a switch?

A

use an if-else-if ladder when the conditions controlling the selection process do not rely upon a single value. Also، you will need to use an if-else-if ladder when testing floating-point values or other objects that are not of types valid for use in a switch expression.

64
Q

How do you break out of several blocks of loops with just one break statement?

A

The general form of the labeled break statement is shown here: break label; Typically، label is the name of a label that identifies a block of code. When this form of break executes، control is transferred out of the named block of code. The labeled block of code must enclose the break statement، but it does not need to be the immediately enclosing block. A label is any valid Java identifier followed by a colon. Once you have labeled a block، you can then use this label as the target of a break statement. package break4; /* * For school * Using break with a label */ class Break4 { public static void main(String args[]) { int i; for(i=1; i<4; i++) { one: { two: { three: { System.out.println(“\ni is “ + i); if(i == 1) break one; if(i == 2) break two; if(i == 3) break three; //this is never reached System.out.println(“won’t print”); } System.out.println(“After block three”); } System.out.println(“After block two”); } System.out.println(“After block one”); } System.out.println(“After for loop”); } }

65
Q

How do you use multiple control variables in a for loop?

A

multiple loop control variables can be used. Consider the following program: package Comma; /* * For school * Use commas in a for statement */ class Comma { public static void main(String args[]) { int i، j; for(i=0، j=10; i < j; i++، j–) System.out.println(“i and j: “ + i + “ “ + j); } }

66
Q

How would you write a code that uses a for loop dependant on user input?

A

The condition controlling the loop can be any valid Boolean expression. It does not need to involve the loop control variable. In the next example، the loop continues to execute until the user types the letter S at the keyboard: package fortest /* * For school * Loop until an S is typed. */ class ForTest { public static void main(String args[]) throws java.io.IOException { int i; System.out.println(“Press S to stop.”); for(i = 0; (char) System.in.read() != ‘S’; i++) System.out.println(“Pass #” + i); } }

67
Q

So long as it’s stated elsewhere، do you need anything but the boolean return on a for loop?

A

In Java، it is possible for any or all of the initialization، condition، or iteration portions of the for loop to be blank.

68
Q

Very basically stated، what does the enhanced for loop do?

A

The enhanced for provides a streamlined way to cycle through the contents of a collection of objects، such as an array.

69
Q

What is the general structure of a while loop statement in Java?

A

while(condition) statement; where statement may be a single statement or a block of statements، and condition defines the condition that controls the loop. The condition may be any valid Boolean expression. The loop repeats while the condition is true.

70
Q

When do you use a for loop، a while loop، and a do while loop?

A

Use a for loop when performing a known number of iterations based on the value of a loop control variable. Use the do-while when you need a loop that will always perform at least one iteration. The while is best used when the loop will repeat until some condition becomes false.

71
Q

What is a do-while loop and what is its general structure?

A

The last of Java’s loops is the do-while. Unlike the for and the while loops، in which the condition is tested at the top of the loop، the do-while loop checks its condition at the bottom of the loop. This means that a do-while loop will always execute at least once. The general form of the do-while loop is do { statements; } while(condition);

72
Q

How would you code a do-while loop that loops until the user enters the letter q?

A

The following program loops until the user enters the letter q: package dwdemo; /* * For school * Demonstrate the do-while loop. */ class DWDemo { public static void main(String args[]) throws java.io.IOException { char ch; do { System.out.print(“Press a key followed by ENTER: “); ch = (char) System.in.read(); // get a char } while (ch != ‘q’); } }

73
Q

What does the break statement do?

A

It is possible to force an immediate exit from a loop، bypassing any remaining code in the body of the loop and the loop’s conditional test، by using the break statement. When a break statement is encountered inside a loop، the loop is terminated and program control resumes at the next statement following the loop.

74
Q

When inside of nested loops، which loop will the break statement break out of?

A

When used inside a set of nested loops، the break statement will break out of only the innermost loop.

75
Q

Why doesn’t Java have a goto statement?

A

Java does not have a goto statement، because it provides an unstructured way to alter the flow of program execution.

76
Q

What is the “continue” statement?

A

It is possible to force an early iteration of a loop، bypassing the loop’s normal control structure. This is accomplished using continue. The continue statement forces the next iteration of the loop to take place، skipping any code between itself and the conditional expression that controls the loop. Thus، continue is essentially the complement of break. //Use continue. class ContDemo { public static void main(String args[]) { int i; //print even numbers between 0 and 100 for (i = 0; i<=100; i++) { if((i%2) != 0) continue; //iterate System.out.println(i); } } }

77
Q

How can you use a “continue” statement to execute a specific enclosing loop?

A

As with the break statement، continue may specify a label to describe which enclosing loop to continue.

78
Q

What is special about arrays in Java as opposed to other languages?

A

Although arrays in Java can be used just like arrays in other programming languages، they have one special attribute: they are implemented as objects.

79
Q

What is the general form of an array?

A

To declare a one-dimensional array، you can use this general form: type array-name[ ] = new type[size]; Here، type declares the element type of the array. (The element type is also commonly referred to as the base type.) The element type determines the data type of each element contained in the array. The number of elements that the array will hold is determined by size. Since arrays are implemented as objects، the creation of an array is a two-step process. First، you declare an array reference variable. Second، you allocate memory for the array، assigning a reference to that memory to the array variable. Thus، arrays in Java are dynamically allocated using the new operator. int sample[] = new int[10];

80
Q

What is an index in an array and which number does it start with?

A

An index describes the position of an element within an array. In Java، all arrays have zero as the index of their first element.

81
Q

What is the general form for initializing a one-dimensional array?

A

The general form for initializing a one-dimensional array is shown here: type array-name[ ] = { val1، val2، val3، … ، valN }; Here، the initial values are specified by val1 through valN. They are assigned in sequence، left to right، in index order. Java automatically allocates an array large enough to hold the initializers that you specify. There is no need to explicitly use the new operator.

82
Q

How would you write a program that holds 9 1-d array number values and then determines the minimum and maximum values in that array?

A

MinMax program: // Use array initializers class MinMax2 { public static void main(String args[]) { int nums[] = { 99، -10، 100123، 18، -978، 5623، 463، -9، 287، 49}; int min، max; min = max = nums[0]; for(int i=1; i < 10; i++) { if(nums[i] < min) min = nums[i]; if(nums[i] > max) max = nums[i]; } System.out.println(“Min and max: “ + min + “ “ + max); } } //End coding sample Output: Min and max: -978 100123

83
Q

How do you declare a two-dimensional array in Java?

A

To declare a two-dimensional integer array table of size 10، 20 you would write int table[] [] = new int[10] [20]; Pay careful attention to the declaration. Unlike some other computer languages، which use commas to separate the array dimensions، Java places each dimension in its own set of brackets.

84
Q

How do you assign values in a multidimensional array? How would you make a code that has 4 columns and 3 rows? In each row، it counts from 1 to 12 starting with box 0(y)،0(x) and then ending with 0،4 starting again at 1،0.

A

A little bit tricky، but essentially in an array، you define it initially with the rows and columns starting with the y value and then telling it how many rows you want. So int table[] [] = new int[10] [20]; will have 10 rows and 20 columns. To assign them، simply state //r is the desired row and c is desired column table[r][c] = 6 // Demonstrate a two-dimensional array class TwoD { public static void main(String args[]) { int t، i; int table[] [] = new int[3] [4]; for(t=0; t < 3; ++t) { for(i=0; i < 4; ++i) { table[t] [i] = (t*4) + i+1; System.out.print(table[t] [i] + “ “); } System.out.println(); } } } //End of code Output: 1 2 3 4 5 6 7 8 9 10 11 12

85
Q

What is the general form of array initialization for a two-dimensional array?

A

the general form of array initialization for a two-dimensional array is shown here: type-specifier array_name[ ] [ ] = { { val، val، val، …، val }، { val، val، val، …، val }، //etc. { val، val، val، …، val } }; Here، val indicates an initialization value. Each inner block designates a row. Within each row، the first value will be stored in the first position of the subarray، the second value in the second position، and so on. Notice that commas separate the initializer blocks and that a semicolon follows the closing }.

86
Q

How can you declare multiple single-dimension (or multi-dimension) arrays with just one declaration

A

int[] nums، nums2، nums3; // create three arrays This creates three array variables of type int. It is the same as writing int nums []، num2 []، nums3 []; // also، create three arrays

87
Q

How do you return the number of elements an array is capable of holding?

A

One benefit of this approach is that each array has associated with it a length instance variable that contains the number of elements that the array can hold. (In other words، length contains the size of the array.) You can retrieve the length of the array using: array name.length Add to retrieve the length of an array in a table: table name[value].length

88
Q

What is a stack and queue in Java?

A

A stack is a list in which elements can be accessed in first-in، last-out (FILO) order only. A queue is a list in which elements can be accessed in first-in، first-out (FIFO) order only. Thus، a stack is like a stack of plates on a table—the first down is the last to be used. A queue is like a line at a bank—the first in line is the first served.

89
Q

What are the two types of queues?

A

There are two basic types of queues—circular and noncircular. A circular queue reuses locations in the underlying array when elements are removed. A noncircular queue does not reuse locations and eventually becomes exhausted.

90
Q

What does the put() method do in simple terms?

A

The put( ) method، which stores elements،

91
Q

In simple terms، what does the get() method do?

A

To retrieve elements، use the get( ) method

92
Q

What type of variable is considered an object in Java?

A

String defines and supports character strings. In some other programming languages، a string is an array of characters. This is not the case with Java. In Java، strings are objects.

93
Q

How do you construct a String?

A

You can construct a String just like you construct any other type of object: by using new and calling the String constructor. For example: String str = new String(“Hello”); This creates a String object called str that contains the character string “Hello”. In this case، str is initialized to the character sequence “Java strings are powerful.”

94
Q

What are the general forms for a few common methods that operate on strings?

A

The String class contains several methods that operate on strings. Here are the general forms for a few: boolean equals(str) : Returns true if the invoking string contains the same character sequence as str. int length() : Obtains the length of a string. char charAt(index) : Obtains the character at the index specified by index. int compareTo(str) : Returns less than zero if the invoking string is less than str، greater than zero if the invoking string is greater than str، and zero if the strings are equal. int indexOf(str) : Searches the invoking string for the substring specified by str. Returns the ine=dex of the first match or -1 on failure. int lastIndexOf(str) : Searches the invoking string for the substring specified by str. Returns the index of the last match or -1 on failure.

95
Q

What is the difference between using the equals() method on a string and using == ?

A

The equals( ) method compares the character sequences of two String objects for equality. Applying the == to two String references simply determines whether the two references refer to the same object.

96
Q

What does it mean for a string to be immutable، and why isn’t this fact a drawback?

A

The contents of a String object are immutable. That is، once created، the character sequence that makes up the string cannot be altered. This restriction allows Java to implement strings more efficiently. Even though this probably sounds like a serious drawback، it isn’t. When you need a string that is a variation on one that already exists، simply create a new string that contains the Page 163desired changes. Since unused String objects are automatically garbage collected، you don’t even need to worry about what happens to the discarded strings. It must be made clear، however، that String reference variables may، of course، change the object to which they refer. It is just that the contents of a specific String object cannot be changed after it is created.

97
Q

How do you create a changeable string in Java? Which method allows you to do this?

A

Java offers a class called StringBuffer، which creates string objects that can be changed. For example، in addition to the charAt( ) method، which obtains the character at a specific location، StringBuffer defines setCharAt( )، which sets a character within the string. Java also supplies StringBuilder، which is related to StringBuffer، and also supports strings that can be changed. However، for most purposes you will want to use String، not StringBuffer or StringBuilder.

98
Q

What does the substring do generally speaking?

A

The substring( ) method returns a new string that contains a specified portion of the invoking string. Because a new String object is manufactured that contains the substring، the original string is unaltered، and the rule of immutability remains intact.

99
Q

What is the general form of a substring

A

The form of substring( ) that we will be using is shown here: String substring(int startIndex، int endIndex) Here، startIndex specifies the beginning index، and endIndex specifies the stopping point.

100
Q

How do you use strings in a switch?

A

Here is an example that demonstrates controlling a switch with a String: // Use a string to control a switch statement class StringSwitch { public static void main(String args[]) { String command = “cancel”; switch(command) { case “connect”: System.out.println(“Connecting”); break; case “cancel”: System.out.println(“Connecting”); break; case “disconnect”: System.out.println(“Connecting”); break; default: System.out.println(“Connecting”); break; } } } // End code Output: Connecting However، switching on strings can be less efficient than switching on integers. Therefore، it is best to switch on strings only in cases in which the controlling data is already in string form. In other words، don’t use strings in a switch unnecessarily.

101
Q

When does an exception error occur?

A

An exception is an error that occurs at run time.

102
Q

What class do all exception classes derive from?

A

All exception classes are derived from a class called Throwable. Thus، when an exception occurs in a program، an object of some type of exception class is generated.

103
Q

What are the two direct subclasses of the Throw able class?

A

There are two direct subclasses of Throwable: Exception and Error.

104
Q

Where do exceptions of type Error subclasses occur and how do you handle them?

A

Exceptions of type Error are related to errors that occur in the Java Virtual Machine itself، and not in your program. These types of exceptions are beyond your control، and your program will not usually deal with them.

105
Q

Where do errors of subclass Exception occur? What is a notably important subclass of Exception?

A

Errors that result from program activity are represented by subclasses of Exception. For example، divide-by-zero، array boundary، and file errors fall into this category. In general، your program should handle exceptions of these types. An important subclass of Exception is RuntimeException، which is used to represent various common types of run-time errors.

106
Q

What are the five keywords that handle Java exceptions?

A

Java exception handling is managed via five keywords: try، catch، throw، throws، and finally. They form an interrelated subsystem in which the use of one implies the use of another.

107
Q

How do you monitor for exceptions in your code?

A

Program statements that you want to monitor for exceptions are contained within a try block. If an exception occurs within the try block، it is thrown. Your code can catch this exception using catch and handle it in some rational manner.

108
Q

Make question here

A

System-generated exceptions are automatically thrown by the Java run-time system. To manually throw an exception، use the keyword throw. In some cases، an exception that is thrown out of a method must be specified as such by a throws clause.

109
Q

What keyword do you use while exception handling if a code block must be executed upon exiting a try block?

A

Any code that absolutely must be executed upon exiting from a try block is put in a finally block.

110
Q

What is the general form of a try/catch block?

A

Here is the general form of the try/catch exception handling blocks: try { // block of code to monitor for errors } catch (ExcepType1 exOb) { // handler for ExcepType1 } catch (ExcepType2 exOb) { // handler for ExcepType2 } . . . Here، ExcepType is the type of exception that has occurred. When an exception is thrown، it is caught by its corresponding catch statement، which then processes the exception. As the general form shows، there can be more than one catch statement associated with a try. When an exception is caught، exOb will receive its value.

111
Q

How would you write a cod that trys to create an array that has a value index past the arraysboundry? How would it catch the error?

A

The following program purposely generates such an exception and then catches it: //Demonstrate exception handling. class ExcDemo1 { public static void main(String args[]) { int nums[] = new int [4]; try { //Create a try block System.out.println(“Before exception is generated.”); //Generate an index out-of-bounds exception. nums[7] = 10; //Attempts to index past nums boundary. System.out.println(“This wont be displayed.”); } catch (ArrayIndexOutOfBoundsException exc) { //Catch array boundary errors //Catch the exception. System.out.println(“Index out-of-bounds!”); } System.out.println(“After catch statement.”); } }

112
Q

When does the code inside a try block stop running if there is an error?

A

When an exception occurs، the exception is thrown out of the try block and caught by the catch statement. At this point، control passes to the catch، and the try block is terminated.

113
Q

What happens if a method that doesn’t have its own try/catch statement is called in a method that does have its own try/catch method? What if the method did have its own try-catch statement that was set off?

A

//An exception can be generated by one method and caught by another. class ExcTest { //Generate an exception. static void genException() { int nums[] = new int [4]; System.out.println(“Before exception is generated.”); //Generate an index out-of-bounds exception. nums[7] = 10; //Exception generated here. System.out.println(“This wont be displayed.”); } } class ExcDemo2 { public static void main(String args[]) { try { ExcTest.genException(); } catch (ArrayIndexOutOfBoundsException exc) { //Catch the exception. System.out.println(“Index out-of-bounds!”); } System.out.println(“After catch statement.”); } } Since genException( ) is called from within a try block، the exception that it generates (and does not catch) is caught by the catch in main( ). Understand، however، that if genException( ) had caught the exception itself، it never would have been passed back to main( ).

114
Q

What happens when you have an exception that isn’t handled by your program?

A

In general، if your program does not catch an exception، then it will be caught by the JVM. The trouble is that the JVM’s default exception handler terminates execution and displays a stack trace and error message.

115
Q

How many catch statements can you pair with just one try statement?

A

As stated earlier، you can associate more than one catch statement with a try. In fact، it is common to do so. However، each catch must catch a different type of exception.

116
Q

Why do you put a subclass catch before its superclass?

A

A catch clause for a superclass will also match any of its subclasses. For example، since the superclass of all exceptions is Throwable، to catch all possible exceptions، catch Throwable. If you want to catch exceptions of both a superclass type and a subclass type، put the subclass first in the catch sequence. If you don’t، then the superclass catch will also catch all derived classes. This rule is self-enforcing because putting the superclass first causes unreachable code to be created، since the subclass catch clause can never execute.

117
Q

What is the catch code fragment that you would use to catch all exceptions?

A

In this case، catch(Throwable) catches all exceptions

118
Q

What is the general form of a throw statement?

A

it is possible to manually throw an exception by using the throw statement. Its general form is shown here: throw exceptOb; Here، exceptOb must be an object of an exception class derived from Throwable.

119
Q

How would you make a code that throws an arithmetic exception with text before، during the catch، and after?

A

Here is an example that illustrates the throw statement by manually throwing an ArithmeticException: //Manually throw an exception. class ThrowDemo { public static void main(String args[]) { try { System.out.println(“Before throw.”); throw new ArithmeticException(); //Throw an exception } catch (ArithmeticException exc) { //Catch the exception. System.out.println(“Exception caught.”); } System.out.println(“After try/catch block.”); } }

120
Q

Why is the “new” keyword important while creating a throw statement?

A

Notice how the ArithmeticException was created using new in the throw statement. Remember، throw throws an object. Thus، you must create an object for it to throw. That is، you can’t just throw a type.

121
Q

What is the Rethrow statement and when might you use it?

A

An exception caught by one catch statement can be rethrown so that it can be caught by an outer catch. The most likely reason for rethrowing this way is to allow multiple handlers access to the exception. For example، perhaps one exception handler manages one aspect of an exception، and a second handler copes with another aspect. Remember، when you rethrow an exception، it will not be recaught by the same catch statement. It will propagate to the next catch statement.

122
Q

How would you make a code that rethrows a dived-by-zero error? Remember، rethrows are probably most useful when 2 or more classes are involved.

A

//Rethrow an exception. class Rethrow { public static void genException() { //Here، numer is longer than denom. int numer[] = {4، 8، 16، 32، 64، 128، 256، 512}; int denom[] = {2، 0، 4، 4، 0، 8} for(int i = 0; i < numer.length; i++) try { System.out.println(numer[i] + “ / “ + denom[i] + “ is “ + numer[i] / denom[i]); } catch(ArithmeticException exc) { //Catch divide by zero error. System.out.println(“Can’t divide by zero!”); catch(ArithmeticException exc) { //Catch array length error. System.out.println(“No matching element found!”); throw exc; //Rethrow the exception. } } } } class RethrowDemo public static void genException() { try { Rethrow.genException(); } catch(ArrayIndexOutOfBoundsException exc) { //Recatch exception System.out.println(“Fatal error - “ + “program terminated.”); } } } In this program، divide-by-zero errors are handled locally، by genException( )، but an array boundary error is rethrown. In this case، it is caught by main( ).

123
Q

What are the 7 more commonly used methods defined by Throwable?

A

Since all exceptions are subclasses of Throwable، all exceptions support the methods defined by Throwable. Several commonly used ones are shown in:

124
Q

What is the general form of a method that includes a throws clause?

A

Here is the general form of a method that includes a throws clause: ret-type methName(param-list) throws except-list { // body } Here، except-list is a comma-separated list of exceptions that the method might throw outside of itself.

125
Q

What type of methods need a throws clause and which dont?

A

exceptions that are subclasses of Error or RuntimeException don’t need to be specified in a throws list. Java simply assumes that a method may throw one. All other types of exceptions do need to be declared. Failure to do so causes a compile-time error.

126
Q

What does the prompt() method do?

A

Let’s look at an example that handles IOException. It creates a method called prompt( )، which displays a prompting message and then reads a character from the keyboard. Since input is being performed، an IOException might occur. However، the prompt( ) method does not handle IOException itself. Instead، it uses a throws clause، which means that the calling method must handle it.

127
Q

What are uncheck exceptions? Can you remember all 19 of them and what they do?

A

In the language of Java، these are called unchecked exceptions because the compiler does not check to see if a method handles or throws these exceptions. The unchecked exceptions defined in java.lang are listed:

128
Q

What are check exceptions in Java? Can you remember all 8 of them and what they do?

A

those exceptions defined by java.lang that must be included in a method’s throws list if that method can generate one of these exceptions and does not handle it itself. These are called checked exceptions.

129
Q

What are chained exceptions?

A

Chained exceptions were added to Java by JDK 1.4. The chained exception feature allows you to specify one exception as the underlying cause of another. For example، imagine a situation in which a method throws an ArithmeticException because of an attempt to divide by zero. However، the actual cause of the problem was that an I/O error occurred، which caused the divisor to be set improperly. Although the method must certainly throw an ArithmeticException، since that is the error that occurred، you might also want to let the calling code know that the underlying cause was an I/O error.

130
Q

What are the 2 chained exception methods added to throwable and what are their general form?

A

The chained exception methods added to Throwable are getCause( ) and initCause( ). These methods are shown here: Throwable getCause( ) Throwable initCause(Throwable causeExc) The getCause( ) method returns the exception that underlies the current exception. If there is no underlying exception، null is returned. The initCause( ) method associates causeExc with the invoking exception and returns a reference to the exception. Thus، you can associate a cause with an exception after the exception has been created.

131
Q

What are the two ways in which java errors can be reported? When should you use one over the other?

A

In general، errors can be reported in two ways: return values and exceptions. When is one approach better than the other? Simply put، in Java، exception handling should be the norm. Certainly، returning an error code is a valid alternative in some cases، but exceptions provide a more powerful، structured way to handle errors. They are the way professional Java programmers handle errors in their code.