Friday, March 18, 2011

Passing Variables into Methods- Java Passing Mechanism

Every Programming Language has its own way of passing the variables into methods. There are basically two ways of passing variables- Pass by Reference and Pass By Value. The former deals with the passing of reference or pointer to particular variable and the latter involves passing a copy of the variable to the method. C supports both ways of passing and the Pass By Reference is supported b means of Pointers. Every Java Beginner ponders over “Is Java a Pass By Value?” or “Is it a Pass By reference?” or “Both?”. Before answering the question i would like to throw light on Passing Object Reference variables and Passing primitive reference variables.

Object Reference Variables: These are the variables which refer to the object of the declared type or its subtype. Something like

Animal a = new Animal()

where a is the reference variable

Passing Object Reference Variables:

When a object variable is passed into the method, only the copy of the Object reference is passed and not the Object itself. The bit pattern in the reference variable is copied into the method parameter. What is this bit pattern? This bit pattern is the address of the specific object in the memory (on the heap). In other words, both the caller and the called method will now have identical copies of the reference and thus both will refer to the same exact object on the heap.

Code Example:

import java.awt.Dimension;
class PassObjectRef

public static void main(String[] args)

Dimension plotDimension = new Dimension(20,30);
PassObjectRef passObj=new PassObjectRef();
System.out.println("B4 Updating: "+
"W: "+plotDimension.width+"H:"+plotDimension.height);
//Before the object values are altered

passObj.updateDimension(plotDimension );
System.out.println("After Updating: "+"W:"+plotDimension.width+" H:"+plotDimension.height);
//After the object values are altered

void updateDimension(Dimension dim)

dim.height+=10; //Notice the values being changed here.


B4 Updating: W: 20 H: 30
After Updating: W: 40 H: 40

Notice that the values being updated in the updateDimension() method are being also reflected outside the scope of the method. That means both the plotDimension and dim object references are referring to the same object on the heap.

Passing Primitive Variables:

When a primitive variable is passed the value with in the variable is copied into the method parameter, which is nothing but the pass-by-copy-of-the-bits-in-the-variable.

Code Snippet:

class PassPrimVar

public static void main(String[] args)
int primitiveVariable =4;
PassPrimVar passObj =new PassPrimVar();
System.out.println("Before Updating Value: "+primitiveVariable );
// Value being printed before changing

System.ou.println("After Updating Value: "+primitiveVariable );
// Value being printed after changing. Notice there is no difference

void updateValue(int var)

var+=40; //Value being Changed Here
System.out.println("While Updating Value: "+var);



Before Updating Value: 4
While Updating Value: 44
After Updating Value: 4

Notice that the Value is same before and after the updateValue() method has been executed. But in the method the value has been changed. In other words the value being changed in the method is not being reflected in the main() method, its local to the scope of the method in which it is changed.

Does Java Use Pass-By-Value?

Here is the main confusion- Does Java Use Pass By Reference for Object Reference Passing and Pass By Value for Primitive Variable Passing? Java is actually pass-by-value for all variables running within a single VM. Pass By Variable is nothing but passing the variable value. It is same even if you pass and object reference variable or an primitive variable, you are always passing the copy of the bits in the variable. So for passing Object reference variable you are passing the copy of bits which actually is the reference (or address) to the object on the heap and this results in both the reference variables referring to the same object. Because two identical reference variables refer to the exact same object, if the called method modifies the object, the caller will see that the object the caller’s original variable refers to has also been changed. But keep in mind- Suppose in the called method the object reference is reassigned a new object, the caller’s original variable will still refer to the same object on the heap. In this case there will be two references and two objects on the heap. See the code excerpt below:

void do()

Animal animal = new Animal(”Dog”);
//New Animal object created on the heap with name Dog referenced by animal
kill(animal); // animal being passed to the kill() method

void kill(Animal ani)

Method receives a copy of the reference, but animal and ani both still refer to same object

ani =new Animal(”Cat”);

But after this statement, the animal reference still refers to the object by name “Dog”,but the ani reference now refers to the object by name “Cat”.
There are 2 references referring to 2 different objects on the heap.


Coming to the passing of primitive variables it is pretty simple and straight forward. When you pass the primitvie variable into a method, you’re passing a copy of the bits representing the value. For example if you pass an int variable with the value 6, and try to change the value in the called method, we can change it but the modifications will not be reflected in the caller’s vairable.

