0% found this document useful (0 votes)
4 views26 pages

Java Basics Exam Review Guide

The document is an exam review for CSC 101 at San Francisco State University, covering Java basics, elementary programming concepts, and selections. It includes true/false questions, multiple-choice questions, and coding exercises related to Java programming. The review aims to prepare students for their upcoming exam by testing their knowledge on various Java programming topics.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views26 pages

Java Basics Exam Review Guide

The document is an exam review for CSC 101 at San Francisco State University, covering Java basics, elementary programming concepts, and selections. It includes true/false questions, multiple-choice questions, and coding exercises related to Java programming. The review aims to prepare students for their upcoming exam by testing their knowledge on various Java programming topics.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CSC 101 Intro to Computing

San Francisco State University


Exam Review

1 Java Basics
1. ( True / False ) Public classes in Java and the name of the .java file MUST be the same.
2. ( True / False ) Java classes must begin with a captial letter.
3. ( True / False ) The main method is the entry point to a Java program.
4. ( True / False ) There is no different between [Link] and [Link] printing functions.
5. ( True / False ) Java is a case-sensitive language.
6. What character is used to move text or the cursor to the next line?
A. \n
B. next
C. \b
D. \t
7. What is the extension of the Java source code file?
A. .c
B. .cpp
C. .java
D. .class
E. .py
8. What is the marker for starting a line comment in Java?
A. //
B. #
C. /* */
D. ”’
E. –
F. /** */
9. What is the marker for starting a block comment in Java?
A. //
B. #
C. /* */
D. ”’
E. –
F. /** */
10. What is the marker for starting a JavaDoc comment in Java?
A. //
B. #
C. /* */
D. ”’
E. –
F. /** */

1
11. What is the character used for denoting a Java code block?
A. { }
B. [ ]
C. ( )

12. Every Java statement must end with what character?


A. ;
B. ;
C. .
D. ,
E. \n
13. What are the 3 types of errors discussed in class?

14. What is a syntax/compile time error?

15. What is a logic error?

16. What is a runtime error?

17. If a program compiles fine, but it produces incorrect result, then the program suffers .
A. a compile error
B. a runtime error
C. a logic error

