Home Java Java Data Types (with examples)

Java Data Types (with examples)

Java has many data types and operations, making it suited for various programming tasks. These are pretty helpful in all aspects of Java, whether you’re writing a simple program or developing a complex application or software. In Java, data the two core categories of types include primitive data and data types that aren’t primitive.

Java’s Data Types

Java’s variables must be of a specific data type. There are two groups of data types:

  • Byte
  • short
  • int
  • long
  • float
  • double
  • boolean, and
  • char

The list above are examples of primitive data types. On the other hand, Strings, Arrays, and Classes are examples of non-primitive data types.

Types of Primitive Data

A primitive data type determines both types of variable values and size, which has no extra functions. In Java, primitive data types make up a count of eight:

Data TypeSize of DataExplanation
byte1 bytehas whole numbers from -128 to 127
short2 byteshas entire numbers from -32,768 to 32,767
int4 byteshas whole numbers from -2,147,483,648 to 2,147,483,647
long8 byteshas whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
float4 byteshas numbers that are fractions. Enough to store between 6 and 7 decimal digits
double8 bytesStores fractional numbers. Sufficient for storing 15 decimal digits
boolean1 bitStores true or false values
char2 bytesStores a single character/letter or ASCII values

Numbers

There are two sorts of primitive number types:

  • Integer types store whole integers, which are either positive or negative such as 123 or -456.
  • Byte, short, int, and long are all valid types.

The numeric value determines which type you should choose. Floating-point types represent numbers with a fractional portion and one or more decimals. Float and double are the two types.

Even though Java has multiple numeric types, the most commonly used for numbers are int (for whole numbers) and double for floating-point numbers. However, we’ll go through each one in detail as you read on.

Integer Types

Byte

From -128 to 127, the byte data type can hold entire values. When you know the value will be between -128 and 127, you can use this instead of int or other integer types to conserve memory:

byte numVal = 113;
System.out.println(numVal);
Short

The full numbers -32768 to 32767 can be stored in the short data type:

short numVal = 4389;
System.out.println(numVal);
Int

Whole numbers between -2147483648 and 2147483647 can be stored in the int data type. Therefore, when creating variables with a numeric value, the int data type is the ideal data type in general.

int numVal = 100000;
System.out.println(numVal);
Long

From -9223372036854775808 to 9223372036854775807, the long data type can store entire numbers. When int is insufficient to store the value, this is utilized. It’s important to note that the value should conclude with an “L”:

long numVal = 15000000000L;
System.out.println(numVal);

Types of Floating Points

It would be best to use a floating-point type when you need a decimal number, such as 9.99 or 3.14515.

Float

Fractional numbers between 3.4e-038 and 3.4e+038 can be stored using the float data type. It’s important to note that the value should conclude with an “f”:

float floatVal = 6.85f;
System.out.println(floatVal);
Double

Fractional numbers between 1.7e-308 and 1.7e+308 can be stored in the double data type. It’s important to note that the value should conclude with a “d”:

Is it better to use float or double?

The precision of a floating-point value is the number of digits following the decimal point that the value can have. The precision of float variables is just six or seven decimal digits, but the accuracy of double variables is around 15 digits.
As a result, it is safer to utilize double for most calculations.

Numbers in Science

A scientific number with a “e” to represent the power of ten can also be a floating point number:

float floatVal = 35e3f;
double doubleVal = 12E4d;
System.out.println(floatVal);
System.out.println(doubleVal);

Booleans

The boolean keyword is used to specify a boolean data type, which can only take the values true or false:

boolean isCodeUnderscoredLegit = true;
boolean isCodeEasy = false;
System.out.println(isCodeUnderscoredLegit); // Outputs true
System.out.println(isCodeEasy); // Outputs false

Conditional testing uses Boolean values extensively, which you’ll learn more about later.

Characters

A single character is stored in the char data type.
Single quotes, such as ‘Z’ or ‘b,’ must surround the character:

char studentScore = 'A';
System.out.println(studentScore);

You can also use ASCII values to display specific characters:

