Java: how to initialize String[]? - java

Error
% javac StringTest.java
StringTest.java:4: variable errorSoon might not have been initialized
errorSoon[0] = "Error, why?";
Code
public class StringTest {
public static void main(String[] args) {
String[] errorSoon;
errorSoon[0] = "Error, why?";
}
}

You need to initialize errorSoon, as indicated by the error message, you have only declared it.
String[] errorSoon; // <--declared statement
String[] errorSoon = new String[100]; // <--initialized statement
You need to initialize the array so it can allocate the correct memory storage for the String elements before you can start setting the index.
If you only declare the array (as you did) there is no memory allocated for the String elements, but only a reference handle to errorSoon, and will throw an error when you try to initialize a variable at any index.
As a side note, you could also initialize the String array inside braces, { } as so,
String[] errorSoon = {"Hello", "World"};
which is equivalent to
String[] errorSoon = new String[2];
errorSoon[0] = "Hello";
errorSoon[1] = "World";

String[] args = new String[]{"firstarg", "secondarg", "thirdarg"};

String[] errorSoon = { "foo", "bar" };
-- or --
String[] errorSoon = new String[2];
errorSoon[0] = "foo";
errorSoon[1] = "bar";

In Java 8 we can also make use of streams e.g.
String[] strings = Stream.of("First", "Second", "Third").toArray(String[]::new);
In case we already have a list of strings (stringList) then we can collect into string array as:
String[] strings = stringList.stream().toArray(String[]::new);

I believe you just migrated from C++, Well in java you have to initialize a data type(other then primitive types and String is not a considered as a primitive type in java ) to use them as according to their specifications if you don't then its just like an empty reference variable (much like a pointer in the context of 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?"};
}
}

String[] arr = {"foo", "bar"};
If you pass a string array to a method, do:
myFunc(arr);
or do:
myFunc(new String[] {"foo", "bar"});

String[] errorSoon = new String[n];
With n being how many strings it needs to hold.
You can do that in the declaration, or do it without the String[] later on, so long as it's before you try use them.

You can always write it like this
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.
}

You can use below code to initialize size and set empty value to array of Strings
String[] row = new String[size];
Arrays.fill(row, "");

String Declaration:
String str;
String Initialization
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";
We can get individual character in String:
char chr=str.charAt(0);`//output will be S`
If I want to to get individual character Ascii value like this:
System.out.println((int)chr); //output:83
Now i want to convert Ascii value into Charecter/Symbol.
int n=(int)chr;
System.out.println((char)n);//output:S

String[] string=new String[60];
System.out.println(string.length);
it is initialization and getting the STRING LENGTH code in very simple way for beginners

Related

How to pass two arrays into one varargs

I want to pass two arrays of Strings into one string varsargs.
ie.
public void doSomething(String... ){
}
public void test(){
String[] arrayOne = ...
String[] arrayTwo = ...
doSomething(arrayOne, arrayTwo); //Doesn't work but just for an example
}
Is the best way to just concat the two arrays or is there a better way of doing this?
Sadly not possible in java as there is no spread operator (like in Kotlin, Ecmascript 6). You have to work your way around this by creating an intermediate array:
String[] arrayThree = new String[arrayOne.length + arrayTwo.length];
System.arraycopy(arrayOne, 0, arrayThree, 0, arrayOne.length);
System.arraycopy(arrayTwo, 0, arrayThree, arrayOne.length, arrayTwo.length);
doSomething(arrayThree);
Or using Streams:
String[] arrayThree = Stream.concat(Arrays.stream(arrayOne), Arrays.stream(arrayTwo))
.toArray(String[]::new);
doSomething(arrayThree);
As said, this is possible in kotlin and can be done like this:
val arrayOne: Array<String> = ...
val arrayTwo: Array<String> = ...
doSomething(*arrayOne, *arrayTwo)
or even in javascript:
const arrayOne = ...
const arrayTwo = ...
doSomething([...arrayOne, ...arrayTwo]);
This is because a vararg has to be the last parameter in a function. Here is an extract from Oracle documentation:
https://docs.oracle.com/javase/8/docs/technotes/guides/language/varargs.html
The three periods after the final parameter's type indicate that the final argument may be passed as an array or as a sequence of arguments. Varargs can be used only in the final argument position
String... is replaced by String[], so you can't pass two array in one function expecting a vararg.
You would have to merge your arrays into one.
You can only pass multiple array in the varargs if they all are of same type
public static void doSomething(String[] ...args){
}
public static void test(){
String[] arrayOne = {};
String[] arrayTwo = {};
doSomething(arrayOne, arrayTwo); //Doesn't work but just for an example
}
You can merge two arrays with this instruction:
import org.apache.commons.lang3;
// ...
String[] both = (String[])ArrayUtils.addAll(arrayOne , arrayTwo);
doSomething(both);
// ...
or you can pass both arrays.
public void doSomething(String[] pArrayOne, String[] pArrayTwo ){
}
public void test(){
String[] arrayOne = ...
String[] arrayTwo = ...
doSomething(arrayOne, arrayTwo);
}

Java split() into new String[]

Is it possible to split a string into an string array that hasn't been declared?
I want to add a string array to a list, so currently I have it set like this vars.add(new String[]{s}); where s is a string. Is there anyway to make it add s.split("|")?
Or is the only option:
String [] ns = s.split("|");
vars.add(ns);
I was playing in netbeans, where I would this make a string array, with this string "A|C|D|E":
new String(s).split("|");
Is this what you're looking for?
ArrayList<String[]> vars = new ArrayList<String[]>();
String s = "A|C|D|E";
vars.add(s.split("\\|"));
Note that if you want to add the Strings individually to the list, you must do it slightly differently.
ArrayList<String> vars = new ArrayList<String>();
String s = "A|C|D|E";
for (Sting str : s.split("\\|"))
vars.add(str);

