Java Basics Review Two-----modifiers and string

Source: Internet
Author: User
Tags modifier modifiers

Objective

In the previous article, we reviewed the basic Java data types, and this article reviews some of the modifiers in Java and string.

Modifier description

Java modifiers fall into two main categories:

    • Access modifiers
    • Non-access modifiers

Where access modifiers mainly include private, default, protected, public.
Non-access modifiers mainly include static, final, abstract, synchronized.

Access modifiers

Access modifiers can use this table to describe access rights:

modifier Current Class in the same package sub-class Other Packages
Public Y Y Y Y
Protected Y Y Y N
Default Y Y N N
Private Y N N N

A simple view of the access level, the level is from low to high.

 private<default<protected<public
Private

Variables and methods that are modified by private are restricted to use in this class only.
So private is the most stringent level of access, mainly used to hide some of the details of the class implementation and protection of class data.
For example, the Pojo class is a method that uses the private modifier variable to provide a setter and getter externally.
Also, if you use private to modify the constructor, the class cannot be instantiated. This can be seen frequently in singleton mode!

Although private is primarily used to modify variables and methods, it can also be decorated with inner classes, but internal classes.

For example:

public class Test{    //修饰一个私有变量    private int count=1;    //修饰一个私有方法    private int add(int i,int j){        return i+j;   }    private class Test1{                }}

Note: Private cannot decorate an external class.

Because the variables and methods in the test class are private, the other classes cannot be called!
Cases:

public class Test2 {    public static void main(String[] args) {        Test t=new Test();        //下面的变量和方法是无法获取的        //t.count=2;        //t.add(1,2);    }}

Description: In fact, the private modification of the method and variables can be used to call the reflection, but this is not explained.

default

Default: Just do not use any modifiers. Classes, interfaces, variables, methods are all available. However, it is limited to the same package.

For example:

class Test{     int count=1;     int add(int i,int j){            return i+j;     }    interface Test1{    }}
protected

Variables and methods modified by protected are only visible to classes and all subclasses within the same package.

For example:

public class Test{    protected int count=1;    protected int add(int i,int j){            return i+j;     }     protected class Test1{     }}

Can be called directly under the same package, if not the same package, you need to inherit to use.

public class Test2 extends Test{    public static void main(String[] args) {        Test t=new Test();        t.count=2;        t.add(1,2);    }}

Note: Protected cannot decorate an external class.

Public

Public: Decorated classes, interfaces, variables, and methods are available to all classes.

For example:

   public class Test{    public int count=1;    public int add(int i,int j){            return i+j;     }  }
Non-access modifiers

Java also provides a number of non-access modifiers in order to implement some other functionality.

Static

static: Used to modify class variables and class methods.

Static variables :
When static modifies a class variable, it has only one copy of its static variable, no matter how many times the class is instantiated. Static variables are also known as class variables. A local variable cannot be declared as a static variable.

static method :
Static methods cannot use non-static variables of a class when modifying a class method. Static methods can be called directly from the class name, so the this and Super keywords cannot be used in static methods.

Example:

 public class Test{    public  String name="xuwujing";    public  static String name2="xuwujing";        public  static String getName() {    //这个一句 会报错  因为静态方法是不能使用类的非静态变量    //String reult=name;    //这一句就可以    String reult=name2;    return reult;     }        //main方法是静态方法,可以直接调用本类中的静态方法和静态变量    public static void main(String[] args) {        System.out.println(name2);        System.out.println(getName());    }        //该方法是不静态方法,所以调用本类中的静态方法和静态变量时,    //需要使用classname.variablename和 classname.methodname的方式访问    private void print(){        System.out.println(Test.name2);        System.out.println(Test.getName());     }    }

Here, by the way, static blocks.
In the JVM class loading mechanism, if the class has a direct parent class and the class is not initialized, the parent class is initialized first, and the initialization statements are executed sequentially if there are initialization statements in the class.
Perhaps the above two sentences are not very well understood, then here we run the code to see the results, through the results may be able to better understand the words of the above statement.

Example:

class HelloA {    public HelloA() {        System.out.println("HelloA");     }        { System.out.println("I'm A class"); }         static { System.out.println("static A"); } }public class HelloB extends HelloA{    public HelloB() {        System.out.println("HelloB");     }        { System.out.println("I'm B class"); }          static { System.out.println("static B"); }         public static void main(String[] args) {        new HelloB();   }

Results:

static Astatic BI'm A classHelloAI'm B classHelloB

So is the result of returning from this class A feeling of a better understanding?
When you create an object, the constructor's call order is:

Initializes a static member, then calls the parent class constructor, initializes the non-static member, and finally calls itself the constructor.

Then the use of the static modifier can be summed up as follows:

