The Complete Guide to Java Data Types and Variables

Time:2023-10-4

catalogs

I. Literal constants

1.1 What constants?

1.2 Six common types of constants

II. Data types

2.1 What are data types?

2.2 Basic data types:

2.3 Referencing data types

III. Variables

3.1 What are variables?

3.2 Naming rules for variables

3.3 Scope of variables

3.4 Modification of variables by final

IV. Type conversion

4.1 What is type conversion?

4.2 Automatic type conversion

4.3 Forced type conversion

4.4 Precautions

4.5 Type Lifting

V. String types

5.1 What are Java string types?

5.2 How to create and use strings?

5.3 Common String Operations

5.3 Conversion between strings and different types


The Complete Guide to Java Data Types and Variables

The Complete Guide to Java Data Types and Variables

Declaration: Java’s data types and variables

In Java, a data type is the type of data stored in a variable. Java supports a variety of basic data types, including integer, floating-point, character, boolean, and so on. For different data types, Java also provides different literal constants to represent their values. It is important to understand data types and their characteristics when programming with Java.

I. Literal constants

1.1 What constants?

Literal constants are constant values that are used directly in a program without computation or manipulation. In Java, literal constants include the following types:

1.2 Six common types of constants

1. Integer constants
Integer constants represent integer values, and can be used with theDecimal, Octal or Hexadecimalto indicate.

int decimalValue = 10; // decimal
int octalValue = 012; // Octal
int hexValue = 0xA; // hexadecimal

2. Floating-point constants
Floating-point constants represent real values, includingSingle precision floating pointanddouble precision floating point type

float floatValue = 3.14f; // single precision float type
double doubleValue = 3.14; // double precision floating point type

3. Character constants
Character constants represent a single character withsingle quoteBracket up.

char charValue = 'a'; // Character Constant

4. String constants
String constants represent strings consisting of multiple characters and are represented by thedouble quoteBracket up.

String stringValue = "Hello, World!" ; // String constant

5. Boolean constants
Boolean constantsIndicates true or falseusetrueandfalseKeywords denote.

boolean boolValue_1 = true; // boolean constant
boolean boolValue_2 = false; // boolean constant

6. null constants
The null constant indicates that theempty object reference

String strValue = null; // null constant

II. Data types

2.1 What are data types?

Java’s data types are divided into two categories: basic data types and reference data types. Basic data types include integer, floating-point, character, and boolean, which are all built-in types provided by the Java language. Reference data types include classes, interfaces, arrays, and so on, and they are all custom types in the program.

2.2 Basic data types:

1. Integer
Integer data types includebyte, short, int sum longThere are four types, which occupy 1, 2, 4 and 8 bytes respectively and have different ranges of values. The table below:

Integer data type
typologyspace occupiedrange of values
byte1 byte-128~127
short2 bytes-32768~32767
int 4 bytes-2147483648~2147483647
long8 bytes-9223372036854775808~9223372036854775807

2. Floating-point
Floating-point data types includefloat and doubleTwo typesThey occupy 4 and 8 bytes respectively and have different precision and value ranges.


 

float f = 3.14f; 
double d = 3.14;
Floating-point data type
typologyspace occupiedAccuracy Range
float4 bytesAccuracy of 6~7 digits
double8 bytesAccuracy of 15~16 bits

3. Character type
The character data type char occupies 2 bytes.Used to represent Unicode encoded characters.

char c = 'a'; // character data type

4. Boolean
The boolean data type boolean has only two values: true and false., occupies 1 byte.

boolean b1 = true; // boolean data type
boolean b2 = false; // boolean data type


2.3 Referencing data types

Reference data types in Java include classes, interfaces, arrays, enumerations, annotations, and so on. These types of data are stored by reference in heap memory.

1. Classes

Classes are the foundation of object-oriented programming, and all classes in Java are reference data types. Classes can contain members such as properties, methods, and constructors, and class members are used by creating objects.

