Reproduced at: http://c.biancheng.net/java/40/
Java is an object-oriented programming language. Classes in Java connect methods and data types to form a self-contained processing unit. However, basic type objects cannot be defined in Java. In order to treat basic types as objects and connect related methods, Java provides wrapper classes for each basic type, such as Integer for int type values, Boolean for boolean type values, etc. In this way, these basic types can be converted into objects for processing.
Although Java can handle basic types directly, in some cases, it needs to be treated as an object, so it needs to be converted into a wrapper class. This chapter will introduce various wrapper classes provided by Java and the use of System class in detail.
Learning points of this chapter
- Learn about common methods of Java base class Object
- Master the creation of Integer objects and the methods provided
- Master the creation of Float object and its methods
- Master the creation of Double object and its methods
- Master the creation of Character objects and the methods they provide
- Master the creation of Boolean objects and the methods provided
- Master the creation of Byte objects and the methods provided
- Master the usage of three static variables of System class
- Be familiar with the member methods provided by the System class
Java wrapper classes, boxing and unpacking
stay Java It advocates the idea that everything is an object. However, from the division of data types, we know that data types in Java are divided into basic data types and reference data types, but how can basic data types be called objects? Therefore, Java has designed corresponding classes for each basic data type, which are called Wrapper Classes, and sometimes called overlay classes or data type classes.
The relationship between package class and basic data type is shown in the following table.
Serial number | Basic data type | Packaging |
---|---|---|
1 | byte | Byte |
2 | short | Short |
3 | int | Integer |
4 | long | Long |
5 | char | Character |
6 | float | Float |
7 | double | Double |
8 | boolean | Boolean |
From the above table, we can see that except that the names defined by Integer and Character are quite different from those defined by basic data types, the names of the other six types are easy to master.
boxing and unboxing
After understanding the packaging class, the following introduces the concepts of packing and unpacking of packaging class. In fact, these two concepts are not difficult to understand. The process of converting a basic data type into a wrapper class is called boxing. For example, wrapping int into an object of Integer class; The process of changing a wrapper class into a basic data type is called unpacking. For example, the object of the Integer class is re simplified to int.
Manually instantiating a packing class is called manual unpacking. Before java version 1.5, you must unpack manually, and then you can unpack automatically. That is, when you convert the basic data type and the corresponding packaging class, the system will automatically unpack and unpack. There is no need for manual operation, which provides more convenience for developers. For example:
public class Demo { public static void main(String[] args) { int m = 500; Integer obj = m; // Automatic packing int n = obj; // Automatic unpacking System.out.println("n = " + n); Integer obj1 = 500; System.out.println("obj Equivalent to obj1 The returned result is" + obj.equals(obj1)); } }
Operation results:
n = 500
Obj is equivalent to obj1, and the returned result is true
Automatic unpacking is a common function, which readers need to master.
Application of packaging
Let's explain the use of 8 packaging classes. The following are common application scenarios.
1) Realize the conversion between int and Integer
int can be boxed through the constructor of Integer class, and Integer can be unpacked through the intValue method of Integer class. For example:
public class Demo { public static void main(String[] args) { int m = 500; Integer obj = new Integer(m); // Manual packing int n = obj.intValue(); // Manual unpacking System.out.println("n = " + n); Integer obj1 = new Integer(500); System.out.println("obj Equivalent to obj1 The returned result is" + obj.equals(obj1)); } }
Operation results:
n = 500
Obj is equivalent to obj1, and the return result is true
2) Converts a string to a numeric type
The following two methods are provided in the Integer and Float classes:
① Integer class (String to int)
int parseInt(String s);
s is the string to convert.
② Float class (String to float type)
float parseFloat(String s)
Note: when using the above two methods, the data in the string must be composed of numbers, otherwise a program error will occur during conversion.
The following is an example of converting a string to a numeric type:
public class Demo { public static void main(String[] args) { String str1 = "30"; String str2 = "30.3"; // Change string to int int x = Integer.parseInt(str1); // Change string to float type float f = Float.parseFloat(str2); System.out.println("x = " + x + ";f = " + f); } }
Operation results:
x = 30;f = 30.3
3) Converts an integer to a string
The Integer class has a static toString() method that converts integers to strings. For example:
public class Demo { public static void main(String[] args) { int m = 500; String s = Integer.toString(m); System.out.println("s = " + s); } }
Operation results:
s = 500
Detailed explanation of Java Object class
Object is Java A special class in the class library and the parent of all classes. That is, Java allows you to assign any type of Object to a variable of type Object. After a class is defined, if no inherited parent class is specified, the default parent class is the Object class. Therefore, the following two classes represent the same meaning.
public class MyClass{...}
Equivalent to
public class MyClass extends Object {...}
Since all Java classes are subclasses of the Object class, any Java Object can call the methods of the Object class. Common methods are shown in Table 1.
method | explain |
---|---|
Object clone() | Create a new object that is the same as the object's class |
boolean equals(Object) | Compare two objects for equality |
void finalize() | The object garbage collector calls this method when the garbage collector determines that there are no more references to the object |
Class getClass() | Returns the instance class of an object runtime |
int hashCode() | Returns the hash code value of the object |
void notify() | Activate a thread waiting on the object's monitor |
void notifyAll() | Activate all threads waiting on the object's monitor |
String toString() | Returns a string representation of the object |
void wait() | Causes the current thread to wait before another thread calls the notify() method or notifyAll() method of this object |
Among them, toString(), equals() and getClass() methods are commonly used in Java programs.
toString() method
The toString() method returns the string of the object. When the program outputs an object or connects an object with a string, the system will automatically call the toString() method of the object to return the string representation of the object.
The toString() method of the Object class returns a string in the format of "runtime class name @ hexadecimal hash code", but many classes override the toString() method of the Object class to return a string that can express the information of the Object.
hashCode: each Java object has a hash code attribute. The hash code can be used to identify the object and improve the execution efficiency of the object in the collection operation.
First look at the following code:
// Define the Demo class, which actually inherits the Object class class Demo { } public class ObjectDemo01 { public static void main(String[] args) { Demo d = new Demo(); // Instantiate Demo objects System.out.println("No toString()Output:" + d); System.out.println("add toString()Output:" + d.toString()); } }
The output result is:
Output without toString(): Demo@15db9742
Add toString() output: Demo@15db9742
The above program randomly outputs some address information. From the running results of the program, it can be clearly found that the final output results with and without toString() are the same, that is, when the Object is output, the toString() method in the Object class will be called to print the content. Therefore, using this feature, you can obtain some Object information through toString (), such as the following code.
public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String toString() { return "full name:" + this.name + ": Age" + this.age; } public static void main(String[] args) { Person per = new Person("C Language Chinese network", 30);// Instantiate the Person object System.out.println("Object information:" + per);// The print object calls the toString() method } }
The output result is:
Object information: Name: C language Chinese website: age 30
The toString() method in the Object class is overridden in the Person class in the program, so that the toString() method overridden by the subclass is called when the Object is output directly.
equals() method
When learning string comparison earlier, I introduced two comparison methods, namely = = operator and equals() method. The = = operator compares whether two reference variables point to the same instance. The equals() method compares whether the contents of two objects are equal. Usually, string comparison only cares about whether the contents are equal.
Its format is as follows:
boolean result = obj.equals(Object o);
Where obj represents one object to be compared and o represents another object.
Example 1
Write a Java program to realize the authentication function of user login. The user is required to enter the login user name and password from the keyboard. When the user name entered by the user is equal to admin and the password is also equal to admin, it indicates that the user is a legal user and prompts that the login is successful. Otherwise, it prompts the user name or password error message.
Here, use the equals() method to compare the string entered by the user with the string object saved in admin. The specific code is as follows:
import java.util.Scanner; public class Test01 { // Verify user name and password public static boolean validateLogin(String uname, String upwd) { boolean con = false; if (uname.equals("admin") && upwd.equals("admin")) { // Compare two String objects con = true; } else { con = false; } return con; } public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("------Welcome to big data management platform------"); System.out.println("user name:"); String username = input.next(); // Gets the user name entered by the user System.out.println("password:"); String pwd = input.next(); // Get the password entered by the user boolean con = validateLogin(username, pwd); if (con) { System.out.println("Login succeeded!"); } else { System.out.println("Wrong user name or password!"); } } }
The above code uses the equals() method in the validateLogin() method to compare two String objects. When the uname object is the same as the String object that saves admin, uname Equals ("admin") is true; Similarly, when the upwd object is the same as the String object that holds admin, upwd Equals ("admin") is true. When the user name and password entered by the user are admin, it indicates that the user is a legal user and prompts the login success information. Otherwise, it prompts the error information of incorrect user name or password.
The running results of the program are as follows:
------Welcome to big data management platform------ user name: adinm password: admin Wrong user name or password! ------Welcome to big data management platform------ user name: admin password: admin Login succeeded!
getClass() method
The getClass() method returns the Class to which the object belongs, which is a Class object. Through the Class object, you can obtain various information of the Class, including the Class name, parent Class and the name of the interface it implements.
Example 2
Write an example to demonstrate how to call getClass() method on String type, and then output its parent class and implemented interface information. The specific implementation code is as follows:
public class Test02 { public static void printClassInfo(Object obj) { // Get class name System.out.println("Class name:" + obj.getClass().getName()); // Get parent class name System.out.println("Parent class:" + obj.getClass().getSuperclass().getName()); System.out.println("The interfaces implemented are:"); // Get the implemented interface and output it for (int i = 0; i < obj.getClass().getInterfaces().length; i++) { System.out.println(obj.getClass().getInterfaces()[i]); } } public static void main(String[] args) { String strObj = new String(); printClassInfo(strObj); } }
The running results of the program are as follows:
Class name: java.lang.String Parent class: java.lang.Object The interfaces implemented are: interface java.io.Serializable interface java.lang.Comparable interface java.lang.CharSequence
Receive objects of any reference type
Since the Object class is the parent class of all objects, all objects can be converted to Object, which also includes array and interface types, that is, all reference data types can be received using Object.
interface A { public String getInfo(); } class B implements A { public String getInfo() { return "Hello World!!!"; } } public class ObjectDemo04 { public static void main(String[] args) { // Instantiate an interface A a = new B(); // Object upward transformation Object obj = a; // Object downward transformation A x = (A) obj; System.out.println(x.getInfo()); } }
The output result is:
Hello World!!!
It can be found from the above code that although the interface cannot inherit a class, it is still a subclass of the Object class. Because the interface itself is a reference data type, it can be transformed upward.
Similarly, you can also use Object to receive an array, because the array itself is also a reference data type.
public class ObjectDemo05 { public static void main(String[] args) { int temp[] = { 1, 3, 5, 7, 9 }; // Receiving arrays using object Object obj = temp; // Pass array reference print(obj); } public static void print(Object o) { // Judge the type of object if (o instanceof int[]) { // Downward transformation int x[] = (int[]) o; // Cyclic output for (int i = 0; i < x.length; i++) { System.out.print(x[i] + "\t"); } } } }
The output result is:
1 3 5 7 9
The above program uses Object to receive an integer array. Because the array itself belongs to the reference data type, you can use Object to receive the array content, judge whether the type is an integer array through instanceof, and then output.
Tip: because the Object class can receive any reference data type, Object is used as a method parameter in many class library designs, which is more convenient to operate.
Detailed explanation of Java Integer class
The Integer class wraps a value of the basic type int in an object. The Integer class object contains a field of type int. In addition, this class provides multiple methods that can convert between int and String types. It also provides some other constants and methods that are very useful when dealing with int types.
Construction method of Integer class
There are two constructors in the Integer class:
- Integer(int value): construct a newly allocated integer object that represents the specified int value.
- Integer(String s): construct a newly allocated integer object that represents the int value indicated by the String parameter.
For example, the following code uses the above two construction methods to obtain Integer objects:
Integer integer1 = new Integer(100); // Create an Integer object with an int variable as a parameter Integer integer2 = new Integer("100"); // Create an Integer object with a String variable as a parameter
Common methods of Integer class
The Integer class contains some methods related to int type operations. Table 1 lists these common methods.
method | Return value | function |
---|---|---|
byteValue() | byte | Returns the value of the Integer as byte |
shortValue() | short | Returns the value of the Integer as short |
intValue() | int | Returns the value of this Integer as int |
toString() | String | Returns a String object representing the Integer value |
equals(Object obj) | boolean | Compares whether this object is equal to the specified object |
compareTo(Integer anotherlnteger) | int | Compare two Integer objects numerically. If they are equal, 0 is returned; If the value of the calling object is less than the value of otherlnteger, a negative value is returned; If the value of the calling object is greater than the value of otherlnteger, a positive value is returned |
valueOf(String s) | Integer | Returns an Integer object that holds the specified String value |
parseInt(String s) | int | Converts a numeric string to an int value |
In the actual programming process, the string is often converted to the value of int type, or the value of int type is converted to the corresponding string. The following code demonstrates how to implement these two functions:
String str = "456"; int num = Integer.parseInt(str); // Converts a string to a numeric value of type int int i = 789; String s = Integer.toString(i); // Converts a numeric value of type int to a string
Note: in the process of converting a string to an int type value, if the string contains characters of non numeric type, the program execution will encounter an exception.
Example 1
Write a program, create a String type variable in the program, and then convert it to binary, octal, decimal and hexadecimal output.
public class Test03 { public static void main(String[] args) { int num = 40; String str = Integer.toString(num); // Convert numbers to strings String str1 = Integer.toBinaryString(num); // Convert numbers to binary String str2 = Integer.toHexString(num); // Convert numbers to octal String str3 = Integer.toOctalString(num); // Convert numbers to hexadecimal System.out.println(str + "The binary number of is:" + str1); System.out.println(str + "The octal number of is:" + str3); System.out.println(str + "The decimal number of is:" + str); System.out.println(str + "The hexadecimal number of is:" + str2); } }
The output results after operation are as follows:
40 The binary number of is 101000 40 The octal number of is: 50 40 The decimal number is: 40 40 The hexadecimal number of is: 28
Constant of Integer class
The Integer class contains the following four constants.
- MAX_VALUE: a constant with a value of 231-1, which represents the maximum value that the int type can represent.
- MIN_VALUE: a constant with a value of - 231, which represents the minimum value that the int type can represent.
- SIZE: used to represent the bit number of int value in the form of binary complement.
- TYPE: represents the Class instance of the basic TYPE int.
The following code demonstrates the use of constants in the Integer class.
int max_value = Integer.MAX_VALUE; // Gets the maximum value that the int type can take int min_value = Integer.MIN_VALUE; // Gets the minimum value that the int type can take int size = Integer.SIZE; // Gets the binary bit of type int Class c = Integer.TYPE; // Gets the Class instance of the base type int
Java Float class
The float class wraps a value of the basic type float in an object. The float class object contains a field of type float. In addition, this class provides multiple methods that can convert between float type and String type. It also provides constants and methods commonly used when dealing with float type.
Construction method of Float class
There are three constructors in the Float class.
- Float(double value): construct a newly allocated float object, which represents the parameters converted to float type.
- Float(float value): construct a newly allocated float object, which represents the basic float parameters.
- Float(String s): construct a newly allocated float object, which represents the float value indicated by the String parameter.
For example, the following code uses the above three construction methods to obtain the Float object:
Float float1 = new Float(3.14145); // Create a Float object with a variable of type double as a parameter Float float2 = new Float(6.5); // Create a float object with a variable of type float as a parameter Float float3 = new Float("3.1415"); // Create a Float object with a variable of type String as a parameter
The float class contains some methods related to float operation, as shown in Table 1.
method | Return value | function |
---|---|---|
byteValue() | byte | Returns the value of the Float as byte |
doubleValue() | double | Returns the value of the Float as double |
floatValue() | float | Returns the value of the float as a float type |
intValue() | int | Returns the value of the Float as int (cast to int) |
longValue() | long | Return the value of the Float as long (cast to long) |
shortValue() | short | Return the value of the Float in short type (cast to short type) |
isNaN() | boolean | Returns true if the Float value is a non numeric value, otherwise false |
isNaN(float v) | boolean | Returns true if the specified parameter is a non numeric value; otherwise, returns false |
toString() | String | Returns a String object representing the Float value |
valueOf(String s) | Float | Returns the Float object that holds the specified String value |
parseFloat(String s) | float | Converts a numeric string to a float value |
For example, convert the string 456.7 to a numeric value of float type, or convert the numeric value 123.4 of float type to a corresponding string. The following code demonstrates how to realize these two functions:
String str = "456.7"; float num = Float.parseFloat(str); // Converts a string to a numeric value of type float float f = 123.4f; String s = Float.toString(f); // Converts a numeric value of type float to a string
Note: in the process of converting a string to a float type value, if the string contains characters of non numeric type, the program execution will encounter an exception.
Common constants of Float class
The Float class contains many constants, of which the more common constants are as follows.
- MAX_VALUE: a constant with a value of 1.4E38, which represents the maximum value that the float type can represent.
- MIN_VALUE: a constant with a value of 3.4E-45, which represents the minimum value that the float type can represent.
- MAX_EXPONENT: the maximum exponent that a finite float variable may have.
- MIN_EXPONENT: the smallest exponent that a normalized float variable may have.
- MIN_NORMAL: a constant that holds the minimum standard value of a float type value, i.e. 2-126.
- NaN: a constant that holds non numeric values of type float.
- SIZE: the number of bits used to represent the float value in the form of binary complement.
- TYPE: represents the Class instance of the basic TYPE float.
The following code demonstrates the use of constants in the Float class.
float max_value = Float.MAX_VALUE; // Gets the maximum value that the float type can take float min_value = Float.MIN_VALUE; // Gets the minimum value that the float type can take float min_normal = Float.MIN_NORMAL; // Gets the minimum standard value that the float type can take float size = Float.SIZE; // Gets the binary bit of the float type
Java Double class
The double class wraps a value of the basic type double in an object. The double class object contains a field of type double. In addition, this class also provides multiple methods that can convert double type and String type to each other. At the same time, it also provides constants and methods commonly used when dealing with double type.
Construction method of Double class
There are two construction methods in the Double class.
- Double(double value): construct a newly allocated double object, which represents the parameters converted to double type.
- Double(String s): construct a newly allocated double object, which represents the double value indicated by the String parameter.
For example, the following code uses the above two construction methods to obtain the Double object:
Double double1 = new Double(5.456); // Create a double object with a variable of type double as a parameter Double double2 = new Double("5.456"); // Create a Double object with a variable of type String as a parameter
Common methods of Double class
The double class contains some methods related to double operation, as shown in Table 1.
method | Return value | function |
---|---|---|
byteValue() | byte | Returns the value of the Double as byte |
doubleValue() | double | Returns the value of the double as type double |
fioatValue() | float | Returns the value of the Double as a float type |
intValue() | int | Returns the value of the Double as int (cast to int) |
longValue() | long | Return the value of the Double as long (cast to long) |
shortValue() | short | Return the value of the Double as short (cast to short) |
isNaN() | boolean | If the Double value is a non numeric value, return true; otherwise, return false |
isNaN(double v) | boolean | Returns true if the specified parameter is a non numeric value; otherwise, returns false |
toString() | String | Returns a String object representing the Double value |
valueOf(String s) | Double | Returns the Double object that holds the specified String value |
parseDouble(String s) | double | Converts a numeric string to a Double numeric value |
For example, convert the string 56.7809 to a double value, or convert the double value 56.7809 to a corresponding string. The following code demonstrates how to implement these two functions:
String str = "56.7809"; double num = Double.parseDouble(str); // Converts a string to a numeric value of type double double d = 56.7809; String s = Double.toString(d); // Converts a numeric value of type double to a string
In the process of converting a string to a value of double type, if the string contains characters of non numeric type, the program execution will encounter an exception.
Common constants of the Double class
The Double class contains many constants, of which the more common constants are as follows.
- MAX_VALUE: a constant with a value of 1.8E308, which represents the constant of the maximum positive finite value of type double.
- MIN_VALUE: a constant with a value of 4.9E-324, which represents the minimum positive non-zero value that can be maintained by double type data.
- NaN: a constant that holds non numeric values of type double.
- NEGATIVE_INFINITY: a constant that maintains negative infinity of type double.
- POSITIVE_INFINITY: a constant that maintains positive infinity of type double.
- SIZE: represents the bit number of double value in binary complement form.
- TYPE: represents the Class instance of the basic TYPE double.
Java Number class
Number is an abstract class and a superclass (i.e. parent class). Number belongs to java.lang package, and all wrapper classes (such as Double, Float, Byte, Short, Integer and Long) are subclasses of abstract class number.
The Number class defines some abstract methods to return the value of an object in various numeric formats. For example, the xxxValue() method converts the Number object to a value of xxx data type and returns. These methods are shown in the following table:
method | explain |
---|---|
byte byteValue(); | Returns a value of type byte |
double doubleValue(); | Returns a value of type double |
float floatValue(); | Returns a value of type float |
int intValue(); | Returns a value of type int |
long longValue(); | Returns a value of type long |
short shortValue(); | Returns a value of type short |
Abstract classes cannot be instantiated directly, but their concrete subclasses must be instantiated. The following code demonstrates the use of the Number class:
Number num = new Double(12.5); System.out.println("return double Value of type:" + num.doubleValue()); System.out.println("return int Value of type:" + num.intValue()); System.out.println("return float Value of type:" + num.floatValue());
Execute the above code and the output results are as follows:
return double Value of type: 12.5 return int Value of type: 12 return float Value of type: 12.5
Java Character class
The Character class is a wrapper class for the Character data type char. The object of Character class contains a single field of type char, which can treat the basic data type as an object. Its common methods are shown in Table 1.
method | describe |
---|---|
void Character(char value) | Construct a newly assigned Character object to represent the specified Character value |
char charValue() | Returns the value of this Character object, which represents the basic Character value |
int compareTo(Character anotherCharacter) | Compares two Character objects based on numbers |
boolean equals(Character anotherCharacter) | Comparing this object with the specified object, the result is true if and only if the parameter is not null, but a Character object containing the same Character value as this object |
boolean isDigit(char ch) | Determines whether the specified character is a number, if through character GetType (CH) the general category type of the characters provided is DECIMAL_DIGIT_NUMBER, the characters are numbers |
boolean isLetter(int codePoint) | Determines whether the specified character (Unicode code point) is a letter |
boolean isLetterOrDigit(int codePoint) | Determines whether the specified character (Unicode code point) is a letter or number |
boolean isLowerCase(char ch) | Determines whether the specified character is lowercase |
boolean isUpperCase(char ch) | Determines whether the specified character is uppercase |
char toLowerCase(char ch) | Converts character parameters to lowercase using case mapping information from a Unicode data file |
char toUpperCase(char ch) | Converts character parameters to uppercase using case mapping information from a Unicode data file |
You can create a Character object from the Character value. For example, the following statement creates a Character object for Character S.
Character character = new Character('S');
The CompareTo() method compares this character with other characters and returns an integer array. This value is the standard code difference between the two characters. The return value of the equals() method is true if and only if the two characters are the same. As shown in the following code:
Character character = new Character('A'); int result1 = character.compareTo(new Character('V')); System.out.println(result1); // Output: 0 int result2 = character.compareTo(new Character('B')); System.out.println(resuit2); // Output: - 1 int result3 = character.compareTo(new Character('1')); System.out.println(result3); // Output: - 2
Example 1
When registering a member, you need to verify whether the user name, password, gender, age, e-mail address and other information entered by the user meet the standards. If they meet the standards, you can register. Then, let's use some static methods in the Character class to complete this program. The specific implementation steps are as follows.
1) Create a Register class, and create a validateUser() method in this class to verify the user name, password and age entered by the user. The code is as follows:
public class Register { public static boolean validateUser(String uname,String upwd,String age) { boolean conUname = false; // Whether the user name meets the requirements boolean conPwd = false; // Whether the password meets the requirements boolean conAge = false; // Whether the age meets the requirements boolean con = false; // Verification passed if (uname.length() > 0) { for (int i = 0;i < uname.length();i++) { // Verify that the user name is all letters and cannot contain spaces if (Character.isLetter(uname.charAt(i))) { conUname = true; } else { conUname = false; System.out.println("The user name can only be composed of letters and cannot contain spaces!"); break; } } } else { System.out.println("User name cannot be empty!"); } if (upwd.length() > 0) { for (int j=0;j<upwd.length();j++) { // Verify that the password consists of numbers and letters and cannot contain spaces if (Character.isLetterOrDigit(upwd.charAt(j))) { conPwd = true; } else { conPwd = false; System.out.println("The password can only consist of numbers or letters!"); break; } } } else { System.out.println("Password cannot be empty!"); } if (age.length() > 0) { for (int k = 0;k < age.length();k++) { // Verify that age consists of numbers if (Character.isDigit(age.charAt(k))) { conAge = true; } else { conAge = false; System.out.println("Incorrect age input!"); break; } } } else { System.out.println("Age must be entered!"); } if (conUname && conPwd && conAge) { con = true; } else { con = false; } return con; } }
In the validateUser() method, use the for loop to traverse the user name, password and age entered by the user, verify each Character, and judge whether it meets the requirements. In the process of verification, the isLetter() method, isLetterOrDigit() method and isDigit() method of Character class are used respectively.
2) Write the test class Test04, call the validateUser() method in the Register class, verify the data entered by the user, and output the verification results. The code is as follows:
import java.util.Scanner; public class Test04 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("------------User registration--------------"); System.out.println("user name:"); String username = input.next(); System.out.println("password:"); String pwd = input.next(); System.out.println("Age:"); String age = input.next(); boolean con = Register.validateUser(username,pwd,age); if (con) { System.out.println("Registration succeeded!"); } else { System.out.println("Registration failed!"); } } }
In the main() method, call the validateUser() method of the Register class to obtain a boolean variable, which indicates whether the verification has passed. When the variable value is true, it indicates that the verification is passed and the prompt message of successful registration is output; Otherwise, it means that the verification fails and the prompt of registration failure is output.
Run the program. When the registered user name is not composed of all letters, it will prompt "the user name can only be composed of letters and cannot contain spaces!" Information, as shown below.
------------User registration-------------- user name: tg_xiake password: xiake Age: 123 The user name can only be composed of letters and cannot contain spaces! Registration failed!
When the registered age is not only composed of numbers, you will be prompted with "incorrect age input!", As shown below.
------------User registration-------------- user name: admin password: admin Age: 123a Incorrect age input! Registration failed!
When the registered password is not only composed of numbers or letters, the prompt "password can only be composed of numbers or letters!", As shown below.
------------User registration-------------- user name: admin password: admin! Age: 25 The password can only consist of numbers or letters! Registration failed!
If the registered user name, password and age are verified, the output "registration succeeded!", As shown below.
------------User registration-------------- user name: admin password: admin Age: 123 Registration succeeded!
Java Boolean class
The Boolean class wraps a value whose basic type is Boolean in an object. The object of a Boolean class contains only one field of type Boolean. In addition, this class also provides many methods for the mutual conversion of Boolean and String, and provides other common methods that are very useful when dealing with Boolean.
Construction method of Boolean class
The Boolean class has the following two construction forms:
Boolean(boolean boolValue);Boolean(String boolString);
Where boolValue must be true or false (case insensitive), and boolString contains the string true (case insensitive), then the new Boolean object will contain true; otherwise, it will contain false.
Common methods of Boolean class
The Boolean class contains some methods related to Boolean operations, as shown in Table 1.
method | Return value | function |
---|---|---|
booleanValue() | boolean | Returns the value of the Boolean object with the corresponding Boolean value |
equals(Object obj) | boolean | Judge whether the object calling this method is equal to obj. true is returned if and only if the parameter is not null and represents a Boolean object with the same Boolean value as the object calling the method |
parseBoolean(String s) | boolean | Parses a string parameter to a boolean value |
toString() | string | Returns a String object representing the boolean value |
valueOf(String s) | boolean | Returns a boolean value represented by the specified string |
Example 1
Write a Java Program to demonstrate how to use different construction methods to create Boolean objects, and call the main method of Boolean value() to re convert the created objects into Boolean data output. The code is as follows:
public class Test05 { public static void main(String[] args) { Boolean b1 = new Boolean(true); Boolean b2 = new Boolean("ok"); Boolean b3 = new Boolean("true"); System.out.println("b1 Convert to boolean The values are:" + b1); System.out.println("b2 Convert to boolean The values are:" + b2); System.out.println("b3 Convert to boolean The values are:" + b3); } }
The program is very simple. The output results after running are as follows:
b1 Convert to boolean The values are: true b2 Convert to boolean The values are: false b3 Convert to boolean The values are: true
Common constants of Boolean class
The Boolean class contains many constants, among which the more common constants are as follows.
- true: the Boolean object corresponding to the base value true.
- false: Boolean object corresponding to the base value false.
- TYPE: Class object representing the basic TYPE boolean.
Java Byte class
The Byte class wraps a value with a base type of Byte in an object. The object of a Byte class contains only one field of type Byte. In addition, this class also provides methods for converting Byte and String to each other, and provides some constants and methods that are very useful when dealing with Byte.
Construction method of Byte class
The Byte class provides two construction methods to create Byte objects.
1. Byte(byte value)
The byte object created in this way can represent the specified byte value. For example, the following example takes 5 as a byte type variable, and then creates a byte object.
byte my_byte = 5; Byte b = new Byte(my_byte);
2. Byte(String s)
The byte object created by this method can represent the byte value specified by the String parameter. For example, the following example takes 5 as a variable of type String, and then creates a byte object.
String my_byte = "5"; Byte b = new Byte(my_byte);
Note: a numeric String variable must be used as a parameter to successfully create a. Otherwise, a NumberFormatException exception will be thrown.
Common methods of Byte class
The Byte class contains some methods related to Byte operation, as shown in Table 1.
method | Return value | function |
---|---|---|
byteValue() | byte | Returns a byte object with a byte value |
compareTo(Byte bytel) | int | Compares two Byte objects numerically |
doubleValue() | double | Returns the value of this Byte as a double value |
intValue() | int | Returns the value of this Byte as an int value |
parseByte(String s) | byte | Parses a String parameter into an equivalent byte form |
toStringO | String | Returns a String object representing this byte value |
valueOf(String s) | Byte | Returns a Byte object that holds the value given by the specified String |
equals(Object obj) | boolean | Compare this object with the specified object. If the object calling this method is equal to obj, it returns true; otherwise, it returns false |
Common constants of Byte class
The Byte class contains many constants, of which the more common constants are as follows.
- MIN_VALUE: the minimum value that the byte class can take.
- MAX_VALUE: the maximum value that the byte class can take.
- SIZE: the number of bits used to represent the byte value in the form of binary complement.
- TYPE: represents the Class instance of the basic Class byte.
Detailed explanation of Java System class
The System class is located in Java Lang package, representing the current Java The running platform of the program, many system level attributes and control methods are placed inside this class. Since the construction method of this class is private, the object of this class cannot be created, that is, the class cannot be instantiated.
The System class provides some class variables and class methods, which can be called directly through the System class.
Member variables of the System class
The System class has three static member variables, PrintStream out, InputStream in, and PrintStream err.
1. PrintStream out
Standard output stream. This stream is open and ready to receive output data. Typically, this stream corresponds to a display output or another output target specified by the host environment or the user.
For example, a typical way to write a row of output data is:
System.out.println(data);
The println method is a method belonging to the stream class PrintStream, not a method in the System.
2. InputStream in
Standard input stream. This stream is open and ready to provide input data. Typically, this stream corresponds to keyboard input or another input source specified by the host environment or the user.
3. PrintStream err
Standard error output stream. Its syntax is the same as system Similar to out, error messages can be output without providing parameters. It can also be used to output other information specified by the user, including the value of the variable.
Example 1
Write a Java program and use the System class described in this section to input characters from the keyboard and display them. The specific implementation code is as follows:
import java.io.IOException; public class Test06 { public static void main(String[] args) { System.out.println("Please enter a character and press enter to end the input:"); int c; try { c = System.in.read(); // Read input characters while(c != '\r') { // Judge whether the input character is enter System.out.print((char) c); // Output character c = System.in.read(); } } catch(IOException e) { System.out.println(e.toString()); } finally { System.err.println(); } } }
In the above code, system in. The read() statement reads in a character, and the read() method is a method owned by the InputStream class. Variable c must use int type instead of char type, otherwise compilation will fail due to loss of precision.
If the above program inputs Chinese characters, it will not output normally. If you want to output Chinese characters normally, you need to turn system In is declared as an instance of InputStreamReader type, and the final code in the try statement block is:
InputStreamReader in = new InputStreamReader(System.in, "GB2312"); c = in.read(); while(c != '\r') { System.out.print((char) c); c = in.read(); }
As shown in the above code, the statement InputStreamReader in=new InputStreamReader(System.in, "GB2312") declares a new object in, which inherits from the Reader. At this time, you can read the complete Unicode code and display normal Chinese characters.
Member methods of the System class
Some System level operation methods are provided in the System class. The common methods are arraycopy(), currentTimeMillis(), exit(), gc() and getProperty().
1. arraycopy() method
This method is used to copy an array, that is, copy an array from the specified source array, starting at the specified location and ending at the specified location of the target array. The method is defined as follows:
public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length)
Where src represents the source array, srcPos represents the starting position of copying from the source array, dest represents the target array, destPos represents the starting position of the target array to be copied, and length represents the number of copies.
Example 2
The following example code demonstrates the use of the arraycopy() method:
public class System_arrayCopy { public static void main(String[] args) { char[] srcArray = {'A','B','C','D'}; char[] destArray = {'E','F','G','H'}; System.arraycopy(srcArray,1,destArray,1,2); System.out.println("Source array:"); for(int i = 0;i < srcArray.length;i++) { System.out.println(srcArray[i]); } System.out.println("Target array:"); for(int j = 0;j < destArray.length;j++) { System.out.println(destArray[j]); } } }
As the above code, copy the data from subscript 1 in the array srcrarray to the position from subscript 1 in the array destArray. A total of two are copied. That is, copy srcrarray [1] to destArray[1] and srcrarray [2] to destArray[2]. After copying, the elements in the array srcrarray will not change, but the elements in the array destArray will change to E, B, C and H. The following is the output result:
Source array: A B C D Target array: E B C H
2. currentTimeMillis() method
The function of this method is to return the current computer time. The format of the time is the number of milliseconds difference between the current computer time and GMT (Greenwich mean time) at 0:0:0 on January 1, 1970. It is generally used to test the execution time of the program. For example:
long m = System.currentTimeMillis();
The above statement will get a long integer number, which is the current time expressed as a difference.
Example 3
Using the currentTimeMillis() method to display time is not intuitive, but it is easy to calculate time. For example, the following code can be used to calculate the time required for the program to run:
public class System_currentTimeMillis { public static void main(String[] args) { long start = System.currentTimeMillis(); for(int i = 0;i < 100000000;i++) { int temp = 0; } long end = System.currentTimeMillis(); long time = end - start; System.out.println("Program execution time" + time + "second"); } }
The value of the variable time in the above code represents the number of milliseconds required for the execution of the for loop in the code. This method can be used to test the execution efficiency of programs with different algorithms, and can also be used to realize the precise delay during thread control in the later stage.
3. exit() method
This method is used to terminate the currently running Java virtual machine. The specific definition format is as follows:
public static void exit(int status)
When the value of status is 0, it indicates normal exit, and when it is non-zero, it indicates abnormal exit. Using this method, the exit function of the program can be realized in the graphical interface programming.
4. gc() method
The function of this method is to request the system to recycle garbage and complete the garbage removal in memory. Whether the system recycles immediately depends on the implementation of the garbage collection algorithm in the system and the execution of the system. It is defined as follows:
public static void gc()
5. getProperty() method
This method is used to obtain the value corresponding to the attribute named key in the system. The specific definitions are as follows:
public static String getProperty(String key)
The common attribute names and descriptions of attributes in the system are shown in Table 1.
Attribute name | Attribute description |
---|---|
java.version | Java runtime environment version |
java.home | Java installation directory |
os.name | The name of the operating system |
os.version | Operating system version |
user.name | User's account name |
user.home | User's home directory |
user.dir | User's current working directory |
Example 4
The following example demonstrates the use of the getProperty() method.
public class System_getProperty { public static void main(String[] args) { String jversion = System.getProperty("java.version"); String oName = System.getProperty("os.name"); String user = System.getProperty("user.name"); System.out.println("Java Runtime environment version:"+jversion); System.out.println("The current operating system is:"+oName); System.out.println("The current user is:"+user); } }
Run the program, and the output results are as follows:
Java Runtime environment version: 1.6.0_26 The current operating system is: Windows 7 The current user is: Administrator
Tip: many system level parameters and corresponding values can be obtained by using the getProperty() method. There are no more examples here.