char myVar1 = 65, myVar2 = 66, myVar3 = 67;
System.out.println(myVar1);
System.out.println(myVar2);
System.out.println(myVar3);

The ASCII Table Reference contains a complete list of all ASCII values.

Strings

A sequence of characters is stored using the String data type (text). In addition, use double quotes to surround string values:

String helloCode = "Hello Codeunderscored";
System.out.println(helloCode);

Because the String type is so widely utilized and integrated with Java, it is sometimes referred to as “the special ninth type.”

Don’t worry if you’re not familiar with the term “object.” It relates to an object, a String in Java is a non-primitive data type. Methods on the String object are used to execute various operations on strings.

Types of Non-Primitive Data

Because they refer to things, non-primitive data types are termed reference types. The following are the fundamental distinctions between primitive and non-primitive data types:

  • In Java, primitive types are predefined (that is, they have already been declared). Java does not specify non-primitive types, which the programmer constructs except for string.
  • Non-primitive types, on the other hand, can be used to call methods that perform specific actions, whereas primitive types cannot.
  • Non-primitive types can be null, whereas primitive types always have a value.
  • A lowercase letter begins with a primitive type, while an uppercase letter begins with a non-primitive one.
  • The size of a primitive type is determined by the data type, whereas non-primitive types are all the same size.

Strings, Arrays, Classes, Interfaces, and other non-primitive types are examples.

Interfaces

Interfaces are another approach to implement abstraction in Java. An interface is an “abstract class” that is used to put together related functions with empty bodies:

// interface
interface Human {
  public void humanSound(); // interface method (does not have a body)
  public void run(); // interface method (does not have a body)
}

The interface must be “implemented” (kind of like inherited) by another class with the implements keyword to access the interface functions (instead of extends). The “implement” class provides the body of the interface method:

// Interface
interface Human {
  public void humanSound(); // interface method (does not have a body)
  public void sleep(); // interface method (does not have a body)
}

// Lady "implements" the Human interface
class Lady implements Human {
  public void humanSound() {
    // The body of humanSound() is provided here
    System.out.println("The lady screams: wee wee");
  }
  public void sleep() {
    // The body 's sleep() is provided here
    System.out.println("Zzz");
  }
}

class Main {
  public static void main(String[] args) {
    Lady theLady = new Lady();  // Create a Lady object
    theLady.humanSound();
    theLady.sleep();
  }
}
Interface Remarks

Interfaces, like abstract classes, cannot be used to construct objects. For instance, in the example above, it is not possible to create a “Human” object in the MyMainClass.

The “implement” class provides the body for interface methods that don’t have one. It would help override all of an interface’s methods when implementing it. By default, interface methods are abstract and public. Also, by default, interface attributes are public, static, and final. A constructor is also not allowed in an interface as it cannot create objects.

When Should You Use Interfaces?

1) To increase security, hide certain information and only display the most critical aspects of an object (interface).

2) “Multiple inheritance” is not supported in Java (a class can only inherit from one superclass).
However, because the class can implement many interfaces, it can be done with interfaces.
Note: To use several interfaces, use a comma to separate them (see example below).

interface InterfaceOne {
  public void interfaceOneMethod(); // interface method
}

interface InterfaceTwo {
  public void interfaceTwoMethod(); // interface method
}

// InterfaceClass "implements" InterfaceOne and  InterfaceTwo
class InterfaceClass implements InterfaceOne, InterfaceTwo {
  public void interfaceOneMethod() {
    System.out.println("Some text..");
  }
  public void interfaceTwoMethod() {
    System.out.println("Some other text...");
  }
}

class Main {
  public static void main(String[] args) {
    InterfaceClass theObj = new InterfaceClass();
    theObj.interfaceOneMethod ();
    theObj.interfaceTwoMethod ();
  }
}

Java Objects and Classes

Java’s primary focus as a computer language is on objects.

In Java, everything is linked to classes and objects and their characteristics and methods.
A computer, for example, is an object in real life. The computer has characteristics like weight and color and procedures like start and shutdown.

