I have found very interesting but yet very strange String and array mixing up(syntax). See below code:
Example A:
int x = (int)(Math.random()*4 );
String n = new String[] {"FF", "RR"}[x];
System.out.println(n) ;
It outputs "FF" or "RR" when the random number is 0 or 1. My question is how that can happen. I am unable to understand the syntax used in Example A. I have used a very normal String array syntax just as below :
String s[] ;
s = new String[]{"dd", "rr"};
Or
String s [] = {"gg", "ss"};
But I haven't seen the top syntax (Example A). Can someone pitch in to help me understand how the top syntax is treated and executed. Advance thanks.
String n = new String[] {"FF", "RR"}[x];
^^^^^^^^^^^^^^^^^^^^^^^^^
This creates an anonymous array containing two elements, "FF" and "RR". An anonymous array is a temporary object that has no name and is destroyed as soon as the statement is finished executing. That anonymous array is then indexed using the [] operator.
String n = new String[] {"FF", "RR"}[x];
^^^
This returns the x'th element of the anonymous array.
Note that there appears to be a bug in this program; if the random number causes x to be greater than 1, you'll get an ArrayIndexOutOfBoundsException.
new String[] {"FF", "RR"} is an expression of type "array of String". This is why you can assign it to s in
String[] s = new String[] {"FF", "RR"};
Since it's of type "array of Strings", you can use the [] operator on it to get the String at a given index. And you must put an int inside the brackets. And xis an int.
So new String[] {"FF", "RR"}[x] is the element at index x of the array new String[] {"FF", "RR"}. This element is of type String. So you can assign it to the variable n, which is also declared as a String.
That's basically the same thing as doing
char c = "hello".charAt(2);
or
int i = new Person().getName().substring(2).indexOf('o');
It is bascially the same as your second notation.
The second line is equivalent to
String s[]= new String[]{"FF","RR"};
String n = s[x];
It's just that s is anonymous in this instance.
This of it like this: When you are normally access an element in a String array, what do you do?
String s = arr[0];
That gets the first element in the array. Now you are doing this:
String n = new String[] {"FF", "RR"}[x];
You are simply getting an element from the array immediately upon creation. Or, the xth element. Note that you program will fail if the random number is outside the bounds of the array.
Related
I am writing program to eliminate vowels in a String. What I want to do is check if the value of the character in the string is a Vowel. If it is false I want to store it in another array as follows:
if(isVowel(char_str[i]) == false) {
temp[index] = char_str[i];
index = index + 1;
}
I get an array out of Bounds exception for the 2nd line. I have initialised both the arrays as follows:
String str="Education";
char char_str[]=str.toCharArray();
char temp[] = {};
Can someone explain exactly what I am doing that is causing the error. I am a bit out of touch with the working of arrays in Java.
You cannot add an element to an array like this without specifying the array length. You can use ArrayList instead to add new elements without specifying the length. So either initialize the array length like this -
char temp[] = new char[100]; // Assuming 100 is the highest length
or declare an ArrayList like this -
List<Character> temp = new ArrayList<Character>();
You can add a new element to an ArrayList by using the add method.
temp.add(char_str[i]);
You are attempting to access an element of an empty array.
This line
char temp[] = {};
Creates an empty array - one with no elements.
So this
temp[index] = ...
Will explode because there are no positions to assign a value to.
Allocate some space, eg:
char temp[] = new char[str.length()];
I would like to know how to split a field through array using Java. For example we have GLaccount like AAAA-BBBB-CCCC and we would like to split each component and store it in an variable however the GLaccount may have AAAA-BBBB (no third component) so in this case variable segment3 throws NULL POINTER exception so I am not sure on how to fix this since I am new to Java.
String GL = getOwner().getGL("GLACCT");
String segment1 = GL.split("-")[0];
String segment2 = GL.split("-")[1];
String segment3 = GL.split("-")[2];
Using split("-" ) will give you an array of strings.
before using array value, you can check the size of array that if it contains enough elements to use..
String GL = getOwner().getGL("GLACCT");
String[] array=GL.split("-");
String segment1 = array[0];
String segment2 = array[1];
//check if array have 3rd element
if(array.length >2)
String segment3 = array[2];
else
System.out.println("No third element") ;
Use split method (once) and check returned array length :
String[] values3 = "AAAA-BBBB-CCCC".split("-");
// values.length == 3
String[] values2 = "AAAA-BBBB".split("-");
// values2.length == 2
import java.util.Arrays;
List<String> list = Arrays.asList(GL.split("-"));
With this code you do not need to think if you have 2,3 or 10 strings, and to add new if for every new one.
ArrayList<String> str = new ArrayList<String>();
String s1 ="Test1";
String s2 ="Test2";
str.add(s1);
str.add(s2);
I want to compare a string to one of the elements of the array.
String b = "Test1";
b.equals(str[index??]);
How can i get the index of str?
It's an arrayList. Therefore, to store a value of the array with a certain index, use this:
ArrayList.get(index);
Now, you can make this equal to a variable like this:
String mStr = ArrayList.get(index);
If I have an arrayList with the values "1, 2, 3, 4" it's important to note, index 0 is the value 1.
ArrayList.get(0) //HERE, THE INDEX IS ZERO, MEANING THE VALUE OF THE ARRAY LIST WOULD BE 1
Output:
1
That is easily confused; index 0 = first value. Just be sure to use the get() method.
To further compare strings, set that values equal to strings:
String FIRSTSTRING= ArrayList.get(0);
String SECONDSTRING= ArrayList.get(1);
Here, I am comparing the first and second values of the array list.
If you found this helpful, mark it as best answer. If you need more help, feel free to ask me, I am always happy to help!
{Ruchir}
You want List.get(int) (where int is the index). For example,
List<String> al = Arrays.asList("Test1", "Test2");
System.out.println(al.get(0).equals("Test1"));
the output is
true
You can try something like this
ArrayList<String> str = new ArrayList<String>();
...
boolean found = false;
for(String string : str)
found =b.equals(string);
Other than that,you can use get method of list.
You can use indexOf() method.
ArrayList<String> str = new ArrayList<String>();
String s1 ="Test1";
String s2 ="Test2";
str.add(s1);
str.add(s2);
System.out.println(str.indexOf("Test1"));
If you want to use the str.get(index) method and then check use a loop, But I find this more complicated.
for(int i = 0; i < list.size(); ++i)
if(list.get(i).equals("rtes"))
return i;
Use Binary Search if your Array is sorted. Otherwise, just go linearly in the arraylist, and compare the values.
in your case:
boolean find = false;
for(i=0;i<str.length;i++){
if(str.get(i) == b){
find = true;
break;
}
}
I have some problem when using array in Java. If I declare an array of character like this, my program will throw exception "out of bound array":
char[] ipx = {};
for( int i =0; i <= 63 ; i++ ){
ipx[i] = myString.charAt(i);
}
I do not know why it is ok when i replace the first line by:
char[] ipx = new char[64];
I think both of them are correct because i used to delare new string like this:
String newString = "";
what's the difference between those ?
Many thanks for any help you may be able to provide
I do not know why it is ok when i replace the first line by:
Because char[] ipx = {}; is equivalent to char[] ipx = new char[0]; // zero sized array;
and in latter case char[] ipx = new char[64]; you allocate 64 chars for your array.
No, it has to be initialized to a size at some point. In your example, you can just use: myString.toCharArray();
Typically you'd use Lists for things of unknown size and then do myList.toArray();
In a nutshell, you should not attempt to draw any parallels between String and char[]. They are very different creatures in Java.
If you wish to access element k of an array, you need to ensure that k is a valid index (i.e. that the array is large enough). A zero-length array ({}) is not large enough for any element access.
Is it possible to contruct array in Java without number of elements?
In your case, yes, just replace
char[] ipx = {};
for( int i =0; i <= 63 ; i++ ){
ipx[i] = myString.charAt(i);
}
by
char[] ipx = myString.toCharArray();
You can also use a ArrayList<Character> without declaring the number of elements.
Yes, all arrays in java are basic data structures and must have a pre-defined fixed length. Changing the length necessarily requires creating a new array.
If you want to handle collections of objects with variable size, what you want is a Collections Object from the Java libraries, which is more intelligent than a basic data array.
The List class in particular, ArrayList, will perform exactly what you want. It is a List of objects (instead of an array) and will resize itself naturally as you add or remove elements.
If you do char[] ipx = {}, it means you create a reference ipx. Same as you do char* ipx in C++, which is a pointer points to a random address. In order to store elements in it, you need to allocate memory like in C++ you need to do char* ipx = new char[64]. Therefore, if you only do char[]ipx = {} which is equivalent to char[]ipx = new char[0] in Java.
I have a brief question about how Java handles arrays. Below is my code:
//import java.util.Arrays;
import static java.lang.System.out;
public class Arrays
{
public static void main(String[] args)
{
String [][] multiArray = new String[10][8];
int k = 1;
while (k <= 61) {out.print('-'); k++;}
out.println ();
for (int i = 0; i < multiArray.length; i++)
{
for (int j = 0; j < multiArray[i].length; j++)
{
multiArray[i][j] = i + "" + j;
out.print ("| " + multiArray[i][j] + " ");
}
out.println ("|");
}
k = 1;
while (k <= 61) {out.print('-'); k++;}
out.println();
}
}
I understand that you have to create a double "for" loop to print out values for both dimensions and that you have to have:
multiArray[i].length
so that it knows to reference the length of the second dimension. I just don't understand how it works.
What I'm confused about is this: At the very beginning of the program, directly after I declare my array, if I write a statement like:
system.out.println (multiArray.length);
It will print the value of 10, which is the length I declared in the first dimension. If I, however, create some random variable like "int a = 0" or "int idontgetthis = 0" and then I write:
system.out.println (multiArray[a].length);
it somehow knows to print the length of the second dimension, 8. So my question is, how does it know how to do this? It's killing me!! lol
Because multiArray is really an array of arrays. So multiArray[a] is a reference to an object. That object is itself an array. That array has a length (8), and a property called length which can be used to return that length.
Basically, it is a concept confusion, by doing:
String[] array;
you are declaring that you will have an array of Strings with an unknown lenght.
A call to: System.out.println(array.length) at this moment will fail with a compilation error because array is not yet initialized (so the compiler can't know how long it is).
By doing:
String[] array = new String[8]
you declare that you will have and array of String and initialize it, specifying it will have space for 8 Strings, the compiler then allocates space for this 8 Strings.
Something important to notice is that even when the compiler now knows that you will store 8 Strings in your array, it will fill it with 8 nulls.
So a call to System.out.println(array.length) at this point will return 8 (Compiler knows the size) but a call to System.out.println(array[1]) will return a Null Pointer Exception (You have 8 nulls in it).
Now, in the example you presented, you are declaring a bidimensional array, this is, an array that will contain other arrays.
Bidimensional arrays are initialized as String[][] multiarray = new String[10][8]; and the logic is the same as in simple arrays, the new String[10][8]; indicates the lenght of the array that contains the other arrays, and the new String[10][8]; indicates the length of the contained arrays.
So doing system.out.println(multiArray[x].length); after initializing multiarray is translated as "What is the length of the Xth contained array?", which the compiler, thanks to your initialization, now knows is 8 for all the contained arrays, even when they are full of nulls at the moment.
Hope it helps to add a bit more understanding!
You could try looking at it like this.
public class Arrays{
public static class EightStrings {
public String[] strings = new String[8];
}
EightStrings[] tenOfThem = new EightStrings[10];
}