In this Java article we want to talk about Variables and Data Types in Java, Java is popular object oriented programming language used for developing different types of applications, from mobile apps to enterprise software. in this article we want to talk about one of the fundamental concepts of Java programming, variables and data types.
Variables
In Java variable is a named container that holds a value of a certain data type. Variables are used to store and manipulate data within a program. for declaring a variable in Java, you need to specify its data type, followed by its name like this.
1 2 3 |
int age; // declares an integer variable named age double price; // declares double precision floating point variable named price String message; // declares string variable named message |
After that variable is declared, you can assign value to it using the assignment operator (=).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class HelloWorld { public static void main(String[] args) { int age = 20; // assigns value 20 to the age variable double price = 9.99; // assigns value 9.99 to the price variable String message = "Geekscoders.com"; // assigns string "Geekscoders.com" to the message variable System.out.println(age); System.out.println(price); System.out.println(message); } } |
Run the code this will be the result
Data Types
In Java every variable has a data type that specifies the kind of data it can hold. Java has two categories of data types: primitive types and reference types.
Primitive types are the basic building blocks of Java data types. they include:
boolean | represents true or false values |
byte | represents integer values between -128 and 127 |
short | represents integer values between -32,768 and 32,767 |
int | represents integer values between -2,147,483,648 and 2,147,483,647 |
long | represents integer values between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807 |
float | represents single-precision floating-point values |
double | represents double-precision floating-point values |
char | represents a single character using Unicode encoding |
For example, to declare an integer variable named age, you would use int data type.
1 |
int age; |
Reference types on the other hand are more complex data types that are derived from classes or interfaces. they include:
String | represents a sequence of characters |
Arrays | represents a collection of elements of the same data type |
Classes | represents a blueprint for creating objects |
For example to declare a String variable named message, you can use the String data type:
1 |
String message; |
So we can say that variables and data types are essential concepts in Java programming. they allows you to store and manipulate data within your programs. by understanding Java primitive and reference data types, you can write more robust and efficient Java programs.