Chapter:Variables and types - Exercises

From Juneday education
Jump to: navigation, search

Exercises on variables and types

Variables

Q1

We have a variable nrOfGirls that has the value 14. We also have a variable called nrOfBoys with the value 13. If you were asked to add the values of the two variables together, what would be the result?

Expand using link to the right to see a hint.

The result would be a value of 27. The nrOfGirls has the value 14 and nrOfBoys has the value 13. Adding the values would be adding 13 and 14, which is 27.

Note for students learning the C programming language: Note about the variable names. The names are typical for Java variables. They would probably be called nr_of_girls and nr_of_boys in the C programming language but that's not important for these exercises.

Q2

TODO: Remove this and put in the exercises dedicated for C programming only!

Assume a person knows the address of the memory where nrOfGirls is stored. This person writes the value 123 in that memory. What would be the sum of nrOfGirls and nrOfBoys be if you were to add them together again?

Expand using link to the right to see a hint.

136. The nrOfGirls now has the value 123 and nrOfBoys has the value 13 Adding the values would be adding 123 and 13, which is 136.

Please note that in the Java programming language, the programmer never can access the address of a variable like that, but it actually is quite possible in languages like C. In Java, the only way to overwrite the value of a variable is to use the variable itself.

Other programming language allow the manipulation of the value at the address in the memory itself.

Types

Q1

If you want to count the number of goals in a game of handball, what would be a good type for a variable?

Expand using link to the right to see a hint.

Some kind of integer variable. Decimals are not needed - it wouldn't make sense to keep track of a fraction of a goal - e g 1/3 of a goal. The authors do not know of any game that has ended 27.25 - 23. So to keep things simple and to skip the unnecessary, let's use an integer. In Java you can use int.

Q2

If you want to store the name of a person in a variable, what would be a good type for that name?

Expand using link to the right to see a hint.

String. String is a reference type, and we'll talk a lot about reference types and classes in later chapters.

Warning: This is a Java-specific answer. There is no String type in for instance the C programming language.

Q3

You want to store the mean value of the results on an exam. Can you recommend any type?

Expand using link to the right to see a hint.

It's not unlikely that we'll end up with decimals so a type that supports that would be good. So let's say a double

Q4

Add an integer variable with the current value of 1 with another integer variable with the value 1. What is the resulting sum?

Expand using link to the right to see a hint.

Adding 1 to 1 is simple. The result is 2.

Declaration

Q1

Declare an int type variable called nrStudent.

Expand using link to the right to see a hint.

int nrStudent;

The above is a typical naming of a variable in the Java programming language. If you are more interested in the C programming language, the variable would more typically have been called:

int nr_student;

Q2

Imagine we have two variables with exactly the same name. What would be meaning of that? If you find this question hard to answer you're most likely thinking correctly. Don't spend too much time on this question.

Expand using link to the right to see a hint.

If it would be possible to declare two variables in the same scope, with the same name, which is not possible in the languages known by the authors of these lectures and exercises, it would be hard to come up with a reasonable interpretation of what it would mean to use one of the two variables. This is the reason why it is not allowed to use the same variable name twice. At least for now... So the meaning of this would be ... well, hard to come up with. When you learn about scope, you will see that there are rules for when you can use the same name twice, and how to know what name refers to what variable for instance.

Assignment

Q1

Declare an integer variable, temperature, and assign it the value 13

Expand using link to the right to see a hint.

Let's declare an integer variable. The first thing we need to is to specify the type. In this case we were asked to declare an integer so let's use the integer called int.

The next thing we should specify is the name we want to use, let's go for temperature. Ok, finally we should assign the variable a value, to be more specific 13. So let's use the assignment operator. And as always, Java (in particular the Java compiler) wants you to be explicit and specify when your statement is finished. We do this with a ; (semicolon).

  int temperature;
  temperature = 13;

Q2

Now, the declaration and assignment should be done on the same line.

Expand using link to the right to see a hint.

Let's do the declaration and assignment in one line:

  int temperature = 13;

Q3

After the code in the first question, assign the value 31 to the temperature variable.

Expand using link to the right to see a hint.

