T E C h O C E A N H U B

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.

Copyright ©TechOceanhub All Rights Reserved.