public class lhy {
    public static void main(String[] args) {
        class Person {
 String name;
 int age;

    void sayHello() {
 System.out.println("Hello, my name is " + name + ", I'm " + age + " years old.");
}
        }

        Person p = new Person(); // create an object p of class Person
        p.name = "Tom";
        p.age = 25;
        p.sayHello(); // Output: Hello, my name is Tom, I'm 25 years old.

    }
}

The output is as follows.

The Complete Guide to Java Data Types and Variables


2. Interfaces

An interface is an abstract type that defines a signature for a set of methods, but no concrete code that implements those methods. Interfaces can be implemented by classes, and a class can implement multiple interfaces.

interface Flyable {
  void fly();
}

class Bird implements Flyable {
  public void fly() {
    System.out.println("I'm a bird, I'm flying.");
  }
}

Bird b = new Bird(); // create object b of class Bird
b.fly(); // Output: I'm a bird, I'm flying.

The output is as follows:

The Complete Guide to Java Data Types and Variables


3. Arrays

An array is a container that stores multiple data of the same type. Arrays in Java can store any type of data, including basic types and reference types.

int[] nums = new int[]{1, 2, 3}; // declare an array nums of type int
String[] names = new String[]{"Tom", "Jerry", "Alice"}; // Declare an array of names of type String

4. Enumeration

An enumeration is a special type that restricts variables to taking only the values defined in the enumeration, which avoids errors in cases such as using numbers or strings to represent states.

enum Color {
  RED, GREEN, BLUE
}

Color c = Color.RED; // declare a variable c of type Color

5. Note

An annotation is a type of markup used to provide metadata information that can be used on elements such as classes, methods, variables, etc. to describe their attributes and characteristics. Annotations can be obtained through the reflection mechanism

In addition to the reference data types mentioned above, Java has many other data types such asAssembly, projectionetc. These data types are also very commonly used in Java development. In the actual development, developers need to choose the appropriate data type to complete the development task according to the specific business requirements.

III. Variables

3.1 What are variables?

In the program, in addition to the constants that are always the same, there are some contents that may change frequently, such as: the person’s age, height, grades and scores, mathematical function results, etc., for theIn the case of these often-changing elements, theJavaprogram, called variablesAnd data types are used to define different kinds of variables

The syntactic format for defining a variable is:

Datatype Variable name = initial value.
public class lhy {
    public static void main(String[] args) {
        int a = 10; // Define the shaping variable a, a is the variable name also known as the identifier, and the value placed in this variable is 10

        double d = 3.14;
        char c = 'A';
        boolean b = true;
        System.out.println(a);
        System.out.println(d);
        System.out.println(c);
        System.out.println(b);
        a = 100; // a is a variable, the value in a can be modified, note: = in java means assignment, i.e., 100 is given to a, the value stored in a is 100
        System.out.println(a);
// Note: You can define more than one variable of the same type on a single line.
        int a1 = 10, a2 = 20, a3 = 30;
        System.out.println(a1);
        System.out.println(a2);
        System.out.println(a3);

    }
}

As shown below:

The Complete Guide to Java Data Types and Variables


3.2 Naming rules for variables

The naming of variables needs to follow certain rules, the variable name must be composed of letters, numbers, underscores or dollar signs, can not start with a number, and can not be a Java keyword.

int myNumber; // correct variable name
double $price; // correct variable name
char _firstChar; // correct variable name
boolean isOK; // correct variable name
String 1stString; // wrong variable name, can't start with a number

3.3 Scope of variables

The scope of a variable is the extent to which the variable is accessible within the program; variables in Java have scope, that is, the variable is visible only within the block of code in which it is declared.

public void foo() {
    int a = 10; // only visible in the foo() method
    if (a > 5) {
        int b = 20; // only visible in if blocks
    }
    System.out.println(a); // you can access the variable a
    System.out.println(b); // Error, can't access variable b
}

3.4 Modification of variables by final

In Java, a variable can also be modified by final, which indicates that the variable is a constant and cannot be changed once it is assigned a value.

final int a = 10; // Declare a constant a, which cannot be changed.
final double PI = 3.14; // Declare a constant PI that cannot be changed.

IV. Type conversion

4.1 What is type conversion?