What's the difference between String and String[]?

Could anyone help me understand the difference? I need to understand for my class and they seem the same to me.
String or String[]
String is -> a series of characters in your code that is enclosed in double quotes.
More details a bout String
String[] -> An array is a container object that holds a fixed number of values of a Strings.
More about Arrays
The difference between String and String[] is that String is used to declare a single instance of a String object:
String name = "Cupcake";
On the other hand, String[] is used to declare an array of multiple strings:
String[] names = new String[] { "Joe", "Alice" };
In Java generally, arrays of type <Type> are declared using the following syntax:
<Type>[] types;
From the official Java documentation for arrays:
An array's type is written as type[], where type is the data type of the contained elements; the brackets are special symbols indicating that this variable holds an array.
String is used to create a single object of type String
String[] is an Array, containing a specified number of String objects.
String is a class, and String a represents an object of this class (the String class represents an object containing a sequence of characters). While String a[] represents an array of objects of this type.
An array is a kind of container. It can contain various objects inside. In this case with String[] you are specifying that this container has only String objects
String a = "abc"; /*this is a String, notice it references only to one
object, which is a sequence of characters*/
String b[] = new String[]{"abc", "def"}; /*this is a String array.
It is instantiated with 2 String objects, and it cannot
contain anything else other than String or its sub classes (i.e: no Integers or neither Object). */
Similar to array, String[] is used to store more than one string at a time.
Following is a sample program for String[]
public class JavaStringArrayExample {
public static void main(String args[]) {
// declare a string array with initial size
String[] schoolbag = new String[4];
// add elements to the array
schoolbag[0] = "Books";
schoolbag[1] = "Pens";
schoolbag[2] = "Pencils";
schoolbag[3] = "Notebooks";
// this will cause ArrayIndexOutOfBoundsException
// schoolbag[4] = "Notebooks";
// declare a string array with no initial size
// String[] schoolbag;
// declare string array and initialize with values in one step
String[] schoolbag2 = { "Books", "Pens", "Pencils", "Notebooks" }
// print the third element of the string array
System.out.println("The third element is: " + schoolbag2[2]);
// iterate all the elements of the array
int size = schoolbag2.length;
System.out.println("The size of array is: " + size);
for (int i = 0; i < size; i++) {
System.out.println("Index[" + i + "] = " + schoolbag2[i]);
}
// iteration provided by Java 5 or later
for (String str : schoolbag2) {
System.out.println(str);
}
}
}
Hope this will give you an idea.

How do i get the elements form an Object array to a String array?

I get a coding error in eclips Type mismatch, cannot convert Object to String. All data going into AL is String Type and AL is declared as String.
If i can just have AL go to a String[] that would be better.
heres my code:
Object[] Result;
AL.toArray (Result);
String[] news= new String[Result.length];
for (int i1=0;i1<news.length;i1++){
news[i1]=Result[i1]; <=====here is where the error shows up
Change this:
news[i1]=Result[i1];
to this:
news[i1]=Result[i1].toString();
Try type casting.
news[i1] = (String) Result[i1];
However, it is probably a good idea to check the type of Result[i1] before type casting like that. So you could do something like
if( Result[i1] instanceof String){
news[i1] = (String) Result[i1];
}
If you are absolutely sure that every object in Result array is String type, why don't you use String[] in the first place? Personally, I'm not a big fan of Object[]...
String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);
You can supply the ArrayList.toArray() method with an existing array to define what type of array you want to get out of it.
So, you could do something like this:
String[] emptyArray = new String[0];
String[] news = AL.toArray(emptyArray);
Try this code:
public static void main(String[] args)
{
Object[] Result = {"a1","a2","a3"};
String[] AL = new String[Result.length];
for(int a=0; a<Result.length; a++)
{
AL[a] = Result[a].toString();
}
System.out.println(AL[0]);
System.out.println(AL[1]);
System.out.println(AL[2]);
}
Since AL is, as you report, an ArrayList<String>, this should do what you want in one line of code:
String[] news = AL.toArray(new String[AL.size()]);

How can I initialize a String array with length 0 in Java?

The Java Docs for the method
String[] java.io.File.list(FilenameFilter filter)
includes this in the returns description:
The array will be empty if the directory is empty or if no names were accepted by the filter.
How do I do a similar thing and initialize a String array (or any other array for that matter) to have a length 0?
As others have said,
new String[0]
will indeed create an empty array. However, there's one nice thing about arrays - their size can't change, so you can always use the same empty array reference. So in your code, you can use:
private static final String[] EMPTY_ARRAY = new String[0];
and then just return EMPTY_ARRAY each time you need it - there's no need to create a new object each time.
String[] str = new String[0];?
String[] str = {};
But
return {};
won't work as the type information is missing.
Ok I actually found the answer but thought I would 'import' the question into SO anyway
String[] files = new String[0];
or
int[] files = new int[0];
You can use ArrayUtils.EMPTY_STRING_ARRAY from org.apache.commons.lang3
import org.apache.commons.lang3.ArrayUtils;
class Scratch {
public static void main(String[] args) {
String[] strings = ArrayUtils.EMPTY_STRING_ARRAY;
}
}
Make a function which will not return null instead return an empty array you can go through below code to understand.
public static String[] getJavaFileNameList(File inputDir) {
String[] files = inputDir.list(new FilenameFilter() {
#Override
public boolean accept(File current, String name) {
return new File(current, name).isFile() && (name.endsWith("java"));
}
});
return files == null ? new String[0] : files;
}
You can use following things-
1. String[] str = new String[0];
2. String[] str = ArrayUtils.EMPTY_STRING_ARRAY;<br>
Both are same.

Categories

Resources