So the bottom line is- Java always uses Pass By Value- Be it for passing Object Reference Variable or primitive variables.

Shadowing Variables:

Shadowing involves redeclaring a variable that’s already been declared somewhere else (In the lines of code before the current line).
The effect of shadowing is to hide the previously declared variable in such a way that it may look as though you’re using the hidden variable, but you’re actually using the shadowing variable. You might find reasons to shadow a variable intentionally, but typically it happens by accident and causes hard-to-find bugs. On the exam, you can expect to see questions where shadowing plays a role.

You can shadow an instance variable by declaring a local variable of the same name, either directly or as part of an argument:
class Ferrari {
static int size = 7;
static void changeIt(int size) {
size = size + 200;
System.out.println("size in changeIt is " + size);
public static void main (String [] args) {
Ferrari f = new Ferrari();
System.out.println("size = " + size);
System.out.println("size after changeIt is " + size);

The preceding code appears to change the size instance variable in the changeIt() method, but because changeIt() has a parameter named size, the local size variable is modified while the instance variable size is untouched. Running class Ferrari prints

Output as

size = 7
size in changeIt is 207
size after changeIt is 7

Things become more interesting when the shadowed variable is an object reference, rather than a primitive:
class Car {
int carNum = 28;
class Ferrari {
Car myCar = new Car();
void changeIt(Car myCar) {
myCar.carNum = 99;
System.out.println("myCar.carNum in changeIt is " + myCar.carNum);
myCar = new Car();
myCar.carNum = 420;
System.out.println("myCar.carNum in changeIt is now " + myCar.carNum);
public static void main (String [] args) {
Ferrari f = new Ferrari();
System.out.println("f.myCar.carNum is " + f.myCar.carNum);
System.out.println("f.myCar.carNum after changeIt is "
+ f.myCar.carNum);

The preceding code prints out this:
f.myCar.carNum is 28
myCar.carNum in changeIt is 99
myCar.carNum in changeIt is now 420
f.myCar.carNum after changeIt is 99

You can see that the shadowing variable (the local parameter myCar in changeIt()) can still affect the myCar instance variable, because the myCar parameter receives a reference to the same Car object. But when the local myCar is reassigned a new Car object, which we then alter by changing its carNum value, Ferrari’s original myCar instance variable is untouched.

Important Notes:

1. The Java programming language doesn't let you pass methods into methods. But you can pass an object into a method and then invoke the object's methods.
2. Everything in Java is passed by value. Objects, however, are never passed at all.
3. The values of variables are always primitives or references, never objects.

Thanks to Reference of Mohamed Sanaulla ..

Tuesday, March 15, 2011

different types of Views in Android

Views and ViewGroups

An Activity contains Views and ViewGroups. A View is a widget that has an appearance on screen. Examples of widgets are buttons, labels, text boxes, etc. A View derives from the base class android.view.View.

One or more Views can be grouped together into a ViewGroup. A ViewGroup (which is by itself is a special type of View) provides the layout in which you can order the appearance and sequence of views. Examples of Viewgroups are LinearLayout, FrameLayout, etc. A ViewGroup derives from the base class android.view.ViewGroup.

Android supports the following ViewGroups:

* LinearLayout
* AbsoluteLayout
* TableLayout
* RelativeLayout
* FrameLayout
* ScrollView

SurfaceView and View:

- Views are drawn in UI thread and surfaceView are drawn in a seperate thread. So if rendering takes long time, its better to use SurfaceView. Then for animations also, its better to use surfaceView.

- SurfaceView uses more resoources than View, so use it when you really want.

The data-view model

This is the model used by the library Swing of Java notably. The view is the interface through which the user interacts with the software. Data are stored separately and can be displayed in different views.
The view may also change the data according to the context, for example, change the text according to the user's language.

The Android model

Android extends this views/data model, it provides a new model that is suitable for equipment activated at all times. The structure of applications is defined as follows:

1. The views (Class android.view.View)

The interface of a program for Android is a tree of views.
The image at right shows four views inside a screen (an activity).

2. The file AndroidManifest.xml

It defines the components of the application and their relationships. It gives the permissions to application as to what it can do with users. It can also give permission to components of the application.

3. The components of the application:

* Activity ( class).
This is something that the user can do, translated into program. It corresponds to a screen, but can have multiple views.
* Intent (android.content.Intent class).
Describes an action which must be performed.
* Service ( ).
Program that operates in background.
* Content Provider (android.content.ContentProvider class).
It encapsulates data and provides them commonly to several programs.
* Notification ( and classes).
Class which informs the user about what is happening.

Besides components, there are also resources that can be XML files, image files as jpeg. They use the android.content.Resources interface and are stored in the res directory.

Monday, March 14, 2011

Anti-Theif Software for all Nokia Phones

Anti-theft softwares works well on Nokia models like the 6600, 7610, 6630, 6670, N 70, N 72, N 80, N 93, N 95 and also on a few models of other mobile makers.

1.Install AntiTheif1.*****_Full.sis
2.Register withy any number ,Enjoy with full version.
Default password is 0000

how to find imsi number?
Press "*#06#" in your mobile

procedure of installing this software
Select .sis file in your phone and open it
Allow all Request's as Yes
Installing location should be in Mobile (not in memory card).

Rapid Share Links.

Block or Disable Stolen or Lost Mobile(Cell) Phone Using IMEI Number

Block or Disable Stolen or Lost Mobile(Cell) Phone Using IMEI Number:

International Mobile Equipment Identity i.e IMEI number popular known as Mobile phone's serial number is a 15 digit code that will appear on the mobile screen when you press * # 0 6 # Copy the number down and keep it for future reference.

This number is unique to your handset and helps you disabling and blocking yours stolen or lost phone in future . Motoralla Users can also try press #,* to retrive IEMI Number of your Phones

How To Use IMEI Number to Block Phones

If your mobile phone is lost or stolen you can inform your network provider with yours IMEI number who can then put the serial number on a shared database. This list stops this particular phone from registering on any network and will be useless for anyone even if the mobile phone's SIM card is changed!

Get Mobile Information Using IMEI Number

You can also get all yours mobile phone information using yours Mobile IMEI number all you need is to try the IMEI Number Analysis

JAVA Basics

Encapsulation: Encapsulation is a way in which data and code are binded together and data used within the program in kept safe from outside manipulation by making the instance...Hiding the data within the class and making it available only through the methods. This technique is known as encapsulation.
Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding.

Object - Objects have states and behaviors. Example: A dog has states-color, name, breed as well as behaviors -wagging, barking, eating. An object is an instance of a class.

Class - A class can be defined as a template/ blue print that describe the behaviors/states that object of its type support.

Methods - A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed.

Instant Variables - Each object has its unique set of instant variables. An object.s state is created by the values assigned to these instant variables.
Java Modifiers:
Like other languages it is possible to modify classes, methods etc by using modifiers. There are two categories of modifiers.

Access Modifiers : defualt, public , protected, private
Visible to the package. the default. No modifiers are needed.
Visible to the class only (private).
Visible to the world (public).
Visible to the package and all subclasses (protected).
Non-access Modifiers : final, abstract, strictfp.
The static modifier for creating class methods and variables
The final modifier for finalizing the implementations of classes, methods, and variables.
The abstract modifier for creating abstract classes and methods.
The synchronized and volatile modifiers, which are used for threads.

A class can contain any of the following variable types.
Local variables : variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed.
Instance variables: Instance variables are variables within a class but outside any method. These variables are instantiated when the class is loaded. Instance variables can be accessed from inside any method, constructor or blocks of that particular class.
Class variables: Class variables also known as static variables are declared with the static keyword in a class .Class variables are variables declared with in a class, outside any method, with the static keyword.
Access Control and Inheritance:
The following rules for inherited methods are enforced:
Methods declared public in a superclass also must be public in all subclasses.
Methods declared protected in a superclass must either be protected or public in subclasses; they cannot be private.
Methods declared without access control (no modifier was used) can be declared more private in subclasses.
Methods declared private are not inherited at all, so there is no rule for them.
The break Keyword:
The break keyword is used to stop the entire loop. The break keyword must be used inside any loop or a switch statement.
The break keyword will stop the execution of the innermost loop and start executing the next line of code after the block.
The continue Keyword:
The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop.
In a for loop, the continue keyword causes flow of control to immediately jump to the update statement.
In a while loop or do/while loop, flow of control immediately jumps to the Boolean expression.

Switch Statement:
The variable used in a switch statement can only be a byte, short, int, or char.
You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.
The value for a case must be the same data type as the variable in the switch, and it must be a constant or a literal.
When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.
Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached.
A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.
The finalize( ) Method:
It is possible to define a method that will be called just before an object's final destruction by the garbage collector. This method is called finalize( ), and it can be used to ensure that an object terminates cleanly.
Exception Handling:
You need to understand the three categories of exceptions:
Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation.
Runtime exceptions: A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation.
Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.
All exceptions must be a child of Throwable.

Inheritance the most commonly used keyword would be extends andimplements. These words would determine whether one object IS-A type of another. By using these keywords we can make one object acquire the properties of another object.

public class Animal{
public class Mammal extends Animal{
public class Reptile extends Animal{
public class Dog extends Mammal{
Now if we consider the IS-A relationship we can say:
Mammal IS-A Animal
Reptile IS-A Animal
Dog IS-A Mammal
Hence : Dog IS-A Animal as well.
HAS-A relationship:
These relationships are mainly based on the usage. This determines whether a certain class HAS-A certain thing. This relationship helps to reduce duplication of code as well as bugs.
Lets us look into an example:
public class Vehicle{}
public class Speed{}
public class Van extends Vehicle{
private Speed sp;

Rules for method overriding:

The argument list should be exactly the same as that of the overridden method.
The return type should be the same or a subtype of the return type declared in the original overridden method in the super class.
The access level cannot be more restrictive than the overridden method's access level. For example: if the super class method is declared public then the overridding method in the sub class cannot be either private or public. However the access level can be less restrictive than the overridden method's access level.
Instance methods can be overridden only if they are inherited by the subclass.
A method declared final cannot be overridden.
A method declared static cannot be overridden but can be re-declared.
If a method cannot be inherited then it cannot be overridden.
A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final.
A subclass in a different package can only override the non-final methods declared public or protected.
An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws exceptions or not. However the overridden method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. The overriding method can throw narrower or fewer exceptions than the overridden method.
Constructors cannot be overridden.

JAVA Design patterns part-1

Java Design Patterns

Design is blue print of something so it can be defined as creation of something in mind.

Pattern, we can define it as guideline.

Design pattern is a widely accepted solution to a recurring design problem.

Java design patterns are devided into 3 types

1)Structural Patterns

2)Behavioral Patterns

3)Creational Patterns

Structural Patterns:

Structural Patterns describe how objects and classes can be combined to form structures. The difference is that class patterns describe relationships and structures with the help of inheritance. Object patterns, describe how objects can be associated and aggregated to form structures by using object composition.

In Structural Pattern we have 7 types. Which are

1)Adapter Pattern:

Adapter - Match interfaces of different classes.

The Adapter pattern is used to translate the interface of one class into another interface.A class adapter uses multiple inheritance to adapt one interface to another.There are two ways to do this: by inheritance, and by object composition (aggregation).The UML diagram is

And the general understandable view is

Benefits: Allows two or more incompatible object to communicate and interact Improves reusability of older functionality

2)Bridge Pattern: Decouple an abstraction or interface from its implementation so that the two can vary independently.The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.

The collections class framework in the Java API provides several examples of use of the bridge pattern. Both the ArrayList? and LinkedList? concrete classes implement the List interface. The List interface provides common, abstract concepts, such as the abilities to add to a list and to ask for its size. The implementation details vary between ArrayList? and LinkedList?, mostly with respect to when memory is allocated for elements in the list.


The electric equipments you have at home and their switches. For e.g., the switch of the fan. The switch is the interface and the actual implementation is the Running of the fan once its switched-on. Still, both the switch and the fan are independent of each other. Another switch can be plugged in for the fan and this switch can be connected to light bulb.

And the UML diagram is

Benefits: Implementation can be selected or switched at run-time. The abstraction and implementation can be independently extended or composed.

3)Composite Pattern:

Composite pattern allows treating different objects in a similar fashion. In order to treat objects in a uniformed manner we need to inherit them from a common interface.We

represent a part-whole relationship in a tree structure.

Following figure shows how different objects are called in a uniform manner.

And the UML diagram is


Define class hierarchies consisting of primitive objects and composite objects.

Makes it easier to add new kind of components.

4) Decorator Pattern: The Decorator pattern lets you attach additional responsibilities and modify instance functionality dynamically.The decorator pattern can be used to make it possible to extend (decorate) the functionality of a class at runtime. This is achieved by designing a new decorator class that wraps the original class. This wrapping could be achieved by the following sequence of steps:

1. Subclass the original "Component" class into a "Decorator" class (see UML diagram).

2. In the Decorator class, add a Component pointer as a field.

3. Pass a Component to the Decorator constructor to initialize the Component pointer.

4. In the Decorator class, redirect all "Component" methods to the "Component" pointer.

5. In the Decorator class, override any Component method(s) whose behavior needs to be modified.

The decorator pattern is an alternative to subclassing. Subclassing adds behavior at compile time whereas decorating can provide new behavior at runtime.

Here is the UML diagram of the Decorator pattern followed by a description of the various involved components.

Component: Defines the interface for objects that can have responsibilities added to them dynamically.
ConcreteComponent: Defines an object to which additional responsibilities can be attached.
Decorator: maintains a reference to a Component object and defines an interface that conforms to Component's interface.

ConcreteDecorator: adds responsibilities to the component.


More flexibility than static inheritance.

Avoids feature-laden classes high up in the hierarchy.

Simplifies coding because you write a series of classes each targeted at a specific part of the functionality rather than coding all behavior into the object.

Enhances the object's extensibility because you make changes by coding new classes.

5)Facade Pattern (Face or Front Appearance): The Fa├žade pattern allows you to simplify this complexity by providing a simplified interface to these subsystems. This simplification may in some cases reduce the flexibility of the underlying classes, but usually provides all the function needed for all.

This design pattern provides an integrated (combined) interface to a set of interfaces in a subsystem. It defines a higher-level interface that makes the subsystem easier to use. A facade is an object that provides a simplified interface to a larger body of code, such as a class library.

Example: Facade as the name suggests means the face of the building. The people walking past the road can only see this glass face of the building. They do not know anything about it, the wiring, the pipes and other complexities. The face hides all the complexities of the building and displays a friendly face.


The main benefit with the Facade pattern is that we can combine very complex method calls and code blocks into a single method that performs a complex and recurring task. It also reduces code dependencies between libraries or packages.

6)Flyweight Pattern: Fly weight pattern is useful where we need to create many objects and these entire objects share some kind of common data.

Consider following figure. We need to print visiting card for all employees in the organization. We have two parts of data one is the variable data i.e. the employee name and the other is static data i.e. address. We can minimize memory by just keeping one copy of the static data and referencing the same data in all objects of variable data. So we create different copies of variable data, but reference the same copy of static data. With this we can optimally use the memory.


Reduce the number of objects created, decrease memory footprint and increase performance.

7) Proxy Pattern:

A proxy is a class functioning as an interface to something else. The proxy could interface to the resource that is expensive or impossible to duplicate. This actual object can be a huge image or a data object which is very large and cannot be duplicated. So you can create multiple proxies and point towards the actual object (memory consuming object) and perform operations. This avoids duplication of the heavy object and thus saving memory. Proxies are references which points towards the actual object.

There are several cases where a Proxy can be useful. Few of them as follow.

1. If an object, such as a large image, takes a long time to load.

2. If the object is on a remote machine and loading it over the network may be slow, especially during peak network load periods.

3. If the object has limited access rights, the proxy can validate the access permissions for that user.

In proxy pattern, typically one instance of the complex object is created, and multiple proxy objects are created, all of which contain a reference to the single original complex object. Any operations performed on the proxies are forwarded to the original object. Once all instances of the proxy are out of scope, the complex object's memory may be deallocated.


Gives the ability to control access to an object, whether it's because of a costly creation process of that object or security issues.

How to make a call using cmd in andorid

On windows XP/Ubuntu , open a command console.

Type “telnet”. The telnet client starts.
Then, type, o localhost 5554
This connects the telnet client to the android emulator (assuming emulator is running locally listening on port 5554. Else this connection fails)
Now type
gsm call 0987654321
The last parameter could be any number(Phone number).
This simulates a call to the emulator.