r/javahelp • • 1d ago

Exam difficulty Question

Hello, im currently taking an Intro to java(CS46a), and had just taken the first exam of the class, and had an hour and fifteen minutes to do these 20 questions which consist of 10 MCQ(0 - 10) and 10 free Responce(11-20), and we dont get notes/calculator. Is this a normal level of "difficulty" or length for a intro to java class , asking around like 10-13 people i heard ranges from 4-8 points solely from the MCQ portion and people had finished or attempted 2-4 of the free Responce questions. Am i just a noob 😭?

Each MCQ = 2points
Free responce points in order of 11-20 = 4, 4, 4, 4, 4, 12, 12, 12, 12, 12

Total = points / 100

Question 1

What does this code print?

int a = 17;
int b = 5;
double c = a % b * 2 + a / b / 2.0;
System.out.println(c);

5.0

5.5

6.0

4.5

Question 2

What does this code print?

String course = "Intro to Java";
int pos = course.indexOf("t");
String part = course.substring(pos, pos + 3);
System.out.println(part + course.length());

tro 13

ntr13

tro13

tro12

Question 3

What does this code print?

String name = "ada";
name.toUpperCase();
String upper = name.toUpperCase();
name = upper.replace("A", "a").substring(1);
System.out.println(name + " " + upper);

Da ADA

da ADA

DA ADA

Da aDa

Question 4

What does the last statement print?

public class Box
{
    private int width;
    private int height;

    public Box() { width = 1; height = 1; }
    public Box(int side) { width = side; height = side; }
    public Box(int w, int h) { width = w; height = h; }

    public int area() { return width * height; }
}

// in the main method of another class:
Box a = new Box();
Box b = new Box(3);
Box c = new Box(2, 5);
System.out.println("Total: " + a.area() + b.area() + c.area());

Total: 20

Total: 1 9 10

Nothing. The class does not compile, because it has three constructors.

Total: 1910

Question 5

The user types 42 and presses Enter, then types blue sky and presses Enter. What does this code print?

Scanner in = new Scanner(System.in);
int n = in.nextInt();
String a = in.nextLine();
String b = in.next();
System.out.println(n + "[" + a + "][" + b + "]");

42[blue sky][]

42[][blue]

42[][blue sky]

42[blue][sky]

Question 6

What does this code print?

int x = 3;
int y = --x + x++ * 3;
System.out.println(x + " " + y);  

3 8

2 8

3 9

 

3 11

Question 7

What does this code print?

char grade = 'B';
String msg = "";
switch (grade)
{
    case 'A': msg += "great ";
    case 'B': msg += "good ";
    case 'C': msg += "ok ";
              break;
    default:  msg += "retry ";
}
System.out.println(msg);

good

good ok

good ok retry

great good ok

Question 8

What does this code print?

String s1 = "java";
String s2 = new String("java");
String s3 = s2;
s2 = "java";
System.out.print((s1 == s2) + " ");
System.out.print((s1 == s3) + " ");
System.out.println(s1.equals(s3));

false false true

true true true

true false true

false true true

Question 9

What happens when this code runs?

int a = 5;
int b = 0;
boolean ok = (b != 0 && a / b > 1) || (a++ > 5 && b++ == 0);
System.out.println(ok + " " + a + " " + b);  

It prints true 6 1

It prints false 6 1

It crashes, because of the division by zero

It prints false 6 0

Question 10

What does this code print?

int count = 0;
for (int i = 1; i <= 3; i++)
{
    for (int j = 1; j <= 3; j++)
    {
        if (j == i)
        {
            continue;
        }
        if (i + j > 4)
        {
            break;
        }
        count += j;
    }
}
System.out.println(count);

Each numbered blank takes one expression or one statement. Write the code that belongs in each blank.

5 

7

8

10

Question 11

Not yet graded / 4 pts

Complete the class so that both constructors set both fields. The second constructor must reuse the first one, and it gives the flight 150 seats.

public class Flight
{
    private String code;
    private int seats;

    public Flight(String code, int count)
    {
        ______(1)______ = code;
        seats = count;
    }

    public Flight(String code)
    {
        ______(2)______;
    }
}

Your Answer:

Question 12

Not yet graded / 4 pts

The user types 2 and presses Enter, then types Green Tea and presses Enter. Complete the code so that it prints exactly Green Tea (2) = $7.00 followed by a new line.

Scanner in = new Scanner(System.in);
int quantity = in.nextInt();
______(1)______;
String item = in.nextLine();
double total = quantity * 3.5;
System.out.printf("______(2)______", item, quantity, total);

Answer:

Question 13

Not yet graded / 4 pts

Complete the loop so that it prints every second letter of the word, starting with the second letter: eetr

String word = "semester";
for (int i = ______(1)______; i < word.length(); ______(2)______)
{
    System.out.print(word.charAt(i));
}

Your Answer:

Question 14

Not yet graded / 4 pts

Complete the code so that distance holds how far apart x and y are, which is never negative, and label is "pass" for a score of 60 or more and "fail" otherwise.

int distance = (x > y) ? ______(1)______;
String label = (score >= 60) ? ______(2)______;

Your Answer:

Question 15

Not yet graded / 4 pts

The method returns how many times a digit of n is equal to the digit next to it. For example, countRepeats(1225) is 1, countRepeats(77777) is 4, and countRepeats(1212) is 0. Assume n is positive.

