Arrays and Strings

An Array consists of data items of the same type, all with the same name. The size of an Array is "static". Once you have created an "array", you cannot change the number of elements it holds. If you create an array with 42 occurrences, then it will always have 42 elements. An array is a Data structure. If you wish create an array where the numbers of elements can be changed, you use class vector. In java, an array is a group of contiguous memory locations that all have the same name and same type.
This declares that x is an array of char variables.
char [ ] x ;
Allocating the array decides the numbers of elements.
x = new char [5] ;
If you remember "x" is a reference, the syntax above is more understandable. When you allocate an array, the elements are automatically initialized.
primitives:
numeric primitives are zeroed,
char primitives are made spaces,
Boolean primitives are made false
References:
For an array of any other type the "references" are made null.
x [0] = 'z' ;
This assigns the char Z to the first array position.
x [1]= 'q' ;
This assigns the char 'q' to the second array position.
An array is a full-fledge object. you can declare an array either of two ways:
char [ ] x; or char [ ] ;
If you put the brackets on the data type, you can declare multiple references as all being the same type of array.
char [ ] x. y. z; In this case, x, y, and z are all as char arrays. "length." For example:
int y = 0 ;
int [ ] x;
x = new int [5] ;
y = x.length;
Notice, "length" is not a method, it is a property. you can use an "Initializer List" enclosed in braces to quickly insert values in your array:
int n [ ] = { 12, 44, 98, 1, 28 } ;
Because this list has five values in it, the resulting array will have five elements. If we had a char array, it would be like this:
char m [ ] = { 't', 'I' , ' M' , 'Y' } ;

6.1 Constant variables and the final qualifier
When used in a variable's declaration, the keyword "final" indicates that the variable can never be changed.
final int ARRARY_SIZE = 10;
If you have chosen to make your variable "final" then you must initialize it in the same statement that declares it—you have no other alternative,
When we call a method and pass the method a primitive –data-type variable, we are always passing a copy of the original, not the original. Thus, if the method changes the variable it receives, only the copy is changed not the original.
int x = 3;
x is a primitive variable. If we call a method with x as an argument, we make a copy of x and the original copy is not affected by any changes we make in the copy.
int x = 3;
yMethod (x)
public int yMethod (int y)
{
return y++;
}
If we pass x to a method, a copy y is made and any changes happen to the copy. Now, we have char [ ] out = { 'H' , 'e' , 'l' , 'p' } ;
If we pass the reference out to a method, we again pass a copy, but the copy points back to the original, and so our method can change the original.

6.2 Passing an array to a Methasfod
As you saw in the previous example, when we wish to pass an array to a method, the array's signature must be expecting to receive an array. Thus, the method was declard:
public void strMethd (char [ ] data )
{
}
The method was clearly designed to receive a char array, which it names data. But we called the method , we only used the bare name of the array we were sending. We didn’t use the square brackets.
strMethd (out);
If we pass entire array—meaning just the array name without any square brackets- then we are passing the reference and the original array can be changed in the method. But, if we pass just one array value (and include the square array brackets) then we are just passing a copy and the original cannot be changed. If we pass just the naked array name, the original array can be accessed and changed.
char [ ] out;

wholeArray (out)
public void wholeArray (char [ ] data )
{
data [2] = 'L' ;
// will change original array
}
If we pass just a single array value, we can't change the original table'
char [ ] out ;
pieceofArray (out [2] )
public void pieceofArray (char d )
{
d = 'x';
// won't change original array
}

public void start ( )
{
char [ ] out = {'H', 'e' , 'l' , 'p' } ;
display.append ( "Before out=" + out [0] + out [1] ;
wholeArray (out) ;
pieceofArray (out [1] )
display.append ( "/nAfter out=" + out [0] + out [1] ;
+ out [2] + out [3] ) ;
}
public void pieceofArray (char [ ] data )
char change = '1' ;
display.append ( "/nAfter out=" + out [0] + out [1] ;
+ out [2] + out [3] ) ;
}
public void pieceofArray (char datum )
{
datum '= 'w' ;
}
The call using the entire array was able to change the original. The call using just a single element was not able to change the original.

