Java Basics Review Part 2 - Modifiers and Strings

foreword

In the last article, I reviewed the basic data types of Java, and this article will review some modifiers and String in Java.

Introduction to Modifiers

Java Modifiers are mainly divided into two categories:
- Access Modifiers
- Non-Access Modifiers

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

access modifier

Access modifiers can use the following table to describe access rights:

modifier current class In the same package Subclass other packages
public AND AND AND AND
protected AND AND AND N
default AND AND N N
private AND N N N

Simply look at the access level, the level is from low to high.

 privatedefaultprotectedpublic

private

Variables and methods modified by private can only be used in this class.
So private is the strictest access level, mainly used to hide some details of the class and protect the data of the class.
For example, the pojo class uses private to modify variables and provides setter and getter methods to the outside world.
Also, if private is used to modify the constructor, the class cannot be instantiated. This is often seen in the singleton pattern!

Although private is mainly used to modify variables and methods, inner classes can also be modified, but only inner classes.

E.g:

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

Note: private cannot modify outer classes.

Because the variables and methods in the Test class are private, other classes cannot call them!
example:

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

Note: In fact, private modified methods and variables can be called using reflection, but they are not explained here.

default

default: just don't use any modifiers. Classes, interfaces, variables, methods can all be used. But only in the same package.

E.g:

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 in the same package.

E.g:

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

It can be called directly under the same package. If it is not in the same package, it needs to be inherited before it can be used.

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 modify outer classes.

public

public: Modified classes, interfaces, variables, and methods are available to all classes.

E.g:

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

non-access modifier

Java also provides many non-access modifiers in order to implement some other functions.

static

static : Used to modify class variables and class methods.

Static variables :
When static modifies class variables, no matter how many times the class is instantiated, there is only one copy of its static variables. Static variables are also known as class variables. Local variables cannot be declared as static variables.

Static method :
When static is modifying a class method, the static method cannot use the non-static variables of the class. Static methods can be called directly through 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 static block.
In the JVM class loading mechanism, if the class has a direct parent class and the class has not been initialized, the parent class is initialized first; if there are initialization statements in the class, these initialization statements are executed in turn.
Maybe the above two sentences are not easy to understand, so let's run the code to see the results, and we may be able to better understand the above sentences through the results.

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();   
}

result:

static A
static B
I'm A class
HelloA
I'm B class
HelloB

So does it feel better to understand based on the results returned by this class?
The order in which constructors are called when an object is created is:

First initialize static members, then call the parent class constructor, then initialize non-static members, and finally call its own constructor.

Then the use of the static modifier can be summarized as follows:

  1. Static variables have only one copy in memory and are shared among all instances of the class.
  2. Instance methods and instance variables cannot be directly accessed in static methods, and vice versa.
  3. The this and super keywords cannot be used in static methods.
  4. Static methods cannot be modified by abstract.
  5. Both static methods and static variables can be accessed directly by the class name.
  6. When the class is loaded, the static code block is loaded only once. When there are multiple static variables or blocks, they are loaded in declaration order.

final

final : used to decorate classes, methods and variables.
Final modified classes cannot be inherited, modified methods cannot be redefined by inherited classes, and modified variables are constants and cannot be modified.
If the above statement is not easy to understand, we can experiment by writing relevant code.
Define a final modified variable, method, and class. Then perform 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 the following conclusions:

final-modified class: indicates that the class cannot be inherited;
final-modified method: indicates that the method cannot be overridden;
final-modified variable: indicates that the variable can only be assigned once and the value cannot be modified (constant);

abstract

abstract : Used to create abstract classes and abstract methods.

Java is an object-oriented language, and abstract classes are a mechanism for defining abstract concepts in the Java language. It is precisely because of this that Java has powerful object-oriented capabilities.

Decorative class

Will make this class an abstract class, this class will not be able to generate object instances, but can be used as the type of object variable declaration (see the example below), that is, the compile-time type. An abstract class is equivalent to a semi-finished product, and subclasses need to inherit and override the abstract methods.

Modification method

It will make this method an abstract method, that is, only a declaration but no implementation, which requires subclasses to inherit the implementation.

Here is still a simple example to understand.

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. Both abstract classes and abstract methods need to be modified by abstract. Abstract methods must be defined in abstract classes.
2. An instance of an abstract class cannot be created because it is meaningless to call an abstract method.
3. Only after covering all the abstract methods in the abstract class, its subclasses can be instantiated. Otherwise the subclass is still an abstract class.

Precautions:

1. Abstract classes cannot be used to instantiate objects. The sole purpose of declaring an abstract class is to expand the class in the future.
2. A class cannot be modified by abstract and final at the same time . If a class contains abstract methods, the class must be declared abstract, otherwise a compilation error will occur.
3. An abstract method is a method without any implementation, and the concrete implementation of the method is provided by the subclass. 4. Abstract methods cannot be declared as final and static.
5. Any subclass that inherits an abstract class must implement all abstract methods of the superclass, unless the subclass is also an abstract class.
6. If a class contains several abstract methods, then the class must be declared as an abstract class. An abstract class may not contain abstract methods.

synchronized

synchronized : The modified method can only be accessed by one thread at a time. It is very common to use in multithreading.
The explanation of synchronized 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 the lock of the class instance that calls the method before it can be executed, otherwise the thread to which it belongs is blocked. The lock is not released until the method returns, after which the blocked thread can acquire the lock and re-enter the executable state. This mechanism ensures that for each class instance at the same time, at most one of its member functions declared synchronized is in the executable state (because at most one can obtain the lock corresponding to the class instance), thus effectively avoiding class member variables (as long as all methods that might access class member variables are declared synchronized).

