Java Data Types: Examples of Primitive and Reference Types

Répondu en utilisant GPT-4o-mini par Java Q&A Hub

Question :

Give me some Java Data Types Example

Réponse :

In Java, data types are divided into two main categories: primitive data types and reference data types. Here are examples of each:

Primitive Data Types

  1. int: Represents a 32-bit signed integer.

    int age = 25;
    
  2. double: Represents a double-precision 64-bit floating point.

    double salary = 55000.50;
    
  3. char: Represents a single 16-bit Unicode character.

    char initial = 'A';
    
  4. boolean: Represents a value that can be either true or false.

    boolean isJavaFun = true;
    
  5. float: Represents a single-precision 32-bit floating point.

    float pi = 3.14f; // Note the 'f' suffix
    
  6. byte: Represents an 8-bit signed integer.

    byte smallNumber = 100;
    
  7. short: Represents a 16-bit signed integer.

    short mediumNumber = 10000;
    
  8. long: Represents a 64-bit signed integer.

    long largeNumber = 100000L; // Note the 'L' suffix
    

Reference Data Types

  1. String: Represents a sequence of characters.

    String greeting = "Hello, World!";
    
  2. Arrays: A collection of elements of the same type.

    int[] numbers = {1, 2, 3, 4, 5};
    
  3. Classes: User-defined data types that can contain fields and methods.

    class Person {
        String name;
        int age;
        
        Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
    }
    
    Person person = new Person("Alice", 30);
    
  4. Interfaces: A reference type in Java, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types.

    interface Animal {
        void makeSound();
    }
    
    class Dog implements Animal {
        public void makeSound() {
            System.out.println("Woof");
        }
    }
    
  5. Collections: Such as ArrayList, HashMap, etc.

    import java.util.ArrayList;
    
    ArrayList<String> fruits = new ArrayList<>();
    fruits.add("Apple");
    fruits.add("Banana");
    

These examples illustrate the basic data types available in Java, both primitive and reference types. Each type serves different purposes and is used based on the requirements of the program.