A class functions similarly to an object constructor or a “blueprint” for constructing things.

Creating a Class

Use the term class to create a class:

# Main.java
# Creation of a class named "Main" with a variable a:

public class Main {
  int a = 20;
}

Remember from the Java Syntax concepts that a class should always begin with an uppercase letter and that the java file name should be the same as the class name.

Making a new object

A class in Java is used to build an object. We’ve already created the Main class, so we can now create objects. To create a Main object, type the class name, then the object name, followed by the keyword new:

Example: Create a “theObj” object and print the value of a:

public class Main {
  int a = 20;

  public static void main(String[] args) {
    Main theObj = new Main();
    System.out.println(theObj.a);
  }
}
Objects in Multiples

You can make numerous objects of the same type:

public class Main {
  int a = 20;

  public static void main(String[] args) {
    Main theOneObj = new Main();  // Object 1
    Main theTwoObj = new Main();  // Object 2
    System.out.println(theOneObj.a);
    System.out.println(theTwoObj.a);
  }
}
Example: Create two Main objects Using Several Classes

You can also build a class object and use it in a different class. It is frequently used to organize classes (one class contains all properties and methods, while the other has the main() function (code to be run)).

Keep in mind that the java file should have the same name as the class. We’ve created two files in the same directory/folder in this example:

// Main.java

public class Main {
int a = 5;
}

// Second.java

class Second {
  public static void main(String[] args) {
    Main theObj = new Main();
    System.out.println(theObj.a);
  }
}
javac Main.java
javac Second.java

When you’ve finished compiling both files, you’ll be able to tun the Second.java file as follows:

java Second.java

Arrays in Java

Arrays store many values in a single variable instead of defining distinct variables for each item. To declare an array, use square brackets to determine the variable type:

String[] computers;

We’ve now declared a variable that will hold a string array. Further, we can use an array literal to add values to it by placing the items in a comma-separated list inside curly braces:

String[] computers = {"HP", "Lenovo", "DELL", "Chrome Book"};

You may make an array of integers as follows.

int[] numVal = {30, 40, 50, 60};
Access to an Array’s Elements

The index number is used to access an array element. In the computer’s array above, this statement gets the value of the first element:

String[] computers = {"HP", "Lenovo", "DELL", "Chrome Book"};
System.out.println(computers[0]);
// Outputs HP

Note that array indexes begin at 0. As a result, the first element is [0]. The second element is [1], and so on.

Make a Change to an Array Element

Refer to the index number to change the value of a certain element:

computers[0] = "IBM";

String[] computers = {"HP", "Lenovo", "DELL", "Chrome Book"};
computers[0] = "IBM";
System.out.println(computers[0]);
// Now outputs IBM instead of HP
Length of Array

Establishing the length of an array is an aspect of the length property in an array:

String[] computers = {"HP", "Lenovo", "DELL", "Chrome Book"};
System.out.println(computers.length);
// Outputs 4
Iterate Over an Array

The for loop can be used to loop through the array elements, and the length property can be used to determine how many times the loop should execute. All elements in the computer’s array are output in the following example:

String[] computers = {"HP", "Lenovo", "DELL", "Chrome Book"};
int i =0;
for (i; i < computers.length; i++) {
  System.out.println(computers[i]);
}

In addition, with For-Each, you may loop through an array. There’s also a “for-each” loop, which is only used to loop through array elements:

Syntax

for (type variable : arrayname) {
  ...
}

Using a “for-each” loop, the following example prints all members in the vehicles array:

String[] computers = {"HP", "Lenovo", "DELL", "Chrome Book"};
for (String i : computers) {
  System.out.println(i);
}

You might understand the preceding example when we break it down as follows: print the value of i for each String element (called i – as in index) in computers. When comparing the for loop and the for-each loop, you’ll notice that the technique is easier to code, requires no counter (since it uses the length property), and is more readable.

Arrays with several dimensions

An array of arrays is a multidimensional array. Add each array within its own set of curly brackets to make a two-dimensional array:

int[][] numVals = { {11, 12, 13, 14}, {15, 16, 17} };

numVals is now an array that contains two arrays as items. To get to the items in the numVals array, you’ll need two indexes: one for the array and one for each element within it. This example uses the third member (2) of numVals’ second array (1):

int[][] numVals = { {11, 12, 13, 14}, {15, 16, 17} };
int a = numVals[1][2];
System.out.println(a); // Outputs 7

To acquire the items of a two-dimensional array, we can use a for loop inside another for loop though we still need to point to the two indexes:

public class Main {
  public static void main(String[] args) {
    int[][] numVals = { {11, 12, 13, 14}, {15, 16, 17} };
    for (int i = 0; i < numVals.length; ++i) {
      for(int j = 0; j < numVals[i].length; ++j) {
        System.out.println(numVals[i][j]);
      }
    }
  }
}

Strings in Java

Text is stored using strings. A String variable is made up of a group of characters encased in double-quotes:

Example: Create a String variable with the following value:

String greeting = "Codeunderscored";
Length of the String

A String in Java is an object which comprises methods that may perform specific actions on strings. For example, the length of a string may be obtained with the length() method:

String txtVal = "Codeunderscored";
System.out.println("The length of the text string is: " + txtVal.length());
Additional String Methods

There are numerous string functions, such as toUpperCase() and toLowerCase():

String txtVal = "Code underscored";
System.out.println(txtVal .toUpperCase()); // Outputs "CODE UNDERSCORED"
System.out.println(txtVal .toLowerCase()); // Outputs "code underscored"

Finding a Character in a String is a difficult task. The indexOf() method retrieves the first occurrence of a supplied text in a string (including whitespace):

String txtVal = "Please find where 'locate' occurs!";
System.out.println(txtVal .indexOf("find")); // Outputs

Java starts counting at zero. 0 is the first place in a string, 1 is the second, and two is the third.

Concatenating strings

The + operator is responsible for joining two strings together. It is referred to as concatenation:

String prefixName = "Code";
String suffixName = "underscored";
System.out.println( prefixName + " " + suffixName);

To make a space between firstName and lastName on print, we’ve placed an empty text (” “) between them. You can also concatenate two strings with the concat() method:

String prefixName = "Code";
String suffixName = "underscored";
System.out.println(prefixName .concat(suffixName));

Characters with Unique Qualities

Because strings must be enclosed in quotes, Java will misinterpret this string and generate the following error:

String txtVal = "Codeunderscored are the "Vikings" from the web.";

The backslash escape character is an excellent way to avoid this problem. Special characters are converted to string characters using the backslash () escape character. In addition, In Java, there are more than six escape sequences that are valid as follows:

Escape characterResultDescription
\’Single quote
\”Double quote
\\Backslash
\nNew Line
\rCarriage Return
\tTab
\bBackspace
\fForm Feed

In a string, the sequence \” inserts a double quote:

String txt = "We are the so-called \"Vikings\" from the north.";

In a string, the sequence \’ inserts a single quote:

String txt = "It\'s alright.";

The following sequence \ adds a single backslash to a string:

String txt = "The character \ is called backslash.";

Adding Strings and Numbers

The + operator is used in Java for both addition and concatenation.

  • Numbers are added to the equation.
  • Strings are joined together.

When two numbers are added together, the result is a number:

int a = 50;
int b = 30;
int c = a + b; // c will be 80 (an integer/number)

Combining two strings leads to a string concatenation:

String a = "50";
String b = "30";
String c = a + b; // c will be 5030 (a String)

Combining a number and a string, you get a string concatenation:

String a = "50";
int b = 30;
String c = a + b; // c will be 5030 (a String)

Conclusion

Any computer language’s most crucial foundation is its data types. It is the most vital notion for any newcomer. The data type is required to express the kind, nature, and set of operations associated with the value it stores.

Java data types are incredibly fundamental. It is the first thing you should learn before moving to other Java concepts.

You may also like

Leave a Comment