- Java Fundamentals
- Gazihan Alankus Rogério Theodoro de Brito Basheer Ahamed Fazal Vinicius Isola Miles Obare
- 2208字
- 2021-06-11 13:37:55
Type Casting
To convert an int of value of 23 into a long literal, we would need to do what is called type casting:
int num_int = 23;
long num_long = (long)num_int;
In the second line, we cast the num_int of the int type to a long literal by using the notation (long)num_int. This is referred to as casting. Casting is the process of converting one data type into another. Although we can cast a long to an int, remember that the number might be outside the int range and some numbers will be truncated if they can't fit into the int.
As is with int, long can also be in octal, hexadecimal, and binary, as shown in the following code:
long num = 117L;
long hex_num = 0x75L;
long oct_num = 0165L;
long bin_num = 0b1110101L;
Exercise 5: Type Casting
It's often important to change one type to another. In this exercise, we will convert an integer into a floating point:
- Import Scanner and create a public class:
import java.util.Scanner;
public class Main
{
static Scanner sc = new Scanner(System.in);
public static void main(String[] args)
- Input a number as an integer:
{
System.out.println("Enter a Number: ");
int num1 = sc.nextInt();
- Print out the integer:
System.out.println("Entered value is: " + num1);
- Convert the integer into a floating point:
float fl1 = num1;
- Print out the floating point:
System.out.print("Entered value as a floating point variable is: " + fl1);
}
}
byte Data Type
A byte is an 8-bit digit that can hold values in the range of -128 to 127. byte is the smallest primitive data type in Java, and can be used to hold binary values. To assign a value to a byte, it has to be in the range -128 to 127, otherwise the compiler will raise an error:
byte num_byte = -32;
byte num_byte1 = 111;
You can also cast an int to a byte, as we did with long:
int num_int = 23;
byte num_byte = (byte)num_int;
In addition to casting, we can assign a byte to an int:
byte num_byte = -32;
int num_int = num_byte;
We, however, cannot directly assign an int to a byte without casting. The following code will raise an error when you try to run it:
int num_int = 23;
byte num_byte = num_int;
This is because an integer can be outside the byte range (-128 to 127) and hence some precision will be lost. Java doesn't allow you to assign out of range types to lower range types. You have to cast so that the overflow bits will be ignored.
short Data Type
short is a 16-bit data type that can hold numbers in the range of -32,768 to 32,767. To assign a value to a short variable, make sure it is in the specified range, otherwise an error will be thrown:
short num = 13000;
short num_short = -18979;
You can assign a byte to a short because all the values of a byte fall in the short's range. However, the reverse will throw an error, as explained with byte and int. To convert an int into a short, you have to cast to avoid the compile errors. This also applies to converting a long into a short:
short num = 13000;
byte num_byte = 19;
num = num_byte; //OK
int num1 = 10;
short s = num1; //Error
long num_long = 200L;
s = (short)num_long; //OK
Boolean Data Type
A boolean is a true or false value:
boolean finished = true;
boolean hungry = false;
Note
Some languages, such as like C and C++, allow Booleans to take a value of 1 for true and 0 for a false. Java doesn't allow you to assign 1 or 0 to Boolean and this will raise a compile-time error.
char Data Type
The char data type is used to hold a single character. The character is enclosed in single quotes. Examples of characters are 'a', 'b', 'z', and '5'. Char types are 16 bit and cannot be negative. Char types are essentially integers from 0 to 65,535 to represent Unicode characters. Examples of how to declare chars are as follows:
char a = 'a';
char b = 'b';
char c = 'c';
char five = '5';
Note that chars are enclosed in single quotes, NOT double quotes. Enclosing a char in double quotes changes it to a string. A string is a collection of one or more chars. An example of a String is "Hello World":
String hello = "Hello World";
Enclosing a char in double quotes will raise an error because the compiler interprets double quotes as a string, not a char:
char hello = "Hello World"; //ERROR
Likewise, enclosing more than one character in single quotes raises a compiler error because chars should be only one character:
String hello = 'Hello World'; //ERROR
In addition to chars being used to hold single characters, they can also be used to hold escape characters. Escape characters are special characters that have a special use. They consist of a backslash followed by a character and are enclosed in single quotes. There are 8 predefined escape characters, as shown in the following table, along with their uses:

