Java: ¿cómo inicializar String []?
Error
% javac StringTest.java
StringTest.java:4: variable errorSoon might not have been initialized
errorSoon[0] = "Error, why?";
Código
public class StringTest {
public static void main(String[] args) {
String[] errorSoon;
errorSoon[0] = "Error, why?";
}
}
9 answers
Necesitas inicializar errorSoon
, como se indica en el mensaje de error, solo tiene declarado.
String[] errorSoon; // <--declared statement
String[] errorSoon = new String[100]; // <--initialized statement
Necesita inicializar la matriz para que pueda asignar el almacenamiento de memoria correcto para los elementos String
antes de puede comenzar a configurar el índice.
Si solo declara la matriz (como lo hizo) no hay memoria asignada para los elementos String
, sino solo un identificador de referencia para errorSoon
, y lanzará un error cuando intente inicializar una variable en cualquier índice.
Como nota al margen, también puede inicializar la matriz String
dentro de llaves, { }
como así,
String[] errorSoon = {"Hello", "World"};
Que es equivalente a
String[] errorSoon = new String[2];
errorSoon[0] = "Hello";
errorSoon[1] = "World";
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-17 16:37:46
String[] args = new String[]{"firstarg", "secondarg", "thirdarg"};
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-08 10:10:44
String[] errorSoon = { "foo", "bar" };
Or o {
String[] errorSoon = new String[2];
errorSoon[0] = "foo";
errorSoon[1] = "bar";
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-04-01 23:42:30
Creo que acaba de migrar desde C++, Bueno, en java tiene que inicializar un tipo de datos(otros tipos primitivos y String no es un considerado como un tipo primitivo en java ) para usarlos de acuerdo con sus especificaciones si no lo hace, entonces es como una variable de referencia vacía (como un puntero en el contexto de C++).
public class StringTest {
public static void main(String[] args) {
String[] errorSoon = new String[100];
errorSoon[0] = "Error, why?";
//another approach would be direct initialization
String[] errorsoon = {"Error , why?"};
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-16 18:48:07
String[] errorSoon = new String[n];
Siendo n cuántas cadenas necesita contener.
Puede hacerlo en la declaración, o hacerlo sin la cadena [] más adelante, siempre y cuando sea antes de intentar usarlas.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-04 22:23:46
En Java 8 también podemos hacer uso de flujos, por ejemplo,
String[] strings = Stream.of("First", "Second", "Third").toArray(String[]::new);
En caso de que ya tengamos una lista de cadenas (stringList
), entonces podemos recopilar en una matriz de cadenas como:
String[] strings = stringList.stream().toArray(String[]::new);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-12 10:00:56
Siempre puedes escribirlo así
String[] errorSoon = {"Hello","World"};
For (int x=0;x<errorSoon.length;x++) // in this way u create a for loop that would like display the elements which are inside the array errorSoon.oh errorSoon.length is the same as errorSoon<2
{
System.out.println(" "+errorSoon[x]); // this will output those two words, at the top hello and world at the bottom of hello.
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-12 16:43:04
Declaración de cadena:
String str;
Inicialización de cadena
String[] str=new String[3];//if we give string[2] will get Exception insted
str[0]="Tej";
str[1]="Good";
str[2]="Girl";
String str="SSN";
Podemos obtener caracteres individuales en Cadena:
char chr=str.charAt(0);`//output will be S`
Si quiero obtener un valor Ascii de carácter individual como este:
System.out.println((int)chr); //output:83
Ahora quiero convertir el valor Ascii en Charecter/Symbol.
int n=(int)chr;
System.out.println((char)n);//output:S
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-03 07:10:44
String[] string=new String[60];
System.out.println(string.length);
Es la inicialización y obtener el código de LONGITUD de CADENA de una manera muy simple para principiantes
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-04 21:03:44