Introduction to Java lang package


Java.lang provides the basic classes of java language programming (package classes of basic data types, Class, math, and thread classes). The application of classes in the lang package does not require manual import.
1. The Object class is the parent class of all classes in the Java system

Methods implemented by Object: clone (can be called only if the Cloneable interface is implemented); getClass, toString, hashCode, equals, finalize (release resources), wait, notifyAll, notify.

2. Encapsulation class of basic data types
8 basic data types in java:
1) Integer byte: 8 bits, -128~127; short: 16 bits, -32768 ~ 32767; int: 32 bits, -2^31-1~2^31 (2.1 billion); long: 64 bits.
2) Floating point type (float, double): float: 32 bits, suffix F or f, 1 sign bit, 8 bits exponent, 23 bits significant mantissa; double: 64 bits, most commonly used, suffix D or d, 1 bit Sign bit, 11-bit exponent, 52-bit effective tail.
3) Character type (char): char: 16-bit, is an integer type, 0~2^16-1 (65535). Cannot be 0 characters. 
4) A boolean type: true and false.
  char--> automatic conversion: byte-->short-->int-->long-->float-->double cast will not be rounded
. Basic data type encapsulation class: In order to automatically convert basic data type values Into the corresponding object, java1.5 introduced the automatic boxing and unboxing mechanism (for example, the collection does not support the basic data type, but can directly put the basic data type; when the method is called).
Automatic boxing: the compiler calls valueOf();
unboxing: manually calling intValue(), doubleValue().
Disadvantages of automatic boxing:
1), generate a large number of unnecessary objects
Integer sum = 0;
 for(int i=1000; i<5000; i++){
   sum+=i;
}
2) For object equality comparison, JVM will cache Integer objects from -128 to 127, so the following obj1==obj2
Integer obj1 = 1;
Integer obj2 = 1;
all encapsulated classes cannot be inherited.
The math package Bigdecimal: used for amount calculations (both float/double will lose a certain precision).
BigDecimal b1 = new BigDecimal("1.34");//1.34  
double d=1.01;
BigDecimal b2 = BigDecimal.valueOf(d);//1.34  
BigDecimal operations do not operate on the original value, but return a new BigDecimal object.
The comparison of BigDecimal uses the compareTo method of BigDecimal.
3. Math
Common methods: floor, ceil, round (returns an integer value) Math.round(5.2644555 * 100) * 0.01d; supports rounding to the specified exact number of digits.
Random number: Math.random()[0,1.0) double type number. The util package Random under the
util package:
Random rand =new Random(25);
rand.nextInt(100); does not include the maximum value.
Decimals in the interval [0,1.0): double d1 = r.nextDouble();
Decimals in the interval [0,5.0): double d2 = r.nextDouble() * 5;
4. String
String objects are stored in the constant pool and heap. When they appear in quotation marks, they are stored in the constant pool like basic type data. New String objects are stored in the heap.
For example: String str1 = "ab" + "cd"; <=>String str1 = "abcd"; Create an object in the constant pool.
final String s1 = "b"; String s2 = "a" + s1; Note that variables modified by final are also stored in the constant pool s2=="ab".
String's substring (int beginIndex, int endIndex) value range [beginIndex, endIndex) starts from 0
The difference between String, StringBuffer, and StringBuilder
(1) String is an immutable string object.
(2) String thread safety. The methods and functions in StringBuffer and StringBuilder are completely equivalent. The methods in StringBuffer are modified with the synchronized keyword, which is thread-safe, while StringBuilder is not thread-safe without this modification.
(3) The execution efficiency of String, StringBuilder, and StringBuffer: StringBuilder > StringBuffer > String Of course, this is relative, not necessarily in all cases. For example, String str = "hello"+ "world" is more efficient than StringBuilder st = new StringBuilder().append("hello").append("world"). Therefore, these three classes have their own advantages and disadvantages, and should be selected and used according to different situations: when strings are added or changed less, it is recommended to use the form of String str="hello"; In the case of many addition operations, it is recommended to use StringBuilder, and if multi-threading is used, StringBuffer is used.
Five, System
The constructor of the System class is modified by private and is not allowed to be instantiated. The methods in a class are also static methods with static modification.
1) Three objects: InputStream in;//Standard input stream PrintStream out;//Standard output stream PrintStream err;//Standard error stream. Such as System.out.println();
2) Common methods: arraycopy (copied array, starting position, copied to array, starting position, copy length); array copy;
currentTimeMillis() and getTime methods in Date class are completely is the same;
gc() garbage, recycling must not be called manually;

exit() exits the virtual machine, the method never returns normally. This is the only case where it is possible to exit the program without executing the finally.

6. Exception

1. The java exception mechanism provides try, catch, and finally.
Such as: try
{//Exception code that needs to be detected}
catch(Exception e)
{//Exception handling, that is, handling exception code}
finally
{//Code that will be executed}
1) try and catch can be nested;
2) Try and catch must exist at the same time;
3) A try can have multiple catches;
4) The code of finally will be executed, and before the try returns quickly;
5) I haven't thought about it yet.
At the same time, the throw and throws keywords are also provided. You can use the throw keyword to throw an exception at any position of try and catch. Throws is the exception that the code will throw at the end of the method declaration.
2. All exceptions in the java exception class
inherit from Exception. We can also create custom exceptions, but we must inherit Exception, add a constructor, and use supper to call the parent class constructor.
3. Common exceptions
Error:
ClassFormatError The Java virtual machine attempts to read a Java class from a file, and it is thrown when it detects that the content of the file does not conform to the valid format of the class;
OutOfMemoryError When the available memory is not enough for the Java virtual machine to allocate to This error is thrown when an object is thrown.
CheckException:
IOException
SQLException
ClassNotFoundException
FileNotFoundException
InterruptedException
TimeoutException
CloneNotSupportedException
FileAlreadyExistsException
UnknownHostException
RuntimeException:
NullPointerException - Null pointer reference exception
IndexOutOfBoundsException - Subscript out of bounds exception
ArithmeticException - Arithmetic operation exception
ClassCastException - Type casting exception.
IllegalArgumentException - Illegal argument passed exception.
ArrayStoreException - Storing an object into an array that is incompatible with the declared type Exception
NegativeArraySizeException - Creating an array of negative size Error Exception
NumberFormatException - Number format exception
SecurityException - Security exception
UnsupportedOperationException - Unsupported operation exception

七、Thread









Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325152487&siteId=291194637