Introduction to Java Basic Class library

Source: Internet
Author: User

As we have said, Java has compiled many classes for programmers that have been tested and basically without errors, and these classes are the basis of our programming. If we don't take advantage of these existing classes, our programming will become extremely complex, so we should master the contents of the Java base Class library as much as possible. This chapter and the next chapter will introduce readers to the Java Basic class library structure and some common classes and how to reference Java technical documentation, so that readers can further improve their

Learning Focus

Concept of the Package

Several basic classes in the Java.lang

How to read Java technical documentation

Common tool Classes

The eighth Chapter Java Basic Class Library introduction

8.1 Concept of the package

A package is a collection of. class files that can be used in Java to interpret the files that it interprets to execute, which is also generated by the Java source file, the. java file, which is compiled. Java is an object-oriented language that is characterized by reuse, which is a tool for organizing and managing. class files, so it exists to help us implement code reuse. A package is a loosely-structured concept, in general, where functionally identical or related classes are organized in a package, such as the classes in the Java.io package are related to input and output, and the classes in the Java.applet package are related to applet programs.

8.1.1 Building Packages

A package is actually a folder in which the. class file is stored. Packages can be structured like a directory structure, and each layer is "." To separate, such as Java.io,java.awt,java.awt.color. Because Java classes often need to run on the Internet, it is possible to have classes with the same name, and the program will not know which class to use. However, if you put the class in a different package and make the package name unique, there will be no confusion.

The program defines the keyword package, which is in the following format:

Package Name:

For example:

Package Myjavaprogram;

Package Cn.com.companyname.myname

This statement must be placed in the first sentence of a source file, and there are no spaces before the statement. The package name is generally in lowercase. We know that a source file may have multiple classes, where only one class is public, and these classes are compiled to produce a. class file, which means that the class in the source file, compiled by a. class file, belongs to a package named Myjavaprogram. This defines the Myjavaprogram package. In general, the source files to be packaged are placed in the package, and then the source files are compiled in the package, the. class file is put into the package. Of course the Javac compiler also has several parameters that can be implemented to determine the source file source and. class file placement, and so on, you can implement the source file and the. class file are not in the same directory. Here are the various parameters and their explanations.

-G generates all debug information

-g:none does not generate any debug information

-g:{lines,vars,source} only generates partial debug information

-O Optimization

-nowarn does not generate a warning

-verbose output compiler's working record

-deprecation output the location of all outdated APIs

-classpath<path> declaring the path to the User class library

-sourcepath<path> declaration find the path to the source file

-bootclasspath<path> overriding the Boot class file path

-extdirs<dirs> Overwrite Installation extension path

-d<directory> declares where to put the generated. class file

-enconding<encoding> How the source file is encoded

-traget<release> generating class files for a virtual machine that is not a specified version

8.1.2 a reference to a package

Using the import statement, you can introduce the required public classes, such as:

Import java.io.*;

This statement indicates that all public classes in java.io are introduced into the current package. The system first follows the path of Classpath, and then finds the desired class according to the package name, such as Classpath for C:\package\mypakage, and the package name Cn.com.companyname.myname. The system follows the following path to find the desired class: C: \package\mypackage\cn\com\companyname\myname, which is to connect the environment variable to the package name, form the path, and then look for the class under this path. For the Java class Library, you do not need to add classpath because the path has been automatically registered at the time of installation, and you must change classpath to use classes in your own defined package.

There is also a way to use a class in a package, which is to write all its package names in the program, but it is cumbersome and does not use import statements, such as:

Java.io.FileInputStream in = new Java.io.FileInputStream ();

If we use most of the classes in a package, but use wildcards to refer to packages, it is better to list the required classes, which can save a lot of system resources.

8.2 Structure of the Java language class library

Java 2 Platform Class Library 1.3.1 version of a total of 76 packages for programmers, each package is responsible for different functions, in addition to Java.lang, the contents of other packages as long as the import statement is referenced, you can use in the program. All of these classes are introduced and used, and Java provides extremely well-developed technical documentation, which frees up programmers to put more time into the design of objects rather than syntax and some local algorithms.

To make it easier for the reader to use the Java documentation, we introduce the packages provided by Java, which can be consulted according to your needs. Where the package name is followed by a ". *" representation which includes a series of related packages.

Table 8.1 Java-provided packages

Package Name Content Introduction

Java.applet provides the classes needed to create applets, including the communication classes that help applets access their content

JAVA.AWT.* provides classes for creating a user interface and drawing, managing graphics, images

Java.beans.* provides the classes needed to develop Java beans

