What is the difference between String... variable and String varible[] in Java? - java

we can have two declaration for String array
1>String... sampleStringArray;
2>String sampleStringArray[];
can anyone tell me the difference

The first is an example of varargs and the wikipedia notes These values will be available inside the method as an array, must be the last parameter in a given method, and is otherwise accessed as an array (also it wasn't added to the language until Java 5).

Related

what is this concept called and from which version of java

Can you please let me know which version of java below flower bracket ({}) is introduced? what is concept name for this.
Object[] arg = {abc.getAbctNumber()};
here abc is object of java class and getAbcNumber() is a java method. I understand that arg object will be assigned with the value of return value of getAbcNumber() method.
{} is used to specify an array literal. So in your case you're specifying an array of objects with one element.
There is no such thing as a "flower bracket" in java. What you are seeing here, is an array being populated by a method.
You are creating an array with this syntax similar to:
int myarray[] = {1, 2, 3};
which will create an array of three ints. Your array will be created with an object.
This looks like a list initializer (not sure about the terminology, I don't do a lot of Java). In this case arg is an array of type Object and it's being initialized with a single value, which is the result of abc.getAbctNumber().
Consider an initializer with more than one value and it starts to become more clear:
Object[] arg = {
abc.getAbctNumber(),
abc.getSomeOtherNumber(),
abc.getSomethingElse()
};
That would initialize the arg array with three elements, the results of three different methods.
There is nothing called Flower bracket(at least I don't know about that). And in your Object[] arg = {abc.getAbctNumber()}; {} represent an array of one element and that element being an Object that is returned by method getAbctNumber()

Partially filled array, deleting duplicate array

I am doing one exercise in Absolute Java.
The Question is: Write a static method that has a partially filled array of characters as a formal parameter and that deletes all repeated letters from the array. The method should have two formal parameters: an array parameter and a formal parameter of type int that gives the number of array positions used. When the letter is deleted, the remaining letters are moved one position to fill in the gap.
What I think of is using hashset, it should be the most easiest way.
And another way that I am thinking is converting array to list , deleting the duplicates element and then transfer it back.
Here is a problem for me: how to write that code?? (why I am asking it?)
public static char[] deleteRepeats(char[] array, int size)
{
ArrayList<String> newarray = new ArrayList<String>();
newarray = Arrays.asList(array);
}
it says type mismatching, how can I correct the code?
Another question is: Back to the initial question, how to use partially filled array to implement it?
ArrayList<String> newarray = new ArrayList<String>();
Is an array list of Generic type String. However your parameters are of char type. Therefore they are not interchangeable. That's whats throwing the Type Mismatch error.
You are right using a Set is the easiest way to implement it. However I don't know whether the exercise wants you to manually do the work.
However you if you cannot use the wrapper class Character and must use the char type then you must do manual conversion if you are going to get a Set to do your replacement work for you.
EDIT:
You cannot use Arrays.asList() method to get a list like that. That method takes java objects as arguments not primitive types. And when you pass the char[] the only object it sees is the array itself.
So the result is a List<char[]> since generics do not support primitive types.

Java array convention: String[] args vs. String args[]

I am currently teaching students as a tutor programming conventions. I've told them that they can find most conventions in the Oracle Code Conventions.
In my last tutorial a student asked if:
public static void main(String args[])
or
public static void main(String[] args)
is written by convention or if there is a difference. I have never seen the first version before, so I'm very sure that the second one is a convention. But I don't have a source for that.
Can you give me a source (preferably from oracle, like the page I've linked above) that makes clear which of both is convention?
Equivalence of both expressions
I know that both expressions are equivalent:
The JLS 7, p. 292 states:
An array type is written as the name of an element type followed
by some number of empty pairs of square brackets [].
but also on p. 293:
The [] may appear as part of the type at the beginning of the declaration,
or as part of the declarator for a particular variable, or both.
For example:
byte[] rowvector, colvector, matrix[];
This declaration is equivalent to:
byte rowvector[], colvector[], matrix[][];
But this doesn't help for the convention-quesiton.
So they are identical (not specs, but here is a source).
They produce the same bytecode in a small example, so I'm very sure that they are also identical in praxis.
This is not from Oracle but I think it will help.
It is from Kathy Sierra's book SCJP Sun Certified Programmer for Java 6
int[] key;
int key [];
When declaring an array reference, you should always put the array brackets
immediately after the declared type, rather than after the identifier (variable
name). That way, anyone reading the code can easily tell that, for example, key is a
reference to an int array object, and not an int primitive.
Oracle's Code Conventions do not explicitly state it, but in all examples they use the brackets immediately after the declared type.
In their example code (which should be considered authoritative in this context) they use:
private Object[] instanceVar3;
Also on the page detailing the initialization of variables they have this example that demonstrates the possible problems of putting the brackets behind the variable name:
int foo, fooarray[]; //WRONG!
One could be tempted to do this and think one were declaring several arrays. Althoug this syntactically correct (as brimborium pointed out in the comments), Oracle didn't put the capital letters there for nothing. Better to be safe, clear and also type less by putting the brackets behind the type to show clearly what you want to declare.
There is one obscure use case for the late brackets:
int x, xs[], xxs[][];
How much this is useful, I let the reader be the judge.
One advantage of using [] immediately after array type is:
If you want to declare multiple arrays then you to write like:
int[] a,b,c;
But if you use [] after the array name, then we have to use[] after every array variable like:
int a[],b[],c[];

static method - when to return an array argument as void and return as an array?

I've been reading this section about static methods and about passing arrays by call-by-reference. So my question is: When is it ever a good time to return an array argument as an array as opposed to void?
Thanks in advance!
I've been reading this section about static methods passing arrays by call-by-reference.
If this is a Java article, site, blog, book, whatever, you should probably find a better one. Java doesn't use "call-by-reference" on any parameters. Anyone who says that either doesn't understand Java, or doesn't understand what "call by reference" means.
Java passes all arguments by value. Period.
The point of confusion is that some people don't understand that Objects and arrays in Java are always references. So when you pass an array (for instance) as an argument, you are passing the reference to the array by value. However, this ins NOT a nitpick. Passing a reference by value is semantically very different to true "call by value".
Re the actual quote:
"All of these examples highlight the basic fact that the mechanism for passing arrays in Java is a call by reference mechanism with respect to the contents of the array" (Sedgewick).
I understand what he is saying, given the qualification " with respect to the contents of the array". But calling this "call by reference" is misleading. (And clearly, you were mislead by it, to a certain degree!)
I would also argue that it is technically wrong. The terms "call-by-value", "call-by-reference", "call-by-name" (and so on are) about parameter passing / returning. In this case, the parameter is the array as a whole, not the contents of the array. And at that level, the semantics are clearly NOT call-by-reference. (Assigning a new array reference to the parameter name in the method does not update the array variable in the caller.) The fact that the behaviour is not distinguishable from call-by-reference with respect to the array contents does not make it call-by-reference.
Now to the meat of your question ...
When is it ever a good time to return an array argument as an array as opposed to void?
It is not entirely clear what you mean, but I assume that you are talking about these two alternatives:
public void method(String arg, String[] result) ...
versus
public String[] method(String arg) ...
I'd say that the second form is normally preferable because it is easier to understand and to use. Furthermore, the second form allows the method to choose the size of the result array. (With the first form, if the array is too small or too large, there is no way to return the reference to a reallocated array.)
The only cases where the first form should be used are:
when the functional requirements for the method depend on it being to update an existing array, or
when there is an overarching need to minimize the number of objects that are allocated; e.g. to minimize GC pauses.
The first case might arise if the array is already referenced in other data structures, and finding / updating those references would be difficult. It also might arise if the array is large, and the cost of making a copy would dominate the cost of the real work done by the method.
All parameters passed into a method in java are reference expect the primitive type, so wherever inside or outside the method it just keeps one object storage in memory, Static method are even NOT treated as any special case here. In your case of returning this array or a void type, it would not make any differences.
If you return this array, the returned value is what exactly you just now passed into this method.
WELL, ultimately... passing an array by value is slow. It has to grab a block of memory and copy the array. If the array is only a few bytes in size, its not a big deal. But if its a large chunk of memory, then this will be a slow IO operation. ESPECIALLY if this is happening in a tight loop, it will hurt performance.
Passing by reference will allow you to create a buffer ahead of time and reuse it.

Explaining some details about String

Hi y'all I have a very simple question. I am studying different websites that talk about arrays and I see this part which I don't understand very well.
In the (1) Why does the 'myString.length()' has a '()', why not just myString.length as in the example (2)??
In the (1) Why does the 'System.out.println(myString.substring(i,i+1))' has 'myString.substring(i,i+1)' why not just 'myString(i,i+1)' ??
In the (1) Why does the 'System.out.println(myString.substring(i,i+1))' has two values '(i,i+1)' why not just 'System.out.println(myString.substring(i))' as in example (2)??
1. String myString="abcedaslkhldfag";
for(int i=0; i<myString.length(); i++)
System.out.println(myString.substring(i,i+1));
2. for(int i=0; i<anArrayOfints.length; i++){
System.out.println(anArrayOfints[i]);
}
Thank you
I found it in this website http://www.javaclass.info/classes/java-array/array-examples-demonstration-and-code-snippets.php
First, about Arrays and Strings.
You are comparing totally different classes.
Array types are special objects that are dynamically created. Even array of primitives are objects (unlike in C) so it might have certain member variables/methods.
Have a look here: Array members
String is a class which encapsulates behavior suitable for strings, such as substring, trim etc. The actual data is stored internally as a character array, so there is a close connection between them, but the class itself represents more than just the characters.
Secondly, about subString method.
Methods called on a string object follow the syntax as specified by the API.
public String substring(int beginIndex)
public String substring(int beginIndex,int endIndex)
Have a look at the String API here. You will find there a length() method that returns the length of the String.
A note about "Arrays" class.
There is a class called "Arrays" that became available as part of the collections framework. The purpose of this class was to include behaviors that where commonly used on all types of arrays(such as sorting and searching).
The Array class extends java.lang.Object. Therefore array is an instance of Object. Arrays have one instance variable called length. It's a variable so you dont need the ().
And the string class has a member function called length, which is why you need the ().
The first one, myString is a string, which is an object. You are calling a method called length() of type String to know the length of the string. This method calculates the number of chars in the string and returns that number. And subString() is also a method that takes two parameters, begin and end index. This is just standard that is created by Java. To know more about the string methods, here.
The second one is continuous memory of data, an array. The length of the array is also stored in the array and is accessed using '.length'
This is because length() is a method on the String class, while length is an instance variable on the Array class.
As for myString.substring(i, i + 1), this is a method being called on an instance of the String class, which will return a new String instance containing the substring. In fact, myString.substring(i) does exist in the API, and would return the substring that starts at i and ends with the last character in myString.
Note that anArrayOfints[i] returns the int stored at element i in the array.
1, myString has a method named length. When use a method, you must specific the arguments which should be included in "()". In the (2), length means an attribute. Just use it as a variable.
2, substring is method. When use a method of some object, you can imagine you are sending command to this object. myString can not understand "myString(i,i+1)". You should specific the method or the command "subString"
3, anArrayOfints is an array object. Just like a list of something. You should specific a number to pick a element up.

Categories