Java Programming

 

     

 

Types and Type Casting

 

 

What is wrong with this code?

long y = 42;
int w = y;

// long y = 42;
// int w = (int) y; // this is an example of a cast operator (int), we are explicitly type casting a long value into // an int value for this operation thus there is no longer an error.

float f = 3.14f;
int z = (int) f; // x will equal 3 because it was type cast from type float to type int and there are not decimal //values in int so all values after the decimal point are dropped.
System.out.println("The value of f is " + f + " and z is " + z);

//Strings: What is wrong with this code?

String num = "2";
int x = 2;
if (x == num) // remember == is the equality operator - it checks to see if two values are the same
{
System.out.println(num + "is equal to " + x);
}

//There is actually an Integer class with a method that will convert a string to an integer

int g = Integer.parseInt("34"); // this will return an integer value of 34.
System.out.println("The value of z is " + g);