The java.io provides system input and output through data streams, object sequences, and file system implementations.

Java.lang.* Basic class libraries for Java programming languages

Java.math provides concise arithmetic of integers and basic functions of decimal math

Java.net provides all the classes used to implement network communication applications

JAVA.RMI.* provides all classes related to remote method calls

Java.security.* provides the classes needed to design a network security scenario

JAVA.SQL provides access to and processing of classes from Java standard data source data

Java.text provides classes and interfaces for handling messages that are text, date, number, and syntax independent of natural language formatting

Java.util.* includes collection class, event processing mode, date Time tool and other common tools

Javax.accessibility defines a mechanism for mutual access between user interface components

javax.naming.* Unnamed service provides a range of classes and interfaces

Javax.rmi.* provides users with an application interface for remote method calls

JAVAX.SOUND.* provides the classes and interfaces required for MIDI input, output, and compositing

Javax.swing.* provides a series of lightweight user interface components that are commonly used in the current Java UI.

Introduction to common classes in 8.3 Java.lang package

This package is the most basic Java language package, without the class in this package, our programming is very difficult, they are the most basic content of programming. All classes in this package are automatically introduced by the system, so the program can use any one of these classes without an import statement. This package has 4 parts: interfaces, classes, exceptions, and errors.

8.3.1 Object class

The object class is the direct or indirect parent of all classes in a Java program and the parent class of all classes in the class library, and any class is derived from the object class, which is the root node on the inheritance tree. So it contains the properties and methods that will be inherited by all classes, the following is the method of the object class, and the method that all classes contain:

Protected Object Clone () throws Clonenotsupportedexception

Generates a copy of the current object and returns the copied object, which is object type, but all classes that need to use the method must implement interface cloneable, otherwise the runtime throws an exception to the Clonenotsupportedexception class.

Public final Class GetClass ()

Returns a class class object for the current object at run time.

public int hashcode ()

Returns a hash code value, with different objects having different hash code value.

Public Boolean equals (Object obj)

Returns true if the current object is the same as the parameter object, otherwise false.

Public String toString ()

Returns a string that reflects this object's information, typically making the object belong to a class.

Public final void Notify ()

This is a method of multithreading, which is used to wake up one of the multiple threads that are waiting on the monitor

Public final void Notifyall ()

This method is to wake up all the threads waiting for the monitor

Public final void Wait (long timeout) throws Interrupedexception

The method is to let the current thread discard the declaration of the object's synchronization, that is, to discard the lock on the object, enter the waiting column until the Notify () or Notifyall () method wakes up, or the time specified in the parameter expires, the unit of timeout is milliseconds.

Public final void Wait (long Timeout,int Nanos) throws Interrupedexception

This method has one more parameter than the previous, the second parameter means nanoseconds (One-zero seconds), and the wait time of this method becomes the same as the time indicated by the two parameters, and the time control is more accurate.

Public final void Wait () throws Interrupexception

The meaning of this method is the same as wait (0)

protected void Finalize () throws Throwable

This method is used to clear the object from memory and is automatically called by the rubbish collector, which can be overloaded by the programmer to display some information when the object is cleared.

8.3.2 class

Class is very special, and its objects will be accompanied by each class. When a class X is compiled, a special object (class object) is generated, which is hidden in the X.class file, and the class object is generated automatically by the compilation system.

For the reader to further understand when the class is loaded into memory, let's look at an example:

Example 8.1 Time of loading in class

The source files for Sweetshop.java are as follows:

Class candy{

static{

System.out.println ("Loading Candy");

}

}

classgum{

static{

System.out.println ("Loading Gum");

}

}

Class cookie{

static{

System.out.println ("Loading Cookie");

}

}

public class sweetshop{

public static void Main (string[] args) {

SYSTEM.OUT.PRINTLN ("Inside main");

New Candy ();

System.out.println ("After creating Candy");

try{

Class.forName ("Gum");

}catch (ClassNotFoundException e) {

E.printstacktrace ();

}

System.out.println ("After Class.forName (\" gum\ ")");

New Cookie ();

System.out.println ("After creating Cookie");

}

}

This program first defines 3 classes, each with only one static initializer, since the static initializer is executed when the class is loaded into memory, so it can be used to indicate when the class is loaded into memory. Then enter a certain hint before each object is created, so that we can see exactly when each class is loading memory. Class.forName ("Gum") in the procedure, see the following section for further explanations of the basis. The program output is as follows:

Inside Main

Loading Candy

After creating Candy

Loading Gum

After Class.forName ("Gum")

Loading Cookies