Java Being a strongly typed programming language , When variables of different types are assigned values to each other , There will be stricter calibration .
int a = 10;
long b = 100L;
b = a; // can be compiled
a = b; // compilation failure
in Java in which a type conversion is performed when the types of the data involved in the operation are inconsistent. Java There are two main categories of type conversions in:automatic type conversion (implicitly) respond in singingforced type conversion (explicit)

automatic type conversion

4.2 Automatic type conversion

The code is not processed in any way, the compiler does it automatically when the code is compiled Features: Conversion of small data ranges to numbers Automatically performs this function if the data range is large.

The following code:

System.Out.println(1024); // integers are int by default
System.Out.println(3.14); // Floating-point types are double by default
int a = 100;
long b = 10L;
b = a; // a and b are both plastic, a has a small range and b has a large range, when assigning a to b, the compiler automatically raises a to long and then assigns it
a = b; // compiler error, long range is larger than int range, there will be data loss, unsafe.
float f = 3.14F;
double d = 5.12;
d = f; // the compiler will convert f to a double and then make the assignment
f = d; // double means the data range is large, handing a float directly to a double would be unsafe with data loss
byte b1 = 100; // compilation passes, 100 is not out of range for byte, compiler implicitly converts 100 to byte
byte b2 = 257; // compilation failed, 257 is out of data range for byte, there is data loss

4.3 Forced type conversion

Forced type conversion: when the operation is performed, the code needs to go through a certain formatting process, which cannot be done automatically. Characteristics: large data range to small data range.

The following code:

int a = 10;
long b = 100L;
b = a; // int-->long, data range from small to large, implicit conversion
a = (int)b; // long-->int, data range from largest to smallest, need strong conversion, otherwise compilation fails


float f = 3.14F;
double d = 5.12;
d = f; // float-->double, data range from small to large, implicit conversion
f = (float)d; // double-->float, data ranges from large to small, need strong conversion or compilation fails


a = d; // error, type incompatibility
a = (int)d; // int doesn't have as large a range of data as double, so it needs to be strong-converted and discarded after the decimal point.


byte b1 = 100; // 100 defaults to int, no byte range, implicit conversion
byte b2 = (byte)257; // 257 defaults to int, over byte range, need to show conversion, otherwise report error


boolean flag = true;
a = flag; // compilation failure: type incompatibility
flag = a; // compilation failure: type incompatibility

4.4 Precautions

1. Assignment between variables of different numeric types , Indicates that a type with a smaller range can be implicitly converted to a type with a larger range.
2. If you need to assign a type with a large range to a type with a small range , Requires forced type conversion , still Possible loss of accuracy
3. When assigning a constant to a literal value , Java Automatically checks against a range of numbers
4. Forced type conversions don’t always work.Disjoint types cannot be converted to each other


4.5 Type Lifting

What is Type Elevation?

When different types of data operate on each other, theSmaller data types will be promoted to larger data types
as shown below

1. intwithlongBetween:intIt will be promoted tolong

int a = 10;
long b = 20;
int c = a + b; // compiler error: a + b== "int + long--> long + long will lose data when assigned to int
long d = a + b; // compiled successfully: a + b==>int + long--->long + long assigned to long

2. byte with byte arithmetic operation
byte a = 10;
byte b = 20;
byte c = a + b;
System.out.println(c);

// Compilation error
Test.java error: Incompatible type: conversion from int to byte may be lossy
byte c = a + b;
       ^

Analysis: (1)

byte and byte They’re all the same type. , But there is a compilation error . The reason. , even though a and b all byte, But the calculation a + b will first convert a and b All upgraded to int, Re-calculate. , The results obtained are also int, It’s a gift to c, The above error occurs .
Due to the computer’s CPU This is usually done in accordance with the 4 Reads and writes data from memory in units of bytes . For ease of hardware realization , (various things) such as byte and short This is less than 4 Type of bytes , It will first be upgraded to int, Re-participate in the calculations.
The correct way to write:
byte a = 10;
byte b = 20;
byte c = (byte)(a + b);
System.out.println(c);
Summary:
1. Mixing operations with different types of data, Smaller ranges will be upgraded to larger ranges.
2. with regards to short, byte this kind of ratio 4 byte-small type, It will first be upgraded to 4 byte int , commutation (math.).