We're asked to assign a new value. Since the variable temperature is already declared we don't declare it again, and fact is we cannot do that since it is not allowed, so we're skipping the declaration this time.

  int temperature =  13; // same as before
  temperature = 31;      // re-assign with new value - but no type declaration!

Q4

So far we have assigned values to variables. Is that all we can do? No, of course not. But we haven't learned so much about things like functions, expressions and so on. Still we will ask you to assign a calculated value to a variable. Let's first start with agreeing on the fact that 10 + 3 equals 13. If you don't agree we ask you to go to your math teacher and ask for the money back..

But let's start with the things we already know. Declare an integer variable, temperature, and assign it the value 12. Declaration and assignment should be done on the same line.

Expand using link to the right to see a hint.

This is something we've done before, so let's simply write.

  int temperature =  12;

Q5

After the code in the previous exercise, assign the temperature variable 10 + 3

Expand using link to the right to see a hint.

Ok, time to practice on using the + (which is an operator, more on this later).

  int temperature =  12; // Same as before
  temperature =  10 + 3; // we changed our mind - it is actually a little warmer

In the code above, the right hand side (10 + 3) calculated first. After the calculation the assignment is done. The variable now has the value 13.

Q6

Declare an integer variable, count, on one line and assign it the value 12

Expand using link to the right to see a hint.

This should be fairly easy by now:

  int count = 12;

Q7

After the code in the previous exercise, assign the value 31 to the count variable.

Expand using link to the right to see a hint.

Ok , let's assign the variable a new value:

 count = 31;

Q8

Let's use the variable itself on the right side of the assignment operator (=). Assign the variable count the value of itself (the current value) + 10,

If we as an example say x = x + 10; the system starts by checking the right side (x + 10) and calculates (or evaluates) that. If we assume that x had the value 13, then the right side will become 23 since 13 + 10 is 23. After this is done the system will continue by assigning that value, 23, to the x variable.

Expand using link to the right to see a hint.

Ok, now we're going to have some fun. If someone asked you to add 3 to the digit written on a post-it note, you would have no problem doing that. That's what we're doing on the right side of the assignment operator. And then if someone asked to replace the value on the post it note with the newly calculated sum you'd probably have no problem doing that either, assuming you have a pen.

So let's do this in code. Languages such as Java starts of by calculating the sum on the right side, just as we did in the example with the post-it note. And then the sum is assigned to the variable `temperature`.

  count = count + 10; // current value and then 10 more!

Q9

Let's assume we have three variables as below:

  int nrGirls =  13;
  int nrBoys  =  15;
  int nrStudents;

Assign nrStudents the sum of the nrGirls and nrBoys. You should let the computer do the calculation using the + operator.

Note: The variables are named as in Java Coding Standards, in C you'll use different naming convention for the variables.

Expand using link to the right to see a hint.

  nrStudents = nrGirls + nrBoys;

Again, the right hand side of the assignment operator (=) is calculated before the assignment so the sum of of nrGirls (which has the value 15) and nrBoys (which has the value 13) is calculated to 28 and then the nrStudents is assigned that value (28).

Type cast

Q1

Throughout the exercises below we will use the Java type byte.

For students interested in learning the C programming language: If you're using this material learning C we want you to think of the C type char instead.

Throughout the following exercises it is assumed that we have the are familiar with following types:

      byte -128 through +127
      int  -2 147 483 648 through +2 147 483 647
      char 0 through 65 535

Will the following code work?

  byte nrStudents;
  nrStudents = 123;

Expand using link to the right to see a hint.

Yes. 123 fits inside the allowed values for a byte.

Q2

Will the following code work?

   byte nrStudents;
   nrStudents = 789;

Expand using link to the right to see a hint.

No. 789 is a bigger value than a byte can store. The Java compiler would not allow this. It actually checks the magnitude of literals.

Q3

Will the following code work?

   int nrStudents;
   nrStudents = 123;

Expand using link to the right to see a hint.

Yes. 123 is allowed for an int.

Q4

Will the following code work?

   int nrStudents;
   nrStudents = 789;

Expand using link to the right to see a hint.

Yes. 789 fits inside an int variable.

Q5

