Sunday, January 9, 2011

Beauty and Java

String class in immutable, i have already mentioned in the previous post. StringBuffer class is mutable. Mutable means it can be changed. We can declare a string in two ways.

1.String s = "hi"; or 2.String s = new String("hi");
During 1 memory for "hi" is allocated at the free pool of memory which is in the method area whereas in 2 it allocated in heap area.
Suppose, another string is declared 3. String s1 = "hi" then s1 will not be allocated new memory. The address of s is copied into s1. so s==s1 returns true. where as 4. String S1 = new String("hi") will allocate new address and s == s1 returns false.

We generally do s+="bye". to make the string "hibye". But, as I have mentioned String class is immutable and you cannot change it. What actually happens is JVM internally creates a StringBuffer object. StringBuffer class has append(), insert(), replace etc. the code is
s = new StringBuffer().append("bye").toString. The object class has a toString method which converts all the objects into String object. the address in s will now be changed to new value which points to hibye. Garbage collector picks the previous "hi".
BTW garbage collector not only works on heap are but also method area.

String class has the following methods:
charAt(), indexOf(),compareTo(),equals(), equalsIgnoreCase(), subString(start, end). for ex: "hello world".subString(3,6) will return "lo ". (end -1) inclusive.

Wrapper classes: They exist for every primitive data type. The uses of them are: type casting and passing primitive data types as objects.
 Any input form keyboard, may be a int or float, will be received as string. So, these wrapper classes have methods like parseInt(), parseFloat(), which will be invoked internally.
Suppose, theres a method
int i = 10;
void objectparam(object o)

we cannot pass i into it. so we should create object by instantiating Integer class.

CLASS CLASS

A class class has the following methods:
 String getClass()
Class getSuperClass() return the object of the super class
Interface[] getInterfaces() returns the array of objects of interfaces it implemented
Methods[] getMethods() ...... return all public methods right from the Object class to the current class
Methods[] getDeclaredMethods() ..... returns all methods of all access types of the current class

We need to import Java.Lang.Reflect to access getMethods(),getFields(), getConstructors()

SYSTEM CLASS

System class has static methods like:
PrintStream out,err
InputStream in
arrayCopy
gc     invokes the garbage collector by my not be immediate
exit
getProperty
loadLibrary

2 comments: