CS1: Lecture 7 – What’s Wrong With These?

Dear students,

Today’s a bit of a clean-up day. There are some ideas that didn’t quite fit into our previous discussions, and I’ve also had the chance to see your code a few times now and want to address some concerns. Let’s have a day of miscellany.

What’s Wrong With This?

There are two dimensions of code: syntax and semantics. Syntax refers to the grammatical rules of the language: statements must end in a semi-colon, curly braces must be balanced, and so on. Semantics refers to the meaningfulness of the code: do variable names properly reflect the data they contain, do method names reflect the actions, types must be compatible, and so on. We error on both dimensions all the time. The good news is that syntax errors will start to disappear as you learn the rules of Java and you will also learn to fix them quickly when they happen. The bad news is that semantic errors will haunt us forever.

We’re going to play a little game. I’ll show some chunks of code that have errors in them. Only one has a syntax error. You will confer with your neighbor and try to figure out what’s wrong.

  • Problem A
    int nPoints = homework + exams + bribe;
    double nGrade = (int) Math.round(nPoints / (double) nPointsPossible);

    I use the name nThings when the variable stores the count or number of things. Not everything is a count and not every variable should start with n.
  • Problem B
    Scanner in1 = new Scanner(System.in);
    System.out.print("a: ");
    int a = in1.nextInt();
    Scanner in2 = new Scanner(System.in);
    System.out.print("b: ");
    int b = in2.nextInt();

    Only one Scanner is needed when retrieving input from System.in. Reuse that one instance.
  • Problem C
    Scanner in1 = new Scanner(System.in);
    System.out.print("Name: ");
    int Name = in1.nextLine();

    Variable names should start with a lowercase first letter. Always. This distinguishes them from class names. If you violate formatting convention, you will draw upon you the anger of collaborators who will rewrite it and you.
  • Problem D
    String String = new String("String").toString();

    This is gross! But it demonstrates that variable names and type names are in separate universes and do not conflict with each other.
  • Problem E
    public class TaxCalculator {
      Scanner in = new Scanner(System.in);
      double price = in.nextDouble();
      double cost = price * 1.055;
      System.out.printf("Cost: %.2f%n", cost);

    In Java, all your code needs to be tucked inside a method—a main method at this point.
  • Problem F
    int i = 127;
    byte b = i;

    You can’t squeeze a 4-byte quantity into a 1-byte quantity.
  • Problem H
    Scanner in = new Scanner(System.in);
    int a = in.nextInt();
    int b = in.nextInt();
    String message = "The sum is " + a + b;

    This doesn’t print the sum. It prints the concatenation. That’s because + is a left-associative operator. Also at work here is promotion, which we discuss below.


We’ve got four integer types and two floating point types, and now we’ve seen String, which is an anything-goes type. Sometimes we need to move data from one type to another. Whether that’s legal or not depends on the direction you are going in this ladder:


If you are going from a lower type to a higher type, then you can freely transition. This is called an upcast. For instance, let’s store a byte in an int:

byte b = 100;
int i = b;

But if you go the other direction in a downcast, you face the potential loss of information. The higher types can store a broader range of numbers that might not fit in the smaller type. The Java compiler requires that we sign off on this potential information loss with a cast:

int i = 10000;
byte b = (byte) i;

Technically, an upcast can also result in a loss of information because not all whole numbers can be stored in a floating point number. But this danger is largely ignored and will perhaps be our ruin.


Sometimes casting happens automatically when an operator combines operands of different types. Consider this code:

Scanner in = new Scanner(System.in);
int a = in.nextInt();
int b = in.nextInt();
String message = "The sum is " + a + b;

This doesn’t runs, but perhaps doesn’t yield the expected result. "The sum is " is a String, and as soon as you involve a String in an operation, we’re going to get a String result. There’s no explicit cast, but there’s an implicit one. When an operator combines a more general type and a more specific type, the more specific type is automatically converted to the more general type. This is called promotion.


In case we have extra time, we’ll try our hand at a few more String problems:

  • Given a line of comma-separated names, extract out the fifth.
  • Ask the user for a mod problem (for example, 100 % 3) and compute its value.


Here’s your TODO list of things to complete before next class:

  • Read chapter 3, the contents of which we will start discussing next time. Write down 2-3 questions or observations on a quarter sheet to be turned in at the beginning of next lecture.
  • Make sure you are committing and pushing after every coding session! Don’t save configuration issues until Monday. I will be attending a virtual conference Sunday and Monday and will have less time to help you. We will still have class and office hours.

See you next class!


P.S. It’s time for a haiku!

Proposals are Strings
Rejections are booleans
My heart is in chars

P.P.S. Here’s the code we wrote together in class…


package lecture0918.cs148;

import java.util.Random;

public class Loss {
  public static void main(String[] args) {
    for (int i = 0; i < 100000000; ++i) {
      float iAsFloat = i;
      int iAsIntFromFloat = (int) iAsFloat;
      if (iAsIntFromFloat != i) {
        System.out.printf("%d vs. %d", i, iAsIntFromFloat);


Leave a Reply

Your email address will not be published. Required fields are marked *