Internship Training--java Foundation (2)

Source: Internet
Author: User
Tags modifiers

Internship Training--java Foundation (2)

1 Java variable types

In the Java language, All variables must be declared before they are Used. The basic format for declaring variables is as Follows:

Type identifier [= value][, identifier [= value] ...];

Format description: type is a Java data type. Identifier is the variable Name. You can declare multiple variables of the same type by separating them with Commas.

The following is a list of the declaration instances for some Variables. Note that some of the initialization procedures are Included.

int a, b, c;         // declares three integers of type int: a, b, c int // declares three integers and assigns an initial value byte z =;         // declaring and Initializing Z String s = "runoob";  // declaring and initializing the string s Double // a double-precision floating-point variable pi is declared char x = ' x ';        // the value of the declared variable x is the character ' x '. 

The types of variables supported by the Java language are:

    • Class variable: A variable that is independent of the method and is decorated with static.
    • Instance variable: A variable that is independent of the method, but has no static adornment.
    • Local Variable: A variable in a method of a class.

Example

 public class variable{    staticint allclicks=0;    // class Variables      String str= "hello world";  // instance variable      public void method () {         int i =0;  // Local Variables      }}
1.1 Java Local variables
    • A local variable is declared in a method, a construction method, or a block of statements;
    • Local variables are created when methods, construction methods, or block of statements are executed, and when they are executed, the variables are destroyed;
    • Access modifiers cannot be used for local variables;
    • A local variable is only visible in the method, construction method, or block of statements that declares it;
    • Local variables are allocated on the STACK.
    • The local variable has no default value, so the local variable is declared and must be initialized before it can be used.
Instance

In the following instance, age is a local variable. Defined in the Pupage () method, its scope is limited to this method.

Package yqq.study;

public class Test {
public void Pupage () {
int age = 0;//initialization will error
Age = Age + 7;
System.out.println ("puppy Age is:" + ages);
}

public static void main (string[] Args) {
Test test = new test ();
Test.pupage ();
}

}

1.2 Instance Variables
    • Instance variables are declared in a class, but outside of methods, construction methods, and statement blocks;
    • When an object is instantiated, the value of each instance variable is then determined;
    • Instance variables are created when the object is created and destroyed when the object is destroyed;
    • The value of the instance variable should be referenced by at least one method, construct method, or statement block, so that the external can obtain instance variable information through these methods;
    • Instance variables can be declared before use or after use;
    • An access modifier can modify an instance variable;
    • Instance variables are visible to methods, construction methods, or block statements in a class. In general, you should set the instance variable to Private. By using the access modifier, The instance variable is visible to the child class;
    • The instance variable has a default Value. The default value for a numeric variable is 0, the default value for a Boolean variable is false, and the default value for the reference type variable is Null. The value of a variable can be specified at the time of declaration, or it can be specified in a constructor method;
    • Instance variables can be accessed directly from the variable Name. however, in static methods and other classes, you should use the fully qualified name: Obejectreference.variablename.
Instance
ImportJava.io.*; public classEmployee {//This instance variable is visible to the child class     publicString name; //private variable, only visible in this class    Private Doublesalary; //assigning a value to name in the constructor     publicEmployee (String Empname) {name=empname; }    //set the value of the salary     public voidSetsalary (DoubleEmpsal) {salary=empsal; }    //Printing Information     public voidprintemp () {System.out.println ("name:" +name); System.out.println ("salary:" +salary); }     public Static voidmain (String args[]) {Employee empone=NewEmployee ("yqq"); Empone.setsalary (1000.000);    Empone.printemp (); }}
1.3 Class variables (static variables)
    • Class variables, also known as static variables, are declared in the class with the static keyword, but must be outside the method construction method and statement Block.
    • No matter how many objects a class creates, the class has only one copy of the class Variable.
    • Static variables are seldom used except when declared as Constants. Constants are variables declared as public/private,final and static Types. Constants cannot be changed after Initialization.
    • Static variables are stored in a static storage Area. are often declared as constants, and static declaration variables are seldom used ALONE.
    • Static variables are created at the beginning of the program and are destroyed at the end of the Program.
    • has similar visibility to instance Variables. however, in order to be visible to the consumer of a class, most static variables are declared as public types.
    • The default value is similar to the instance Variable. The default value for numeric variables is 0, the boolean default is false, and the reference type default value is Null. The value of a variable can be specified at the time of declaration, or it can be specified in a constructor method. In addition, static variables can be initialized in static statement blocks.
    • Static variables can be accessed by:classname.variablename .
    • Class variable names are generally recommended to use uppercase when the class variable is declared as public static final Type. If the static variable is not public and final, it is named in the same way as the instance variable and the local Variable.
ImportJava.io.*; public classEmployee {//salary is a static private variable    Private Static Doublesalary; //department is a constant     public Static FinalString DEPARTMENT = "developer";  public Static voidmain (String Args[]) {salary= 10000; System.out.println (DEPARTMENT+ "average salary:" +salary); }}

2 Java Modifiers

In java, you can use access controls to protect access to classes, variables, methods, and construction methods. Java supports 4 different kinds of access Rights.

The default, also known as default, is visible within the same package and does not use any Modifiers.

private, specified with the private modifier, visible within the same class.

common, specified with the public modifier, visible to all Classes.

protected, specified with the protected modifier, visible to classes and all subclasses within the same package.

We can use the following table to illustrate access rights:

Access control
modifier Current Class in the same package descendant class Other Packages
public Y Y Y Y
protected Y Y Y N
default Y Y N N
private Y N N N
static modifier
    • Static variables:

      The static keyword is used to declare static variables that are independent of an object, regardless of how many objects a class instantiates, and its static variables have only one copy. Static variables are also known as Class Variables. A local variable cannot be declared as a static variable.

    • Static method:

      The static keyword is used to declare an object-independent method. Static methods cannot use non-static variables of a class. The static method obtains the data from the parameter list and then computes the Data.

Access to class variables and methods can be accessed directly using classname.variablename and classname.methodname .

The static modifier is used to create class methods and class variables, as shown in the following example.

 packageyqq.study; public classInstancecounter {Private Static intnuminstances = 0; protected Static intGetCount () {returnnuminstances; }    Private Static voidaddinstance () {numinstances++;    } instancecounter () {instancecounter.addinstance (); }     public Static voidmain (string[] arguments) {System.out.println ("starting with" + instancecounter.getcount () + "instances");
Inntancecounter.getcount () No new, can also be used directly for(inti = 0; I < 500; ++I) {NewInstancecounter (); } System.out.println ("Created" + instancecounter.getcount () + "instances"); }}

3 Read and write files

is a Class-level diagram that describes the input stream and the output Stream.

Instance

Here is an example demonstrating the usage of InputStream and outputstream:

ImportJava.io.*;  public classfilestreamtest{ public Static voidmain (String Args[]) {Try{      byteBwrite [] = {11,21,3,40,5}; OutputStream OS=NewFileOutputStream ("test.txt");  for(intx=0; X < bwrite.length; X + +) {os.write (bwrite[x]);//writes the bytes} os.close (); InputStream is=NewFileInputStream ("test.txt"); intSize =is.available ();  for(inti=0; i< size; i++) {System.out.print (Char) Is.read () + "");    } is.close (); }Catch(ioexception e) {System.out.print ("Exception"); }    }}

The above program first creates the file Test.txt and writes the given number in binary form into the file and outputs it to the Console.

The above code is written by the binary, there may be garbled, you can use the following code example to solve the garbled problem:

//file name: Filestreamtest2.javaImportJava.io.*; public classFileStreamTest2 { public Static voidMain (string[] Args)throwsIOException {File F=NewFile ("a.txt"); FileOutputStream FOP=NewFileOutputStream (f); //Build FileOutputStream object, file does not exist automatically newOutputStreamWriter writer=NewOutputStreamWriter (fop, "UTF-8"); //build the OutputStreamWriter object, parameters can specify the encoding, default is the operating system default encoding, Windows is GBKWriter.append ("chinese input"); //Write to BufferWriter.append ("\ r \ n"); //line BreakWriter.append ("中文版"); //Flush Cache punch, write to file, if no content is written below, direct close also writesWriter.close (); //the write stream is closed and the buffer contents are written to the file, so the comment aboveFop.close (); //turn off the output stream and release system resourcesFileInputStream FIP=NewFileInputStream (f); //Building FileInputStream ObjectsInputStreamReader Reader=NewInputStreamReader (fip, "UTF-8"); //build the InputStreamReader object with the same encoding as the writeStringBuffer SB=NewStringBuffer ();  while(reader.ready ()) {sb.append (Char) Reader.read ()); //go to char and add to StringBuffer object} System.out.println (sb.tostring ());        Reader.close (); //turn off Read streamFip.close (); //close the input stream and release system resources    }}

4 Java Exception Handling

Http://www.runoob.com/java/java-exceptions.html

A little Blue.

Refer to the Novice tutorial

Internship Training--java Foundation (2)

Related Article

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.