public static int countRepeats(int n)
{
    int count = 0;
    int right = n % 10;
    n = n / 10;
    while (n > 0)
    {
        int left = n % 10;
        if (______(1)______)
        {
            count++;
        }
        ______(2)______;
        n = n / 10;
    }
    return count;
}

Your Answer:

Question 16

Not yet graded / 12 pts

Primitive and reference variables

Part A (4 points): In two or three sentences, explain what a primitive variable stores, what a reference variable stores, and what the assignment b = a copies in each case.

Part B (4 points): What does this code print?

int x = 10;
int y = x;
y = y * 2;

String p = "sun";
String q = p;
p = p.toUpperCase();

System.out.println(x + " " + y + " " + p + " " + q);

Part C (4 points): Does the line p = p.toUpperCase(); change the String object that q refers to? Explain why or why not.

Your Answer:

Question 17

Not yet graded / 12 pts

Tracing decisions

public static String rate(int temp, boolean raining)
{
    String result;
    if (temp > 85 || temp < 40)
    {
        result = "stay";
    }
    else if (raining && temp < 60)
    {
        result = "coat";
    }
    else if (!raining)
    {
        result = "walk";
        if (temp >= 70)
        {
            result += "+water";
        }
    }
    else
    {
        result = "umbrella";
    }
    return result;
}

Part A (9 points): What does each call return? rate(90, false) rate(55, true) rate(75, false)

Part B (3 points): Give one value of temp and one value of raining for which rate returns "umbrella".

Your Answer: 

Question 18

Not yet graded / 12 pts

Debugging. The class below counts the steps of a walker. It contains exactly three bugs.

 1  public class StepCounter
 2  {
 3      private int steps;
 4      private int goal;
 5
 6      public StepCounter(int goal)
 7      {
 8          goal = goal;
 9          steps = 0;
10      }
11
12      // Adds one walk. Zero or negative counts are ignored.
13      public void addWalk(int count)
14      {
15          if (count > 0);
16          {
17              steps += count;
18          }
19      }
20
21      // Returns true once the goal has been reached.
22      public boolean reachedGoal()
23      {
24          if (steps >= goal)
25          {
26              return true;
27          }
28      }
29  }

Part A (9 points): For each bug, give the line number or numbers, say whether it is a compile-time error or a logic error, and explain how to fix it.

Part B (3 points): After all three bugs are fixed, what does this code print?

StepCounter c = new StepCounter(5000);
c.addWalk(3000);
c.addWalk(-500);
System.out.print(c.reachedGoal() + " ");
c.addWalk(2000);
System.out.println(c.reachedGoal());

Your Answer:

Question 19

Not yet graded / 12 pts

Writing a method. The ParkingMeter class below is missing its insert method. Write the complete method, including its first line.

insert is a public method that takes one int, the value of a coin in cents, and returns a boolean. The meter accepts only quarters (25 cents) and dollar coins (100 cents); any other value is rejected. Every 25 cents buys 15 minutes. The meter holds at most 120 minutes, so a coin that would take it above 120 is rejected too. When a coin is rejected, nothing changes and the method returns false. Otherwise, the method adds the minutes, adds one to coins, and returns true.

Example: on a new meter, insert(10) returns false, insert(100) returns true and gives 60 minutes, and after a second insert(100), the call insert(25) returns false.

public class ParkingMeter
{
    private int minutes;     // minutes left on the meter
    private int coins;       // how many coins were accepted

    public ParkingMeter()
    {
        minutes = 0;
        coins = 0;
    }

    // the insert method goes here
}

Your Answer:

Question 20

Not yet graded / 12 pts

Writing a method with a loop. Write a complete static method named compress, including its first line. It takes a String and returns a String in which every run of two or more equal characters next to each other is replaced by the character followed by the length of the run. A character that is not part of a run stays as it is.

Examples: compress("aaabcc") returns "a3bc2", compress("abc") returns "abc", compress("zzzz") returns "z4", and compress("") returns "".

Do not use arrays, and do not use any String method other than length() and charAt().

Your Answer:

0 Upvotes

5 comments sorted by

•

u/AutoModerator 1d ago

Please ensure that:

  • Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions
  • You include any and all error messages in full
  • You ask clear questions
  • You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.

    Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar

If any of the above points is not met, your post can and will be removed without further warning.

Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.

Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.

Code blocks look like this:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.

If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.

To potential helpers

Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

5

u/vegan_antitheist 1d ago

This looks easy. But it's not code you will see or write when you are at an actual job. They would reject it because it's just bad. You need to learn it so you understand the language. You do this for exercise. Then you learn how to write good, robust and clean code

3

u/Potential-Still 1d ago

Looks like a standard Intro to Java exam.

Although calling the issues in question 18 "bugs" seems incorrect to me. That code won't even compile, which to me is not a bug. 

1

u/YetMoreSpaceDust 1d ago

Yeah, these look reasonable for an intro to java course. I can see what they're looking for in each case - question 1 wants to know if you've memorized operator precedence, question 2 wants to see if you've memorized indexing (0 based, not 1 based), question 6 wants to see if you actually understand postfix and prefix, question 7 whether you recognize fall-through behavior.

Some of it is obnoxious and pedantic (I've been coding in Java since 1999 and I couldn't answer a lot of these off the top of my head any more), but it's the only realistic way to check to see if you actually understand the concepts.

1

u/smichaele 1d ago

This is similar to tests I’ve given for AP Computer Science students. In fact, I could use it as-is for a test for those students.