Data types in Java

Data Types in Java

Hello! This is Vitaly Lesnykh. In this lesson of the "Java Basics for Beginners" course, we will discuss what data types are. Data types are the foundation of any programming language. They allow Java to understand what information we are storing and what operations we can perform on it.

In Java, every object and variable has a specific type. The data type defines the size of memory, the range of values and the available operations.

Primitive Data Types

In Java, there are 8 primitive data types. They are divided into four groups:

  • Boolean (boolean)
  • Integer (byte, short, int, long)
  • Floating Point (float, double)
  • Character (char)

Table of Primitive Types

Type Size (bit) Value Range Example
boolean 1 true or false boolean isActive = true;
byte 8 -128 ... 127 byte age = 25;
short 16 -32,768 ... 32,767 short year = 2025;
int 32 -2,147,483,648 ... 2,147,483,647 int distance = 10000;
long 64 -9,223,372,036,854,775,808 ... 9,223,372,036,854,775,807 long population = 7900000000L;
float 32 approximately ±3.4e38 float price = 19.99f;
double 64 approximately ±1.7e308 double pi = 3.1415926535;
char 16 one Unicode character char letter = 'A';

Logical Data Type

The boolean type is used to store logical values true (true) and false (false). It is often used in conditions and loops.


boolean isJavaFun = true;
if (isJavaFun) {
    System.out.println("Да, Java — это весело!");
}
  

Integer Types

To store whole numbers without a fractional part, the types byte, short, int and long are used. They differ in memory size and value range.


byte small = 10;
int medium = 1000;
long big = 10000000000L;

System.out.println(small + ", " + medium + ", " + big);
  

Floating Point Types

To store numbers with fractional parts, the float and double types are used. In most cases, double is used as it provides higher precision.


float weight = 72.5f;
double height = 1.82;
System.out.println("Weight: " + weight + " kg, Height: " + height + " m");
  

Character type

The type char stores a single character in Unicode encoding. This can be not only a Latin letter, but also a digit, sign, or even a character from another script.


char letter = 'Ж';
System.out.println("Letter: " + letter);
  

Type Conversion

Sometimes it is necessary to convert one type to another. For example, from int to double or vice versa. Java does this either automatically (implicit conversion) or manually (explicit conversion).


// Implicit conversion (int -> double)
int a = 5;
double b = a; // b = 5.0

// Explicit conversion (double -> int)
double x = 9.99;
int y = (int) x; // y = 9
  
It is important to remember: when converting types with loss of precision (for example, from double to int) the fractional part is discarded.

Homework

To reinforce the topic of data types, complete the following exercises:

  1. Create variables of all eight primitive types and assign values to them. Output them to the console.
  2. Try converting values between the types int, double and char.
  3. Create a boolean variable and use it in an if condition.
  4. Write a program that calculates the average of three numbers of type double.
  5. Try to exceed the range of the byte type and see what happens.
These tasks will help understand how memory works and the ranges of values in Java. The deeper you delve into types, the more reliable your code will be.

This was Vitaly Lesnykh with you. Subscribe to the channel and continue learning Java step by step!

Test — How well did you understand the lesson?


🌐 in English
Всего лайков:0

Оставить комментарий

Мой канал в социальных сетях
Отправляя email, вы принимаете условия политики конфиденциальности

Полезные статьи:

Struct, методы и интерфейсы в Go vs Java | Types - Language
Серия: Go для Java-разработчиков — разбираем struct, interface, receiver types и type embedding В этой статье мы разберем, как в Go строится архитектура типов. Для Java-разработчика это особенно важн...
Go vs Java -  сравнение модели памяти: happens-before, visibility, reorder, synchronization events, write/read barriers
Модель памяти — это слой между программой и процессором. Современные CPU агрессивно оптимизируют выполнение: инструкции могут переставляться, данные могут храниться в кешах ядер, а операции могут выпо...
Циклы в Java: for, while, do while, Операторы continue и break
Привет! С вами Виталий Лесных. Сегодня мы продолжим курс «Основы Java для начинающих» и разберём одну из важнейших тем программирования — циклы. Цикл — это повторение выполнения кода до тех пор, пок...

Новые статьи:

Конкурентность — это не про «запустить много потоков». Это про договорённости между ними. Представь кухню ресторана: — повара (потоки / горутины) — заказы (задачи) — и главный вопрос: как они коорди...
История начинается не с академической теории, а с типичной production-проблемы. Представьте сервис: 48 CPU 300+ потоков нагрузка 200k операций в секунду много shared state Команда использует обы...
Когда HashMap начинает убивать продакшн: инженерная история ConcurrentHashMap
Представьте обычный продакшн-сервис. 32 CPU сотни потоков кэш конфигурации / сессий / rate limits десятки тысяч операций в секунду И где-то внутри — обычный Map. Сначала всё выглядит безобидно. Map&...
Fullscreen image