Table of contents
3.4 variables are final modified
5.1 What is the Java string type?
5.2 How to create and use strings?
5.3 Conversion between strings and different types
Declaration: Java data types and variables
In Java, a data type refers to 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. Understanding data types and their characteristics is very important when programming in Java.
1. Literal constants
1.1 What constant?
Literal constants refer to constant values that are used directly in the program without calculation or processing. In Java, literal constants include the following types:
1.2 Common six constant types
1. Integer constants
Integer constants represent integer values, which can be expressed in decimal, octal or hexadecimal .
int decimalValue = 10; // 十进制
int octalValue = 012; // 八进制
int hexValue = 0xA; // 十六进制
2. Floating-point constants
Floating-point constants represent real values, including single-precision floating-point and double-precision floating-point .
float floatValue = 3.14f; // 单精度浮点型
double doubleValue = 3.14; // 双精度浮点型
3. Character constants
A character constant represents a single character, enclosed in single quotes .
char charValue = 'a'; // 字符常量
4. String constant
A string constant represents a string composed of multiple characters, enclosed in double quotes .
String stringValue = "Hello, World!"; // 字符串常量
5. Boolean constants
Boolean constants represent true or false , expressed with true and false keywords.
boolean boolValue_1 = true; // 布尔型常量
boolean boolValue_2 = false; // 布尔型常量
6. Null constant
The null constant represents a null object reference .
String strValue = null; // null常量
2. Data type
2.1 What is a data type?
Java data types are divided into two categories: primitive data types and reference data types. Basic data types include integer, floating-point, character, and Boolean, which are built-in types provided by the Java language. Reference data types include classes, interfaces, arrays, etc., which are all types defined in the program.
2.2 Basic data types:
1. Integer
Integer data types include byte, short, int and long four types, which occupy 1, 2, 4 and 8 bytes respectively, and have different value ranges. The following form:
type | take up space | Ranges |
byte | 1 byte | -128~127 |
short | 2 bytes | -32768~32767 |
int | 4 bytes | -2147483648~2147483647 |
long | 8 bytes | -9223372036854775808~9223372036854775807 |
2. Floating-point type
Floating-point data types include float and double , which occupy 4 and 8 bytes respectively, and have different precision and value ranges.
float f = 3.14f;
double d = 3.14;
type | take up space | Accuracy range |
float | 4 bytes | Accuracy is 6~7 digits |
double | 8 bytes | Accuracy is 15~16 digits |
3. Character type
The character data type char occupies 2 bytes and is used to represent Unicode encoded characters.
char c = 'a'; // 字符型数据类型
4. Boolean
The Boolean data type boolean has only two values: true and false , occupying 1 byte.
boolean b1 = true; // 布尔型数据类型
boolean b2 = false; // 布尔型数据类型
2.3 Reference Data Types
Reference data types in Java include classes, interfaces, arrays, enumerations, annotations, etc. These types of data are stored in heap memory by reference.
1. class
Classes are the basis of object-oriented programming, and all classes in Java are reference data types. A class can contain members such as properties, methods, and constructors, and the members of the class 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(); // 创建Person类的对象p p.name = "Tom"; p.age = 25; p.sayHello(); // 输出:Hello, my name is Tom, I'm 25 years old. } }
The output is as follows:
2. Interface
An interface is an abstract type that defines the signature of 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(); // 创建Bird类的对象b
b.fly(); // 输出:I'm a bird, I'm flying.
The output is as follows:
3. Arrays
An array is a container that stores multiple data of the same type. An array in Java can store any type of data, including basic types and reference types.
int[] nums = new int[]{1, 2, 3}; // 声明一个int类型的数组nums
String[] names = new String[]{"Tom", "Jerry", "Alice"}; // 声明一个String类型的数组names
4. Enumeration
Enumeration is a special type, which limits variables to only take values defined in the enumeration, which can avoid errors in situations such as using numbers or strings to represent status.
enum Color {
RED, GREEN, BLUE
}
Color c = Color.RED; // 声明一个Color类型的变量c
5. Notes
Annotation is a tag used to provide metadata information, which 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 also has many other data types, such as collections, maps, etc. These data types are also very commonly used in Java development. In actual development, developers need to select appropriate data types according to specific business needs to complete development tasks.
3. Variables
3.1 What is a variable?
In the program, in addition to constant constants, some content may change frequently, such as: a person's age, height, grade scores, calculation results of mathematical functions, etc. For Java program , called variables . The data type is used to define different kinds of variables .
The syntax for defining variables is:
data type variable name = initial value;
public class lhy {
public static void main(String[] args) {
int a = 10; // 定义整形变量a,a是变量名也称为标识符,该变量中放置的值为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是变量,a中的值是可以修改的,注意:= 在java中表示赋值,即将100交给a,a中保存的值就是100
System.out.println(a);
// 注意:在一行可以定义多个相同类型的变量
int a1 = 10, a2 = 20, a3 = 30;
System.out.println(a1);
System.out.println(a2);
System.out.println(a3);
}
}
As follows:
3.2 Variable naming rules
The naming of variables needs to follow certain rules. The variable name must consist of letters, numbers, underscores or dollar signs, cannot start with a number, and cannot be a Java keyword.
int myNumber; // 正确的变量名
double $price; // 正确的变量名
char _firstChar; // 正确的变量名
boolean isOK; // 正确的变量名
String 1stString; // 错误的变量名,不能以数字开头
3.3 The scope of variables
The scope of a variable refers to the scope that the variable can access in the program. Variables in Java have scope, that is, the variable is only visible in the code block in which it is declared.
public void foo() {
int a = 10; // 只在foo()方法中可见
if (a > 5) {
int b = 20; // 只在if语句块中可见
}
System.out.println(a); // 可以访问变量a
System.out.println(b); // 错误,无法访问变量b
}
3.4 variables are final modified
In Java, a variable can also be modified by final, indicating that the variable is a constant, and once assigned, it cannot be changed.
final int a = 10; // 声明一个常量a,不能再被改变
final double PI = 3.14; // 声明一个常量PI,不能再被改变
Four. Type conversion
4.1 What is type conversion?
int a = 10;
long b = 100L;
b = a; // 可以通过编译
a = b; // 编译失败
automatic type conversion
4.2 Automatic type conversion
The code does not need to undergo any processing, and the compiler will automatically process it when the code is compiled . Features: It will be automatically converted from a small data range to a large data range .
The following code:
System.Out.println(1024); // 整型默认情况下是int
System.Out.println(3.14); // 浮点型默认情况下是double
int a = 100;
long b = 10L;
b = a; // a和b都是整形,a的范围小,b的范围大,当将a赋值给b时,编译器会自动将a提升为long类型,然后赋值
a = b; // 编译报错,long的范围比int范围大,会有数据丢失,不安全
float f = 3.14F;
double d = 5.12;
d = f; // 编译器会将f转换为double,然后进行赋值
f = d; // double表示数据范围大,直接将float交给double会有数据丢失,不安全
byte b1 = 100; // 编译通过,100没有超过byte的范围,编译器隐式将100转换为byte
byte b2 = 257; // 编译失败,257超过了byte的数据范围,有数据丢失
4.3 Mandatory type conversion
Mandatory type conversion: When performing operations, the code needs to undergo certain format processing, which cannot be completed automatically. Features: From large data range to small data range.
The following code:
int a = 10;
long b = 100L;
b = a; // int-->long,数据范围由小到大,隐式转换
a = (int)b; // long-->int, 数据范围由大到小,需要强转,否则编译失败
float f = 3.14F;
double d = 5.12;
d = f; // float-->double,数据范围由小到大,隐式转换
f = (float)d; // double-->float, 数据范围由大到小,需要强转,否则编译失败
a = d; // 报错,类型不兼容
a = (int)d; // int没有double表示的数据范围大,需要强转,小数点之后全部丢弃
byte b1 = 100; // 100默认为int,没有超过byte范围,隐式转换
byte b2 = (byte)257; // 257默认为int,超过byte范围,需要显示转换,否则报错
boolean flag = true;
a = flag; // 编译失败:类型不兼容
flag = a; // 编译失败:类型不兼容
4.4 Precautions
4.5 Type promotion
What is type promotion?
1. Between int and long : int will be promoted to long
int a = 10;
long b = 20;
int c = a + b; // 编译出错: a + b==》int + long--> long + long 赋值给int时会丢失数据
long d = a + b; // 编译成功:a + b==>int + long--->long + long 赋值给long
byte a = 10;
byte b = 20;
byte c = a + b;
System.out.println(c);
// 编译报错
Test.java:5: 错误: 不兼容的类型: 从int转换到byte可能会有损失
byte c = a + b;
^
Analysis:
byte a = 10;
byte b = 20;
byte c = (byte)(a + b);
System.out.println(c);
Five. String type
5.1 What is the Java string type?
In Java, a string is an object, which is composed of a series of characters, which can contain letters, numbers, symbols, etc. 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, use a string literal or a string constructor . A string literal is a sequence of characters enclosed in double quotes, for example:
String str1 = "Hello, World!";
The string constructor can create a new string object by passing it a character array or another string , for example:
char[] charArray = {'H', 'e', 'l', 'l', 'o'};
String str2 = new String(charArray);
String str3 = new String("Hello");
To access characters in a string, you can use character indices or string methods. 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 many methods for manipulating strings, including the following common examples:
string comparison
To compare two strings for equality, you can use the equals() method , for example:
String str4 = "Hello";
boolean isEqual = str3.equals(str4); // true
string concatenation
Two strings can be concatenated using the plus operator or the concat() method , for example:
String str5 = "Hello";
String str6 = "World";
String str7 = str5 + " " + str6; // "Hello World"
String str8 = str5.concat(" ").concat(str6); // "Hello World"
string length
You can use the length() method to get the number of characters in a string , for example:
int length = str1.length(); // 13
String interception
You can use the substring() method to get a substring of a string , for example:
String subStr = str1.substring(0, 5); // "Hello"
string conversion
You can use the toUpperCase() and toLowerCase() methods to convert a string to uppercase or lowercase , 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
You can use the method to convert a string to an integer. For example: Integer.parseInt()
String str = "123";
int num = Integer.parseInt(str);
Convert String to Float
You can use the method to convert a string to a float. For example: Double.parseDouble()
String str = "3.14";
double num = Double.parseDouble(str);
Integer or float converted to string
You can use String.valueOf()
the method to convert an integer or floating point number to a string. For example:
int num = 123;
String str1 = String.valueOf(num);
double num2 = 3.14;
String str2 = String.valueOf(num2);
string to char array
You can use toCharArray()
the method to convert a string to a character array. For example:
String str = "Hello";
char[] charArray = str.toCharArray();
character array to string
A character array can be converted to a string using String(char[] data)
the constructor. For example:
char[] charArray = {'H', 'e', 'l', 'l', 'o'};
String str = new String(charArray);
Well, this is the end here, if there is anything wrong, please point it out in the comment area, thank you.
It is not easy to create, if possible, please support me three times. Teacher Wutiao would agree very much