6.3 Double-Subscripted arrays
This is the syntax for a double-subscripted array
char demo [ ] [ ]
Java does not directly support two- dimensional arrays—however, it lets you define an array where each element is an array—thereby achieving the same effect.

6.4 Strings and characters
Strings do a lot of things we have not been aware of.
public class Test
{
public static void main (string [ ] args )
{
string w = "welcome to" ;
string j = "Java" ;
float v = 1.2f ;
string txt;
tex = w + j + v + ",";
system.out.println (txt) ;
}
}
Note—There are 3 String variables referenced here and 5 blocks of character storage are allocated?

public class Test
{
public static void main (string [ ] args )
{
string w = "welcome to" ;
string j = "Java" ;
float v = 1.2f ;
string txt;
tex = w + j + v + ",";
system.out.println (txt) ;
}
}
Why does such a tiny program need so many areas of memory? Let's explore the answer to that question in detail. All Java characters are stored in 16-bit Unicode, so they are able to store international character sets. In Unicode, every character requires 2 bytes. Under this system, "Hello, world." would require 26 bytes to store in memory.
To create String, we do something like,
String myname = "Joe";
// intitialized to Joe
or
String myname = new String ("joe") ;
// initialize to joe
The bottom method is less familiar, but more correct under the object-Oriented method. The top method is a convenience we use in order to make string manipulation easier. Another convenience is in String concatenation:
String a = "hello";
String b = "world";
String capital;
c = a + b;
We accept that we're not arithmetically adding these two strings. Rather, the plus [+] operator has been overload. "Overloading" is when something has a different meaning depending on it context. When we do this: capital + b; it seems like we are really doing this: capital = a.concat(b): In fact, secretly, we're using another class called a StringBuffer, which we'll get to a little later.
Take the following example, where we are concatenating a String a with an int i:
String a = "Ten ";
int I = 4;
String c ;
c = a + 1;

Since I is being "added" to a String, the compiler knows it needs to convert I to a string also. The complier creates a new String block just to hold the converted integer. Anytime you concatenate a String with another type, the other type is first converted into a string and then the two are concatenated. Really, this is done using method toString()which every object inherits from object
capital= a.concat (String) b) ;
If you concatenate other primitive data types with a string, it has similar effect:
string a = "" ;
Boolean b = false;
String capital ="Microsoft is dishonest =";
a = c + b:
Microsoft is dishonest=false
The += operator is also overloaded;
String capital = "Microsoft" ;
String b = "rules";
c += b;
{ capital = = "Microsoft rules")
The following example is crackerjack Certification question:
String a = " ";
int b = 2;
int capital = 3;
a = b+capital:
This is a syntax error. To force the conversion to string, at least one of the operands on the + sign must be a string. What about this example. Where we're concatenating a String object to regular object. What happens here?
String a = " " ;
String b = "Test";
Employee e = new Employee ("GW" , "Bush") ;
a = b + e;
This still produces a String and is equivalent to:
a = b + e.toString ( ) ;
Class String is located at the top of the class hierarchy. The class is declared as final, which means it cannot be Subclassed, cannot be Superclass to any Subclass. Class String contains 48 methods. These method allow you to do many with a String object except change that String. There are many methods anything with a String except change that string. There are many method that take a String arhument and return a String. None of these allow you to change the original String. These methods may appear to change the string, but they don't they merely return a different String. Once a String object is instantiated, it can never be changed. String is immutable. That means, once they are created, they can't be change. Because String object are immutable they can be shared.
Here we have three String objects, a, b, capital which happen to contain identical strings. Because they are identical, the Java compiler only stores one copy of the String "hello".
String a = "hello " ;
String b = "hello " ;
String c = "hello " ;
a, b and capital are merely pointers to the same space.
Once the compiler discovers that the string object is the same for all three, it used the same String for all three, we are reassigning a reference, or making it point to a different place. We're not changing the String.
String a = "hello " ;
String b = "hi " ;
String capital
capital = a;
capital = b;
This helps explain what is happening when e compare two Strings in this manner: if (a==b); We are comparing the references, not the objects.

