Explaining some details about String - java

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.

Related

What is the difference between String... variable and String varible[] in 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).

When to use a substring to pass to a method vs passing whole string and using integers to specify boundary

Say you have a string where you are part way processing it but you ran into a part that is to be handled by a different method. Is it better to pass the entire string and use ints to show the boundaries or should a substring be created and passed as the argument to the other method?
The use is for a method that is processing an expression but if brackets are encountered another method is called.
So for example say I have a method process (String str). In it there's a line if(str.charAt(i) == '(') that calls another method that is responsible for finding the closing bracket. Would it be better to pass the method str.substring(i, str.length) or just have the method take a second parameter and pass it i so it knows where to start working from?
Because string are immutable. When you call subString on a instance you create new object. So in case of performance is better to pass the whole String and the indexes of start and end, but instead passing the String you may want to pass char[].
In Java 7 you can use class Segment for representation.
You could also use the CharSequence as attribute for methods. This will assure that you will not mutate the object and still have the flexibility of array of chars.

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 ArrayList problem (involves valueOf())

So I have this function, combinations, which adds to an arraylist all permutations of a string.
public static void combinations(String prefix, String s, ArrayList PermAttr) {
if (s.length() > 0) {
PermAttr.add(prefix + s.valueOf(s.charAt(0)));
combinations(prefix + s.valueOf(s.charAt(0)), s.substring(1), PermAttr);
combinations(prefix, s.substring(1), PermAttr);
}
}
Now, I have this arrayList tryCK which let us say is {"A","B"}.
I have another arrayList CK which is also {"A","B"}, but it was derived from the combinations function above.
When I do tryCK.equals(CK) it returns true.
But when I put it through a another function I have on both tryCK and CK, for tryCK it returns true and CK it returns false, even though they are exactly the same lists.
So, my question is, does using .valueOf(s.charAt()) change some inner type?
This is super hard to explain but I do not want to post the full code.
First of All, you don't even really need to use valueOf because most always, Java is just fine concatenizing characters to the end of strings.
PermAttr.add(prefix + s.charAt(0));
Second, If you are going to use valueOf, at least reference it from the class String, not an instance of a String object...
PermAttr.add(prefix + String.valueOf(s.charAt(0)));
Third, a better naming convention would be helpful:
permAttr.add(prefix + s.valueOf(s.charAt(0)));
Fourth, there are plenty of ways to check the contents of your ArrayList, try making sure they actually contain the same values instead of assuming they do:
for(String s : CK)
System.out.println(s);
Fifth, you summed up with "So, my question is, does using .valueOf(s.charAt()) change some inner type?" and the answer is:
valueOf(s.charAt(int)) will return a String object. If you were not anticipating a string, then yes, this changes the type of the object. This String functions normally with all other Strings (like the ones you are concatenizing it with) and should do anything a String can do. So if you were expecting a String type, then no, it does not change any type.
Sixth, make sure if you are comparing strings to use the equals() method.
DO NOT USE:
if(s1 == s2)
this will check to see if the reference the same location in memory.
USE
if(s1.equals(s2))
this will check to see if the values of the Strings are the same.
I think that's all I got. GOOD LUCK!
First issue: you're using String.valueOf as if it were an instance method, when it's actually a static method. That leads to very misleading code.
Second issue: you don't have a consistent naming convention. Parameters should generally be camel cased - naming a parameter PermAttr leads to method calls such as:
PermAttr.add(prefix + s.valueOf(s.charAt(0)));
which looks like a static method call in a class called PermAttr.
Third issue: you're using String.valueOf for no reason - you're already using string concatenation, so using just:
prefix + s.charAt(0)
would be fine.
None of those are actually responsible for whatever's wrong (which we can't easily tell without a short but complete example demonstrating the problem) but they are making it harder to understand the code.
I suggest you fix the above issues, and put this into the context of a short but complete program which does demonstrate the problem. It should then be reasonably easy to work out what's wrong.

Java StringBuffer questions

class MyStringBuffer {
//TODO explain: why you would need these data members.
private char[] chars; //character storage.
private int length; //number of characters used
public String toString(){
//TODO
//Hint: just construct a new String from the ‘chars’ data member
//and return this new String – See API online for how create
//new String from char[]
This is only part of the code, I didn't want to post the whole thing. I just to focus on this and then then move on when I fully understand it.
1) What does he mean when he said construct a new String from the 'chars' data member? I'm confused as to what he wants me to do. Am I suppose to do something with char charAt(int index)? or something like this: StringBuffer sb = new StringBuffer("test");?
2) Does construct and create mean the same thing in Java?
What does he mean when he said construct a new String from the 'chars' data member? I'm confused as to what he wants me to do. Am I suppose to do something with char charAt(int index)? or something like this: StringBuffer sb = new StringBuffer("test");?
Do either of those things create a String? (Hint: no)
How do you create an instance of a particular class in Java? (Hint: review your notes on new. Hint 2: look at the javadocs for the java.lang.String class.).
Does construct and create mean the same thing in Java?
Java objects are created by a constructor, so it is reasonable to use "construct" and "create" interchangeably.
(Technically they don't mean exactly the same thing. An object is created by allocating its memory and calling a class constructor. So if you are being pedantic, constructing is part of the process of creating an object. But there's no need to be pedantic.)
1) The easy way to create a string from chars:
String result = new String(chars, 0, length);
Note, you probably can't just use the String(char[]) constructor, because the existence of the length member implies that some elements of chars may not be used. If you don't specify what elements to use, you could end up with extra chars (maybe NULs, maybe garbage) at the end of the string.
2) Not exactly. While the object is created (the memory for the object itself allocated) at the time the constructor's called, at that time it's just a blob of memory. The object is not fully constructed (read: any class invariants may not necessarily hold) until the constructor returns. This means the difference between the two only applies in the constructor, though, so it's common for people to use "create" and "construct" almost interchangeably.
You need an array of chars because, well, you have to store the characters somewhere. You could store them in a String but then you would have little need of a StringBuffer, whose raison d'etre is to be more efficient than a String (you generaly use the more efficient StringBuffer to construct a string, then use .toString() to get a real String object).
The length would be used to specify the length of the StringBuffer. You may thing you could just use the length of the character array but it's actually more efficient, when reducing the size of the StringBuffer, to not re-allocate a smaller array, especially if you may just end up needing more anyway.
The String constructor you would need for this scheme would be String (char[] value, int offset, int count) using an offset of zero and a count of length. This would allow you to use only the desired subset of the char array.
As he says, have a look at the API, where you will find a String constructor that takes an array of characters: http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#String%28char[]%29 .

Categories