  1. Static variables have only one copy in memory and are shared across all instances of the class.
  2. You cannot directly access instance methods and instance variables in a static method, or vice versa.
  3. The This and Super keywords cannot be used in static methods.
  4. Static methods cannot be modified by an abstract.
  5. Both static and static variables can be accessed directly through the class name.
  6. When the class is loaded, the static code block is loaded only once. When there are more than one static variable or block, it is loaded in declaration order.
Final

final : Used to modify classes, methods, and variables.
The final modified class cannot be inherited, the decorated method cannot be redefined by the inheriting class, the modified variable is constant, and is not modifiable.
If the above statements are not well understood, we can experiment by writing the relevant code.
Defines a final modified variable, method, and class. Then perform the relevant tests

Example:

 public class Test{        //定义一个final修饰的变量    public  static final String name="xuwujing";      public static void main(String[] args) {        //这句会报错  因为该变量已经被final修饰了        name="张三";    }    //类加上final之后,该类是无法被继承的    final class Test2{    }    //这句会报错,因为Test2是被final修饰的类    class Test3 extends Test2{    }        class Test4{        //定义一个被final修饰的方法         final Date getTime(){            return new Date();        }    }        class Test5 extends Test4{        //这句会报错,因为final方法是不能被子类修改的。        Date getTime(){        return new Date();        }    }  

From the above code results, we can draw a conclusion:

Final decorated class: Indicates that the class cannot be inherited;
Final Modification method: Indicates that the method cannot be overridden;
Final Modified variable: Indicates that the value cannot be modified (constant) after the variable can be assigned only once;

Abstract

Abstract: Used to create abstraction classes and abstract methods.

Java is an object-oriented language, and abstract classes are a mechanism for defining abstract concepts in the Java language, and because of this, it gives Java a powerful object-oriented capability.

Modifier class

Makes this class an abstract class that will not generate an object instance, but can be used as the type declared by the object variable (see later instance), which is the compile-time type. Abstract classes are equivalent to a class of semi-finished products, which require subclasses to inherit and overwrite the abstract methods.

Modification methods

Will make this method an abstract method, that is, only the declaration and not the implementation, the subclass must inherit the implementation.

A simple example is still used to understand this.

public class AbstractTest{    public static void main(String[] args) {        //这句会报错,因为抽象类不能实例化        // Animal a=new Animal();        //抽象类可以实例化重写该类抽象方法的子类        Animal a = new Dog();        a.show();    }}abstract class Animal{    abstract void show();    public void print(){        System.out.println("Animal");    }}//继承抽象类需要实现抽象类的方法class Dog extends Animal{       @Override    void show() {        System.out.println("This is Dog!");    }}

Summarize:

1. Abstract classes and abstract methods need to be modified by abstractions. Abstract methods must be defined in an abstract class.
2. Abstract class cannot create an instance because it is meaningless to invoke an abstract method.
3, only after overriding all abstract methods in the abstract class, its subclasses can be instantiated. Otherwise, the subclass is an abstract class.

Precautions:

1. Abstract classes cannot be used to instantiate objects, and the sole purpose of declaring abstract classes is to augment the class in the future. 2. A class cannot be both abstract and final
Modified. If a class contains an abstract method, the class must be declared as an abstract class, or a compilation error will occur.
3, abstract method is a method without any implementation, the specific implementation of the method is provided by the subclass. 4. Abstract methods cannot be declared final and static.
5. Any subclass that inherits an abstract class must implement all the abstract methods of the parent class, unless the subclass is also an abstract class.
6. If a class contains several abstract methods, the class must be declared as an abstract class. Abstract classes can contain no abstract methods.

Synchronized

synchronized: The modified method can only be accessed by one thread at a time. It is common to use in multi-threading.
Synchronized's explanation is as follows:

The Synchronized method Controls access to class member variables: Each class instance corresponds to a lock, and each synchronized method must obtain a lock on the class instance that invokes the method to execute, otherwise the owning thread is blocked, and once the method executes, the lock is exclusive until the lock is released from the method return , the blocked thread can then get the lock and re-enter the executable state. This mechanism ensures that at the same time for each class instance, at most one of its member functions that declare synchronized is in an executable state (because at most one can obtain the corresponding lock for that class instance), This effectively avoids access violations of class member variables (as long as all methods that may access the class member variable are declared as synchronized).

In simple terms, it is the use of synchronized modified method, when the multi-threaded access at the same time, will only let a line enters upgradeable access, other threads wait, when the thread is finished, then let the next access, and so on.

There are also two less common modifiers in Java,transient and native.

transient: the Java Virtual machine (JVM) skips that particular variable when the instance variable is modified by transient.
Native: The method modified by native is actually a native method implemented by another language. For example, a long timestamp is obtained in Java: System.currentTimeMillis(); It is actually decorated by native,
The source code is:

