In this lab, you will explore the different data types in Java. Understanding data types is fundamental to programming because they define the kind of values that can be stored and manipulated within a program. Java provides various data types, including primitive data types (e.g., int
, double
, char
, boolean
) and reference types (e.g., objects and arrays). In this lab, you will declare variables of different data types, perform operations on them, and observe how Java handles different types of data.
By the end of this lab, you will be able to:
cd ~
DataTypesExample.java
:nano DataTypesExample.java
public class DataTypesExample {
public static void main(String[] args) {
// Integer data type
int myInt = 25;
System.out.println("Integer: " + myInt);
// Double (floating-point) data type
double myDouble = 3.14159;
System.out.println("Double: " + myDouble);
// Character data type
char myChar = 'A';
System.out.println("Character: " + myChar);
// Boolean data type
boolean myBoolean = true;
System.out.println("Boolean: " + myBoolean);
// String (reference type)
String myString = "Hello, World!";
System.out.println("String: " + myString);
}
}
CTRL + O
, then hit Enter
to confirm the filename.CTRL + X
.javac
command:javac DataTypesExample.java
DataTypesExample.class
. Verify this by running:ls
java
command:java DataTypesExample
Integer: 25
Double: 3.14159
Character: A
Boolean: true
String: Hello, World!
DataTypesExample.java
file again using Nano:nano DataTypesExample.java
// Perform arithmetic operations with int and double
int sum = myInt + 10;
double product = myDouble * 2;
// Output the results
System.out.println("Sum of myInt + 10: " + sum);
System.out.println("Product of myDouble * 2: " + product);
javac DataTypesExample.java
java DataTypesExample
long
, float
, and byte
:// Long data type
long myLong = 100000L;
System.out.println("Long: " + myLong);
// Float data type
float myFloat = 5.75f;
System.out.println("Float: " + myFloat);
// Byte data type
byte myByte = 100;
System.out.println("Byte: " + myByte);
javac DataTypesExample.java
java DataTypesExample
// Casting double to int
int castedInt = (int) myDouble;
System.out.println("Casted double to int: " + castedInt);
// Casting int to double
double castedDouble = myInt;
System.out.println("Casted int to double: " + castedDouble);
javac DataTypesExample.java
java DataTypesExample
.class
files:rm *.class
In this lab, you explored the basic data types in Java, including integers, floating-point numbers, characters, booleans, and strings. You learned how to declare and initialize variables, perform arithmetic operations, and work with type casting. Understanding data types is crucial for ensuring that your program works efficiently and handles data correctly.