Category : Java | Sub Category : Data type, Variable and Arays | By Prasad Bonam Last updated: 2023-08-15 12:28:33 Viewed : 535
an overview of Java data types, variables, and arrays, along with examples and outputs.
1. Java Data Types:
Java has two categories of data types: primitive data types and reference data types.
Primitive Data Types: These are the basic building blocks for storing simple values.
byte
: 8-bit signed integershort
: 16-bit signed integerint
: 32-bit signed integerlong
: 64-bit signed integerfloat
: 32-bit floating-pointdouble
: 64-bit floating-pointchar
: 16-bit Unicode characterboolean
: Represents true or falseReference Data Types: These include objects, arrays, and other user-defined types.
2. Variables:
Variables are named memory locations used to store values of different data types.
Syntax for declaring a variable:
javadata_type variable_name;
Examples:
javaint age;
double salary;
char initial;
boolean isActive;
3. Arrays:
Arrays are used to store multiple values of the same data type in a single variable. Arrays have a fixed size when they are created.
Syntax for declaring an array:
javadata_type[] array_name = new data_type[array_size];
Examples:
javaint[] numbers = new int[5];
double[] prices = new double[10];
String[] names = new String[3];
Here are some examples and outputs to demonstrate these concepts:
javapublic class DataTypesVariablesArraysExample {
public static void main(String[] args) {
// Primitive Data Types
int age = 25;
double height = 170.5;
char grade = `A`
boolean isActive = true;
System.out.println("Age: " + age);
System.out.println("Height: " + height);
System.out.println("Grade: " + grade);
System.out.println("Is Active: " + isActive);
// Arrays
int[] numbers = new int[5];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
System.out.println("Array elements:");
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
// Reference Data Types
String name = "John Doe";
System.out.println("Name: " + name);
}
}
Output:
yamlAge: 25
Height: 170.5
Grade: A
Is Active: true
Array elements:
10
20
30
40
50
Name: John Doe
In this example, we have covered primitive data types, variables, and arrays. We have declared variables of different data types, initialized an array, and printed their values. The output showcases the values stored in the variables and the array.