 public static native long currentTimeMillis();
String

The String type is probably our most common object.
First, string is not a basic data type, but an object and an immutable object. View source code can be the string class is final decorated, is not inherited!

When the string is not initialized, it is null, indicating that it has not been created, and naturally there is no space allocated;
And the "" and New String () are not NULL, they are already created, only the value is empty! And the memory space is also allocated.

There are 15 ways to construct a String, two of which are obsolete and contain char[],byte[],int[],string,stringbuffer,stringbuilder.
When we create a string object, we typically use string str= "xxx", but sometimes we also use the new string () to initialize the session string.
For example:

    String hello="hello";    String newHello=new String("hello");    char []cHello ={'h','e','l','l','o'};    String str=new String(cHello);

Note: The string class is immutable, so once you create a string object, its value cannot be changed.

String Common methods

After describing the use of string, let's enumerate some of the commonly used methods of string.

1.length: Returns the length of this string.
2.charAt: Returns the char value at the specified index.
3.compareTo: Compare this string with another object.
4.concat: Connects the specified string to the end of this string.
5.split: Splits this string according to the match of the given regular expression.
6.equals: Compares this string to the specified object.
7.endsWith: Tests whether this string ends with the specified suffix.
8.startsWith: Tests whether this string ends with the specified prefix.
9.getBytes: Encodes this String into a byte sequence using the platform's default character set and stores the result in a new byte array.
10.INDEXOF: Returns the index at which the specified character first appears in this string.
11.replace: Returns a new string that is obtained by replacing all OldChar that appear in this string with Newchar. 12:substring: Returns a new string that is a substring of this string.
...

Refer to the API documentation for more information.

String Object Comparison

As our most commonly used object, string is estimated to have a lot of contact during the interview. In general, the examination to string of constant pool-related issues, mainly when using string comparison, = = and equals are the two methods to determine whether the equivalent. Here are some of the frequently encountered problems with string.
The code is as follows:

              String s1 = "test";            String s2 = new String("test");            String s3 = "te";            String s4 = "st";            String s5 = "te" + "st";            String s6 = s3 + s4;            String s7 = new String(s1);            System.out.println(s1 == s2);             System.out.println(s1 == s5);             System.out.println(s1 == s6);             System.out.println(s7==s1);                   System.out.println(s7.equals(s1));         

Results:

falsetruefalsefalsetrue

If you have experience, you can probably see the results at a glance. But if the experience is not enough, often will eat this loss. Here to explain why this result occurs.

1. Although it looks the same, the new string class will be re-assigned the reference address, and = = is the comparison of the reference address, so false.
2. S5=test can be confirmed before compiling, and the reference address is the same, so it is true;
3. The principle of a string constant pool at this point the value of S6 is obtained at run time, and it reconstructs the string object so that it is false.
4. The same as the first one, is the same, so false.
5.equals only compares values equal and does not care about its reference address.

After reading the above example, take a look at the following
code example:

 String ab="ab"; String c="c"; String ab_c=ab+c; String ab_c1="ab"+"c"; String abc="abc"; System.out.println(ab_c == abc + " : " + ab_c.equals(abc)); System.out.println((ab_c == abc) + " : " + ab_c.equals(abc)); System.out.println((ab_c1 == abc) + " : " + ab_c1.equals(abc));

Operation Result:

False
False:true
True:true

Here, may be surprised, why and I think not the same?
This is actually a trap, which is the precedence of the operator.
The first result is a priority problem, which is calculated first abc + " : " + ab_c.equals(abc) and then compared, so it is false. Similarly, the following is also true, the basic and the above example is similar, here is no longer outlined.

String, StringBuffer, and StringBuilder

The differences between String, StringBuffer, and StringBuilder:

  • The string:string feature is that once you assign a value, you cannot change the character object it points to, and if you change it, it points to a new character object.
  • The Stringbuffer:stringbuffer object can invoke its methods to dynamically add, insert, modify, and delete operations, and do not have to specify the size as an array, so that multiple insertion of characters, a whole take out the effect, so the operation of the string is very flexible and convenient. And after generating the data can be tostring to string, thread safe.
  • StringBuilder: It is used in a single-threaded environment, because all aspects of it are not synchronized decorated, so it is more efficient than stringbuffer.

About string concatenation, in the string class, we most commonly use +, followed by the Append method using StringBuffer or StringBuilder, as for the concat in the string class is seldom used.
In general, if in a small number of strings splicing, we will use +, if the stitching too much, single-threaded use of StringBuilder, multi-threaded use stringbuffer splicing. Because the use of String + in the concatenation of too many strings will be a great use of memory, because it is by virtue of the use of the Append () method, and then the ToString conversion, if a small amount of time, is not feel the difference, But in a lot of splicing when it will be obvious to feel.

code example:

String str="Hello World";String str1="";StringBuffer sbr=new StringBuffer(str); StringBuilder sbd=new StringBuilder(str); long start=System.currentTimeMillis();   for(int i=0;i<10000;i++){     str1+=str;   }   System.out.println("String累加用时:"+(System.currentTimeMillis()-start)+"ms");   long start2=System.currentTimeMillis();   for(int i=0;i<10000;i++){     sbr.append(str);   }   System.out.println("StringBuffer累加用时:"+(System.currentTimeMillis()-start2)+"ms");   long start3=System.currentTimeMillis();   for(int i=0;i<10000;i++){     sbd.append(str);   }   System.out.println("StringBuilder累加用时:"+(System.currentTimeMillis()-start3)+"ms");

Results:

String累加用时:701msStringBuffer累加用时:2msStringBuilder累加用时:0ms

From the output results, we can see the time of the string + stitching method. But using + is really convenient. Therefore, it is suggested here that if the string concatenation number is 101, you can use +, too much with StringBuffer or StringBuilder.

Other

Reference:
44939929

13004291

This is the end of this article, thank you for reading! Welcome message and praise, your support is my greatest motivation to write!
Copyright Notice:
Empty Realm
Blog Park Source: http://www.cnblogs.com/xuwujing
CSDN Source: HTTP://BLOG.CSDN.NET/QAZWSXPCM
Personal blog Source: http://www.panchengming.com
Original is not easy, reproduced please indicate the source, thank you!

Java Basics Review Two-----modifiers and string

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.