Java Fundamentals  «Prev  Next»
Lesson 4Examining Java Data Types
ObjectiveUse data types to represent different types of information in Java.

Examining Java Data Types

Variables are locations in memory that are used to store information. Java supports a variety of data types, which dictate the type of information that can be stored in a variable. You create a variable in Java by specifying the type of the variable and an identifier that uniquely identifies the variable. Let us revisit an earlier example:
int age = 55;
String name = "Ernie";

The first line of code declares a variable named age whose data type is int, which is an integer (whole number) data type. The second line of code declares a variable named name whose data type is String, which holds text. Both of these variable declarations set aside memory for each variable. The data type determines the amount of memory set aside. For example, a Java int is a 32-bit number, so 32 bits of memory are set aside for an int variable. Java data types can be grouped into two major categories:
  1. simple: a core data type that is not derived from any other type and represents a single piece of information (also called a primitive data type)
  2. composite: a data type based on simple types that is used to represent more complex information

Figure 6.4:  Categorization of primitive data types
Figure 6.4: Categorization of primitive Data Types


Integer Number Datatype

The simple (primitive) Java data types include Integer numbers Whole numbers without fractional parts (byte, short, int, long) . Integer numbers are whole numbers without fractional parts, and are represented in Java by the following simple data types:
  1. byte,
  2. short,
  3. int,
  4. long.

The difference between each of these integer data types is the memory required for storage, which determines how large (or small) a number each type can store. As an example, the byte data type requires the least memory (8 bits) but can only store numbers in the range -128 to 127. The int data type requires four times as much memory (32 bits) as byte and can store numbers in the range -2,147,483,648 to 2,147,483,647. The long data type is the largest of the integer types and can store extremely large numbers. Practically speaking, the int type is sufficient in most cases for dealing with a wide range of integer numbers.


Converting Java String to Long The following 2 lines of Java are given?
String mStr = "123";
long m = // 1

Which of the following options when put at //1 will assign 123 to m?
Select 3 options:
  1. new Long(mStr);
  2. Long.parseLong(mStr);
  3. Long.longValue(mStr);
  4. (new Long()).parseLong(mStr);
  5. Long.valueOf(mStr).longValue();



Answers: a, b, e

Explanation:
a) Auto unboxing will occur.
c) longValue is a non-static method in Long class.
d) Long (or any wrapper class) does not have a no-args constructor, so new Long() is invalid.
e) Long.valueOf(mStr) returns a Long object containing 123.
longValue() on the Long object returns 123.

  1. Floating-point numbers: Numbers with fractional parts (float, double)
  2. booleans: Values with one of two possible states: true or false

Purpose of the String.valueOf() method in Java

The `String.valueOf()` method in Java is used to convert various types of data into their corresponding string representation. This method can take different types of arguments, such as primitive data types (int, float, double, boolean, char), objects, and even arrays. Here are some of its common uses:
  1. Primitive Data Types: Converts primitive data types to their string representation.
    int num = 42;
    String str = String.valueOf(num); // str becomes "42"
    
  2. Objects: Converts an object to its string representation. If the object is `null`, it returns the string "null".
    Object obj = new Object();
    String str = String.valueOf(obj); // str becomes the result of obj.toString()
    
    Object nullObj = null;
    String strNull = String.valueOf(nullObj); // strNull becomes "null"
    
  3. Char Array: Converts a character array to a string.
    char[] chars = {'J', 'a', 'v', 'a'};
    String str = String.valueOf(chars); // str becomes "Java"
    

The `String.valueOf()` method is particularly useful when you need to concatenate non-string values to a string or when you need a string representation of various types for printing or logging purposes.


Characters: Individual text characters (char)

Declare Char Literal in Java

The char data type stores individual characters of text such as A, E, I, etc. Characters include text letters and symbols such as & and %, as well as special control characters that are not printable. A string of text in Java can always be broken down into a series of characters. As an example, consider the string of text "JERRY". This string of text consists of the five characters J, E, R, R, and Y. The relationship between characters and strings is significant because the number of characters in a string determines the string's length. Unlike C/C++, Java strings are not implemented as arrays of characters. Even though you can access characters within a string, Java strings use their own data type. More specifically, the String class is used to represent strings in Java. You will learn more about the String class a little later in the module.
  • Character Literals: A char literal is represented by a single character in single quotes:
    char a = 'a';
    char b = '@';
    

    You can also type in the Unicode value of the character, using the Unicode notation of prefixing the value with \u as follows:
    char letterN = '\u004E'; // The letter 'N'
    

    Characters are just 16-bit unsigned integers under the hood, which means you can assign a number literal, assuming it will fit into the unsigned 16-bit range (0 to 65535). For example, the following are all legal:
    char a = 0x892;  // hexadecimal literal
    char b = 982;      // int literal
    char c = (char)70000; // The cast is required; 70000 is out of char range
    char d = (char) -98;    // cast negative number, legal
    

    And the following are illegal and produce "compiler errors":
    char e = -29; // Possible loss of precision; needs a cast
    char f = 70000; // Possible loss of precision; needs a cast
    

    You can also use an escape code (the backslash) if you want to represent a character that cannot be typed in as a literal, including the characters for linefeed, newline, horizontal tab, backspace, and quotes:
    char c = '\"'; // A double quote
    char d = '\n'; // A newline
    char tab = '\t'; // A tab
    


Floating-point numbers: float and double

You need floating-point numbers where you expect decimal numbers. For example, can you define the probability of an event occurring as an integer? No, probability is expressed as a real value between 0 and 1, (0,1). Table 6.4 lists probable scenarios in which the corresponding data is stored as a floating-point number.
Data that is stored as floating-point numbers
Figure 6:4: Data that is stored as floating-point numbers
  • Store Decimal Numbers: In Java, you can use the float and double primitive data types to store decimal numbers. float requires less space than double, but it can store a smaller range of values than double. float is less precise than double and cannot accurately represent certain numbers, even if they arein range. The same limitation applies to double, even if it is a data type that offer more precision. Figure 6.5 lists the sizes and ranges of values for float and double.
    Data that is stored as floating-point numbers
    Figure 6.5: Range of values for decimal numbers

    Sample code of Float assignment:
    float average = 20.123F;
    float orbit = 1763.67f;
    double inclination = 119.1750;
    

Java Basics - Quiz


Take a quiz to test your knowledge of Java programming basics.
Java Basics - Quiz

SEMrush Software