Will the following code work?

   int maleStudents = 12;
   int femaleStudents = 12;
   int nrStudents;
   byte allStudents;

   nrStudents = maleStudents + femaleStudents;
   allStudents = nrStudents;

Expand using link to the right to see a hint.

No. You are not allowed to assign a byte type variable the value of an int type variable, even if you know the value at compile-time. This is a hard rule enforced by the javac compiler.

Q6

Make an explicit type cast to tell the compiler you're ok with the conversion in the previous question.

Expand using link to the right to see a hint.

  allStudents = (byte) nrStudents

Q7

Will the following code work? The answer of course depends upon how we interpret the question.

   int maleStudents = 12;
   int femaleStudents = 12;
   int nrStudents;

   nrStudents = maleStudents + femaleStudents;

Expand using link to the right to see a hint.

It will work. The compiler allows it. When the program executes the sum will be calculated to 24, which is possible to store in an int, so lucky for us, it will also work when we run the program.

However, just because the compiler allows for storing an int value in an int, it is not certain that the calculation will be correct. Any arithmetic might underflow or overflow. If maleStudents (or femaleStudents or both) were a really large int, the addition would overflow and we'd end up with a negative number.

Q8

Will the following code work? This is a question which actually requires a bit of thinking :)

   int maleStudents = 2147483647;
   int femaleStudents = 2147483647;
   int nrStudents;

   nrStudents = maleStudents + femaleStudents;

Expand using link to the right to see a hint.

It will NOT work. When the program executes the sum will be calculated to a value bigger than the max value of an int. The compiler would allow it but the result would be disastrous (or at least not what we wanted it to be).

Q9

Will the following code work? This is a question which actually requires a bit of thinking

   int maleStudents = 2147483647;
   int femaleStudents = 2147483647;
   int nrStudents;

   nrStudents = (int)(maleStudents + femaleStudents);

Expand using link to the right to see a hint.

It will NOT work. When the program executes the sum will be calculated to a value bigger than the max value of an int. The type cast is ok and the compiler would allow it but the result would be disastrous (or at least not what we wanted it to be). The moral here is that the type cast does nothing to prevent overflow (when values are too big). In this case, the type cast is also totally pointless, since we are allowed to do the assignment even without it.

Q10

Will the following code work? This is a question which actually requires a bit of thinking

   int maleStudents   = 123;
   int femaleStudents = 123;
   char nrStudents;

   nrStudents = (maleStudents + femaleStudents);

Expand using link to the right to see a hint.

It will NOT work. The compiler will give an error since you can't store the sum of two ints in a char. In Java, a char can store values between 0 and 65535 inclusive. The sum of two ints has the type int, and it is not allowed to assign a value of type int to a char variable.

Q11

Will the following code work? This is a question which actually requires a bit of thinking

   int maleStudents   = 123;
   int femaleStudents = 123;
   char nrStudents;

   nrStudents = (char)(maleStudents + femaleStudents);

Expand using link to the right to see a hint.

It will work. The compiler is ok with the code, since you do an explicit type cast, and when executing the sum is less the max value of a char (246 is less than 65535). Again, remember that the purpose of the cast is to say to the compiler: "I take full responsibility of this foolish action and I am aware of the consequences if it fails miserably". You can silence the compiler using a cast, but you cannot change the fact that if your assumptions are wrong, you will end up with an overflow situation.