After creating cookies

As can be seen from the above results, the loading of classes is at the time of object creation.

This special class object contains all the information of the owning class, which can be extracted by means of the class class, and we will introduce some methods of class.

public static Class forname (String className) throws ClassNotFoundException

This method is a static method, so call directly with class, the format can refer to the above example. The parameter of this method is a class name, and the return value of the method is the class object of the classes indicated by the formal parameter. The result of this method is to produce a class object that is represented by a formal parameter. Such as:

Class T=class.forname ("Java.lang.Thread")

Public String GetName ()

The method returns the name of the entity (class, interface, array, base data type, and so on) represented by the class object. For example, (new Object ()). GetClass (). The value of GetName () is Java.lang.Object, and of course it can be output in a println () statement. The GetClass () is used to get the class object of the current object, which has the same class object as the object of the same classes.

GetName () returns a String that represents the entity's information in different letters and symbols, "[" represents an array, has several "[" representations of several dimensional arrays, the following letters represent different data types, and "L" represents a class or interface.

Let's look at a few more examples:

(New Object[3]). The value of Getclass.getname () is "[Ljava.lang.Object", which indicates that the current class object corresponds to a one-dimensional array, and that the array element is an object of the Java.lang.Object class.

(New Int[3][4][5][6][7][8][9]). The value of GetClass (). GetName () is "[[[[] [[[I], which indicates that the current class object corresponds to a seven-dimensional array, and the array element is a simple variable of type int.

Public Class Getsuperclass ()

This method is different from the method GetClass () of the object class, which returns an array of class objects that are instances of the class class that are members of the current class that correspond to the public or interface.

Public ClassLoader getClassLoader ()

ClassLoader is an abstract class in the Java.lang package. Any class that loads memory is implemented by an object that is an instance of its derived class, because the definition of a class is the existence of a byte-code file, and loading a class reads those bytecode.

Public Class Getcomponenttype ()

Returns the type of the array member, or null if the current object is not an array.

public int getmodifiers ()

Returns modifiers for a class or interface, such as public,protected,private,final,static and abstract, but they are represented by an int number, for example: public is 0x0001,final to 0x0010, Abstract as 0x0400, these numbers are represented in hexadecimal and are used by Java virtual machines to identify the modified pragmatic

Public Class Getdeclaringclass ()

If the current object is a member of another class, it returns the class object of that category, otherwise it is empty.

8.3.3 Math Class

The Math class is a final class, and the class header definition is: Public final class Math extends Object. It contains common scientific methods of calculation. These methods are static methods that can be called directly through the class name. Here we list the definitions of the properties and methods that are commonly used:

public static final Double E

public static final Double PI

Trigonometric function:

public static double sin (double A)

public static double cos (double a)

public static double tan (double A)

public static double Asin (double A)

public static double ACOs (double A)

public static double Atan (double A)

The radians and angles are converted as follows:

public static double Toradians (double angdeg)

public static double Todegrees (double Angrad)

Algebraic functions:

public static double exp (double A)

public static double log (double A)

public static double sqrt (double A)

public static double Ceil (double A)

public static double floor (double a)

public static double Random ()

The following 3 methods have overloaded methods for other data types:

public static int abs (int a)

public static int max (int a,int b)

public static int min (int a,int b)

8.3.4 string and StringBuffer class

Java provides two classes for string manipulation, one that is frequently used, and the other is StringBuffer. The string class provides a rich string manipulation method that allows programmers to easily use these common algorithms and operations without having to repeat them themselves, which is the object-oriented benefit.

1. Why two classes are used

The string class is used with strings that do not change the values, and string variables in the previous program are all strings whose values have not changed. The StringBuffer class is used for processing of strings that may change. For example, stitching a string in a program, reading a string from a file, and so on. Because the string class object is constant, its processing efficiency is much higher than the StringBuffer class object, so the reader uses the string class whenever possible.

Let's look at a simple example that uses both string and Stringbukffer,

Example 8.2 using two different string classes to reverse a string

The Stringdemo.java test source program is as follows:

public class stringdemo{

public static void Main (string[] args) {

String palindrome= "Dot saw I was Tod";

int Len=palindrome.length ();

StringBuffer dest=new StringBuffer (len);

for (int i= (len-1); i>=0;i--) {

Dest.append (Palindrome.charat (i));

}

System.out.println (Dest.tostring ());

}

}

In this program, we first create a string class object and assign the string "Dot saw I was Tod" to it, and then create a StringBuffer class object as long as it does. Use it to reverse the process. The execution of this program is interesting, in fact, the input string is almost the same (except for the first letter of the capitalization problem), namely:

