Techoceanhub logo

Variables and data types

In Java, variables are used to store data values that can be manipulated and accessed throughout a program. Java is a statically-typed language, which means that each variable must have a declared data type. Here are some common data types and variable declarations in Java:

  1. Primitive Data Types:

    1. byte: 8-bit integer (range: -128 to 127)
    2. short: 16-bit integer (range: -32,768 to 32,767)
    3. int: 32-bit integer (range: -2,147,483,648 to 2,147,483,647)
    4. long: 64-bit integer (range: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807)
    5. float: 32-bit floating-point number (e.g., 3.14f)
    6. double: 64-bit floating-point number (e.g., 3.14)
    7. boolean: true or false
    8. char: single 16-bit Unicode character (e.g., ‘a’, ‘1’, ‘$’)

    Example declarations:

    int age = 25;
    double pi = 3.1416;
    boolean isTrue = true;
    char grade = 'A';

2. Reference Data Types:

  • String: a sequence of characters (e.g., “Hello, World!”)
  • Arrays: a collection of elements of the same type
  • Classes: user-defined types

Example declarations:

String name = "John Doe";
int[] numbers = {1, 2, 3, 4, 5};
MyClass obj = new MyClass();

3. Other Data Types:

  • Enums: a special data type that represents a group of constants
  • Wrapper classes: provide a way to use primitive types as objects (e.g., Integer, Boolean, Character)

Example declarations:

enum Day {MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY}
Integer count = 10;
Boolean isValid = false;

It’s important to note that Java is a strongly-typed language, meaning that variables must be declared with their appropriate types and cannot be used interchangeably without explicit conversions.

Share:

Categories

Archives

Related Posts

Array Destructuring

Array Destructuring Array destructuring is a powerful syntax introduced in ES6 that allows you to unpack elements from an array

Read More »

Explore our Affiliated partner links

hostgator website plan

Hostgator

Best Website hosting plans & Best for 24/7 support.

hostinger webhosting plan

Hostinger

Reasonable website hosting packages for small business & 24/7 Email support

Elementor pro

Design Worpdress website quickly using Elementor Builder and AI

buy elementor website templates

Buy Elementor Website Template

Buy ready made Elementor Website Template from us & Get Free Elementor pro licence for 1 year .