// declare variables
// Instantiate Scanner
Scanner scan = new Scanner(System.in);
// Perform operation
x = scan.nextInt();
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) 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);
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;
Exercise: operations on int and double
- Write a program with two variables, length and width, that outputs the perimeter of a rectangle. Test it with length = 5 and width = 4.
- 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
- Now write a program to convert euros to pounds. Test it using the data Euro 7.40
- Prompt the user to input a number. Output the square of that number.
- Prompt the user to input two numbers. Output the average of those two numbers.
- Prompt the user to input three numbers. Output the sum and the average of those three numbers.
- Assume pi = 3.1415. Prompt the user to input the radius of a circle. Output the circumference and the diameter of that circle
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;
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");