Java Course 2: Types

Integers

// declare variables
int x;
int y;

// Instantiate Scanner
Scanner scan = new Scanner(System.in);

// Perform operation
System.out.println("Enter x?");
x = scan.nextInt();
System.out.println("Enter y?");
y = scan.nextInt();
System.out.println("x x y ="+ x*y);

Casting and Converting

Java is a statically, strongly typed language. You have to declare variable types before you use them (statically typed) and once declared, the variables cannot hold another type.

But sometimes you need to change the type. For example, in the code

int i =4;
System.out.println(i);

System.out.println(i) converts the int i into a String before printing out.

You can make an explicit conversion from int to String as follows

int i =4;
String s = Integer.toString(i);
System.out.println(s);

You can covert Double, Float etc to Strings similarly.

To convert the other way, e.g. from a String to an integer use the following

String s = "34"
int i = Integer.parseInt(s);

The fact that you can’t simply use i.toString() is an interesting one and part of a big debate about the way Java is put together. Briefly, Java doesn’t treat types like int and double as classes. That means you have to put them in a class wrapper when you want to perform some operations on them. Languages such as Scala treat all types as classes.

The following code will print out int c as a number and a char, depending on cast.

int c = 67;
System.out.println(c);
System.out.println((char)c);

Exercise: operations on int and double

  1. Write a program with two variables, length and width, that outputs the perimeter of a rectangle. Test it with length = 5 and width = 4.
  2. At the time of writing, the exchange rate for pounds to euros is 1 GBP = 1.19984 Euros. Write a program that will convert pounds to euros. Test it using the data GBP4.50
  3. Now write a program to convert euros to pounds. Test it using the data Euro 7.40
  4. Prompt the user to input a number. Output the square of that number.
  5. Prompt the user to input two numbers. Output the average of those two numbers.
  6. Prompt the user to input three numbers. Output the sum and the average of those three numbers.
  7. Assume pi = 3.1415. Prompt the user to input the radius of a circle. Output the circumference and the diameter of that circle

Good Practice

What’s the purpose of the following two code snippets? Which is better programming practice? Give some reasons why.

double x = 35.51*1.17;
System.out.println(x);

or

double pounds = 35.51;
double euroRate = 1.17;
double euros = pounds * euroRate;

System.out.println("£"+ pounds + " = " + euros + " euros");
System.out.println("at an rate of "+ euroRate + " euros to the pound");

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.