DoT SW I was ToD

2. Creation of objects

In general, creating a string takes a method that assigns a value directly to a string object, with a value enclosed in double quotation marks, such as:

String palindrome= "Dot saw I was Tod";

Of course, you can create a new string object just as you would any other object, and Java provides several more common construction periods for string. For example, using a character array or StringBuffer, the following is a case of creating a string object using a character array:

Char[] helloarray={' h ', ' e ', ', ' l ', ' l ', ' o '};

String Hellostring=new string (Helloarray);

System.out.println (hellostring);

3. Common methods of string

The common methods of string are as follows:

public int Length ()

return string length

public char charAt (int index)

Returns the character of the index position, index from 0 to length ()-1

public void GetChars (int srcbegin,int srcend,char[] Dst,int dstbegin)

The method is to copy the characters in the string into a character array

Public Boolean equals (Object anobject)

This is an overload of the same method in the object class

public int CompareTo (String anotherstring)

This is the method implemented in the serializable interface, which returns a negative number if the actual string is in the dictionary when compared to the formal parameter string, and the inverse is a positive number.

Public Boolean startsWith (String prefix)

Public Boolean endsWith (String suffix)

The above two methods determine whether a string starts or ends with a formal parameter character, respectively.

public int indexOf (int ch)

The method returns the position of the character indicated by the first occurrence of the parameter in the string, or 1 if there is no character.

public int indexOf (int ch,fromindex)

Starting from Fromindex, returns the position of the first CH character, or returns-1.

public int lastIndexOf (int ch)

Returns the position of the last ch character in a string or-1.

Public String Substring (int beginindex)

Returns a new string that is formed from beginindex in the current string.

Public String substring (int beginindex,int endIndex)

Returns the new string intercepted from the current string, Beginindex is the start bit, and Endindex is the end bit minus 1.

public string concat (String str)

After the parameter string is concatenated to the current string, the addition operation of the string is the method.

Public String replace (char Oldchar,char Newchar)

Change all the same characters in the string to another one.

4. Common methods of StringBuffer

Since the StringBuffer class is a mutable string, all its operations focus on changes to the string, so it first describes its append () and insert () methods, both of which have multiple overloaded methods for different operations.

Public StringBuffer append (String str)

You can tell from the method name that this is a method of extending the string, which is the function of adding the parameter string to the current string, forming a new mutable string. For example:

StringBuffer new StringBuffer ();

S.append ("Start");

S.append ("le");

The result of the above statements is to get a mutable string containing "startle".

Public stringbuffer Insert (int offset,string str)

This method inserts a parameter string into the current string, forming a new mutable string. Where the parameter offset is the offset, which indicates where to insert, 0<=offset<=length ().

Some other common methods of this class are described below:

Public StringBuffer Delete (int start,int end)

Removes the character between start (including) and end (not included).

Public stringbuffer deletecharat (int index)

Deletes the character at the specified position.

Public stringbuffer replace (int start,int end,string str)

The string from start (inclusive) to end (not included) is replaced by Str.

public void Setcharat (int index,char ch)

Change the character at the specified position

Public StringBuffer Reverse ()

Make string reversal

public int Length ()

Returns the number of characters

public int Capacity ()

Return capacity, usually greater than or equal to length ()

public void setLength (int newlength)

Change the number of characters, if the newlength is greater than the original number, the newly added characters are empty (""). Instead, the best few characters in the string are removed. The formal parameter newlength cannot be negative.

Public String substring (int start,int end)

Extracts a substring and returns a String class object.

Public String toString ()

Changes the contents of a mutable string into a String class object. In fact, this method is called automatically when you print variable string content with println.

In the string class and the StringBuffer class, it is worth noting that the parameters used in many methods are used to indicate the position in the string, assuming that the parameter is an int index, then the first character of the string has an index value of 0, a second character of 1, and so on.

8.3.5 System Class

The System class is a unique class, it is a final class, all methods are called with class variables, in other words, no one can instantiate a system class. The system class mainly provides standard input, output, and some information about the environment.

1. Standard input and output

public static final InputStream in--standard input

This property is an object of the Inputsream class, about the InputStream class and the PrintStream class below we introduced in the Java.io package, these classes are about the input, output aspects, they have their own properties and methods, we used the Read () Is the method of the InputStream class, println () and print () are the methods of the PrintStream class.

public static final PrintStream out--standard output

public static final PrintStream err--standard error output

These input and output properties can be derived from the converted output format based on the parameters they use, and the following example prints data of several common data types using the Println method, but the system can print the values of the data differently depending on the type.

Example 8.3 printing of various types of objects with standard output

The source program for Datatypeprinttest.java is as follows:

public class datatypeprinttest{

public static void Main (string[] args) {

Thread objectdata=new thread ();

String stringdata= "Java Mania";

Char[] chararraydata={' A ', ' B ', ' C '};

int integerdata=4;

Long Longdata=long.min_value;

float Floatdata=float.max_value;

Double Doubledata=math.pi;

Boolean booleandata=true;

System.out.println (Objectdata);

System.out.println (StringData);

System.out.println (Chararraydata);

System.out.println (Integerdata);

System.out.println (Longdata);

System.out.println (Floatdata);

System.out.println (Doubledata);

System.out.println (Booleandata);

}

}

The output is:

Thread[thread-0,5,main]

Java Mania

Abc

4

-9223372036854775808

3.4028235E38

3.141592653589793

True

We notice that printing a string variable, the system's action is to print out its contents, and print a thread type variable, the system prints its format is:

class name [name, priority, Group]

2. System Environment Information

The system class provides a way for you to return information about the systems environment:

public static Properties getProperties (argument);

The Java Virtual Machine maintains a series of system environment information, all in the form of a "key name/value" pair, and once the Java Virtual machine is started, the system automatically initializes these variables, which contain a lot of information related to the running environment.

In addition, the system class provides methods that are related to the information about the environment:

public static string SetProperty (string key,string value);

Sets the value of the system variable, key is the name, and value is the key value.

public static Properties getporperties ();

Returns all the system environment environments.

Here is an example, assuming there is a text file called MyProperties.txt, where there is only one line:

Subliminal.message=buy Java now!

We use this file to set the variable, whose name is subliminal, and its value is the content stored in the text file.

3. Other useful methods

The system class has a number of ways to manage the operation of the Java Virtual machine and to obtain the running information of the virtual machine, and here are several methods of the class that reflect some of the functions of the system class.

public static long Currentimemillis ()

Returns the system time, in milliseconds.

public static void exit (int status)

Force shutdown of the Java Virtual Machine and pass state information status to the operating system until the user's program has finished executing, which indicates an abnormal exit

public static void Ge ()

Run the garbage collector

The above content allows us to have a certain understanding of the contents of the System class, the properties and methods in this class are related to systems, and many of the methods of this class have borrowed methods from other classes.

8.3.6 data Type class

Each class of simple data types corresponds to a data type class, for example, int corresponds to an integer class, and double corresponds to a double class, which encapsulates a simple data into a class. Some occasions must use this data type class, such as the following collection class, whose members must be classes, not simple variables. And using these classes can do the work that simple variables cannot do, such as converting a numeric string into an integer, and so on. Let's describe some of the methods of these classes in an integer class.

The Max_value and Min_value specify the maximum and minimum values for the int type amount.

Constructor: public integer (int value) and public integer (string s) encapsulate the numeric and numeric strings into an integer class, respectively.

The following methods convert the int amount corresponding to the object of the current data type class to a value of a basic data type:

public int intvalue ()

Public long Longvalue ()

Public double Doublevalue ()

The following is a conversion between a numeric string and a number:

Public String toString ()

public static int parseint (String s)

The public static static integer valueOf (String s) method transforms S into an integer class object.

8.4 Technical documentation for Java

The above is a certain understanding of the contents of the package, which studies the class library in Javadoc.

After downloading J2sdk-1_3_1-doc, locate the Docs folder under it, open the index file (HTML file), and find the Java2 platfrom API under Api&language documentation Specificaion, then select the package you want, and then look at the classes, interfaces, and so on. Or go directly to the API folder under the Docs folder, open index (HTML file), or go to the Select package interface.

After selecting a package, you can see the package name and a simple description, then the contents of the package, divided into interface Summary,class summary,exception Summary and error summary, if you want to see the various types of inheritance structure in the package, You can select the tree in the top menu to see the overall structure in the package. When you select a class to enter, you can see the following (Description of the Double Class):

Java.lang//Package name

Class.double//Class name

Java.lang.Object//Inheritance structure: the direct parent class of the double class in the Java.lang package

| is the number class in Java.lang

The parent class of the +--java.lang.number//number class is the object class in Java.lang

|

+--java.lang.double

All implemented Interfaces://interface implemented by this class

Comparable,serializable

Then there is an overview table (summary) of properties, methods, constructors, and finally a detailed description of the properties, methods, and constructors.

Introduction to Java Basic Class library

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.