Note, however, that it is not common or even very useful to use the Java char type for storing numbers. Use one of the dedicated numeric types instead (byte, short, int or long for whole numbers, and one of float and double for real numbers (floating point numbers).

If you want to experiment with printing a char value to see what character is represented by a number in the unicode table, you can do something like this:

System.out.println( (char)80 );   // will print a 'P' since 'P' has number 80 in the (ascii and) unicode table. 
System.out.println( (char)9762 ); // Will print a radioactivity warning symbol (works on some terminals supporting unicode)

Java primitive types

The purpose of these exercises is to give you a feel for what the primitive types in Java are, including what the type of a literal value is. We'll let you investigate and figure this out in dialog with the javac compiler.

There are no answers to these questions, because we want you to get your hands dirty and to engage in a dialog with your friend, the compiler (who knows everything about what types various literal expressions have).

Q1

Let's say we want to learn what the type of a literal integer value is in Java. How could we do that?

We have learned that the type long is the type that can store the largest (and smallest) integer values. So, we can assume that if the type of a literal integer value is long, we can't store it in an int type variable without a type cast. It's your task to find out if this is true or not.

Copy the following into a file called TestLiterals.java

public class TestLiterals {
  int distanceToMoon = 384400000; // meters
}

Now compile it, using javac TestLiterals.java.

Did it compile? If it did, you know that the literal 384400000 worked well as an int.

Q2

Now, change the type of the variable to short. Compile again.

Did it work? If it did, you know that the literal was at most short. If it didn't, you know that the literal must be of type int because it compiled before and not now.

Q3

So, now you have learned what type the literal code>384400000</code> has in Java, just by testing to store it in variables of different types.

Let's move on and try with floating point numbers.

Add the following to your class body of the TestLiterals.java class declaration:

  float earthGravity = 9.807; // m/s^2

What you did there, was to declare a variable of type float and assign it a floating-point literal value of 9.807 (for Swedish readers: note that the decimal delimiter in Java is a point, and not a comma).

The reason for this exercise is for you to investigate whether 9.807 has the type float or double.

If it has the type float, your class will compile fine. If it doesn't have the type float, the compiler will complain.

Compile the class and carefully read the error message if one is given. If no error message is given, you should think about what that means.

Now, change the declaration to:

  double earthGravity = 9.807; // m/s^2

Save the file (you should always remember to save your file between compilations and edits!).

Compile again.

Now, if it compiles this time, with double but not before when the variable had type float, then you should infer that floating-point values have the type double in Java.

Q4

Now that you know what types literal integer expressions have, and also what type floating-point expressions have, we'll learn you a trick (which is not very useful but perhaps good to know anyway).

You can override the default literal type by appending a letter to the end of a literal number:

  float weight = 78.5F; // kg weight - I should exercise more

Add the above to your file and compile. Note the 'F' appened to the end of the literal expression. It changed the expression to be of type float.

Next, try this:

  int IQ = 65L; // Appending an 'L' to an integer literal expression forces it to be of type long

Now, try to compile again. This won't work, because you now said that the variable of type int should be assigned a value of forced type long (because of the 'L'). You cannot assign a variable of type int a value of type long because there is no guarantee that such values will fit inside the permitted range of values for an int variable.

Delete of comment out the variable declaration and initialization again (put // in front of the line):

//  int IQ = 65L; // Appending an 'L' to an integer literal expression forces it to be of type long

The same can be achieved with floating-point variables, but we leave it up to you to try this out in a similar fashion.

For floating-point literal values, appending an 'F' to the end changes the type to float.

Q5

Next, we'll see what type an expression gets when the operands of a simple operation such as multiplication or division involves different types.

If we know a distance we will be travelling, and the speed we will travel in, then we can calculate the time it will take us to get there, using this formula:

Time = Distance / Velocity

Add the following to your class and try to compile:

  int distance = 50; // km
  double speed = 100.0; // km/h
  int time = distance / speed; // hours

It won't compile. Why, do you think?

Now change the type of the time variable to double. Compile again. Why did it work this time?

The calculation was distance / speed and the types of those variables were int and double respectively. So, what you learned by compiling the above wast that an expression with division where at least one operand has type double, will also be of type double.

What happens is actually this:

Javac sees that one int is divided by one double. The rule is that in such an expression, both operands (in this case distance and speed) are promoted to the same type. Since double is a larger type (it can accept and represent larger values) than int, it is the int expression that is promoted to the larger double type. But then, the whole expression will be of type double (just like you would expect when dividing one double value with another double value).

After you corrected the code so that the time variable also had type double, just like the division expression, it would actually be assigned the value 0.5, which means that it would take you half an hour to travel 50 kilometers, going in 100 km/h. But you already knew that, didn't you? Sometimes computers are not needed to solve problems. But what is needed, is for you to learn about the Java primitive types, in order for you to learn how to use Java to program your computer to solve more complicated problems.

Links

Source code

Further reading

Where to go next

Next page is: Expressions and operators

« PreviousBook TOCNext »