To put it simply, it is to use the synchronized modification method. When multiple threads access at the same time, only one thread will be allowed to access first, and other threads will wait. analogy.

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

transient : When an instance variable is modified by transient, the java virtual machine (JVM) skips the specific variable.
native : The method modified by native is actually a native method implemented by another language. For example, the timestamp of Long type obtained in Java: System.currentTimeMillis();it is actually modified by native, and the
source code is:

 public static native long currentTimeMillis();

String

The String type is probably our most commonly used object.
First of all, String is not a basic data type, but an object, and it is an immutable object. Looking at the source code, the String class is modified by final and cannot be inherited!

String is null when it is not initialized, indicating that it has not been created, and naturally no space is allocated;
while " " and new String() are not null, they have been created, but the value is empty! And also allocated memory space.

String has 15 construction methods, two of which are outdated, including char[], byte[], int[], String, StringBuffer, StringBuilder.
When we create a String object, we usually use String str=”xxx”, but sometimes we also use new String() to initialize the string.
E.g:

    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 roughly describing the usage of String, here we list some 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: Concatenate the specified string to the end of this string.
5.split: Split this string according to the matching of the given regular expression.
6.equals: Compare this string with the specified object.
7.endsWith: Tests whether this string ends with the specified suffix.
8.startsWith: Test whether this string ends with the specified prefix.
9.getBytes: Use the platform's default character set to encode this String as a byte sequence, and store the result into a new byte array.
10.indexOf: Returns the index of the first occurrence of the specified character in this string.
11.replace: Returns a new string obtained by replacing all occurrences of oldChar in this string with newChar. 12:substring: Returns a new string that is a substring of this string.

For more information, please refer to the Api documentation.

String object comparison

String, as our most commonly used object, is expected to come into contact with a lot in interviews. Generally speaking, problems related to the constant pool of String will be considered, mainly when using String for comparison, the two methods of == and equals are used to judge whether they are equivalent. Here are some frequently encountered problems with String.
code show as below:


            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)); 

result:

false
true
false
false
true

If you have experience, you can probably see the results at a glance. But if you are inexperienced, you will often suffer from this loss. Here is an explanation of why this result occurs.

1.虽然看起来是一样的,但是新建一个String类的时候会重新分配引用地址,而 == 就是比较引用地址,所以为false。
2.在编译之前就可以确认s5=test, 并且引用地址一样,所以为true;
3.字符串常量池的原则 这时 s6 的值是在运行时得到的,它会重新构造字符串对象 所以为false。
4.和第一个一样的,就是换汤不换药,所以为false。
5.equals 只比较值相等,不关心它的引用地址。

看完上面的例子之后,再来看看下面的这个
代码示例:

 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));

运行结果:

false
false : true
true : true

到这里,可能就会诧异了,为什么和我想的不一样呢?
这里其实是有陷阱的,也就是运算符的优先级。
第一个结果就是优先级的问题导致的,它会先计算 abc + " : " + ab_c.equals(abc) ,然后再来进行比较,所以为false。同理,下面的也是如此,基本和上面的那个例子差不多,这里就不再概述了。

String、StringBuffer和StringBuilder

String、StringBuffer和StringBuilder的区别:

  • String: String的特点是一旦赋值,便不能更改其指向的字符对象,如果更改,则会指向一个新的字符对象。
  • StringBuffer:StringBuffer对象可以调用其方法动态的进行增加、插入、修改和删 除操作,且不用像数组那样事先指定大小,从而实现多次插入字 符,一次整体取出的效果,因而操作字符串非常灵活方便。并且生成数据之后可以toString转为String,线程安全。
  • StringBuilder: It is used in a single-threaded environment because all aspects of it are not modified by synchronized, so it is also more efficient than StringBuffer.

Regarding the way of string splicing, in the String class, we most commonly use +, followed by the append method of StringBuffer or StringBuilder. As for concat in the String class, it is rarely used.
Generally speaking, if splicing a small amount of strings, we will use +, if splicing too much, use StringBuilder for single thread, and use StringBuffer for multithreading. Because using String's + will greatly use memory when too many strings are spliced, because it still uses the append() method when relying on it, and then performs toString conversion. If it is a small amount, it does not feel good. There is a difference, but it will be clearly felt when a large number of splices are used.

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");

result:

String累加用时:701ms
StringBuffer累加用时:2ms
StringBuilder累加用时:0ms

Here we can see from the output results that the + splicing method of String is time-consuming. But using + is really convenient. Therefore, it is recommended here that if the number of string concatenations is less than 10, you can use +, and if there are too many, use StringBuffer or StringBuilder.

other

Reference:
https://blog.csdn.net/qiumengchen12/article/details/44939929

https://blog.csdn.net/chenssy/article/details/13004291

At this point, this article is over, thank you for reading! Comments and likes are welcome, your support is the biggest motivation for my writing!
Copyright statement:
Author: Nothingness
Blog Garden Source: http://www.cnblogs.com/xuwujing
CSDN Source: http://blog.csdn.net/qazwsxpcm    
Personal Blog Source: http://www.panchengming.com
Original It's not easy, please indicate the source when reprinting, thank you!

Guess you like

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