2
18. The following code has .
public class Test {
public static void main(String[] args) {
[Link]("Welcome to Java!);
}
}

A. a compile error
B. a runtime error
C. a logic error
19. The following code has .
public class Test {
public static void main(string[] args) {
[Link]("Welcome to Java!");
}
}

A. a compile error
B. a runtime error
C. a logic error

3
2 Elementary Programing
1. Name the eight primitive data types.

2. What are their sizes(Number of bits and bytes)? Note: a bit is NOT a primitive type. For example, 1
byte = 8 bits

Type Bits Byte


Bit 1 -
Byte 8 -

3. Please answer the folllwing below:


(a) Declare a variable of type integer with the name x.

(b) Declare a variable of type double with the name money.

(c) Declare and initialize a const variable of type int with the name max.

(d) Declare a variable of type String with the name str.

(e) Declare and initialize a variable of type String with the name msg and the value Hello World!.

(f) Declare and initialize a variable of type boolean with the name flag and the value of false.

4. How would you print the string ”Yay for Exams!”?

4
5. Name five reserved words.

6. List as many java operators as you can without help from any outside sources.

7. How does the increment and decrement operators work? What does it mean for an operator to be post
or pre increment/decrement?

8. What is Java source code compiled into?

9. Write the equivalent of the following statements


(a) y += 1;

(b) x /= 2;

(c) z = z * 9;

(d) i + +

(e) i − −

10. What does 9/10 equal to? Why? What about 9/10.0? Why?

11. What is Type Casting / Type Conversion?

5
12. What does 9/10 equal to? Why? What about 9/10.0? Why?

13. Please complete the code snippets below to make them correct:
(a) Assign the variable c to a.
int c = 3;
long a;

(b) Assign the variable of pi to lPi.


double pi = 3.1415926535;
long lPi;

(c) Assign the variable c to intC.


char c = ’c’;
int intC;

(d) Assign the variable s to b.


short s = 33;
byte b;

(e) Assign the variable i to s.


int i = 213124;
short s;

(f) Assign the variable l to b.


long l = 33123123l;
int b;

(g) Assign the variable b the value of true.


boolean b;

6
(h) Assign the variable x the express 3.2 + 1.
int x;

(i) Assign the variable x the express 3.2 + 1.


double x;

14. What is the exact output of the following code?


double area = 3.5;
[Link]("area");
[Link](area);

A. 3.53.5
B. 3.5 3.5
C. area3.5
D. area 3.5
15. Which of the following are correct ways to declare variables? Please select all that apply.
A. int length; int width;
B. int length, width;
C. int length; width;
D. int length, int width;
16. is the Java assignment operator.
A. ==
B. :=
C. =
D. =:

17. What is the result of 45 / 4?


A. 10
B. 11
C. 11.25
D. 12

18. Which of the following expression results in a value 1?


A. 2 % 1
B. 15 % 4
C. 25 % 5
D. 37 % 6

7
19. Suppose x is 1. What is x after x += 2?
A. 0
B. 1
C. 2
D. 3
E. 4
20. Suppose x is 1. What is x after x -= 1?
A. 0
B. 1
C. 2
D. -1
E. -2
21. What is x after the following statements?
int x = 2;
int y = 1;
x *= y + 1;

A. x is 1.
B. x is 2.
C. x is 3.
D. x is 4.
22. What is x after the following statements?
int x = 1;
x *= x + 1;

A. x is 1.
B. x is 2.
C. x is 3.
D. x is 4.
23. Which of the following statements are the same?
(A) x -= x + 4
(B) x = x + 4 - x
(C) x = x - (x + 4)

A. (A) and (B) are the same.


B. (A) and (C) are the same.
C. (B) and (C) are the same.
D. (A), (B), and (C) are the same.

8
24. To add a value 1 to variable x, you write . Please select all that apply.
A. 1 + x = x;
B. x += 1;
C. x := 1;
D. x = x + 1;
E. x = 1 + x;
25. To add number to sum, you write . (Note: Java is case-sensitive) Please select all that
apply.
A. number += sum;
B. number = sum + number;
C. sum = Number + sum;
D. sum += number;
E. sum = sum + number;

26. What is i printed?


public class Test {
public static void main(String[] args) {
int j = 0;
int i = ++j + j * 5;

[Link]("What is i? " + i);


}
}

A. 0
B. 1
C. 5
D. 6
27. What is i printed in the following code?
public class Test {
public static void main(String[] args) {
int j = 0;
int i = j++ + j * 5;

[Link]("What is i? " + i);


}
}

A. 0
B. 1
C. 5
D. 6

9
28. What is y displayed in the following code?
public class Test {
public static void main(String[] args) {
int x = 1;
int y = x++ + x;
[Link]("y is " + y);
}
}

A. y is 1.
B. y is 2.
C. y is 3.
D. y is 4.
29. What is y displayed?
public class Test {
public static void main(String[] args) {
int x = 1;
int y = x + x++;
[Link]("y is " + y);
}
}

A. y is 1.
B. y is 2.
C. y is 3.
D. y is 4.
30. Are the following four statements equivalent?
number += 1;
number = number + 1;
number++;
++number;

A. Yes
B. No
31. To assign a double variable d to a float variable x, you write .
A. x = (long)d
B. x = (int)d;
C. x = d;
D. x = (float)d;

32. Which of the following expressions will yield 0.5? Please select all that apply.
A. 1 / 2
B. 1.0 / 2
C. (double) (1 / 2)
D. (double) 1 / 2
E. 1 / 2.0

10
33. What is the output of the following code?
double x = 5.5;
int y = (int)x;
[Link]("x is " + x + " and y is " + y);

A. x is 5 and y is 6
B. x is 6.0 and y is 6.0
C. x is 6 and y is 6
D. x is 5.5 and y is 5
E. x is 5.5 and y is 5.0

34. Which of the following assignment statements is illegal?


A. float f = -34;
B. int t = 23;
C. short s = 10;
D. int t = 4.5;

35. What is the value of (double)5/2?


A. 2
B. 2.5
C. 3
D. 2.0
E. 3.0
36. What is the value of (double)(5/2)?
A. 2
B. 2.5
C. 3
D. 2.0
E. 3.0
37. Which of the following expression results in 45.37?
A. (int)(45.378 * 100) / 100
B. (int)(45.378 * 100) / 100.0
C. (int)(45.378 * 100 / 100)
D. (int)(45.378) * 100 / 100.0

38. The expression (int)(76.0252175 * 100) / 100 evaluates to .


A. 76.02
B. 76
C. 76.0252175
D. 76.03
39. If you attempt to add an int, a byte, a long, and a double, the result will be a(n) value.
A. byte
B. int
C. long
D. double

11
3 Selections
1. The ”less than or equal to” comparison operator in Java is .
A. <
B. <=
C. =<
D. <<
E. ! =
2. The equal comparison operator in Java is .
A. <>
B. ! =
C. ==
=
D.
3. What is 1 + 1 + 1 + 1 + 1 == 5?
A. True
B. False
C. There is no guarantee that 1 + 1 + 1 + 1 + 1 == 5 is true.
4. Which of the following code displays the area of a circle if the radius is positive?
A. if (radius ! = 0) [Link](radius * radius * 3.14159);
B. if (radius >= 0) [Link](radius * radius * 3.14159);
C. if (radius > 0) [Link](radius * radius * 3.14159);
D. if (radius <= 0) [Link](radius * radius * 3.14159);
5. Compute the following truth tables:

&& T F

(a) T

∥ T F

(b) T

∧ T F

(c) T

12
6. Given the following variables, what boolean value do these boolean expressions evaluate to?
int x = 5; int y = 9; int k = 0;
a. (x > y) && (k < x)

b. (x > y) || (k < x)

c. (y >= y) && (x < x)

d. !(y == y) || (x < x)

e. !(y != k) && !(k < x)

7. Suppose income is 4001, what is the output of the following code?


if (income > 3000) {
[Link]("Income is greater than 3000");
}
else if (income > 4000) {
[Link]("Income is greater than 4000");
}

A. no output
B. Income is greater than 3000
C. Income is greater than 3000 followed by Income is greater than 4000
D. Income is greater than 4000
E. Income is greater than 4000 followed by Income is greater than 3000
8. The following code displays .
double temperature = 50;

if (temperature >= 100)


[Link]("too hot");
else if (temperature <= 40)
[Link]("too cold");
else
[Link]("just right");

A. too hot
B. too cold
C. just right
D. too hot too cold just right

13
9. Suppose x = 1, y = -1, and z = 1. What is the output of the following statement? (Please indent the
statement correctly first.)
if (x < 0)
if (y > 0)
[Link]("x > 0 and y > 0");
else if (z > 0)
[Link]("x < 0 and z > 0");

A. x > 0 and y > 0;


B. x < 0 and z > 0;
C. x < 0 and z < 0;
D. no output.
10. What is the output of the following code?
int x = 0;
if (x < 4) {
x = x + 1;
}
[Link]("x is " + x);

A. x is 0.
B. x is 1.
C. x is 2.
D. x is 3.
E. x is 4.
11. Analyze the following code:
boolean even = false;
if (even = true) {
[Link]("It is even");
}

A. The program has a compile error.


B. The program has a runtime error.
C. The program runs fine, but displays nothing.
D. The program runs fine and displays It is even.

12. Suppose isPrime is a boolean variable, which of the following is the correct and best statement for testing
if isPrime is true?
A. if (isPrime = true)
B. if (isPrime == true)
C. if (isPrime)
D. if (!isPrime = false)
E. if (!isPrime == false)

14
13. Which of the following is the correct expression that evaluates to true if the number x is between 1 and
100 or the number is negative?
A. 1 < x < 100 && x < 0
B. ((x < 100) && (x > 1)) || (x < 0)
C. ((x < 100) && (x > 1)) && (x < 0)
D. (1 > x > 100) ∥ (x < 0)
14. Assume x = 4 and y = 5, which of the following is true?
A. x < 5 && y < 5
B. x < 5 ∥ y < 5
C. x > 5 && y > 5
D. x > 5 ∥ y > 5
15. Assume x = 4, which of the following is true?
A. !(x == 4)
B. x ! = 4
C. x == 5
D. x ! = 5
16. Assume x = 4 and y = 5, which of the following is true?
A. !(x == 4) ∧ y ! = 5
B. x ! = 4 ∧ y == 5
C. x == 5 ∧ y == 4
D. x ! = 5 ∧ y ! = 4
17. Given |x| <= 4, which of the following is true?
A. x <= 4 && x >= 4
B. x <= 4 && x > -4
C. x <= 4 && x >= -4
D. x <= 4 ∥ x >= -4

18. Given |x| >= 4, which of the following is true?


A. x >= 4 && x <= -4
B. x >= 4 ∥ x <= -4
C. x >= 4 && x < -4
D. x >= 4 ∥ x < -4

19. Which of the following is equivalent to x ! = y? Please select all that apply.
A. !(x == y)
B. x > y && x < y
C. x > y ∥ x < y
D. x >= y ∥ x <= y
20. Suppose x=10 and y=10. What is x after evaluating the expression (y > 10) && (x−− > 10)?
A. 9
B. 10
C. 11

15
21. Suppose x=10 and y=10. What is x after evaluating the expression (y > 10) && (x++ > 10)?
A. 9
B. 10
C. 11

22. Suppose x=10 and y=10. What is x after evaluating the expression (y >= 10) ∥ (x−− > 10)?
A. 9
B. 10
C. 11

23. Suppose x=10 and y=10. What is x after evaluating the expression (y >= 10) ∥ (x++ > 10)?
A. 9
B. 10
C. 11

16
4 Programming Questions
1. Write Java code that reads in an integer from the keyboard and then adds 5 to that number, then prints
it to the console.
public class ExamReview{
public static void main(String args[]){

}
}

2. Write Java code that reads in two integers from the user and then prints the largest of the two to the
console.
public class ExamReview{
public static void main(String args[]){

}
}

17
3. Write Java code that will print the letter grade corresponding to its numerical value. i.e 98 → A.
public class ExamReview{
public static void main(String args[]){
int grd = 87;

}
}

4. Implement a Java program that reads in a Celsius degree as a double from the user, converts it to
Fahrenheit, and then prints the resulting Fahrenheit value to the console. You may use the folllwing
equation:
f ahrenheit = (9/5) ∗ celsius + 32
public class ExamReview{
public static void main(String args[]){
Scanner in = new Scanner([Link]);

}
}

18
5. Write a program that reads in 2 double values, a sub-total and gratuity rate(tip %). The program will
compute the gratuity amount, and the total amount for the bill uncluding the gratuity amount.
public class ExamReview{
public static void main(String args[]){
Scanner in = new Scanner([Link]);

}
}

6. Write a Java program that allows the user to play rock(0), paper(1), scissors(2) with the computer. Your
program should prompt the user to enter an integer, 0 , 1, or 2. Then your program(code provided)
generates a random number 0,1,2. Using these 2 values, your program will determine who wins and
dispays the winner.
public class ExamReview{
public static void main(String args[]){
Scanner in = new Scanner([Link]);
//will be a random number betwen 0 and 2
int cpuMove = (new Random()).nextInt(3);

}
}

19
7. Write a Java program that reads in an integer between 1 and 12 from the user. Then prints the Month
corresponding to the the number. For example, if the user enters 3, your program should print ”March”.
If the user enters a number less than 1 or greater than 12, print ”Invalid Month” to the console.
public class ExamReview{
public static void main(String args[]){
Scanner in = new Scanner([Link]);

}
}

8. ( points) Write a Java program that reads two values from the user. The first value is the number of
notebooks to buy, the second is the price of each notebook. Your program should then calculate the
total cost of the notebooks, including tax, and print it to the console.
public class ExamReview{
public static void main(String args[]){
Scanner in = new Scanner([Link]);
final double TAX_RATE = 0.0825;

20
9. ( points) Write a Java program that reads one value from the user. The value is the number of pizzas
the user want to buy. Your program should do the following:
• Calculate the total cost of the pizzas.
• based on the number of pizzas purchased, apply a discount to the total cost.
– if the user buys less than 5 pizzas, no discount is applied.
– if the user buys 5 or more pizzas apply a 10% discount.
– if the user buys 10 or more pizzas apply a 20% discount.
– if the user buys 20 or more pizzas apply a 30% discount.
• Add 8.25% tax to the total cost of the pizzas.
• Print the total cost of the pizzas to the console.

public class ExamReview{


public static void main(String args[]){
Scanner in = new Scanner([Link]);
final double TAX_RATE = 0.0825;
double PPP = 4.99; //price per pizza

21
10. Write a Java program that calculates electricity bills based on consumption tiers. The user enters their
energy consumption in kWh. The first 100 kWh are billed at $0.10/kWh, the next 200 kWh(between
101 and 300) at $0.15/kWh, and any consumption above 300 kWh at $0.20/kWh. Use conditional logic
to calculate and display the bill amount.
public class ExamReview{
public static void main(String args[]){
Scanner in = new Scanner([Link]);
final double TIER1 = 0.10;
final double TIER2 = 0.15;
final double TIER3 = 0.20;
int consumption = 0;

}
}

22
11. Write a Java program that simulates a very simple ATM machine. The user starts with an initial balance
of$1000.
The program should allow the user to make one of two choices: deposit or withdraw. Depending on
the user’s choice, the program should then ask for the amount to deposit or withdraw and update the
balance accordingly. The program should ensure that the user cannot withdraw more than the current
balance. After the transaction, the program should display the updated balance. Sample Output:

Current balance: $1000


Press 1 to deposit or 2 to withdraw: 2
Enter the amount to withdraw: $200
Transaction successful. Your new balance is: $800

public class Exam{


public static void main(String[] args){
double balance = 1000;
[Link]("Current balance: $" + balance);

}
}

23
12. Create a Java program that calculates the simple interest on a given principal amount, rate of interest,
and time period. The program should prompt the user to enter these values. Use the formula:
Simple Interest = (Principal * Rate * Time) / 100
After calculating the interest, the program should display the total amount after interest.
Sample output:

Enter the principal amount: 1000


Enter the rate of interest (in %): 5
Enter the time period (in years): 2
The simple interest is: $100
The total amount after interest is: $1100

public class Exam{


public static void main(String[] args){
double principal, rate, time, interest;
Scanner input = new Scanner([Link]);

}
}

24
13. Write a Java program that acts as a simple unit converter for lengths. The user should be prompted
to enter a length in meters. The program should then offer the user options to convert this length into
kilometers, feet, or inches. Use the following conversion factors:
• 1 meter = 0.001 kilometers
• 1 meter = 3.28084 feet
• 1 meter = 39.3701 inches
Based on the user’s choice, display the converted length. Sample output:

Enter the length in meters: 100


Press 1 to convert to kilometers, 2 to feet, or 3 to inches: 2
The length in feet is: 328.084

public class Exam{


public static void main(String[] args){
double length;
Scanner input = new Scanner([Link]);

}
}

25
14. Write a Java program that asks the user to enter a year and then determines whether that year is a leap
year. A year is a leap year if it is divisible by 4 but not by 100, unless it is also divisible by 400. Sample
output:

Enter a year: 2020


2020 is a leap year.

public class Exam{


public static void main(String[] args){
int year;
Scanner input = new Scanner([Link]);

}
}

26

Common questions

Powered by AI

To convert a Celsius temperature to Fahrenheit, the formula fahrenheit = (9/5) * celsius + 32 is used. Java programs implementing this formula typically prompt the user for input, perform the conversion as an arithmetic operation, and output the result. This straightforward mathematical conversion showcases fundamental Java I/O and arithmetic operations .

In Java, integer division discards the fractional part, yielding only the integer quotient (e.g., 9/10 results in 0). In contrast, floating-point division retains the decimal value (e.g., 9/10.0 results in 0.9). This distinction is critical for operations requiring precision, and choosing the operation type impacts the outcome significantly, often necessitating type casting or additional handling to meet precise computational requirements .

Type conversion in Java, especially between primitives like int, double, and float, affects data precision and manipulation. Implicit casting (widening) safely converts lower-range data types to higher ones, while explicit casting (narrowing) requires manual casting and risks data loss (e.g., casting a float to an int truncates the decimal part). Careful handling is crucial when performing operations involving mixed types, ensuring correct application and result interpretation .

A Java programmer can utilize conditional logic to calculate electricity bills based on tiered consumption rates. The program reads user input for consumption in kWh and applies different rates depending on the tier structure: $0.10 for the first 100 kWh, $0.15 for usage from 101 to 300 kWh, and $0.20 thereafter. Conditional statements (e.g., if-else) facilitate this tiered pricing, allowing accurate billing based on consumption levels .

In Java, the naming convention requires that the name of a public class must match the name of the .java file to ensure that the Java compiler can locate the correct source file for a given class. This is because each public class is expected to reside in a file with the same name as the class. Failure to adhere to this convention results in a compilation error .

The increment (++) and decrement (--) operators in Java can be used in two forms: postfix (e.g., i++) and prefix (e.g., ++i). In postfix, the original value is used in expressions before the increment or decrement, while in prefix, the value is modified before usage. This distinction is crucial when the operators are part of a larger expression, as it affects the value being used in calculations, potentially altering program logic or outcomes .

Java supports three types of comments: single-line comments using //, multi-line or block comments enclosed within /* */, and Javadoc comments employed for formal documentation, marked by /** */. Each has its specific use case; single-line comments are for brief explanations, block comments for larger text spans, and Javadoc comments are parsed by the javadoc tool to generate code documentation .

Java source code, written in .java files, is compiled by the Java compiler (javac) into bytecode, which is platform-independent and stored in .class files. This bytecode is executed by the Java Virtual Machine (JVM), which interprets or further compiles it to machine code for the host platform. This two-step process provides Java's 'write once, run anywhere' capability, leveraging the JVM for versatility and cross-platform compatibility .

Java's case sensitivity means that variables, classes, and method names must be used consistently in terms of capitalization, which enforces a stricter syntax but also allows greater flexibility in identifier naming. This can lead to errors if a programmer is not careful, as 'Variable', 'variable', and 'VARIABLE' would be treated as distinct entities. This necessitates careful attention to naming conventions and can lead to increased readability and maintainability when properly managed .

Java errors are categorized into syntax errors, runtime errors, and logic errors. Syntax errors occur at compile time due to incorrect use of the language syntax. Runtime errors occur during program execution and can lead to abnormal program termination. Logic errors stem from incorrect logic in the program that compiles correctly but provides incorrect results. Understanding these types helps in diagnosing and correcting issues in Java programming .

You might also like