- Инициализация массива статических объектов в Java
- Java static array in class
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
- How to declare a static String array in Java
- Example
- Output
- Annual Membership
- Training for a Team
- Static Array in Java
- Static Array
- Static Array Example
- Advantages of Static Array
- Disadvantages of Static Array
- Declaring a Static Array
- Static Array Java Program
- Difference Between Static Array and Dynamic Array
Инициализация массива статических объектов в Java
В C++ общеизвестной и полезной практикой является использование списка инициализации для задания значений массива. При этом крайне удобно инициализировать при помощи фигурных скобок объекты в которых поля являются открытыми. Это либо структуры(struct) либо классы, у которых все поля открыты(перед ними указан access specifier как public).
Рассмотрим обычную структуру :
struct my_unary_function string name; string detect_name; double (*handler) (double); >;
Объекты можно создавать и инициализировать на лету(конструктор нам не нужен!) :
my_unary_function sin_func = "Синус", "sin", sin>;
Обратите внимание на синтаксис — во-первых, наличие фигурных скобок. Во-вторых — строгий порядок перечисления значений , соответствующий порядку определения переменных в структуре. У нового объекта — name=”Синус”, detec_name=”sin”, handler=”&sin”.
Теперь, собственно массивы, которые удобно инициализировать также как объекты :
my_unary_function math_functions[] = "Синус", "sin", sin>, "Косинус", "cos", cos>, "Тангенс", "tan", tan> >;
Добавив всего-лишь одну строчку расширится функционал программы. Если пишется калькулятор с поддержкой простейших математических вычислений — то все функции можно определять по полю detect_name в этом массиве, а обработчик определяется полем handler.
Java — встроенная инициализация статических массивов из объектов. В Java — немного другая история. Чаще всего используются статические массивы, тип элементов которых объявлен рядом с ними.
Пример такого определения :
public class InnerClassTest static class Employee private String name; private double salary; public Employee(String n, double s) name = n; salary = s; > public void print() System.out.println(name + " " + salary); > > static Employee[] staff = new Employee[] new Employee("Harry Hacker", 3500), new Employee("Carl Cracker", 7500), new Employee("Tony Tester", 3800), >; public static void main(String[] args) for (Employee e: staff) e.print(); > > >
А можно было бы разделить инициализацию и поместить её в специальный static-блок :
public class Main static Integer[] integerArray; static integerArray = new Integer[] new Integer(1), new Integer(2) >; > public static void main(String args[]) for (int i = 0; i integerArray.length; i++) System.out.println(integerArray[i]); > > >
Такой static-блок является функциональным блоком и в нём также можно выполнять любые действия :
static ArrayListString> list = new ArrayListString>(); static list.add("Bart"); list.add("Lisa"); list.add("Marge"); list.add("Barney"); list.add("Homer"); list.add("Maggie"); System.out.print("Hello!"); >
На самом деле для инициализации ArrayList можно использовать метод java.util.Arrays.asList :
public static final ListString> favorites = Arrays.asList("EJB", "JPA", "Glassfish", "NetBeans");
Java static array in class
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter
How to declare a static String array in Java
Following program shows how to declare a static string array.
Example
public class Tester < private static String[] array; static < array = new String[2]; array[0] = "Hello"; array[1] = "World"; >public static void main(String[] args) < System.out.println("Array: "); for(int i = 0; i < array.length; i++)< System.out.print(array[i] + " "); >> >
Output
- Related Articles
- How to declare an empty string array in C#?
- How to declare an Array Variables in Java?
- Can we declare a static variable within a method in java?
- How to declare Java array with array size dynamically?
- Can We declare main() method as Non-Static in java?
- Declare static variables and methods in an abstract class in Java
- How to declare a class in Java?
- How to declare a constructor in Java?
- How to declare, create, initialize and access an array in Java?
- how can I declare an Object Array in Java?
- Can we declare an abstract method final or static in java?
- How to sort a String array in Java?
- How to declare String Variables in JavaScript?
- How to convert a Double array to a String array in java?
- How to declare a local variable in Java?
Annual Membership
Enjoy unlimited access on 5500+ Hand Picked Quality Video Courses
Training for a Team
Affordable solution to train a team and make them project ready.
- About us
- Refund Policy
- Terms of use
- Privacy Policy
- FAQ’s
- Contact
Copyright © Tutorials Point (India) Private Limited. All Rights Reserved.
We make use of First and third party cookies to improve our user experience. By using this website, you agree with our Cookies Policy. Agree Learn more
Static Array in Java
In Java, array is the most important data structure that contains elements of the same type. It stores elements in contiguous memory allocation. There are two types of array i.e. static array and dynamic array. In this section, we will focus only on static array in Java.
Static Array
An array that is declared with the static keyword is known as static array. It allocates memory at compile-time whose size is fixed. We cannot alter the static array.
If we want an array to be sized based on input from the user, then we cannot use static arrays. In such a case, dynamic arrays allow us to specify the size of an array at run-time.
Static Array Example
For example, int arr[10] creates an array of size 10. It means we can insert only 10 elements; we cannot add a 11th element as the size of Array is fixed.
Advantages of Static Array
- It has efficient execution time.
- The lifetime of static allocation is the entire run time of the program.
Disadvantages of Static Array
- In case more static data space is declared than needed, there is waste of space.
- In case less static space is declared than needed, then it becomes impossible to expand this fixed size during run time.
Declaring a Static Array
The syntax to declare a static array is:
We can also declare and initialize static array as follows:
Static array can also be declared as a List. For example:
Static Array Java Program
StaticArrayExample.java
Let’s see another Java program.
StaticArrayExample.java
Difference Between Static Array and Dynamic Array
The following table describes the key differences between static array and dynamic array.
Static Array | Dynamic Array |
---|---|
Static arrays are allocated memory at compile time. | Dynamic array is located at run-time. |
The size of static array is fixed. | The size of dynamic array is fixed. |
It is located in stack memory space. | It is located in heap memory space. |
int array[10]; //array of size 10 | int* array = new int[10]; |