6.4.1 Length of string
To Fine out the length of a String or the number of characters a String has you use the String's method length():
String a = "Testing";
int x = 0;
x = a.length ( ); {x = = 7 }
To find the length of an array object, you use the property length. Notice, it's not a method. To find the object, you use the method length().

6.4.2 Sub-Strings
You can extract a substring from a larger String object with the substring() method of class String.
String greet = "Howday";
String s = greet.substring (0,4) ;
The first argument 0 is the 1st character of the substring that you do want to copy. The 4 is the 1st character that you don't want to copy.
So … (s is equal to "Howd")

6.4.3 Finding individual characters
The string function char At() allows you to discover and return the character at a certain point in a String.
String a = "Testing";
Char b = ' ';
b = a.charAt (3) ;
{b = =,, t }
6.4.4 Comparing strings
The now know you cannot compare the references of two String objects in order to determine if the referenced objects are equal. You accomplish that goal using the equals() method of class String.
String a = "hello";
String b = "hello";
a.equals (b);

In fact, you can even take a shortcut to the same compare:
String b= "hello";
"hellow".equals (b) ;
In fact, you can even take a shortcut to the same compare:
String b= "Hello";
"hellow".equalsIgnoreCase (b);

String b = "hacker heaven";
String n = " " ;
n = b.replace ('h' , 'H') ;
Remember, this does not change the original, it return a new String object in which the change have been made.
String b = "hacker heaven";
String n = " " ;
n = b.trim ( ) ;
(n = = "hacker heaven" )
This method merely removes any extra spaces from both the front and back of String, Note that this does not alter the original String. Rather, it returns a new String with the leading and trailing spaces omitted.