Table 2.1: Representation of escape characters and their use
Let's say you write a line such as the following:
char nl = '\n';
The char holds a newline and if you try printing it to the console, it skips to the next line.
If you print '\t', a tab is escaped in the output:
char tb = '\t';
A '\\' will print a backslash in the output.
You can use escape characters to format a string according to your desired output. For example, let's look at the following line:
String hello_world = "Hello \n World";
Here's the output:
Hello
World
This is because the escape character '\n' introduces a new line between Hello and World.
In addition, chars can also be expressed in Unicode using the Unicode escape character '\u'. Unicode is an international standard of encoding in which a character is assigned a numeric value that can be used on any platform. Unicode aims to support all the available languages in the world, which is in contrast to ASCII.
Floating-Point Data Types
Floating-point data types are numbers that have a fractional part in their representation. Examples include 3.2, 5.681, and 0.9734. Java has two data types to represent types with fractional parts:
- float
- double
Floating types are represented using a special standard referred to as the IEEE 754 Floating-point standard. This standard was set up by the Institute of Electrical and Electronic Engineers (IEEE) and is meant to make the representation of floating types uniform in the low level parts of the compute. Remember that floating types are usually approximations. When we say 5.01, this number has to be represented in binary format and the representation is usually an approximation to the real number. When working with very high-performance programs where values have to be measured to the order of micro numbers, it becomes imperative that you understand how floating types are represented at the hardware levels to avoid precision loss.
Floating types have two representations: decimal format and scientific notation.
The decimal format is the normal format we usually use, such as 5.4, 0.0004, or 23,423.67.
The scientific notation is the use of the letter e or E to represent a ten raised to a value. For example, 0.0004 in scientific notation is 4E-4 or 4e-4, which is similar to 4 x 10-4 . The number 23,423.67 in scientific notation would be 2.342367E4 or 2.342367e4, which is similar to 2.342367 x 104.
float Data Type
float is used to hold 32-bit fractional numbers in the range 1.4 x 10 -45 and as big as 3.4 x 10 38. That is, the smallest number a float can hold is 1.4 x 10 -45 and the largest number it can hold is 3.4 x 10 38. Floats are followed by a letter f or F to indicate that they are of float type. Examples of floats are shown as follows:
float a = 1.0f;
float b = 0.0002445f;
float c = 93647.6335567f;
Floats can also be represented in scientific notation, as follows:
float a = 1E0f;
float b = 2.445E-4f;
float c = 9.36476335567E+4f;
Java also has a class called Float that can encapsulate floats and offers some useful features. For example, to know the largest float number and the smallest float number available in your environment, you'd call the following:
float max = Float.MAX_VALUE;
float min = Float.MIN_VALUE;
The Float class also has values to represent positive and negative infinity when a division by zero occurs:
float max_inf = Float.POSITIVE_INFINITY;
float min_inf = Float.NEGATIVE_INFINITY;
Floats support two types of zeros: -0.0f and +0.0f. As we already said, float types are represented as approximations in the memory, and so even a zero is not an absolute zero. That is why we have two zeros. When a number is divided by positive zero, we get Float.POSITIVE_INFINITY and when a number is divided by negative zero, we get Float.NEGATIVE_INFINITY.
The Float class also has the constant NaN to indicate a number that is not of a float type:
float nan = Float.NaN;
As with the integral types we have discussed, we can assign an int, byte, short, long, and char to a float, but cannot do the reverse unless we cast.
Note
Casting an integer to a float and then back to an int will not always lead to an original number. Be careful when doing casting between int and float.
double Data Type
double holds 64-bit numbers with fractional parts. That is, the range 4.9 x 10e -324 to 1.7 x 10e 308. Doubles are used to hold larger numbers than floats. They are represented with a d or D at the end. However, by default, in Java, any number with a fractional part is a double, so there is usually no need to append the d or D at the end. Examples of doubles are as follows:
double d1 = 4.452345;
double d2 = 3.142;
double d3 = 0.123456;
double d4 = 0.000999;
Like floats, doubles can also be represented in scientific notation:
double d1 = 4.452345E0;
double d2 = 3.142E0;
double d3 = 1.23456E-1;
double d4 = 9.99E-4;
As you might have already guessed it, Java also provides a class called Double with some useful constants, as shown in the following code:
double max = Double.MAX_VALUE;
double min = Double.MIN_NORMAL;
double max_inf = Double.POSITIVE_INFINITY;
double min_inf = Double.NEGATIVE_INFINITY;
double nan = Double.NaN;
Likewise, we can assign the integral types and float except the boolean type to double and not the other way round until we cast. The following are example operations that are allowed and some that are forbidden:
int num = 100;
double d1 = num;
float f1 = 0.34f;
double d2 = f1;
double d3 = 'A'; //Assigns 65.0 to d3
int num = 200;
double d3 = 3.142;
num = d3; //ERROR: We must cast
num = (int)d3; //OK
Activity 4: Inputting Student Information and Outputting an ID
Storing and outputting variables in foundational in any developing environment. In this activity you will be creating a program that will ask a student to input their data and then output a simple ID card. The program will use integers and strings along with the scanner class in the java.util package.
The following activity uses the string variable and the integer variable to input information about a student and then print it out.
- Import the scanner package and create a new class.
- Import the student name as a string.
- Import the university name as a string.
- Import the student's age as an integer.
- Use System.out.println to print out the student details.
- After running the program, the output should be similar to this:
Here is your ID
*********************************
Name: John Winston
University: Liverpool University
Age: 19
*********************************
Note
The solution for this activity can be found on page 306.
Activity 5: Calculating the Number of Full Fruit Boxes
John is a peach grower. He picks peaches from his trees, puts them into fruit boxes and ships them. He can ship a fruit box if it is full with 20 peaches. If he has less than 20 peaches, he has to pick more peaches so he can fill a fruit box with 20 peaches and ship it.
We would like to help John by calculating the number of fruit boxes that he can ship and the number of peaches left behind, given the number of peaches he was able to pick. To achieve this, perform the following steps:
- Create a new class and enter PeachCalculator as the class name
- Import the java.util.Scanner package:
- In the main() use System.out.print to ask the user for the numberOfPeaches.
- Calculate the numberOfFullBoxes and numberOfPeachesLeft values. Hint: use integer division.
- Use System.out.println to output these two values.
- Run the main program.
The output should be similar to:
Enter the number of peaches picked: 55
We have 2 full boxes and 15 peaches left.
Note
The solution for this activity can be found on page 307.
- Cocos2D-X權(quán)威指南(第2版)
- SoapUI Cookbook
- GraphQL學(xué)習(xí)指南
- C#程序設(shè)計(jì)(項(xiàng)目教學(xué)版)
- C/C++數(shù)據(jù)結(jié)構(gòu)與算法速學(xué)速用大辭典
- Julia 1.0 Programming Complete Reference Guide
- IDA Pro權(quán)威指南(第2版)
- 深入解析Java編譯器:源碼剖析與實(shí)例詳解
- 美麗洞察力:從化妝品行業(yè)看顧客需求洞察
- Microsoft XNA 4.0 Game Development Cookbook
- Getting Started with the Lazarus IDE
- Spring Boot學(xué)習(xí)指南:構(gòu)建云原生Java和Kotlin應(yīng)用程序
- Android開(kāi)發(fā)權(quán)威指南(第二版)
- 系統(tǒng)分析師UML用例實(shí)戰(zhàn)
- Laravel 5.x Cookbook