JAVA Beginners part 13

Static Methods

Math Class has lot of static methods. These methods can be used without a need to create an object of math class. There is no Object needed, no heap space spent. The methods can be called any number of times. They do no use instance variables. 
int x = Math.round(42.2);
int y = Math.min(56,12);
int z = Math.abs(-343);// Use class name instead of Reference 

These methods dont use Instance variables so their behavior doesn’t need to about a specific object.

A class with one or more static methods can be instantiated. Static methods cannot use non static variables as it does not have access to the instance of the class. Also they cannot use non static methods. 

It is possible to call static methods using a reference variable but that is not ideal.

Static variables

value is the same for all instances of the class. One value per class. Static variable is initialized only when the class is first loaded.

public class duck
{
private int size;
private static int duckcount = 0;

public duck()
{
duckcount++;
}
}

duckcount will keep incrementing each time the duck constructor runs because duckcount is static and it wont reset to 0. This will be useful to know the instances of duck created while the program is running. 

 A Duck object does not keep its own copy of duckcount, because duckcount is static , duck objects all share single copy of it. Static variable lives in the class no the object. 

All instances of same class share a single copy of static variable. 

static variables are initialized when the class is loaded. But when is a class loaded ? when the new is called ?
yes or when somebody runs a static method or variable of the class.

Static variables are initialized before any object of that class are created.
Static variables are initialized before the static method runs.

Static variables gets the default values just like the integer, static int player; // player has a default value of 0.

static final variable. a variable can be made to remain constant, by using keyword final.

public static final double PI = 3.141592653589793;

The variable is marked public so that any code can access it.
The variable is marked static so that you don’t need an
instance of class Math (which, remember, you’re not allowed to create).
The variable is marked final because PI doesn’t change (as far as Java is concerned).

static final variables are constants so the name should be upper case with underscore separating the words.

A static final variable must be initialized, if not compiler will throw an error. However you can have a simple static variable not initialized.
You cant have a static variable inside a static method as well, static variable must be at class level.

Final variable means you cannot change its value.
Final method means you cannot override the method.
Final class means you cannot extend the class.

A class may need to marked as final for security purpose.
For instance, String class has to be marker a final because one should not be allowed to create a subclass. Extended String class substituted with their own string subclass objects could make the programs fail.

If you dont want a class to be instantiated , then you can mark the constructor of the class as private.


Few Math methods.

Math.random() = return random value, type is double and value is between 0 – 1.0
double r = math.random();
int 2 = (int) (Math.random()*5);

Math.abs() = returns absolute value. takes arguments such as integer m float

int x = Math.abs(-240) // return 240
double d = Math.abs(240.45) // return 240.45

Math.round() = Rounds of the value to int or double

int x = Math.round(-24.8f) // returns -25
int y = Math.rount(24.45f) // returns 24

Math.min() = returns a value that is minimum of two values.

int x = Math.min(24,240) // return 24
double Math.min(90.5,90.4) // returns 90.4

Math.max() = retusns max of the two values

int x = Math.min(24,240) // return 240
double Math.min(90.5,90.4) // returns 90.5


To treat a primitive data type as an object , we need to wrap it. There are wrapper classes that will do the job.

int x = 32;
Arraylist list = new Array:ist();
list.add(x);

above code will not work in systems running earlier than JAVA 5.0, the list will accept only objects.
which can be obtained by following below method.

wrapping ( Also called as Boxing )
———
Integer iwrap = new Integer(x);// the variable

Integer is the wrapper class. In the same way there are wrapper classes for Boolean,Character,Byte,Short,Long etc
all with same objective of providing a object out of primitive.

unwrapping
———–
int unwrapped = iwrap.intvalue();

Even though this is not relevant for now, but its worth knowing.

How to deal with Integer and Object conversion for List Prior to Java 5.0

public void dooldway ()
{

ArrayList listOfNumbers = new ArrayList() ;
listOfNumbers.add(new Integer (3)) ; // integer cannot be directly added as primitives and objects cannot be used interchangeably. need to convert to object

//to get the integer value out of the list

Integer one = (Integer) listofNumbers.get(0) ;// get the object first
int intone = one.intValue() ;//from the object get the integer

}

with Autoboxing
—————-

Arraylist<Integer> listofnumbers = new Arraylist<Integer>();

listofnumbers.add(3); // Just add it.The Compiler does the wrapping. In other words Compiler is actually storing an Integer object in the List and you get to add as primitive.

int num = listofnumbers.get(0); // Compiler automatically unwraps(unbox) the object to get the value.

more examples of autoboxing.
Integer i = new Integer(42);
i++;

Here is why it matters. Since the compiler does the auto boxing we can use the Integer Object and Int primitive interchangeably.
How ?
see below

test3.jpg

Outside observation.

local variables should be initialized. which is why below code will not compile.

public class textbox
{
       public static void main(String[] args)
       {
            int j;
            System.out.println(j);
        }
}

or

public class textbox2
{
         public static void main(String[] args)
         {
              textbox2 t = new textbox2();
              t.go();
         }
        void go()
        {
              int x;
              System.out.println(x);
         }
}

class variables will take default values.

public class textbox2
{
        int x;
        public static void main(String[] args)
        {
              textbox2 t = new textbox2();
              t.go();
         }
        void go()
        {
         System.out.println(x);
        }
}


a1.jpg

a2

other wrapper classes.

String s = “2”;
int x = Integer.parseInt(s);
double d = Double.parseDouble(“4230.42”);

** This wont work **
String t = “two”;
int x = Integer.parseInt(t);

Compiler will compile but it will fail at run time.

Boolean is a little different
Boolean b = new Boolean(“true”).booleanValue();

Boolean constructor will give the object value and then you need to unwrap it with
the booleanValue method.

 

 


next page 314

More in next part.

References:

Head First Java 2nd Edition

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s