Stack And Heap
In any kind of applications, memory is divided into 2 parts, one is called Stack, and another Heap. Reference is also called pointers in some languages, like C, C++, Object Pascal etc. This is the most difficult part of programming concepts for beginners to understand. I will do my best to describe it the best way I can.
Value Types
Value types are variable types which are allocated and stored into the stack. For example, we all know that int data type allocates 4 bytes from physical memory. This 4 bytes is stored directly in the stack because int is value type. byte, short, int and boolean are value types.
Reference Types
The working principes of reference types are a bit harder to understand. strings and Class objects are reference types. Reference typed objects are allocated into the heap, because strings and classes might require much more memory space then for example int type. Heap is always bigger then stack. So they are allocated into the heap but they also store a number in the stack and this number is the address of the object in the heap, which holds the objects data. Imagine this code:
ClassA a = new ClassA();
Here "a" is a number allocated in the stack which points to the memory space called heap. All members of "a" is stored in heap.
If we declare a class variable without initializing it, then the value of the variable will be null. For example:
ClassA a;
a.SomeMethod(); <-- this line will throw a null reference exception because the variable "a" points to zero (null) into the memory space.
When we create a class instance using the new keyword, this class is allocated in the heap and assigned the address to the variable, which is stored in the stack.
Assignement Operator
I'm sure you have used assignement operator before :D. This operator assignes the value of one variable to another. For example
int i = 4;
int j = 7;
i = j; <-- When this code executed both variables i and j will have the same value (7).
j = 9; <-- When this code executed variable j will have a value of 9 and i a value of 7.
In reallity, assignement operator doesn't assign a value of one variable to another, but it assignes the value which is stored in the stack. Because int is a value type, it's value is stored in the stack, and when we do assignement operation, we copy i's stack value into j's stack value.
But what happens if we assign one reference type variable to another? Before we answer this question, let's write a class which will help us to better understand the difference.
public class ClassA
{
private int _TestInt;
public void setTestInt(int value)
{
_TestInt = value;
}
public int getTestInt()
{
return _TestInt;
}
}
Ook, we have our test class, now let's create 2 instance of our newly created class.
ClassA classA = new ClassA();
classA.setTestInt(3);
ClassA classA2 = new ClassA();
classA.setTestInt(7);
Now let's see what happens when we assign classA2 to classA.
classA = classA2;
int i = classA.getTestInt(); <-- When this code executes, i will be 7.
Now let's try to set classA2's TestInt property to 2.
classA2.setTestInt(2);
int i = classA.getTestInt(); <-- Whoops, what happend here? classA's TestInt property is also set to 2, but we changed only for classA2. Well this is because both variables points to the same memory address in the heap after we assigned classA2 to classA. There stack value are identical and points to the same class instance. So any changes made in one of them will reflect on all of them.
There's also one thing you should consider. When passing value types to a method as parameter, any changes made in that method for the variable will take place only in the method we are calling for, but for reference types, the changes will reflect globally. For example:
void Test()
{
int j = 7;
IncreamentInt(j);
//j == 7 <-- the variable j is left intact. This is because the stack is allocated for every method, so changes made in IncreamentInt will reflect only in IncreamentInt's stack and not to Test's stack.
}
void IncreamentInt(int someInt)
{
someInt++;
//someInt == 8
}
But if we try same approach with reference types, the changes will reflect on both methods, because there is only one heap in the process and both stacks points to the same memory space.
void Test()
{
ClassA a = new ClassA();
a.setTestInt(3);
//a.getTestInt() == 4
}
void IncreamentInt(ClassA c)
{
c.setTestInt(c.getTestInt() + 1);
}
I think I've talked enough for theory. In my next post, I'll get back to NetBeans and mobile application developement. Good luck :)
Thursday, November 1, 2007
Reference And Value Types
Tuesday, October 30, 2007
Advertisement
If you are interested in advertising on this blog, contact me at dato0011(at)portadev.com.
Thursday, September 27, 2007
OOP In Java Part VI
Static Members
Static members are members which are not a part of class instance, but to a class itself. Static members can be variables and methods. For example TestClass c = new TestClass(); here, c is an instance of TestClass class, but TestClass is a class itself. From now, we have learned how to declare members of a class instance, now I'll teach you how to declare a member for a class itself.
public class TestClass
{
public static int getRandom()
{
Random r = new Random();
return r.r.nextInt();
}
}
Random is a class which generates random integer numbers. To use this class import java.util.Random package.
To access our getRandom() method you no longer need to create a class instance. Look at the code below:
int randomInt = TestClass.getRandom();
You can not access class instance's members from static method, instead you can access only static members, but you can access static members from class's instance. For example, you can not call a non-static method from a static method, or access a non-static variable from static method etc.
public class TestClass
{
private int testInt = 3;
public static int getRandom()
{
Random r = new Random();
return r.r.nextInt() + testInt; <-- This code won't compile, because we accessed a non-static field from static method.
}
}
In order to make this code work, simply declare the testInt variable as static.
public class TestClass
{
private static int testInt = 3;
public static int getRandom()
{
Random r = new Random();
return r.r.nextInt() + testInt; <-- This one is ok, because testInt is static now.
}
public void IncreaseTestInt()
{
testInt++; <-- This code also is fine, because we can access static fields from member methods.
}
}
Wednesday, September 26, 2007
OOP In Java Part V
Java Packages
Java packages is like namespaces in C++ and C#. It is used to organize classes into namespaces. Every class that you use are located in their namespaces. So a class must have it's own namespace. When you create a Mobile Application Project with NetBeans, a default package is automatically created where is located you midlet's main class. In our case, the package is called hello. Look at the picture.
Packages are shown under the project name. Right now we have only one package. If we undock the package, we will see classes wich is included in that package. A class can be included only in one package, but a package can include more thatn one class.
To specify a class it's package, simply write "package YourPackageName;" at the top of the code. For example.
package TestPackage;
public class ClassG
{
public void DoSomething()
{
//Here we do something.
}
}
You may change the package name for what you want it to be named. Now it's TestPackage but it can be MyGirlsLegs :). Note that declaring classes in packages doesn't reflect on the IDE automatically. For that, you must create a Java Package from NetBeans and move the class file into that package using drag & drop. To create a Java Package in the IDE simply right click on your project, choose new and hit Java Package. Enter TestPackage as the name and click Finish. Then move the ClassG.java to the new package. You can even add a package in package. Something like subpackages. For example, from the source editor, change TestPackage to TestPackage.AnotherPackage; Then right click on the newly created TestPackage from the ide, click new and hit Java Package. Enter the name of the package as AnotherPackage and click finish. Move the ClassG.java file to the newly created package. Subpackages are sometimes useful to split several classes into packages which have something in common.
When you'll write your own classes, before you are going to use it, you must import the package in which the class is located, otherwise your code won't compile. To import simply add "import YourPackage.SubPackage.*;" or "import YourPackage.*;" at the top of the code. Asterisk at the end of import declaration means that all classes will be imported from the specified package. If you want to import only one class from the package, simply replace ".*" with ".YourClassName".
J2ME comes with it's own class libraries located in different packages. You can import other packages in you class definition or in your Midlet's main class file.
Monday, September 24, 2007
OOP In Java Part IV
Protected Modifier
As I promised, right now I'm going to discuss about the protected modifier. Class member marked with this modifier can not be accessed from outside of the class, just like the private fields, but can be accessed by a child class. A child class is a class which extends the functionallity of other class (Inheriting class). The other class is called a parent class, or super class in java more preciselly.
public class Class1
{
protected void TestClass()
{
//Do something
}
}
public class Class2 extends Class1
{
public void Test()
{
TestClass(); //<-- this is Ok because we accessed the protected member from the child class.
}
}
Class1 c = new Class1();
c.TestClass(); //<-- this is wrong, because we accessed the protected field from outside of the class.
Polymorphism
Polymorphism is for manipulating other data types easily. When we are inheriting classes, we can use child classes as if it were parent classes. For example take a look at this classes.
public class Class1
{
protected void TestClass()
{
//Do something
}
}
public class Class2 extends Class1
{
public void Test()
{
TestClass();
}
}
public class Class3
{
public void TestPolymorphism(Class1 c)
{
//Do something
}
}
Class2 c2 = new Class2();
Class3 c3 = new Class3();
c3.TestPolymorphism(c2);
As you see the method TestPolymorphism expects a parameter of Class1 type, but we passed a Class2 type. What happens now? The code compiles and works fine :). This is because Class2 is a child class of Class1 and it has all the members that Class1 does. In other words, you can use child classes as if it were parent class's type, but you can not use parent class in such a way, because parent classes may not have the members of child's one. For example.
public class Class1
{
protected void TestClass()
{
//Do something
}
}
public class Class2 extends Class1
{
public void Test()
{
TestClass();
}
}
public class Class3
{
public void TestPolymorphism(Class2 c)
{
//Do something}
}
Class1 c1 = new Class1();
Class3 c3 = new Class3();
c3.TestPolymorphism(c1); <-- This code won't compile because Class1 doesn't have all the members that Class2 does.
Object Type
In Java, every type is inherited from the Object type. Object is a primary type from which comes all other types, like int, string, byte etc.
Accessing The Parent Class
If you want to access parent class from child class, use the "super" keyword. For example, imagine we have a destructor in Class1, we have inherited Class2 from Class1 and wrote another destructor for Class2 too. Now when Garbage Collector calls Class2's destructor, we want to call Class1's destructor automatically. For this approach, just call the super's finalize() method from Class2's destructor. For example.
public class Class1
{
public void finalize()
{
//Doing some extra cleanup here.
}
}
public class Class2 extends Class1
{
//now we want to call our parent class's finalize() method.
super.finalize();
}
That's all for today. To be continued... :)
Friday, September 21, 2007
OOP In Java Part III
Inheritance
Inheritance means to extend a class functionality in another one. For example, imagine we have ClassA and ClassB.
public class ClassA
{
public void Test1()
{
//do something
}
public void Test2()
{
//do something
}
}
As you see, ClassA has 2 public methods. Now we want to create a class called ClassB which will have all the properties and methods of ClassA and some extra members, which we do not want to implement in ClassA. There are two methods for this approach. The first one is to copy and paste ClassA and change it's name to ClassB, which is not a pretty solution. The second one is inheritance. We can implement ClassA in ClassB, It's quite simple. Take a look at the code
public class ClassB extends ClassA
{
public void Test3()
{
//do something
}
}
That's it. :) ClassB has all the members of ClassA plus another method called Test3(). Now you can call and access extended functions and members from ClassB.
ClassB b = new ClassB();
b.Test2();
b.Test3();
Please note that in Java language, we don't have multiple inheritance, this means that we can only extend one class when inheriting. In C++ it is possible to inherit from multiple classes, but Java doesn't support multiple inheritance.
Abstract Classes
Abstract classes means that the class can not be initialized. In other words, we can't create an instance of the class because it is abstract. Abstract class is not for direct use, instead it is used for inheritance. We can use abstract classes only if we create another class and extend it with abstract class members. Look at the syntax below.
public abstract class ClassC
{
public void Test4()
{
//do something.
}
}
ClassC c = new ClassC(); <-- This code won't compile, because we tried to create an instance of abstract class.
public class ClassD extends ClassC
{
}
ClassD d = new ClassD();
d.Test4();
This is how we can use abstract classes. You can use abstract classes when you need to create more than one class which shares some members. An ideal example will be an e-Mail client application. We will need here classes like InboxMessage, DraftMessage, SentMessage etc. All of those classes have something in common, for example Date and Message property, Forward method etc. You just create abstract class with Date and Message properties and one Forward method, then you'll just create other classes like Inbox, Draft etc. as I said above and extends them with the base class.
You can create a new class from NetBeans IDE by right clicking on your project -> New -> Java Class.
Thursday, September 20, 2007
This Blog Needs Your Help
Hello
If you find my content interesting and you like it, please take a time to vote us on blog directories. On the right side, find voting links and vote for us please.
Thanks :)