6.4.5 StringBuffer class
An object String cannot be altered after it has been created. An object of class StringBuffer can be altered. We describe the class StringBuffer as a mutable class, meaning it can be changed. StringBuffer are used internally to implement many of the methods in the String class. Every StringBuffer object can hold only a certain amount of characters. A StringBuffer has capacity that describes the number is determined at the time of creation. If not specified when it is instantiated, a StringBuffer has a default capacity of 16 characters. Therefore, you generally specify the capacity when you instantiate your StringBuffer. We say a StringBuffer is Dynamically Resizable. A StringBuffer is instantiated as follows:
StringBuffer d = new StringBuffer ( ) ;
This one will begin with a capacity of 16 characters.
StringBuffer d = new StringBuffer (100 ) ;
StringBuffer e;
e = new stringBuffer ("hellow" ;
This one has capacity of 21 characters, because the initializing String contains 5 characters.
Every StringBuffer starts off with 16 characters of capacity. When you initialize it with String. You Still get the original 16, and your initializing String is just added to that 16, if you add characters to your StringBuffer, it grows in size, it's Dynamically Resizable. You don't worry about its size, it's a question of efficiency.
For example, this StringBuffer would be inefficient:
StringBuffer e:
e = new StringBuffer (99999999) ;
This one will hold 99999999 characters. If you do wish to add to your StringBuffer, you use its append() method.
StringBuffer e:
StringBuffer d = new StringBuffer (100 ) ;
e.append ("key Largo") ;
A StringBuffer makes your code run faster because you create fewer new objects such as temporary Strings. The method append() always adds the characters to the end of the StringBuffer. The method append() is and will convert each to a String automatically. You cannot intermingle String methods with stringBuffer methods.
When the overloaded plus sign [+] concatenates a string to something else, it uses a StringBuffer object:
d= "Ten" + 4 "ya" ;
The above is actually implemented as follows:
d = new StringBuffer ( ).append ("Ten"). append (4). append ("ya") ;
This is initially created with the default capacity.
Method apopend() is the principle way to add characters to the end of a StringBuffer. StringBuffer method insert() is used to place characters into an existing StringBuffer object at a specified location. Method insert() is overloaded 9 times.
Whereas append() adds text to the end of the StringBuffer object, method insert() takes two arguments. The first argument is an integer "offset" that tells the first character position to begin inserting the second argument. The second argument can be any data type.
Classes String and StringBuffer do share a few methods. You can learn the length of a StringBuffer by using the method: length(). Method length() tells you the amount of memory a StringBuffer currently is using. Method capacity(). On the other hand, tells you the total amount of memory allocated to a StringBuffer.
Method reverse() simply reverses the order of the characters in the StringBuffer.
StringBuffer king;
king = new StrngBuffer ("murder");
king.reverse ( ) ;
{ king.toString ( ) == "redrum" ) ;
Method ensureCapacity() simply makes sure that your StringBuffer has at least the capacity you specify. This is primarily an issue of efficiency. One could say the argument of this method is something called "Minimum capacity."
EnsureCapacity (int imnimumCapacity) ;
There is twist on how you apply ensureCapacity()
StrngBuffer sb;
sb = new StrngBuffer ("Test") ;
First (Certification-type question) what is the current capacity of StrngBuffer object sb?
20 = 16 + 4
What would be the capacity of sub after this statement?
StrngBuffer sb;
sb = new StrngBuffer ("Test") ;
sb.ensureCapacity (21)
If you asked for less that was already allocated, nothing changes, However, if you asked to increase the allocation, it gives you the larger of two-times the original plus 2 or your request.
42
Finally, let's test that:
StrngBuffer sb;
sb = new StrngBuffer ("Test") ;
sb.ensureCapacity (43) ;
Since this request is larger than two-times the original allocation, plus two, our request prevails.
43

6.5 Character class
Most methods in the class character are static. Most of these methods take a character argument. They perform either a test or a manipulation on that argument.
Method isDefined() seeks to know if the character that is provided as an argument is defined in the Unicode character set.
int x = "}";
Character.isDefined (x);
true means the character is (x);
This method tries to determine if a character is a digit.
int x = "3";
Character.isDefined (x);
true means the character is a digit.

6.6 String Tokenizer class
The StringTokenizer class is a tremendously useful and tricky class that can be used to do things like break a Sting up into words. What we call a "word", the computer knows as a "Token" or a unit of a String. You will find this term is used commonly in other languages also.
The item used to decide where one token ends and another begins is newline. Although these are the common delimiters, you get to choose what you want to use for a delimiter. In fact, a token can be many characters, not just one.
In fact, you can change the delimiter every time you call a method of the StringTokenizer class object. When you use an object of class StringTokenizer, there is one primary decision they has to be made. If the return Tokens flag is false, then the delimiter characters only separate other tokens. If the returnTokens flag is true, then the delimiter characters are themselves tokens. Remember, a token doesn't have to be just one character, it can be many characters that together comprise the token.
As the StringTokenizer class object moves its way through a String, it automatically knows where it is in the String, you do not have to keep track of that. When you instantiate an object of type StringTokenizer, you have three alternatives arguments for the constructor.
1.) String Stringtobetokenized
2.) String Stringtobetokenized, String delimiter
3.) String Stringtobetokenized,
String delimaiter,
Boolean returnTokens
Default delimiters: " /n, /t, /r "
Default returnTodens = false.

6.6.1 StringTokenizer class Methods
int counTokens ( )
bollean hasMoreToken ( )
Boolean hasMoreElements ( )
object nextElement ( )
String nextToken ( )
String nextToken (string delimaiter)

CountTokens() method counts how many more times this tokenizer object's nextToken can be counted.
int counTokens ()
It returns an integer with that number,
hasMoreTokens() simply tests if there are more tokens available from this tokenizer's String.
Boolean hasMoreTokens() method if returns true, it anticipates that the a call to method nextToden() right after this would succeed in returning a token.
hasMoreElements() is used to override a method inherited from the Enumeration interface, which this class implements.
Boolean hasMoreElements ( )
In effect, this does the same thing as the hasMoreTakens() method, true if there are more tokens.
nextToken() method is the workhorse. It gets the next token waiting in the String that was used to instantiate this object.
String nextToken ( )
If you neglected to precede this call with a successful hasMoreToken() method call, this method can throw a NoSuchElementException. This method overloads nextToken(). It still returns the next token in the String but
String nextToken (String delimiter)
If you neglected to precede this call with a successful hasMoreTokens() method call, this method can throw a NoSuchElementException