Home > Java > javaTutorial > body text

Example analysis of interview questions about java arrays

PHPz
Release: 2023-05-17 10:16:05
forward
874 people have browsed it

1. Basic knowledge

1. Do Java variables have to be initialized?

uncertain. Java array variables are reference data type variables. They are not the array object itself. As long as the array variable points to a valid array object, the array variable can be used. Initializing an array does not initialize the array variable, but initializes the array object - that is, allocating a continuous memory space for the array object, and this continuous memory space is the length of the array.

2. Are all basic type variables placed in stack memory?

wrong. It should be said like this: All local variables are stored in stack memory, whether they are basic type variables or reference type variables, they are stored in their respective method stack areas; but the objects referenced by reference type variables (including Arrays, ordinary Java objects) are always stored in heap memory.

3. When is the reference variable just the variable itself in the stack memory, and when does it become a Java object that refers to the instance?

A reference variable is essentially just a pointer. As long as the program accesses properties through a reference variable, or calls a method through a reference variable, the reference variable will be replaced by the object it refers to.

2. Example code

Rotate array:

For example: the element in the array is 123456, and after flipping it is 561234

give Given an array with length n, it is required to move the last k elements to the front and the first n-k elements to the back.

//先改进面试题一中的方法,将从头到尾翻转改为从i到j翻转
public int[] changeArray2(int[] array, int i, int j) {
 
        int temp = 0;
        while (i < j) {
            temp = array[i];
            array[i] = array[j];
            array[j] = temp;
            i++;
            j--;
        }
        //实现旋转数组就可以通过下面的方式来实现
        //1.翻转前半部分2.翻转后半部分3.反转整个数组
        public int[] swap(int[] array, int k) {
        int n = array.length - 1;// n=5
        changeArray2(array, 0, n - k);
        changeArray2(array, n - k + 1, n);
        changeArray2(array, 0, n);
        return array;
    }
}
Copy after login

The above is the detailed content of Example analysis of interview questions about java arrays. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template