V. String types

5.1 What are Java string types?

In Java, a string is an object that consists of a series of characters that can contain letters, numbers, symbols, and so on.The Java string type is immutable, which means that once a string object is created, it cannot be changed. If you need to modify a string, you need to create a new string object.

5.2 How to create and use strings?

 To create a string object, you can use either a string literal or a string constructor. A string literal is a sequence of characters enclosed by a pair of double quotes, for example:

String str1 = "Hello, World!";

The string constructor canCreating a new string object by passing an array of characters or another string, for example:

char[] charArray = {'H', 'e', 'l', 'l', 'o'};
String str2 = new String(charArray);
String str3 = new String("Hello");

coerceTo access characters in a string, you can use a character index or a string method.For example, to get the first character in a string, you can use the following code:

String str1 = "Hello, World!";
char firstChar = str1.charAt(0);

5.3 Common String Operations

Java provides a number of methods for manipulating strings, including the following common examples:

string comparison

comparisonsTo determine whether two strings are equal, use the equals() method., for example:

String str4 = "Hello";
boolean isEqual = str3.equals(str4); // true

string connection

It is possible to useThe plus operator or the concat() method.Concatenate two strings, for example:

String str5 = "Hello";
String str6 = "World";
String str7 = str5 + " " + str6; // "Hello World"
String str8 = str5.concat(" ").concat(str6); // "Hello World"

String length

canUse the length() method to get the number of characters in a string., for example:

int length = str1.length(); // 13

String Interception

canUse the substring() method to get a substring of a string., for example:

String subStr = str1.substring(0, 5); // "Hello"

string conversion

It is possible to use Convert toUpperCase() and toLowerCase() method strings to upper or lower case., for example:

String str9 = "Hello";
String str10 = str9.toUpperCase(); // "HELLO"
String str11 = str9.toLowerCase(); // "hello"

5.3 Conversion between strings and different types

String to integer conversion

It is possible to use Integer.parseInt() methodologiesConverts a string to an integer. Example:

String str = "123";
int num = Integer.parseInt(str);

String to Floating Point Number Conversion

It is possible to use Double.parseDouble() methodologiesConverts a string to a floating point number. Example:

String str = "3.14";
double num = Double.parseDouble(str);

Converting integers or floating point numbers to strings

canutilizationString.valueOf() methodologiesConverts an integer or floating point number to a string. Example:

int num = 123;
String str1 = String.valueOf(num);

double num2 = 3.14;
String str2 = String.valueOf(num2);

 

Converting strings to character arrays

It is possible to usetoCharArray() methodologiesConverts a string to an array of characters. Example:

String str = "Hello";
char[] charArray = str.toCharArray();

Converting character arrays to strings

It is possible to useString(char[] data) The constructor converts an array of characters to a string. Example:

char[] charArray = {'H', 'e', 'l', 'l', 'o'};
String str = new String(charArray);

Well, that’s the end of it, so if there are any mistakes please point them out in the comments section, thanks.

It’s not easy to create, so if you can, please support me with a few more three-parallels. Mr. Gojo would approve.

The Complete Guide to Java Data Types and Variables

Recommended Today

uniapp and applet set tabBar and show and hide tabBar

(1) Set the tabBar: uni.setTabberItem({}); wx.setTabberItem({}); indexnumberisWhich item of the tabBar, counting from the left, is indexed from 0.textstringnoButton text on tabiconPathstringnoImage PathselectedIconPathstringnoImage path when selectedpagePathstringnoPage absolute pathvisiblebooleannotab Whether to display uni.setTabBarItem({ index: 0, text: ‘text’, iconPath: ‘/path/to/iconPath’, selectedIconPath: ‘/path/to/selectedIconPath’, pagePath: ‘pages/home/home’ }) wx.setTabBarItem({ index: 0, text: ‘text’, iconPath: ‘/path/to/iconPath’, selectedIconPath: ‘/path/to/selectedIconPath’, pagePath: ‘pages/home/home’ }) […]